From 27e43c5d946a4621684d31104be780a5124e1050 Mon Sep 17 00:00:00 2001 From: Reed Allman Date: Tue, 5 Sep 2017 11:36:47 -0700 Subject: [PATCH] remove ccirrelo/supervisor, update everything seems to work even though sirupsen is upper case? :cyfap: --- api/agent/agent.go | 1 - glide.lock | 86 +- glide.yaml | 1 - .../github.com/PuerkitoBio/purell/purell.go | 2 +- .../PuerkitoBio/purell/purell_test.go | 192 +-- vendor/github.com/Shopify/sarama/client.go | 38 +- vendor/github.com/Shopify/sarama/config.go | 7 + .../github.com/Shopify/sarama/crc32_field.go | 6 +- vendor/github.com/Shopify/sarama/message.go | 6 +- .../github.com/Shopify/sarama/message_test.go | 31 + .../Shopify/sarama/mockresponses.go | 10 +- vendor/github.com/Sirupsen/logrus/.gitignore | 1 + vendor/github.com/Sirupsen/logrus/.travis.yml | 15 + .../github.com/Sirupsen/logrus/CHANGELOG.md | 113 ++ .../supervisor => Sirupsen/logrus}/LICENSE | 6 +- vendor/github.com/Sirupsen/logrus/README.md | 507 ++++++++ vendor/github.com/Sirupsen/logrus/alt_exit.go | 64 + .../Sirupsen/logrus/alt_exit_test.go | 83 ++ .../github.com/Sirupsen/logrus/appveyor.yml | 14 + vendor/github.com/Sirupsen/logrus/doc.go | 26 + vendor/github.com/Sirupsen/logrus/entry.go | 279 +++++ .../github.com/Sirupsen/logrus/entry_test.go | 77 ++ .../Sirupsen/logrus/example_basic_test.go | 69 ++ .../Sirupsen/logrus/example_hook_test.go | 35 + vendor/github.com/Sirupsen/logrus/exported.go | 193 +++ .../github.com/Sirupsen/logrus/formatter.go | 45 + .../Sirupsen/logrus/formatter_bench_test.go | 101 ++ .../github.com/Sirupsen/logrus/hook_test.go | 144 +++ vendor/github.com/Sirupsen/logrus/hooks.go | 34 + .../Sirupsen/logrus/hooks/syslog/README.md | 39 + .../Sirupsen/logrus/hooks/syslog/syslog.go | 55 + .../logrus/hooks/syslog/syslog_test.go | 27 + .../Sirupsen/logrus/hooks/test/test.go | 95 ++ .../Sirupsen/logrus/hooks/test/test_test.go | 39 + .../Sirupsen/logrus/json_formatter.go | 79 ++ .../Sirupsen/logrus/json_formatter_test.go | 199 +++ vendor/github.com/Sirupsen/logrus/logger.go | 323 +++++ .../Sirupsen/logrus/logger_bench_test.go | 61 + vendor/github.com/Sirupsen/logrus/logrus.go | 143 +++ .../github.com/Sirupsen/logrus/logrus_test.go | 386 ++++++ .../Sirupsen/logrus/terminal_bsd.go | 10 + .../Sirupsen/logrus/terminal_linux.go | 14 + .../Sirupsen/logrus/text_formatter.go | 191 +++ .../Sirupsen/logrus/text_formatter_test.go | 141 +++ vendor/github.com/Sirupsen/logrus/writer.go | 62 + vendor/github.com/apache/thrift/.gitignore | 11 + vendor/github.com/apache/thrift/.travis.yml | 76 +- .../apache/thrift/aclocal/ax_boost_base.m4 | 247 ++-- .../thrift/aclocal/ax_cxx_compile_stdcxx.m4 | 982 +++++++++++++++ .../aclocal/ax_cxx_compile_stdcxx_11.m4 | 160 +-- .../apache/thrift/build/docker/README.md | 72 +- .../thrift/build/docker/centos-7.3/Dockerfile | 197 +++ .../thrift/build/docker/centos/Dockerfile | 146 --- .../thrift/build/docker/centos6/Dockerfile | 56 - .../{debian => debian-jessie}/Dockerfile | 0 .../build/docker/debian-stretch/Dockerfile | 230 ++++ .../thrift/build/docker/scripts/cmake.sh | 4 +- .../thrift/build/docker/scripts/ubsan.sh | 6 - .../{ubuntu => ubuntu-trusty}/Dockerfile | 0 .../build/docker/ubuntu-xenial/Dockerfile | 236 ++++ .../apache/thrift/compiler/cpp/CMakeLists.txt | 1 + .../apache/thrift/compiler/cpp/README.md | 2 +- vendor/github.com/apache/thrift/configure.ac | 203 ++-- .../c_glib/transport/thrift_ssl_socket.c | 21 +- .../apache/thrift/lib/cpp/Makefile.am | 2 +- .../apache/thrift/lib/cpp/test/CMakeLists.txt | 1 + .../apache/thrift/lib/cpp/test/Makefile.am | 2 +- .../apache/thrift/lib/d/Makefile.am | 2 +- .../thrift/lib/d/src/thrift/transport/http.d | 2 +- .../lib/d/src/thrift/transport/socket.d | 4 +- .../lib/hs/{Thrift.cabal => thrift.cabal} | 0 .../nodejs/lib/thrift/multiplexed_protocol.js | 10 +- .../lib/php/lib/Thrift/Transport/TSocket.php | 6 +- .../apache/thrift/lib/py/src/ext/types.h | 1 + .../apache/thrift/test/cpp/Makefile.am | 2 +- .../thrift/test/go/src/common/mock_handler.go | 335 ------ .../thrift/test/py.twisted/test_suite.py | 5 +- .../github.com/apache/thrift/test/tests.json | 2 +- .../asaskevich/govalidator/validator.go | 2 +- .../cactus/go-statsd-client/.travis.yml | 3 +- .../github.com/ccirello/supervisor/.gitignore | 1 - .../ccirello/supervisor/.travis.yml | 6 - .../github.com/ccirello/supervisor/README.md | 5 - vendor/github.com/ccirello/supervisor/anon.go | 40 - vendor/github.com/ccirello/supervisor/doc.go | 78 -- .../github.com/ccirello/supervisor/group.go | 69 -- .../github.com/ccirello/supervisor/helpers.go | 101 -- .../ccirello/supervisor/stdsupervisor.go | 108 -- .../supervisor/stdsupervisor_example_test.go | 147 --- .../ccirello/supervisor/stdsupervisor_test.go | 109 -- .../ccirello/supervisor/supervisor.go | 245 ---- .../supervisor/supervisor_example_test.go | 42 - .../ccirello/supervisor/supervisor_test.go | 1072 ----------------- .../cloudflare/cfssl/cli/version/version.go | 7 +- .../cfssl/cmd/cfssljson/cfssljson.go | 8 + vendor/github.com/coreos/etcd/.travis.yml | 3 +- .../etcd/Documentation/learning/data_model.md | 2 +- .../Documentation/v2/implementation-faq.md | 70 -- vendor/github.com/coreos/etcd/NEWS | 5 + vendor/github.com/coreos/etcd/README.md | 1 + .../github.com/coreos/etcd/clientv3/README.md | 2 +- .../coreos/etcd/e2e/cluster_test.go | 1 + .../coreos/etcd/e2e/docker/Dockerfile | 2 +- vendor/github.com/coreos/etcd/e2e/v2_test.go | 19 + .../github.com/coreos/etcd/e2e/v2v3_test.go | 21 + vendor/github.com/coreos/etcd/embed/config.go | 1 + vendor/github.com/coreos/etcd/embed/etcd.go | 9 +- .../etcdctl/ctlv3/command/migrate_command.go | 14 +- .../coreos/etcd/etcdctl/ctlv3/ctl_cov.go | 1 + .../github.com/coreos/etcd/etcdmain/config.go | 18 +- .../github.com/coreos/etcd/etcdmain/help.go | 2 + .../coreos/etcd/etcdserver/api/cluster.go | 3 - .../etcd/etcdserver/api/etcdhttp/base.go | 2 +- .../etcd/etcdserver/api/etcdhttp/metrics.go | 6 +- .../etcd/etcdserver/api/etcdhttp/peer.go | 9 +- .../etcd/etcdserver/api/etcdhttp/peer_test.go | 1 - .../etcd/etcdserver/api/v2http/client.go | 34 +- .../etcd/etcdserver/api/v2http/client_test.go | 75 +- .../etcd/etcdserver/api/v2http/http_test.go | 8 +- .../etcd/etcdserver/api/v2v3/cluster.go | 31 + .../coreos/etcd/etcdserver/api/v2v3/doc.go | 16 + .../coreos/etcd/etcdserver/api/v2v3/server.go | 117 ++ .../coreos/etcd/etcdserver/api/v2v3/store.go | 621 ++++++++++ .../etcd/etcdserver/api/v2v3/watcher.go | 140 +++ .../coreos/etcd/etcdserver/api/v3rpc/grpc.go | 4 +- .../etcd/etcdserver/api/v3rpc/maintenance.go | 3 +- .../etcd/etcdserver/api/v3rpc/member.go | 14 +- .../coreos/etcd/etcdserver/apply_v2.go | 34 +- .../coreos/etcd/etcdserver/server.go | 79 +- .../coreos/etcd/etcdserver/server_test.go | 9 +- .../coreos/etcd/etcdserver/v2_server.go | 125 +- .../coreos/etcd/hack/benchmark/bench.sh | 4 +- .../coreos/etcd/integration/cluster.go | 5 +- .../coreos/etcd/integration/cluster_test.go | 10 +- .../coreos/etcd/integration/v3_auth_test.go | 40 + .../coreos/etcd/integration/v3_watch_test.go | 4 + vendor/github.com/coreos/etcd/mvcc/index.go | 46 +- .../coreos/etcd/mvcc/kvstore_bench_test.go | 20 +- .../coreos/etcd/mvcc/watchable_store.go | 6 +- .../coreos/etcd/mvcc/watchable_store_test.go | 46 + vendor/github.com/coreos/etcd/mvcc/watcher.go | 17 +- .../coreos/etcd/pkg/flags/strings.go | 5 +- .../coreos/etcd/pkg/flags/strings_test.go | 5 +- .../coreos/etcd/pkg/netutil/netutil_test.go | 15 + .../coreos/etcd/pkg/pbutil/pbutil_test.go | 4 +- vendor/github.com/coreos/etcd/pkg/srv/srv.go | 3 +- .../coreos/etcd/pkg/srv/srv_test.go | 9 +- .../coreos/etcd/pkg/testutil/assert.go | 6 +- .../github.com/coreos/etcd/pkg/wait/wait.go | 6 +- vendor/github.com/coreos/etcd/raft/README.md | 2 +- .../github.com/coreos/etcd/store/metrics.go | 6 +- .../coreos/etcd/store/store_test.go | 734 ++++------- .../coreos/etcd/store/store_ttl_test.go | 360 ++++++ .../coreos/etcd/store/store_v2_test.go | 62 + .../coreos/etcd/store/store_v2v3_test.go | 42 + vendor/github.com/coreos/etcd/test | 15 +- vendor/github.com/davecgh/go-spew/.travis.yml | 3 +- .../docker-credential-helpers/.gitignore | 2 - .../docker-credential-helpers/.travis.yml | 49 - .../docker-credential-helpers/CHANGELOG.md | 50 - .../docker/docker-credential-helpers/LICENSE | 20 - .../docker-credential-helpers/MAINTAINERS | 166 --- .../docker/docker-credential-helpers/Makefile | 82 -- .../docker-credential-helpers/README.md | 76 -- .../docker-credential-helpers/appveyor.yml | 24 - .../ci/before_deploy.sh | 15 - .../ci/before_script_linux.sh | 22 - .../client/client.go | 121 -- .../client/client_test.go | 213 ---- .../client/command.go | 56 - .../credentials/credentials.go | 186 --- .../credentials/credentials_test.go | 249 ---- .../credentials/error.go | 102 -- .../credentials/helper.go | 14 - .../credentials/version.go | 4 - .../docker-credential-helpers/deb/Dockerfile | 19 - .../docker-credential-helpers/deb/build-deb | 26 - .../deb/debian/compat | 1 - .../deb/debian/control | 25 - .../deb/debian/docker-credential-pass.install | 1 - .../docker-credential-secretservice.install | 1 - .../deb/debian/rules | 17 - .../osxkeychain/cmd/main_darwin.go | 10 - .../osxkeychain/osxkeychain_darwin.c | 228 ---- .../osxkeychain/osxkeychain_darwin.go | 196 --- .../osxkeychain/osxkeychain_darwin.h | 14 - .../osxkeychain/osxkeychain_darwin_test.go | 253 ---- .../osxkeychain/url_go18.go | 13 - .../osxkeychain/url_non_go18.go | 41 - .../pass/cmd/main_linux.go | 10 - .../pass/pass_linux.go | 221 ---- .../pass/pass_linux_test.go | 75 -- .../secretservice/cmd/main_linux.go | 10 - .../secretservice/secretservice_linux.c | 162 --- .../secretservice/secretservice_linux.go | 118 -- .../secretservice/secretservice_linux.h | 13 - .../secretservice/secretservice_linux_test.go | 90 -- .../wincred/cmd/main_windows.go | 10 - .../wincred/wincred_windows.go | 74 -- .../wincred/wincred_windows_test.go | 95 -- vendor/github.com/docker/libnetwork/agent.go | 8 +- .../github.com/docker/libnetwork/circle.yml | 2 + .../libnetwork/common/setmatrix_test.go | 39 + .../windows/overlay/joinleave_windows.go | 5 + .../windows/overlay/ov_endpoint_windows.go | 77 +- .../windows/overlay/ov_network_windows.go | 15 +- .../windows/overlay/overlay_windows.go | 2 +- .../drivers/windows/overlay/peerdb_windows.go | 6 +- .../libnetwork/drivers/windows/windows.go | 24 +- .../github.com/docker/libnetwork/ipvs/ipvs.go | 7 + .../docker/libnetwork/ipvs/ipvs_test.go | 35 + .../docker/libnetwork/ipvs/netlink.go | 7 + .../portallocator/portallocator_freebsd.go | 42 + .../fsouza/go-dockerclient/.travis.yml | 3 +- .../fsouza/go-dockerclient/appveyor.yml | 3 +- .../fsouza/go-dockerclient/container.go | 1 + .../fsouza/go-dockerclient/network.go | 5 +- vendor/github.com/gin-gonic/gin/.travis.yml | 1 + vendor/github.com/gin-gonic/gin/README.md | 124 +- vendor/github.com/gin-gonic/gin/auth.go | 2 +- .../gin-gonic/gin/binding/binding.go | 11 +- .../gin/binding/default_validator.go | 5 + .../github.com/gin-gonic/gin/binding/form.go | 6 +- .../gin-gonic/gin/binding/validate_test.go | 42 + vendor/github.com/gin-gonic/gin/context.go | 14 +- .../gin/examples/custom-validation/server.go | 45 + vendor/github.com/gin-gonic/gin/gin.go | 7 +- vendor/github.com/gin-gonic/gin/ginS/gins.go | 40 +- vendor/github.com/gin-gonic/gin/logger.go | 7 +- vendor/github.com/gin-gonic/gin/recovery.go | 3 +- .../go-openapi/runtime/authinfo_test.go | 6 +- .../go-openapi/runtime/client/auth_info.go | 12 +- .../runtime/client/auth_info_test.go | 12 +- .../go-openapi/runtime/client/request_test.go | 88 +- .../go-openapi/runtime/client/runtime.go | 6 +- .../go-openapi/runtime/client/runtime_test.go | 33 +- .../go-openapi/runtime/client_request_test.go | 6 +- .../runtime/client_response_test.go | 2 +- .../go-openapi/runtime/interfaces.go | 19 +- .../runtime/internal/testing/petstore/api.go | 12 + .../runtime/middleware/body_test.go | 6 +- .../go-openapi/runtime/middleware/context.go | 14 +- .../runtime/middleware/context_test.go | 36 +- .../runtime/middleware/header/header.go | 6 +- .../runtime/middleware/parameter.go | 16 +- .../runtime/middleware/parameter_test.go | 6 +- .../go-openapi/runtime/middleware/redoc.go | 6 +- .../go-openapi/runtime/middleware/request.go | 2 +- .../runtime/middleware/request_test.go | 27 +- .../go-openapi/runtime/middleware/router.go | 6 +- .../go-openapi/runtime/middleware/security.go | 6 +- .../go-openapi/runtime/middleware/spec.go | 2 +- .../runtime/middleware/untyped/api.go | 11 + .../runtime/middleware/untyped/api_test.go | 10 + .../middleware/untyped_request_test.go | 10 +- .../runtime/middleware/validation.go | 33 - .../runtime/middleware/validation_test.go | 26 +- .../go-openapi/runtime/security/authorizer.go | 27 + .../runtime/security/authorizer_test.go | 28 + .../runtime/security/bearer_auth_test.go | 6 +- vendor/github.com/go-openapi/strfmt/time.go | 9 +- vendor/github.com/go-sql-driver/mysql/AUTHORS | 1 + .../github.com/go-sql-driver/mysql/README.md | 4 +- .../go-sql-driver/mysql/connection.go | 23 +- vendor/github.com/go-sql-driver/mysql/dsn.go | 11 +- .../go-sql-driver/mysql/dsn_test.go | 36 +- .../github.com/go-sql-driver/mysql/errors.go | 6 + .../github.com/go-sql-driver/mysql/packets.go | 38 +- .../go-sql-driver/mysql/packets_test.go | 13 +- .../go-sql-driver/mysql/statement.go | 4 +- vendor/github.com/gorilla/mux/README.md | 2 +- vendor/github.com/gorilla/mux/mux.go | 33 + vendor/github.com/gorilla/mux/mux_test.go | 39 + vendor/github.com/gorilla/mux/old_test.go | 8 +- vendor/github.com/gorilla/mux/route.go | 16 + .../github.com/hashicorp/go-memdb/README.md | 2 +- .../github.com/hashicorp/go-memdb/filter.go | 33 + .../hashicorp/go-memdb/filter_test.go | 122 ++ vendor/github.com/hashicorp/go-memdb/memdb.go | 2 +- .../hashicorp/go-memdb/watch-gen/main.go | 15 +- vendor/github.com/hashicorp/go-memdb/watch.go | 49 +- .../hashicorp/go-memdb/watch_few.go | 75 +- .../hashicorp/go-memdb/watch_test.go | 67 +- .../hashicorp/hcl/hcl/parser/parser.go | 14 +- .../json-iterator/go/extra/fuzzy_decoder.go | 7 +- .../go/extra/fuzzy_decoder_test.go | 21 + .../json-iterator/go/feature_config.go | 8 + .../json-iterator/go/feature_iter.go | 8 +- .../go/feature_iter_skip_strict.go | 2 +- .../json-iterator/go/feature_iter_string.go | 6 +- .../json-iterator/go/feature_json_number.go | 2 +- .../json-iterator/go/feature_reflect.go | 13 + .../go/feature_reflect_extension.go | 4 +- .../go/feature_reflect_native.go | 52 + .../go/feature_reflect_object.go | 12 +- .../go/feature_reflect_struct_decoder.go | 2 +- .../json-iterator/go/feature_stream_string.go | 2 + .../go/jsoniter_customize_test.go | 53 + .../json-iterator/go/jsoniter_int_test.go | 40 +- .../json-iterator/go/jsoniter_invalid_test.go | 32 + .../go/jsoniter_struct_decoder_test.go | 2 +- .../magiconair/properties/.travis.yml | 1 + .../magiconair/properties/CHANGELOG.md | 5 + .../magiconair/properties/properties.go | 3 + .../magiconair/properties/properties_test.go | 13 + vendor/github.com/mailru/easyjson/.travis.yml | 9 +- vendor/github.com/mailru/easyjson/Makefile | 3 +- vendor/github.com/mailru/easyjson/README.md | 2 +- .../mailru/easyjson/benchmark/default_test.go | 2 +- .../easyjson/benchmark/jsoniter_test.go | 119 ++ .../mailru/easyjson/easyjson/main.go | 7 +- .../mailru/easyjson/gen/generator.go | 8 +- .../mailru/easyjson/parser/parser_windows.go | 7 +- vendor/github.com/mattn/go-sqlite3/README.md | 2 +- .../github.com/mattn/go-sqlite3/callback.go | 6 + vendor/github.com/mattn/go-sqlite3/sqlite3.go | 62 +- .../mattn/go-sqlite3/sqlite3_go18_test.go | 92 ++ .../mattn/go-sqlite3/sqlite3_libsqlite3.go | 1 + .../mattn/go-sqlite3/sqlite3_other.go | 1 + .../mattn/go-sqlite3/sqlite3_test.go | 177 +++ .../opencontainers/image-spec/MAINTAINERS | 1 + .../image-spec/implementations.md | 2 +- .../zipkin-go-opentracing/collector-http.go | 8 +- .../github.com/pelletier/go-toml/.travis.yml | 2 +- .../github.com/pelletier/go-toml/doc_test.go | 55 +- .../pelletier/go-toml/marshal_test.go | 19 - .../pelletier/go-toml/query/parser.go | 2 +- vendor/github.com/spf13/afero/match.go | 110 ++ vendor/github.com/spf13/afero/match_test.go | 183 +++ vendor/github.com/spf13/afero/memmap.go | 5 + vendor/github.com/spf13/afero/memmap_test.go | 41 + .../spf13/jwalterweatherman/notepad.go | 2 +- vendor/github.com/spf13/pflag/flag.go | 4 + vendor/github.com/spf13/pflag/flag_test.go | 4 +- .../github.com/ugorji/go/codec/codec_test.go | 15 + vendor/github.com/ugorji/go/codec/json.go | 35 +- vendor/github.com/ugorji/go/codec/prebuild.sh | 4 +- vendor/github.com/ugorji/go/codec/test.py | 6 +- vendor/golang.org/x/crypto/sha3/sha3.go | 5 +- vendor/golang.org/x/sys/unix/creds_test.go | 185 +-- vendor/golang.org/x/sys/unix/dev_darwin.go | 24 + .../golang.org/x/sys/unix/dev_darwin_test.go | 49 + vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 + .../golang.org/x/sys/unix/dev_netbsd_test.go | 50 + vendor/golang.org/x/sys/unix/linux/types.go | 55 + vendor/golang.org/x/sys/unix/mkerrors.sh | 4 + .../golang.org/x/sys/unix/mksysnum_netbsd.pl | 2 +- .../golang.org/x/sys/unix/mmap_unix_test.go | 12 + vendor/golang.org/x/sys/unix/syscall_bsd.go | 11 +- .../golang.org/x/sys/unix/syscall_darwin.go | 11 - .../x/sys/unix/syscall_dragonfly.go | 11 - .../golang.org/x/sys/unix/syscall_freebsd.go | 11 - vendor/golang.org/x/sys/unix/syscall_linux.go | 17 +- .../golang.org/x/sys/unix/syscall_netbsd.go | 5 - .../golang.org/x/sys/unix/syscall_openbsd.go | 5 - .../x/sys/unix/zerrors_linux_386.go | 20 + .../x/sys/unix/zerrors_linux_amd64.go | 20 + .../x/sys/unix/zerrors_linux_arm.go | 20 + .../x/sys/unix/zerrors_linux_arm64.go | 20 + .../x/sys/unix/zerrors_linux_mips.go | 20 + .../x/sys/unix/zerrors_linux_mips64.go | 20 + .../x/sys/unix/zerrors_linux_mips64le.go | 20 + .../x/sys/unix/zerrors_linux_mipsle.go | 20 + .../x/sys/unix/zerrors_linux_ppc64.go | 20 + .../x/sys/unix/zerrors_linux_ppc64le.go | 20 + .../x/sys/unix/zerrors_linux_s390x.go | 20 + .../x/sys/unix/zerrors_netbsd_arm.go | 3 + .../x/sys/unix/zsyscall_darwin_386.go | 184 +-- .../x/sys/unix/zsyscall_darwin_amd64.go | 184 +-- .../x/sys/unix/zsyscall_darwin_arm.go | 168 +-- .../x/sys/unix/zsyscall_darwin_arm64.go | 168 +-- .../x/sys/unix/zsyscall_dragonfly_amd64.go | 168 +-- .../x/sys/unix/zsyscall_freebsd_386.go | 168 +-- .../x/sys/unix/zsyscall_freebsd_amd64.go | 168 +-- .../x/sys/unix/zsyscall_freebsd_arm.go | 168 +-- .../x/sys/unix/zsyscall_netbsd_386.go | 168 +-- .../x/sys/unix/zsyscall_netbsd_amd64.go | 168 +-- .../x/sys/unix/zsyscall_netbsd_arm.go | 168 +-- .../x/sys/unix/zsyscall_openbsd_386.go | 168 +-- .../x/sys/unix/zsyscall_openbsd_amd64.go | 168 +-- .../x/sys/unix/zsyscall_openbsd_arm.go | 168 +-- .../x/sys/unix/zsysnum_netbsd_386.go | 1 + .../x/sys/unix/zsysnum_netbsd_amd64.go | 1 + .../x/sys/unix/zsysnum_netbsd_arm.go | 1 + .../golang.org/x/sys/unix/ztypes_linux_386.go | 101 ++ .../x/sys/unix/ztypes_linux_amd64.go | 101 ++ .../golang.org/x/sys/unix/ztypes_linux_arm.go | 101 ++ .../x/sys/unix/ztypes_linux_arm64.go | 101 ++ .../x/sys/unix/ztypes_linux_mips.go | 101 ++ .../x/sys/unix/ztypes_linux_mips64.go | 101 ++ .../x/sys/unix/ztypes_linux_mips64le.go | 101 ++ .../x/sys/unix/ztypes_linux_mipsle.go | 101 ++ .../x/sys/unix/ztypes_linux_ppc64.go | 101 ++ .../x/sys/unix/ztypes_linux_ppc64le.go | 101 ++ .../x/sys/unix/ztypes_linux_s390x.go | 101 ++ .../x/sys/windows/syscall_windows.go | 6 +- .../x/sys/windows/zsyscall_windows.go | 64 +- 397 files changed, 13691 insertions(+), 8828 deletions(-) create mode 100644 vendor/github.com/Sirupsen/logrus/.gitignore create mode 100644 vendor/github.com/Sirupsen/logrus/.travis.yml create mode 100644 vendor/github.com/Sirupsen/logrus/CHANGELOG.md rename vendor/github.com/{ccirello/supervisor => Sirupsen/logrus}/LICENSE (93%) create mode 100644 vendor/github.com/Sirupsen/logrus/README.md create mode 100644 vendor/github.com/Sirupsen/logrus/alt_exit.go create mode 100644 vendor/github.com/Sirupsen/logrus/alt_exit_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/appveyor.yml create mode 100644 vendor/github.com/Sirupsen/logrus/doc.go create mode 100644 vendor/github.com/Sirupsen/logrus/entry.go create mode 100644 vendor/github.com/Sirupsen/logrus/entry_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/example_basic_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/example_hook_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/exported.go create mode 100644 vendor/github.com/Sirupsen/logrus/formatter.go create mode 100644 vendor/github.com/Sirupsen/logrus/formatter_bench_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/hook_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/hooks.go create mode 100644 vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md create mode 100644 vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go create mode 100644 vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/hooks/test/test.go create mode 100644 vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/json_formatter.go create mode 100644 vendor/github.com/Sirupsen/logrus/json_formatter_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/logger.go create mode 100644 vendor/github.com/Sirupsen/logrus/logger_bench_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/logrus.go create mode 100644 vendor/github.com/Sirupsen/logrus/logrus_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/terminal_bsd.go create mode 100644 vendor/github.com/Sirupsen/logrus/terminal_linux.go create mode 100644 vendor/github.com/Sirupsen/logrus/text_formatter.go create mode 100644 vendor/github.com/Sirupsen/logrus/text_formatter_test.go create mode 100644 vendor/github.com/Sirupsen/logrus/writer.go create mode 100644 vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx.m4 create mode 100644 vendor/github.com/apache/thrift/build/docker/centos-7.3/Dockerfile delete mode 100644 vendor/github.com/apache/thrift/build/docker/centos/Dockerfile delete mode 100644 vendor/github.com/apache/thrift/build/docker/centos6/Dockerfile rename vendor/github.com/apache/thrift/build/docker/{debian => debian-jessie}/Dockerfile (100%) create mode 100644 vendor/github.com/apache/thrift/build/docker/debian-stretch/Dockerfile rename vendor/github.com/apache/thrift/build/docker/{ubuntu => ubuntu-trusty}/Dockerfile (100%) create mode 100644 vendor/github.com/apache/thrift/build/docker/ubuntu-xenial/Dockerfile rename vendor/github.com/apache/thrift/lib/hs/{Thrift.cabal => thrift.cabal} (100%) delete mode 100644 vendor/github.com/apache/thrift/test/go/src/common/mock_handler.go delete mode 100644 vendor/github.com/ccirello/supervisor/.gitignore delete mode 100644 vendor/github.com/ccirello/supervisor/.travis.yml delete mode 100644 vendor/github.com/ccirello/supervisor/README.md delete mode 100644 vendor/github.com/ccirello/supervisor/anon.go delete mode 100644 vendor/github.com/ccirello/supervisor/doc.go delete mode 100644 vendor/github.com/ccirello/supervisor/group.go delete mode 100644 vendor/github.com/ccirello/supervisor/helpers.go delete mode 100644 vendor/github.com/ccirello/supervisor/stdsupervisor.go delete mode 100644 vendor/github.com/ccirello/supervisor/stdsupervisor_example_test.go delete mode 100644 vendor/github.com/ccirello/supervisor/stdsupervisor_test.go delete mode 100644 vendor/github.com/ccirello/supervisor/supervisor.go delete mode 100644 vendor/github.com/ccirello/supervisor/supervisor_example_test.go delete mode 100644 vendor/github.com/ccirello/supervisor/supervisor_test.go delete mode 100644 vendor/github.com/coreos/etcd/Documentation/v2/implementation-faq.md create mode 100644 vendor/github.com/coreos/etcd/e2e/v2_test.go create mode 100644 vendor/github.com/coreos/etcd/e2e/v2v3_test.go create mode 100644 vendor/github.com/coreos/etcd/etcdserver/api/v2v3/cluster.go create mode 100644 vendor/github.com/coreos/etcd/etcdserver/api/v2v3/doc.go create mode 100644 vendor/github.com/coreos/etcd/etcdserver/api/v2v3/server.go create mode 100644 vendor/github.com/coreos/etcd/etcdserver/api/v2v3/store.go create mode 100644 vendor/github.com/coreos/etcd/etcdserver/api/v2v3/watcher.go mode change 100644 => 100755 vendor/github.com/coreos/etcd/hack/benchmark/bench.sh create mode 100644 vendor/github.com/coreos/etcd/store/store_ttl_test.go create mode 100644 vendor/github.com/coreos/etcd/store/store_v2_test.go create mode 100644 vendor/github.com/coreos/etcd/store/store_v2v3_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/.gitignore delete mode 100644 vendor/github.com/docker/docker-credential-helpers/.travis.yml delete mode 100644 vendor/github.com/docker/docker-credential-helpers/CHANGELOG.md delete mode 100644 vendor/github.com/docker/docker-credential-helpers/LICENSE delete mode 100644 vendor/github.com/docker/docker-credential-helpers/MAINTAINERS delete mode 100644 vendor/github.com/docker/docker-credential-helpers/Makefile delete mode 100644 vendor/github.com/docker/docker-credential-helpers/README.md delete mode 100644 vendor/github.com/docker/docker-credential-helpers/appveyor.yml delete mode 100644 vendor/github.com/docker/docker-credential-helpers/ci/before_deploy.sh delete mode 100644 vendor/github.com/docker/docker-credential-helpers/ci/before_script_linux.sh delete mode 100644 vendor/github.com/docker/docker-credential-helpers/client/client.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/client/client_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/client/command.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/credentials_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/error.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/helper.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/version.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/deb/Dockerfile delete mode 100755 vendor/github.com/docker/docker-credential-helpers/deb/build-deb delete mode 100644 vendor/github.com/docker/docker-credential-helpers/deb/debian/compat delete mode 100644 vendor/github.com/docker/docker-credential-helpers/deb/debian/control delete mode 100644 vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-pass.install delete mode 100644 vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-secretservice.install delete mode 100755 vendor/github.com/docker/docker-credential-helpers/deb/debian/rules delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/cmd/main_darwin.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_go18.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_non_go18.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/pass/cmd/main_linux.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/pass/pass_linux.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/pass/pass_linux_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/secretservice/cmd/main_linux.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c delete mode 100644 vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h delete mode 100644 vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux_test.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/wincred/cmd/main_windows.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows_test.go create mode 100644 vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go create mode 100644 vendor/github.com/gin-gonic/gin/examples/custom-validation/server.go create mode 100644 vendor/github.com/go-openapi/runtime/security/authorizer.go create mode 100644 vendor/github.com/go-openapi/runtime/security/authorizer_test.go create mode 100644 vendor/github.com/hashicorp/go-memdb/filter.go create mode 100644 vendor/github.com/hashicorp/go-memdb/filter_test.go create mode 100644 vendor/github.com/mailru/easyjson/benchmark/jsoniter_test.go create mode 100644 vendor/github.com/spf13/afero/match.go create mode 100644 vendor/github.com/spf13/afero/match_test.go create mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go create mode 100644 vendor/golang.org/x/sys/unix/dev_darwin_test.go create mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go create mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd_test.go diff --git a/api/agent/agent.go b/api/agent/agent.go index 46a5d1cc9..14671f79b 100644 --- a/api/agent/agent.go +++ b/api/agent/agent.go @@ -22,7 +22,6 @@ import ( "github.com/sirupsen/logrus" ) -// TODO remove ccirello/supervisor from vendor/ // TODO make sure some errors that user should see (like image doesn't exist) bubble up // TODO we should prob store async calls in db immediately since we're returning id (will 404 until post-execution) // TODO async calls need to add route.Headers as well diff --git a/glide.lock b/glide.lock index 43264cc5a..295204b79 100644 --- a/glide.lock +++ b/glide.lock @@ -1,16 +1,14 @@ -hash: 2f996070c68f1ff73bd36879e260fc801034e371cb86671aa5d9f97cdcdf7a05 -updated: 2017-08-24T00:10:34.173574746Z +hash: 60c3aa7f40235c70cfcc42335f9795bd1af326dc46f817aabbe7098fdd9f91a1 +updated: 2017-09-05T11:30:26.153448972-07:00 imports: - name: github.com/amir/raidman version: 1ccc43bfb9c93cb401a4025e49c64ba71e5e668b - subpackages: - - proto - name: github.com/apache/thrift - version: ec64f23d236d7874e3b28ae86c833f57c7aa3389 + version: 9235bec082127e84bf1b0353a0764c9060aca6d2 subpackages: - lib/go/thrift - name: github.com/asaskevich/govalidator - version: 15028e809df8c71964e8efa6c11e81d5c0262302 + version: 73945b6115bfbbcc57d89b7316e28109364124e1 - name: github.com/Azure/go-ansiterm version: fa152c58bc15761d0200cb75fe958b89a9d4888e subpackages: @@ -22,15 +20,13 @@ imports: - name: github.com/boltdb/bolt version: 2f1ce7a837dcb8da3ec595b1dac9d0632f0f99e8 - name: github.com/cactus/go-statsd-client - version: ad551ee7f9f3465fb1ce1695899c612f7808a06a + version: ce77ca9ecdee1c3ffd097e32f9bb832825ccb203 subpackages: - statsd -- name: github.com/ccirello/supervisor - version: 230eff6403e22b43f5fba7b28466dae4718934dd - name: github.com/cenkalti/backoff version: 61153c768f31ee5f130071d08fc82b85208528de - name: github.com/cloudflare/cfssl - version: fb16c3479c6ecbd2211751586b206f71387349e6 + version: 42549e19d448b683fa35bcce1aea3bf193ee8037 subpackages: - api - auth @@ -48,7 +44,7 @@ imports: - signer - signer/local - name: github.com/coreos/etcd - version: 897cadc88c5f4b01a8df6b760ec4b68ff1ece842 + version: 589a7a19ac469afa687ab1f7487dd5d4c2a6ee6a subpackages: - raft/raftpb - name: github.com/coreos/go-semver @@ -56,7 +52,7 @@ imports: subpackages: - semver - name: github.com/davecgh/go-spew - version: adab96458c51a58dc1783b3335dcce5461522e75 + version: a476722483882dd40b8111f0eb64e1d7f43f56e4 subpackages: - spew - name: github.com/dchest/siphash @@ -75,8 +71,6 @@ imports: version: f5a192bcc4c2794e44eb9dd7d91c2be95c5c6342 subpackages: - cli/config/configfile - - cli/config/credentials - - opts - name: github.com/docker/distribution version: 5f6282db7d65e6d72ad7c2cc66310724a57be716 subpackages: @@ -122,24 +116,13 @@ imports: - pkg/pools - pkg/promise - pkg/stdcopy - - pkg/stringid - pkg/system - - pkg/tarsum - pkg/term - pkg/term/windows - - registry - - registry/resumable -- name: github.com/docker/docker-credential-helpers - version: d3d99348972b70dc8133f4c2219007c05b4f8225 - subpackages: - - client - - credentials - name: github.com/docker/go-connections version: 3ede32e2033de7505e6500d6c868c2b9ed9f169d subpackages: - nat - - sockets - - tlsconfig - name: github.com/docker/go-events version: 9461782956ad83b30282bf90e31fa6a70c255ba9 - name: github.com/docker/go-units @@ -149,7 +132,7 @@ imports: subpackages: - store - name: github.com/docker/libnetwork - version: b53529dabef6f28ce23485a29270cd7b8a61db1b + version: ba46b928444931e6865d8618dc03622cac79aa6f subpackages: - datastore - discoverapi @@ -187,7 +170,7 @@ imports: - name: github.com/fsnotify/fsnotify version: 4da3e2cfbabc9f751898f250b49f2439785783a1 - name: github.com/fsouza/go-dockerclient - version: 75772940379e725b5aae213e570f9dcd751951cb + version: 98edf3edfae6a6500fecc69d2bcccf1302544004 - name: github.com/funcy/functions_go version: e046aa4ca1f1028a04fc51395297ff07515cb0b6 subpackages: @@ -205,7 +188,7 @@ imports: - name: github.com/gin-contrib/sse version: 22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae - name: github.com/gin-gonic/gin - version: a8fa424ae529397d4a0f2a1f9fda8031851a3269 + version: 848fa41ca016fa3a3d385af710c4219c1cb477a4 subpackages: - binding - json @@ -225,19 +208,19 @@ imports: subpackages: - fmts - name: github.com/go-openapi/runtime - version: d6605b7c17ac3b1033ca794886e6142a4141f5b0 + version: bf2ff8f7150788b1c7256abb0805ba0410cbbabb subpackages: - client - name: github.com/go-openapi/spec version: 3faa0055dbbf2110abc1f3b4e3adbb22721e96e7 - name: github.com/go-openapi/strfmt - version: 93a31ef21ac23f317792fff78f9539219dd74619 + version: 610b6cacdcde6852f4de68998bd20ce1dac85b22 - name: github.com/go-openapi/swag version: f3f9494671f93fcff853e3c6e9e948b3eb71e590 - name: github.com/go-openapi/validate version: 8a82927c942c94794a5cd8b8b50ce2f48a955c0c - name: github.com/go-sql-driver/mysql - version: 3955978caca48c1658a4bb7a9c6a0f084e326af3 + version: 26471af196a17ee75a22e6481b5a5897fb16b081 - name: github.com/gogo/protobuf version: 100ba4e885062801d56799d78530b73b178a78f3 subpackages: @@ -272,19 +255,19 @@ imports: - name: github.com/gorilla/context version: 08b5f424b9271eedf6f9f0ce86cb9396ed337a42 - name: github.com/gorilla/mux - version: ac112f7d75a0714af1bd86ab17749b31f7809640 + version: 24fca303ac6da784b9e8269f724ddeb0b2eea5e7 - name: github.com/grpc-ecosystem/go-grpc-prometheus version: 6b7015e65d366bf3f19b2b2a000a831940f0f7e0 - name: github.com/hashicorp/go-immutable-radix version: 8aac2701530899b64bdea735a1de8da899815220 - name: github.com/hashicorp/go-memdb - version: 2b2d6c35e14e7557ea1003e707d5e179fa315028 + version: ec43fcf8f202880feb35d2abb40a570c1f4172e9 - name: github.com/hashicorp/golang-lru version: 0a025b7e63adc15a622f29b0b2c4c3848243bbf6 subpackages: - simplelru - name: github.com/hashicorp/hcl - version: 392dba7d905ed5d04a5794ba89f558b27e2ba1ca + version: 8f6b1344a92ff8877cf24a5de9177bf7d0a2a187 subpackages: - hcl/ast - hcl/parser @@ -307,7 +290,7 @@ imports: subpackages: - reflectx - name: github.com/json-iterator/go - version: 887789156aeca0b292a5080b24e650d856c28933 + version: 8c7fc7584a2a4dad472a39a85889dabb3091dfb1 - name: github.com/kr/logfmt version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 - name: github.com/lib/pq @@ -315,9 +298,9 @@ imports: subpackages: - oid - name: github.com/magiconair/properties - version: be5ece7dd465ab0765a9682137865547526d1dfb + version: 8d7837e64d3c1ee4e54a880c5a920ab4316fc90a - name: github.com/mailru/easyjson - version: 2f5df55504ebc322e4d52d34df6a1f5b503bf26d + version: 2a92e673c9a6302dd05c3a691ae1f24aef46457d subpackages: - buffer - jlexer @@ -325,7 +308,7 @@ imports: - name: github.com/mattn/go-isatty version: fc9e8d8ef48496124e79ae0df75490096eccf6fe - name: github.com/mattn/go-sqlite3 - version: 6654e412c3c7eabb310d920cf73a2102dbf8c632 + version: 05548ff55570cdb9ac72ff4a25a3b5e77a6fb7e5 - name: github.com/matttproud/golang_protobuf_extensions version: c12348ce28de40eed0136aa2b644d0ee0650e56c subpackages: @@ -339,7 +322,7 @@ imports: - name: github.com/opencontainers/go-digest version: 279bed98673dd5bef374d3b6e4b09e2af76183bf - name: github.com/opencontainers/image-spec - version: 97ae57f204b5956aa313d453ead9094ff9056b32 + version: 7653c236dd968a4f18c94d588591d98dea106323 subpackages: - specs-go - specs-go/v1 @@ -356,7 +339,7 @@ imports: - ext - log - name: github.com/openzipkin/zipkin-go-opentracing - version: a3f24586d6771f7a52012fc17b05a3f781592173 + version: 37e942825de0f846d15acc3bc9d027c9134a9b25 subpackages: - flag - thrift/gen-go/scribe @@ -366,9 +349,9 @@ imports: - name: github.com/patrickmn/go-cache version: a3647f8e31d79543b2d0f0ae2fe5c379d72cedc0 - name: github.com/pelletier/go-toml - version: 69d355db5304c0f7f809a2edc054553e7142f016 + version: 1d6b12b7cb290426e27e6b4e38b89fcda3aeef03 - name: github.com/pierrec/lz4 - version: 5a3d2245f97fc249850e7802e3c01fad02a1c316 + version: 08c27939df1bd95e881e2c2367a749964ad1fceb - name: github.com/pierrec/xxHash version: a0006b13c722f7f12368c00a3d3c2ae8a999a0c6 subpackages: @@ -394,35 +377,37 @@ imports: subpackages: - xfs - name: github.com/PuerkitoBio/purell - version: 7cf257f0a33260797b0febf39f95fccd86aab2a3 + version: f619812e3caf603a8df60a7ec6f2654b703189ef - name: github.com/PuerkitoBio/urlesc version: de5bf2ad457846296e2031421a34e2568e304e35 - name: github.com/rcrowley/go-metrics version: 1f30fe9094a513ce4c700b9a54458bbb0c96996c - name: github.com/Shopify/sarama - version: 3fee590c5568849516741670af9331a193bbe2a3 + version: 15174039fd207656a0f97f52bc78ec7793deeada +- name: github.com/Sirupsen/logrus + version: 89742aefa4b206dcf400792f3bd35b542998eb3b - name: github.com/sirupsen/logrus version: 89742aefa4b206dcf400792f3bd35b542998eb3b subpackages: - hooks/syslog - name: github.com/spf13/afero - version: 9be650865eab0c12963d8753212f4f9c66cdcf12 + version: ee1bd8ee15a1306d1f9201acc41ef39cd9f99a1b subpackages: - mem - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/jwalterweatherman - version: 0efa5202c04663c757d84f90f5219c1250baf94f + version: 12bd96e66386c1960ab0f74ced1362f66f552f7b - name: github.com/spf13/pflag - version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 + version: 7aff26db30c1be810f9de5038ec5ef96ac41fd7c - name: github.com/spf13/viper version: 25b30aa063fc18e48662b86996252eabdcf2f0c7 - name: github.com/ugorji/go - version: 5efa3251c7f7d05e5d9704a69a984ec9f1386a40 + version: 8c0409fcbb70099c748d71f714529204975f6c3f subpackages: - codec - name: golang.org/x/crypto - version: eb71ad9bd329b5ac0fd0148dd99bd62e8be8e035 + version: 81e90905daefcd6fd217b62423c0908922eadb30 subpackages: - bcrypt - blowfish @@ -440,10 +425,9 @@ imports: - idna - internal/timeseries - lex/httplex - - proxy - trace - name: golang.org/x/sys - version: 9f7170bcd8e9f4d3691c06401119c46a769a1e03 + version: 7ddbeae9ae08c6a06a59597f0c9edbc5ff2444ce subpackages: - unix - windows diff --git a/glide.yaml b/glide.yaml index e26aa8706..dac6a97e3 100644 --- a/glide.yaml +++ b/glide.yaml @@ -15,7 +15,6 @@ import: - package: github.com/cactus/go-statsd-client subpackages: - statsd -- package: github.com/ccirello/supervisor - package: github.com/dchest/siphash - package: github.com/dghubble/go-twitter subpackages: diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go index 645e1b76f..6d0fc190a 100644 --- a/vendor/github.com/PuerkitoBio/purell/purell.go +++ b/vendor/github.com/PuerkitoBio/purell/purell.go @@ -299,7 +299,7 @@ func sortQuery(u *url.URL) { if len(q) > 0 { arKeys := make([]string, len(q)) i := 0 - for k, _ := range q { + for k := range q { arKeys[i] = k i++ } diff --git a/vendor/github.com/PuerkitoBio/purell/purell_test.go b/vendor/github.com/PuerkitoBio/purell/purell_test.go index a3732e5a3..bbd3c89fa 100644 --- a/vendor/github.com/PuerkitoBio/purell/purell_test.go +++ b/vendor/github.com/PuerkitoBio/purell/purell_test.go @@ -16,672 +16,672 @@ type testCase struct { var ( cases = [...]*testCase{ - &testCase{ + { "LowerScheme", "HTTP://www.SRC.ca", FlagLowercaseScheme, "http://www.SRC.ca", false, }, - &testCase{ + { "LowerScheme2", "http://www.SRC.ca", FlagLowercaseScheme, "http://www.SRC.ca", false, }, - &testCase{ + { "LowerHost", "HTTP://www.SRC.ca/", FlagLowercaseHost, "http://www.src.ca/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "UpperEscapes", `http://www.whatever.com/Some%aa%20Special%8Ecases/`, FlagUppercaseEscapes, "http://www.whatever.com/Some%AA%20Special%8Ecases/", false, }, - &testCase{ + { "UnnecessaryEscapes", `http://www.toto.com/%41%42%2E%44/%32%33%52%2D/%5f%7E`, FlagDecodeUnnecessaryEscapes, "http://www.toto.com/AB.D/23R-/_~", false, }, - &testCase{ + { "RemoveDefaultPort", "HTTP://www.SRC.ca:80/", FlagRemoveDefaultPort, "http://www.SRC.ca/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveDefaultPort2", "HTTP://www.SRC.ca:80", FlagRemoveDefaultPort, "http://www.SRC.ca", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveDefaultPort3", "HTTP://www.SRC.ca:8080", FlagRemoveDefaultPort, "http://www.SRC.ca:8080", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "Safe", "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", FlagsSafe, "http://www.src.ca/to%1Ato%8B%EE/OKnowABC~", false, }, - &testCase{ + { "BothLower", "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", FlagLowercaseHost | FlagLowercaseScheme, "http://www.src.ca:80/to%1Ato%8B%EE/OKnowABC~", false, }, - &testCase{ + { "RemoveTrailingSlash", "HTTP://www.SRC.ca:80/", FlagRemoveTrailingSlash, "http://www.SRC.ca:80", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveTrailingSlash2", "HTTP://www.SRC.ca:80/toto/titi/", FlagRemoveTrailingSlash, "http://www.SRC.ca:80/toto/titi", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveTrailingSlash3", "HTTP://www.SRC.ca:80/toto/titi/fin/?a=1", FlagRemoveTrailingSlash, "http://www.SRC.ca:80/toto/titi/fin?a=1", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "AddTrailingSlash", "HTTP://www.SRC.ca:80", FlagAddTrailingSlash, "http://www.SRC.ca:80/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "AddTrailingSlash2", "HTTP://www.SRC.ca:80/toto/titi.html", FlagAddTrailingSlash, "http://www.SRC.ca:80/toto/titi.html/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "AddTrailingSlash3", "HTTP://www.SRC.ca:80/toto/titi/fin?a=1", FlagAddTrailingSlash, "http://www.SRC.ca:80/toto/titi/fin/?a=1", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveDotSegments", "HTTP://root/a/b/./../../c/", FlagRemoveDotSegments, "http://root/c/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveDotSegments2", "HTTP://root/../a/b/./../c/../d", FlagRemoveDotSegments, "http://root/a/d", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "UsuallySafe", "HTTP://www.SRC.ca:80/to%1ato%8b%ee/./c/d/../OKnow%41%42%43%7e/?a=b#test", FlagsUsuallySafeGreedy, "http://www.src.ca/to%1Ato%8B%EE/c/OKnowABC~?a=b#test", false, }, - &testCase{ + { "RemoveDirectoryIndex", "HTTP://root/a/b/c/default.aspx", FlagRemoveDirectoryIndex, "http://root/a/b/c/", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveDirectoryIndex2", "HTTP://root/a/b/c/default#a=b", FlagRemoveDirectoryIndex, "http://root/a/b/c/default#a=b", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "RemoveFragment", "HTTP://root/a/b/c/default#toto=tata", FlagRemoveFragment, "http://root/a/b/c/default", // Since Go1.1, scheme is automatically lowercased false, }, - &testCase{ + { "ForceHTTP", "https://root/a/b/c/default#toto=tata", FlagForceHTTP, "http://root/a/b/c/default#toto=tata", false, }, - &testCase{ + { "RemoveDuplicateSlashes", "https://root/a//b///c////default#toto=tata", FlagRemoveDuplicateSlashes, "https://root/a/b/c/default#toto=tata", false, }, - &testCase{ + { "RemoveDuplicateSlashes2", "https://root//a//b///c////default#toto=tata", FlagRemoveDuplicateSlashes, "https://root/a/b/c/default#toto=tata", false, }, - &testCase{ + { "RemoveWWW", "https://www.root/a/b/c/", FlagRemoveWWW, "https://root/a/b/c/", false, }, - &testCase{ + { "RemoveWWW2", "https://WwW.Root/a/b/c/", FlagRemoveWWW, "https://Root/a/b/c/", false, }, - &testCase{ + { "AddWWW", "https://Root/a/b/c/", FlagAddWWW, "https://www.Root/a/b/c/", false, }, - &testCase{ + { "SortQuery", "http://root/toto/?b=4&a=1&c=3&b=2&a=5", FlagSortQuery, "http://root/toto/?a=1&a=5&b=2&b=4&c=3", false, }, - &testCase{ + { "RemoveEmptyQuerySeparator", "http://root/toto/?", FlagRemoveEmptyQuerySeparator, "http://root/toto/", false, }, - &testCase{ + { "Unsafe", "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", FlagsUnsafeGreedy, "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", false, }, - &testCase{ + { "Safe2", "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", FlagsSafe, "https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", false, }, - &testCase{ + { "UsuallySafe2", "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", FlagsUsuallySafeGreedy, "https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid", false, }, - &testCase{ + { "AddTrailingSlashBug", "http://src.ca/", FlagsAllNonGreedy, "http://www.src.ca/", false, }, - &testCase{ + { "SourceModified", "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", FlagsUnsafeGreedy, "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", true, }, - &testCase{ + { "IPv6-1", "http://[2001:db8:1f70::999:de8:7648:6e8]/test", FlagsSafe | FlagRemoveDotSegments, "http://[2001:db8:1f70::999:de8:7648:6e8]/test", false, }, - &testCase{ + { "IPv6-2", "http://[::ffff:192.168.1.1]/test", FlagsSafe | FlagRemoveDotSegments, "http://[::ffff:192.168.1.1]/test", false, }, - &testCase{ + { "IPv6-3", "http://[::ffff:192.168.1.1]:80/test", FlagsSafe | FlagRemoveDotSegments, "http://[::ffff:192.168.1.1]/test", false, }, - &testCase{ + { "IPv6-4", "htTps://[::fFff:192.168.1.1]:443/test", FlagsSafe | FlagRemoveDotSegments, "https://[::ffff:192.168.1.1]/test", false, }, - &testCase{ + { "FTP", "ftp://user:pass@ftp.foo.net/foo/bar", FlagsSafe | FlagRemoveDotSegments, "ftp://user:pass@ftp.foo.net/foo/bar", false, }, - &testCase{ + { "Standard-1", "http://www.foo.com:80/foo", FlagsSafe | FlagRemoveDotSegments, "http://www.foo.com/foo", false, }, - &testCase{ + { "Standard-2", "http://www.foo.com:8000/foo", FlagsSafe | FlagRemoveDotSegments, "http://www.foo.com:8000/foo", false, }, - &testCase{ + { "Standard-3", "http://www.foo.com/%7ebar", FlagsSafe | FlagRemoveDotSegments, "http://www.foo.com/~bar", false, }, - &testCase{ + { "Standard-4", "http://www.foo.com/%7Ebar", FlagsSafe | FlagRemoveDotSegments, "http://www.foo.com/~bar", false, }, - &testCase{ + { "Standard-5", "http://USER:pass@www.Example.COM/foo/bar", FlagsSafe | FlagRemoveDotSegments, "http://USER:pass@www.example.com/foo/bar", false, }, - &testCase{ + { "Standard-6", "http://test.example/?a=%26&b=1", FlagsSafe | FlagRemoveDotSegments, "http://test.example/?a=%26&b=1", false, }, - &testCase{ + { "Standard-7", "http://test.example/%25/?p=%20val%20%25", FlagsSafe | FlagRemoveDotSegments, "http://test.example/%25/?p=%20val%20%25", false, }, - &testCase{ + { "Standard-8", "http://test.example/path/with a%20space+/", FlagsSafe | FlagRemoveDotSegments, "http://test.example/path/with%20a%20space+/", false, }, - &testCase{ + { "Standard-9", "http://test.example/?", FlagsSafe | FlagRemoveDotSegments, "http://test.example/", false, }, - &testCase{ + { "Standard-10", "http://a.COM/path/?b&a", FlagsSafe | FlagRemoveDotSegments, "http://a.com/path/?b&a", false, }, - &testCase{ + { "StandardCasesAddTrailingSlash", "http://test.example?", FlagsSafe | FlagAddTrailingSlash, "http://test.example/", false, }, - &testCase{ + { "OctalIP-1", "http://0123.011.0.4/", FlagsSafe | FlagDecodeOctalHost, "http://0123.011.0.4/", false, }, - &testCase{ + { "OctalIP-2", "http://0102.0146.07.0223/", FlagsSafe | FlagDecodeOctalHost, "http://66.102.7.147/", false, }, - &testCase{ + { "OctalIP-3", "http://0102.0146.07.0223.:23/", FlagsSafe | FlagDecodeOctalHost, "http://66.102.7.147.:23/", false, }, - &testCase{ + { "OctalIP-4", "http://USER:pass@0102.0146.07.0223../", FlagsSafe | FlagDecodeOctalHost, "http://USER:pass@66.102.7.147../", false, }, - &testCase{ + { "DWORDIP-1", "http://123.1113982867/", FlagsSafe | FlagDecodeDWORDHost, "http://123.1113982867/", false, }, - &testCase{ + { "DWORDIP-2", "http://1113982867/", FlagsSafe | FlagDecodeDWORDHost, "http://66.102.7.147/", false, }, - &testCase{ + { "DWORDIP-3", "http://1113982867.:23/", FlagsSafe | FlagDecodeDWORDHost, "http://66.102.7.147.:23/", false, }, - &testCase{ + { "DWORDIP-4", "http://USER:pass@1113982867../", FlagsSafe | FlagDecodeDWORDHost, "http://USER:pass@66.102.7.147../", false, }, - &testCase{ + { "HexIP-1", "http://0x123.1113982867/", FlagsSafe | FlagDecodeHexHost, "http://0x123.1113982867/", false, }, - &testCase{ + { "HexIP-2", "http://0x42660793/", FlagsSafe | FlagDecodeHexHost, "http://66.102.7.147/", false, }, - &testCase{ + { "HexIP-3", "http://0x42660793.:23/", FlagsSafe | FlagDecodeHexHost, "http://66.102.7.147.:23/", false, }, - &testCase{ + { "HexIP-4", "http://USER:pass@0x42660793../", FlagsSafe | FlagDecodeHexHost, "http://USER:pass@66.102.7.147../", false, }, - &testCase{ + { "UnnecessaryHostDots-1", "http://.www.foo.com../foo/bar.html", FlagsSafe | FlagRemoveUnnecessaryHostDots, "http://www.foo.com/foo/bar.html", false, }, - &testCase{ + { "UnnecessaryHostDots-2", "http://www.foo.com./foo/bar.html", FlagsSafe | FlagRemoveUnnecessaryHostDots, "http://www.foo.com/foo/bar.html", false, }, - &testCase{ + { "UnnecessaryHostDots-3", "http://www.foo.com.:81/foo", FlagsSafe | FlagRemoveUnnecessaryHostDots, "http://www.foo.com:81/foo", false, }, - &testCase{ + { "UnnecessaryHostDots-4", "http://www.example.com./", FlagsSafe | FlagRemoveUnnecessaryHostDots, "http://www.example.com/", false, }, - &testCase{ + { "EmptyPort-1", "http://www.thedraymin.co.uk:/main/?p=308", FlagsSafe | FlagRemoveEmptyPortSeparator, "http://www.thedraymin.co.uk/main/?p=308", false, }, - &testCase{ + { "EmptyPort-2", "http://www.src.ca:", FlagsSafe | FlagRemoveEmptyPortSeparator, "http://www.src.ca", false, }, - &testCase{ + { "Slashes-1", "http://test.example/foo/bar/.", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/bar/", false, }, - &testCase{ + { "Slashes-2", "http://test.example/foo/bar/./", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/bar/", false, }, - &testCase{ + { "Slashes-3", "http://test.example/foo/bar/..", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/", false, }, - &testCase{ + { "Slashes-4", "http://test.example/foo/bar/../", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/", false, }, - &testCase{ + { "Slashes-5", "http://test.example/foo/bar/../baz", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/baz", false, }, - &testCase{ + { "Slashes-6", "http://test.example/foo/bar/../..", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/", false, }, - &testCase{ + { "Slashes-7", "http://test.example/foo/bar/../../", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/", false, }, - &testCase{ + { "Slashes-8", "http://test.example/foo/bar/../../baz", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/baz", false, }, - &testCase{ + { "Slashes-9", "http://test.example/foo/bar/../../../baz", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/baz", false, }, - &testCase{ + { "Slashes-10", "http://test.example/foo/bar/../../../../baz", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/baz", false, }, - &testCase{ + { "Slashes-11", "http://test.example/./foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo", false, }, - &testCase{ + { "Slashes-12", "http://test.example/../foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo", false, }, - &testCase{ + { "Slashes-13", "http://test.example/foo.", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo.", false, }, - &testCase{ + { "Slashes-14", "http://test.example/.foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/.foo", false, }, - &testCase{ + { "Slashes-15", "http://test.example/foo..", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo..", false, }, - &testCase{ + { "Slashes-16", "http://test.example/..foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/..foo", false, }, - &testCase{ + { "Slashes-17", "http://test.example/./../foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo", false, }, - &testCase{ + { "Slashes-18", "http://test.example/./foo/.", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/", false, }, - &testCase{ + { "Slashes-19", "http://test.example/foo/./bar", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/bar", false, }, - &testCase{ + { "Slashes-20", "http://test.example/foo/../bar", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/bar", false, }, - &testCase{ + { "Slashes-21", "http://test.example/foo//", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/", false, }, - &testCase{ + { "Slashes-22", "http://test.example/foo///bar//", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "http://test.example/foo/bar/", false, }, - &testCase{ + { "Relative", "foo/bar", FlagsAllGreedy, "foo/bar", false, }, - &testCase{ + { "Relative-1", "./../foo", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "foo", false, }, - &testCase{ + { "Relative-2", "./foo/bar/../baz/../bang/..", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "foo/", false, }, - &testCase{ + { "Relative-3", "foo///bar//", FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, "foo/bar/", false, }, - &testCase{ + { "Relative-4", "www.youtube.com", FlagsUsuallySafeGreedy, diff --git a/vendor/github.com/Shopify/sarama/client.go b/vendor/github.com/Shopify/sarama/client.go index be103d573..c6510d9d9 100644 --- a/vendor/github.com/Shopify/sarama/client.go +++ b/vendor/github.com/Shopify/sarama/client.go @@ -141,18 +141,20 @@ func NewClient(addrs []string, conf *Config) (Client, error) { client.seedBrokers = append(client.seedBrokers, NewBroker(addrs[index])) } - // do an initial fetch of all cluster metadata by specifying an empty list of topics - err := client.RefreshMetadata() - switch err { - case nil: - break - case ErrLeaderNotAvailable, ErrReplicaNotAvailable, ErrTopicAuthorizationFailed, ErrClusterAuthorizationFailed: - // indicates that maybe part of the cluster is down, but is not fatal to creating the client - Logger.Println(err) - default: - close(client.closed) // we haven't started the background updater yet, so we have to do this manually - _ = client.Close() - return nil, err + if conf.Metadata.Full { + // do an initial fetch of all cluster metadata by specifying an empty list of topics + err := client.RefreshMetadata() + switch err { + case nil: + break + case ErrLeaderNotAvailable, ErrReplicaNotAvailable, ErrTopicAuthorizationFailed, ErrClusterAuthorizationFailed: + // indicates that maybe part of the cluster is down, but is not fatal to creating the client + Logger.Println(err) + default: + close(client.closed) // we haven't started the background updater yet, so we have to do this manually + _ = client.Close() + return nil, err + } } go withRecover(client.backgroundMetadataUpdater) @@ -605,7 +607,17 @@ func (client *client) backgroundMetadataUpdater() { for { select { case <-ticker.C: - if err := client.RefreshMetadata(); err != nil { + topics := []string{} + if !client.conf.Metadata.Full { + if specificTopics, err := client.Topics(); err != nil { + Logger.Println("Client background metadata topic load:", err) + break + } else { + topics = specificTopics + } + } + + if err := client.RefreshMetadata(topics...); err != nil { Logger.Println("Client background metadata update:", err) } case <-client.closer: diff --git a/vendor/github.com/Shopify/sarama/config.go b/vendor/github.com/Shopify/sarama/config.go index 606a4fabe..e0774c60e 100644 --- a/vendor/github.com/Shopify/sarama/config.go +++ b/vendor/github.com/Shopify/sarama/config.go @@ -72,6 +72,12 @@ type Config struct { // Defaults to 10 minutes. Set to 0 to disable. Similar to // `topic.metadata.refresh.interval.ms` in the JVM version. RefreshFrequency time.Duration + + // Whether to maintain a full set of metadata for all topics, or just + // the minimal set that has been necessary so far. The full set is simpler + // and usually more convenient, but can take up a substantial amount of + // memory if you have many topics and partitions. Defaults to true. + Full bool } // Producer is the namespace for configuration related to producing messages, @@ -263,6 +269,7 @@ func NewConfig() *Config { c.Metadata.Retry.Max = 3 c.Metadata.Retry.Backoff = 250 * time.Millisecond c.Metadata.RefreshFrequency = 10 * time.Minute + c.Metadata.Full = true c.Producer.MaxMessageBytes = 1000000 c.Producer.RequiredAcks = WaitForLocal diff --git a/vendor/github.com/Shopify/sarama/crc32_field.go b/vendor/github.com/Shopify/sarama/crc32_field.go index f4fde18ad..e7da08c6f 100644 --- a/vendor/github.com/Shopify/sarama/crc32_field.go +++ b/vendor/github.com/Shopify/sarama/crc32_field.go @@ -2,6 +2,7 @@ package sarama import ( "encoding/binary" + "fmt" "hash/crc32" ) @@ -27,8 +28,9 @@ func (c *crc32Field) run(curOffset int, buf []byte) error { func (c *crc32Field) check(curOffset int, buf []byte) error { crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset]) - if crc != binary.BigEndian.Uint32(buf[c.startOffset:]) { - return PacketDecodingError{"CRC didn't match"} + expected := binary.BigEndian.Uint32(buf[c.startOffset:]) + if crc != expected { + return PacketDecodingError{fmt.Sprintf("CRC didn't match expected %#x got %#x", expected, crc)} } return nil diff --git a/vendor/github.com/Shopify/sarama/message.go b/vendor/github.com/Shopify/sarama/message.go index 86b4ac32d..06f175f67 100644 --- a/vendor/github.com/Shopify/sarama/message.go +++ b/vendor/github.com/Shopify/sarama/message.go @@ -122,13 +122,17 @@ func (m *Message) decode(pd packetDecoder) (err error) { return err } + if m.Version > 1 { + return PacketDecodingError{fmt.Sprintf("unknown magic byte (%v)", m.Version)} + } + attribute, err := pd.getInt8() if err != nil { return err } m.Codec = CompressionCodec(attribute & compressionCodecMask) - if m.Version >= 1 { + if m.Version == 1 { millis, err := pd.getInt64() if err != nil { return err diff --git a/vendor/github.com/Shopify/sarama/message_test.go b/vendor/github.com/Shopify/sarama/message_test.go index d4a37c22d..2afd88c74 100644 --- a/vendor/github.com/Shopify/sarama/message_test.go +++ b/vendor/github.com/Shopify/sarama/message_test.go @@ -14,6 +14,21 @@ var ( 0xFF, 0xFF, 0xFF, 0xFF, // key 0xFF, 0xFF, 0xFF, 0xFF} // value + emptyV1Message = []byte{ + 204, 47, 121, 217, // CRC + 0x01, // magic version byte + 0x00, // attribute flags + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // timestamp + 0xFF, 0xFF, 0xFF, 0xFF, // key + 0xFF, 0xFF, 0xFF, 0xFF} // value + + emptyV2Message = []byte{ + 167, 236, 104, 3, // CRC + 0x02, // magic version byte + 0x00, // attribute flags + 0xFF, 0xFF, 0xFF, 0xFF, // key + 0xFF, 0xFF, 0xFF, 0xFF} // value + emptyGzipMessage = []byte{ 97, 79, 149, 90, //CRC 0x00, // magic version byte @@ -179,3 +194,19 @@ func TestMessageDecodingBulkLZ4(t *testing.T) { t.Errorf("Decoding produced a set with %d messages, but 2 were expected.", len(message.Set.Messages)) } } + +func TestMessageDecodingVersion1(t *testing.T) { + message := Message{Version: 1} + testDecodable(t, "decoding empty v1 message", &message, emptyV1Message) +} + +func TestMessageDecodingUnknownVersions(t *testing.T) { + message := Message{Version: 2} + err := decode(emptyV2Message, &message) + if err == nil { + t.Error("Decoding did not produce an error for an unknown magic byte") + } + if err.Error() != "kafka: error decoding packet: unknown magic byte (2)" { + t.Error("Decoding an unknown magic byte produced an unknown error ", err) + } +} diff --git a/vendor/github.com/Shopify/sarama/mockresponses.go b/vendor/github.com/Shopify/sarama/mockresponses.go index a20314209..d94bd24c6 100644 --- a/vendor/github.com/Shopify/sarama/mockresponses.go +++ b/vendor/github.com/Shopify/sarama/mockresponses.go @@ -180,6 +180,7 @@ type MockFetchResponse struct { highWaterMarks map[string]map[int32]int64 t TestReporter batchSize int + version int16 } func NewMockFetchResponse(t TestReporter, batchSize int) *MockFetchResponse { @@ -191,6 +192,11 @@ func NewMockFetchResponse(t TestReporter, batchSize int) *MockFetchResponse { } } +func (mfr *MockFetchResponse) SetVersion(version int16) *MockFetchResponse { + mfr.version = version + return mfr +} + func (mfr *MockFetchResponse) SetMessage(topic string, partition int32, offset int64, msg Encoder) *MockFetchResponse { partitions := mfr.messages[topic] if partitions == nil { @@ -218,7 +224,9 @@ func (mfr *MockFetchResponse) SetHighWaterMark(topic string, partition int32, of func (mfr *MockFetchResponse) For(reqBody versionedDecoder) encoder { fetchRequest := reqBody.(*FetchRequest) - res := &FetchResponse{} + res := &FetchResponse{ + Version: mfr.version, + } for topic, partitions := range fetchRequest.blocks { for partition, block := range partitions { initialOffset := block.fetchOffset diff --git a/vendor/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/Sirupsen/logrus/.gitignore new file mode 100644 index 000000000..66be63a00 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/.gitignore @@ -0,0 +1 @@ +logrus diff --git a/vendor/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/Sirupsen/logrus/.travis.yml new file mode 100644 index 000000000..a23296a53 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/.travis.yml @@ -0,0 +1,15 @@ +language: go +go: + - 1.6.x + - 1.7.x + - 1.8.x + - tip +env: + - GOMAXPROCS=4 GORACE=halt_on_error=1 +install: + - go get github.com/stretchr/testify/assert + - go get gopkg.in/gemnasium/logrus-airbrake-hook.v2 + - go get golang.org/x/sys/unix + - go get golang.org/x/sys/windows +script: + - go test -race -v ./... diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md new file mode 100644 index 000000000..8236d8b6e --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md @@ -0,0 +1,113 @@ +# 1.0.3 + +* Replace example files with testable examples + +# 1.0.2 + +* bug: quote non-string values in text formatter (#583) +* Make (*Logger) SetLevel a public method + +# 1.0.1 + +* bug: fix escaping in text formatter (#575) + +# 1.0.0 + +* Officially changed name to lower-case +* bug: colors on Windows 10 (#541) +* bug: fix race in accessing level (#512) + +# 0.11.5 + +* feature: add writer and writerlevel to entry (#372) + +# 0.11.4 + +* bug: fix undefined variable on solaris (#493) + +# 0.11.3 + +* formatter: configure quoting of empty values (#484) +* formatter: configure quoting character (default is `"`) (#484) +* bug: fix not importing io correctly in non-linux environments (#481) + +# 0.11.2 + +* bug: fix windows terminal detection (#476) + +# 0.11.1 + +* bug: fix tty detection with custom out (#471) + +# 0.11.0 + +* performance: Use bufferpool to allocate (#370) +* terminal: terminal detection for app-engine (#343) +* feature: exit handler (#375) + +# 0.10.0 + +* feature: Add a test hook (#180) +* feature: `ParseLevel` is now case-insensitive (#326) +* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) +* performance: avoid re-allocations on `WithFields` (#335) + +# 0.9.0 + +* logrus/text_formatter: don't emit empty msg +* logrus/hooks/airbrake: move out of main repository +* logrus/hooks/sentry: move out of main repository +* logrus/hooks/papertrail: move out of main repository +* logrus/hooks/bugsnag: move out of main repository +* logrus/core: run tests with `-race` +* logrus/core: detect TTY based on `stderr` +* logrus/core: support `WithError` on logger +* logrus/core: Solaris support + +# 0.8.7 + +* logrus/core: fix possible race (#216) +* logrus/doc: small typo fixes and doc improvements + + +# 0.8.6 + +* hooks/raven: allow passing an initialized client + +# 0.8.5 + +* logrus/core: revert #208 + +# 0.8.4 + +* formatter/text: fix data race (#218) + +# 0.8.3 + +* logrus/core: fix entry log level (#208) +* logrus/core: improve performance of text formatter by 40% +* logrus/core: expose `LevelHooks` type +* logrus/core: add support for DragonflyBSD and NetBSD +* formatter/text: print structs more verbosely + +# 0.8.2 + +* logrus: fix more Fatal family functions + +# 0.8.1 + +* logrus: fix not exiting on `Fatalf` and `Fatalln` + +# 0.8.0 + +* logrus: defaults to stderr instead of stdout +* hooks/sentry: add special field for `*http.Request` +* formatter/text: ignore Windows for colors + +# 0.7.3 + +* formatter/\*: allow configuration of timestamp layout + +# 0.7.2 + +* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/ccirello/supervisor/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE similarity index 93% rename from vendor/github.com/ccirello/supervisor/LICENSE rename to vendor/github.com/Sirupsen/logrus/LICENSE index 99a3d14a0..f090cb42f 100644 --- a/vendor/github.com/ccirello/supervisor/LICENSE +++ b/vendor/github.com/Sirupsen/logrus/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2016 Ulderico Cirello +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -16,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE \ No newline at end of file +THE SOFTWARE. diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md new file mode 100644 index 000000000..5f656c3e1 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/README.md @@ -0,0 +1,507 @@ +# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. + +**Seeing weird case-sensitive problems?** It's in the past been possible to +import Logrus as both upper- and lower-case. Due to the Go package environment, +this caused issues in the community and we needed a standard. Some environments +experienced problems with the upper-case variant, so the lower-case was decided. +Everything using `logrus` will need to use the lower-case: +`github.com/sirupsen/logrus`. Any package that isn't, should be changed. + +To fix Glide, see [these +comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). +For an in-depth explanation of the casing issue, see [this +comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). + +**Are you interested in assisting in maintaining Logrus?** Currently I have a +lot of obligations, and I am unable to provide Logrus with the maintainership it +needs. If you'd like to help, please reach out to me at `simon at author's +username dot com`. + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash +or Splunk: + +```json +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +exit status 1 +``` + +#### Case-sensitivity + +The organization's name was changed to lower-case--and this will not be changed +back. If you are getting import conflicts due to case sensitivity, please use +the lower-case import: `github.com/sirupsen/logrus`. + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/sirupsen/logrus" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Output to stdout instead of the default stderr + // Can be any io.Writer, see below for File example + log.SetOutput(os.Stdout) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "os" + "github.com/sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stdout + + // You could set this to any `io.Writer` such as a file + // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) + // if err == nil { + // log.Out = file + // } else { + // log.Info("Failed to log to file, using default stderr") + // } + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging through logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Default Fields + +Often it's helpful to have fields _always_ attached to log statements in an +application or parts of one. For example, you may want to always log the +`request_id` and `user_ip` in the context of a request. Instead of writing +`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on +every line, you can create a `logrus.Entry` to pass around instead: + +```go +requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) +requestLogger.Info("something happened on that request") # will log request_id and user_ip +requestLogger.Warn("something not great happened") +``` + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/sirupsen/logrus" + "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake" + logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook(123, "xyz", "production")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` +Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). + +| Hook | Description | +| ----- | ----------- | +| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | +| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. | +| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) | +| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) | +| [AzureTableHook](https://github.com/kpfaulkner/azuretablehook/) | Hook for logging to Azure Table Storage| +| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | +| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | +| [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) | +| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch| +| [Firehose](https://github.com/beaubrewer/logrus_firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/) +| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | +| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) | +| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) | +| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | +| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | +| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | +| [Influxus](http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB](http://influxdata.com/) | +| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | +| [KafkaLogrus](https://github.com/tracer0tong/kafkalogrus) | Hook for logging to Kafka | +| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | +| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) | +| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) | +| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) | +| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | +| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) | +| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | +| [Mattermost](https://github.com/shuLhan/mattermost-integration/tree/master/hooks/logrus) | Hook for logging to [Mattermost](https://mattermost.com/) | +| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | +| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) | +| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | +| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. | +| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) | +| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) | +| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | +| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) | +| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | +| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)| +| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. | +| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | +| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) | +| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)| +| [Syslog](https://github.com/sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | +| [Syslog TLS](https://github.com/shinji62/logrus-syslog-ng) | Send errors to remote syslog server with TLS support. | +| [Telegram](https://github.com/rossmcdonald/telegram_hook) | Hook for logging errors to [Telegram](https://telegram.org/) | +| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) | +| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) | +| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash | +| [SQS-Hook](https://github.com/tsarpaul/logrus_sqs) | Hook for logging to [Amazon Simple Queue Service (SQS)](https://aws.amazon.com/sqs/) | + +#### Level logging + +Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/sirupsen/logrus" +) + +init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(&log.JSONFormatter{}) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(&log.TextFormatter{}) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true`. For Windows, see + [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). +* `logrus.JSONFormatter`. Logs fields as JSON. + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). + +Third party logging formatters: + +* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can by parsed by Kubernetes and Google Container Engine. +* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. +* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. +* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +This means that we can override the standard library logger easily: + +```go +logger := logrus.New() +logger.Formatter = &logrus.JSONFormatter{} + +// Use logrus for standard log output +// Note that `log` here references stdlib's log +// Not logrus imported under the name `log`. +log.SetOutput(logger.Writer()) +``` + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + +#### Tools + +| Tool | Description | +| ---- | ----------- | +|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| +|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | + +#### Testing + +Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: + +* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook +* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): + +```go +import( + "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus/hooks/test" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestSomething(t*testing.T){ + logger, hook := test.NewNullLogger() + logger.Error("Helloerror") + + assert.Equal(t, 1, len(hook.Entries)) + assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal(t, "Helloerror", hook.LastEntry().Message) + + hook.Reset() + assert.Nil(t, hook.LastEntry()) +} +``` + +#### Fatal handlers + +Logrus can register one or more functions that will be called when any `fatal` +level message is logged. The registered handlers will be executed before +logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need +to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. + +``` +... +handler := func() { + // gracefully shutdown something... +} +logrus.RegisterExitHandler(handler) +... +``` + +#### Thread safety + +By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs. +If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. + +Situation when locking is not needed includes: + +* You have no hooks registered, or hooks calling is already thread-safe. + +* Writing to logger.Out is already thread-safe, for example: + + 1) logger.Out is protected by locks. + + 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) + + (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go new file mode 100644 index 000000000..8af90637a --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/alt_exit.go @@ -0,0 +1,64 @@ +package logrus + +// The following code was sourced and modified from the +// https://github.com/tebeka/atexit package governed by the following license: +// +// Copyright (c) 2012 Miki Tebeka . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import ( + "fmt" + "os" +) + +var handlers = []func(){} + +func runHandler(handler func()) { + defer func() { + if err := recover(); err != nil { + fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) + } + }() + + handler() +} + +func runHandlers() { + for _, handler := range handlers { + runHandler(handler) + } +} + +// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +func Exit(code int) { + runHandlers() + os.Exit(code) +} + +// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke +// all handlers. The handlers will also be invoked when any Fatal log entry is +// made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func RegisterExitHandler(handler func()) { + handlers = append(handlers, handler) +} diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit_test.go b/vendor/github.com/Sirupsen/logrus/alt_exit_test.go new file mode 100644 index 000000000..a08b1a898 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/alt_exit_test.go @@ -0,0 +1,83 @@ +package logrus + +import ( + "io/ioutil" + "log" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestRegister(t *testing.T) { + current := len(handlers) + RegisterExitHandler(func() {}) + if len(handlers) != current+1 { + t.Fatalf("expected %d handlers, got %d", current+1, len(handlers)) + } +} + +func TestHandler(t *testing.T) { + tempDir, err := ioutil.TempDir("", "test_handler") + if err != nil { + log.Fatalf("can't create temp dir. %q", err) + } + defer os.RemoveAll(tempDir) + + gofile := filepath.Join(tempDir, "gofile.go") + if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil { + t.Fatalf("can't create go file. %q", err) + } + + outfile := filepath.Join(tempDir, "outfile.out") + arg := time.Now().UTC().String() + err = exec.Command("go", "run", gofile, outfile, arg).Run() + if err == nil { + t.Fatalf("completed normally, should have failed") + } + + data, err := ioutil.ReadFile(outfile) + if err != nil { + t.Fatalf("can't read output file %s. %q", outfile, err) + } + + if string(data) != arg { + t.Fatalf("bad data. Expected %q, got %q", data, arg) + } +} + +var testprog = []byte(` +// Test program for atexit, gets output file and data as arguments and writes +// data to output file in atexit handler. +package main + +import ( + "github.com/sirupsen/logrus" + "flag" + "fmt" + "io/ioutil" +) + +var outfile = "" +var data = "" + +func handler() { + ioutil.WriteFile(outfile, []byte(data), 0666) +} + +func badHandler() { + n := 0 + fmt.Println(1/n) +} + +func main() { + flag.Parse() + outfile = flag.Arg(0) + data = flag.Arg(1) + + logrus.RegisterExitHandler(handler) + logrus.RegisterExitHandler(badHandler) + logrus.Fatal("Bye bye") +} +`) diff --git a/vendor/github.com/Sirupsen/logrus/appveyor.yml b/vendor/github.com/Sirupsen/logrus/appveyor.yml new file mode 100644 index 000000000..96c2ce15f --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/appveyor.yml @@ -0,0 +1,14 @@ +version: "{build}" +platform: x64 +clone_folder: c:\gopath\src\github.com\sirupsen\logrus +environment: + GOPATH: c:\gopath +branches: + only: + - master +install: + - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - go version +build_script: + - go get -t + - go test diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go new file mode 100644 index 000000000..da67aba06 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/doc.go @@ -0,0 +1,26 @@ +/* +Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + + +The simplest way to use Logrus is simply the package-level exported logger: + + package main + + import ( + log "github.com/sirupsen/logrus" + ) + + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } + +Output: + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + +For a full guide visit https://github.com/sirupsen/logrus +*/ +package logrus diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go new file mode 100644 index 000000000..1fad45e08 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/entry.go @@ -0,0 +1,279 @@ +package logrus + +import ( + "bytes" + "fmt" + "os" + "sync" + "time" +) + +var bufferPool *sync.Pool + +func init() { + bufferPool = &sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, + } +} + +// Defines the key when adding errors using WithError. +var ErrorKey = "error" + +// An entry is the final or intermediate Logrus logging entry. It contains all +// the fields passed with WithField{,s}. It's finally logged when Debug, Info, +// Warn, Error, Fatal or Panic is called on it. These objects can be reused and +// passed around as much as you wish to avoid field duplication. +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic + // This field will be set on entry firing and the value will be equal to the one in Logger struct field. + Level Level + + // Message passed to Debug, Info, Warn, Error, Fatal or Panic + Message string + + // When formatter is called in entry.log(), an Buffer may be set to entry + Buffer *bytes.Buffer +} + +func NewEntry(logger *Logger) *Entry { + return &Entry{ + Logger: logger, + // Default is three fields, give a little extra room + Data: make(Fields, 5), + } +} + +// Returns the string representation from the reader and ultimately the +// formatter. +func (entry *Entry) String() (string, error) { + serialized, err := entry.Logger.Formatter.Format(entry) + if err != nil { + return "", err + } + str := string(serialized) + return str, nil +} + +// Add an error as single field (using the key defined in ErrorKey) to the Entry. +func (entry *Entry) WithError(err error) *Entry { + return entry.WithField(ErrorKey, err) +} + +// Add a single field to the Entry. +func (entry *Entry) WithField(key string, value interface{}) *Entry { + return entry.WithFields(Fields{key: value}) +} + +// Add a map of fields to the Entry. +func (entry *Entry) WithFields(fields Fields) *Entry { + data := make(Fields, len(entry.Data)+len(fields)) + for k, v := range entry.Data { + data[k] = v + } + for k, v := range fields { + data[k] = v + } + return &Entry{Logger: entry.Logger, Data: data} +} + +// This function is not declared with a pointer value because otherwise +// race conditions will occur when using multiple goroutines +func (entry Entry) log(level Level, msg string) { + var buffer *bytes.Buffer + entry.Time = time.Now() + entry.Level = level + entry.Message = msg + + entry.Logger.mu.Lock() + err := entry.Logger.Hooks.Fire(level, &entry) + entry.Logger.mu.Unlock() + if err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) + entry.Logger.mu.Unlock() + } + buffer = bufferPool.Get().(*bytes.Buffer) + buffer.Reset() + defer bufferPool.Put(buffer) + entry.Buffer = buffer + serialized, err := entry.Logger.Formatter.Format(&entry) + entry.Buffer = nil + if err != nil { + entry.Logger.mu.Lock() + fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + entry.Logger.mu.Unlock() + } else { + entry.Logger.mu.Lock() + _, err = entry.Logger.Out.Write(serialized) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + } + entry.Logger.mu.Unlock() + } + + // To avoid Entry#log() returning a value that only would make sense for + // panic() to use in Entry#Panic(), we avoid the allocation by checking + // directly here. + if level <= PanicLevel { + panic(&entry) + } +} + +func (entry *Entry) Debug(args ...interface{}) { + if entry.Logger.level() >= DebugLevel { + entry.log(DebugLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Print(args ...interface{}) { + entry.Info(args...) +} + +func (entry *Entry) Info(args ...interface{}) { + if entry.Logger.level() >= InfoLevel { + entry.log(InfoLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warn(args ...interface{}) { + if entry.Logger.level() >= WarnLevel { + entry.log(WarnLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Warning(args ...interface{}) { + entry.Warn(args...) +} + +func (entry *Entry) Error(args ...interface{}) { + if entry.Logger.level() >= ErrorLevel { + entry.log(ErrorLevel, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Fatal(args ...interface{}) { + if entry.Logger.level() >= FatalLevel { + entry.log(FatalLevel, fmt.Sprint(args...)) + } + Exit(1) +} + +func (entry *Entry) Panic(args ...interface{}) { + if entry.Logger.level() >= PanicLevel { + entry.log(PanicLevel, fmt.Sprint(args...)) + } + panic(fmt.Sprint(args...)) +} + +// Entry Printf family functions + +func (entry *Entry) Debugf(format string, args ...interface{}) { + if entry.Logger.level() >= DebugLevel { + entry.Debug(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Infof(format string, args ...interface{}) { + if entry.Logger.level() >= InfoLevel { + entry.Info(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Printf(format string, args ...interface{}) { + entry.Infof(format, args...) +} + +func (entry *Entry) Warnf(format string, args ...interface{}) { + if entry.Logger.level() >= WarnLevel { + entry.Warn(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Warningf(format string, args ...interface{}) { + entry.Warnf(format, args...) +} + +func (entry *Entry) Errorf(format string, args ...interface{}) { + if entry.Logger.level() >= ErrorLevel { + entry.Error(fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Fatalf(format string, args ...interface{}) { + if entry.Logger.level() >= FatalLevel { + entry.Fatal(fmt.Sprintf(format, args...)) + } + Exit(1) +} + +func (entry *Entry) Panicf(format string, args ...interface{}) { + if entry.Logger.level() >= PanicLevel { + entry.Panic(fmt.Sprintf(format, args...)) + } +} + +// Entry Println family functions + +func (entry *Entry) Debugln(args ...interface{}) { + if entry.Logger.level() >= DebugLevel { + entry.Debug(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Infoln(args ...interface{}) { + if entry.Logger.level() >= InfoLevel { + entry.Info(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Println(args ...interface{}) { + entry.Infoln(args...) +} + +func (entry *Entry) Warnln(args ...interface{}) { + if entry.Logger.level() >= WarnLevel { + entry.Warn(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Warningln(args ...interface{}) { + entry.Warnln(args...) +} + +func (entry *Entry) Errorln(args ...interface{}) { + if entry.Logger.level() >= ErrorLevel { + entry.Error(entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Fatalln(args ...interface{}) { + if entry.Logger.level() >= FatalLevel { + entry.Fatal(entry.sprintlnn(args...)) + } + Exit(1) +} + +func (entry *Entry) Panicln(args ...interface{}) { + if entry.Logger.level() >= PanicLevel { + entry.Panic(entry.sprintlnn(args...)) + } +} + +// Sprintlnn => Sprint no newline. This is to get the behavior of how +// fmt.Sprintln where spaces are always added between operands, regardless of +// their type. Instead of vendoring the Sprintln implementation to spare a +// string allocation, we do the simplest thing. +func (entry *Entry) sprintlnn(args ...interface{}) string { + msg := fmt.Sprintln(args...) + return msg[:len(msg)-1] +} diff --git a/vendor/github.com/Sirupsen/logrus/entry_test.go b/vendor/github.com/Sirupsen/logrus/entry_test.go new file mode 100644 index 000000000..99c3b41d5 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/entry_test.go @@ -0,0 +1,77 @@ +package logrus + +import ( + "bytes" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestEntryWithError(t *testing.T) { + + assert := assert.New(t) + + defer func() { + ErrorKey = "error" + }() + + err := fmt.Errorf("kaboom at layer %d", 4711) + + assert.Equal(err, WithError(err).Data["error"]) + + logger := New() + logger.Out = &bytes.Buffer{} + entry := NewEntry(logger) + + assert.Equal(err, entry.WithError(err).Data["error"]) + + ErrorKey = "err" + + assert.Equal(err, entry.WithError(err).Data["err"]) + +} + +func TestEntryPanicln(t *testing.T) { + errBoom := fmt.Errorf("boom time") + + defer func() { + p := recover() + assert.NotNil(t, p) + + switch pVal := p.(type) { + case *Entry: + assert.Equal(t, "kaboom", pVal.Message) + assert.Equal(t, errBoom, pVal.Data["err"]) + default: + t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) + } + }() + + logger := New() + logger.Out = &bytes.Buffer{} + entry := NewEntry(logger) + entry.WithField("err", errBoom).Panicln("kaboom") +} + +func TestEntryPanicf(t *testing.T) { + errBoom := fmt.Errorf("boom again") + + defer func() { + p := recover() + assert.NotNil(t, p) + + switch pVal := p.(type) { + case *Entry: + assert.Equal(t, "kaboom true", pVal.Message) + assert.Equal(t, errBoom, pVal.Data["err"]) + default: + t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) + } + }() + + logger := New() + logger.Out = &bytes.Buffer{} + entry := NewEntry(logger) + entry.WithField("err", errBoom).Panicf("kaboom %v", true) +} diff --git a/vendor/github.com/Sirupsen/logrus/example_basic_test.go b/vendor/github.com/Sirupsen/logrus/example_basic_test.go new file mode 100644 index 000000000..a2acf550c --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/example_basic_test.go @@ -0,0 +1,69 @@ +package logrus_test + +import ( + "github.com/sirupsen/logrus" + "os" +) + +func Example_basic() { + var log = logrus.New() + log.Formatter = new(logrus.JSONFormatter) + log.Formatter = new(logrus.TextFormatter) //default + log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output + log.Level = logrus.DebugLevel + log.Out = os.Stdout + + // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) + // if err == nil { + // log.Out = file + // } else { + // log.Info("Failed to log to file, using default stderr") + // } + + defer func() { + err := recover() + if err != nil { + entry := err.(*logrus.Entry) + log.WithFields(logrus.Fields{ + "omg": true, + "err_animal": entry.Data["animal"], + "err_size": entry.Data["size"], + "err_level": entry.Level, + "err_message": entry.Message, + "number": 100, + }).Error("The ice breaks!") // or use Fatal() to force the process to exit with a nonzero code + } + }() + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "number": 8, + }).Debug("Started observing beach") + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(logrus.Fields{ + "temperature": -4, + }).Debug("Temperature changes") + + log.WithFields(logrus.Fields{ + "animal": "orca", + "size": 9009, + }).Panic("It's over 9000!") + + // Output: + // level=debug msg="Started observing beach" animal=walrus number=8 + // level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 + // level=warning msg="The group's number increased tremendously!" number=122 omg=true + // level=debug msg="Temperature changes" temperature=-4 + // level=panic msg="It's over 9000!" animal=orca size=9009 + // level=error msg="The ice breaks!" err_animal=orca err_level=panic err_message="It's over 9000!" err_size=9009 number=100 omg=true +} diff --git a/vendor/github.com/Sirupsen/logrus/example_hook_test.go b/vendor/github.com/Sirupsen/logrus/example_hook_test.go new file mode 100644 index 000000000..d4ddffca3 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/example_hook_test.go @@ -0,0 +1,35 @@ +package logrus_test + +import ( + "github.com/sirupsen/logrus" + "gopkg.in/gemnasium/logrus-airbrake-hook.v2" + "os" +) + +func Example_hook() { + var log = logrus.New() + log.Formatter = new(logrus.TextFormatter) // default + log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output + log.Hooks.Add(airbrake.NewHook(123, "xyz", "development")) + log.Out = os.Stdout + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(logrus.Fields{ + "omg": true, + "number": 100, + }).Error("The ice breaks!") + + // Output: + // level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 + // level=warning msg="The group's number increased tremendously!" number=122 omg=true + // level=error msg="The ice breaks!" number=100 omg=true +} diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go new file mode 100644 index 000000000..013183eda --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/exported.go @@ -0,0 +1,193 @@ +package logrus + +import ( + "io" +) + +var ( + // std is the name of the standard logger in stdlib `log` + std = New() +) + +func StandardLogger() *Logger { + return std +} + +// SetOutput sets the standard logger output. +func SetOutput(out io.Writer) { + std.mu.Lock() + defer std.mu.Unlock() + std.Out = out +} + +// SetFormatter sets the standard logger formatter. +func SetFormatter(formatter Formatter) { + std.mu.Lock() + defer std.mu.Unlock() + std.Formatter = formatter +} + +// SetLevel sets the standard logger level. +func SetLevel(level Level) { + std.mu.Lock() + defer std.mu.Unlock() + std.SetLevel(level) +} + +// GetLevel returns the standard logger level. +func GetLevel() Level { + std.mu.Lock() + defer std.mu.Unlock() + return std.level() +} + +// AddHook adds a hook to the standard logger hooks. +func AddHook(hook Hook) { + std.mu.Lock() + defer std.mu.Unlock() + std.Hooks.Add(hook) +} + +// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +func WithError(err error) *Entry { + return std.WithField(ErrorKey, err) +} + +// WithField creates an entry from the standard logger and adds a field to +// it. If you want multiple fields, use `WithFields`. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithField(key string, value interface{}) *Entry { + return std.WithField(key, value) +} + +// WithFields creates an entry from the standard logger and adds multiple +// fields to it. This is simply a helper for `WithField`, invoking it +// once for each field. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithFields(fields Fields) *Entry { + return std.WithFields(fields) +} + +// Debug logs a message at level Debug on the standard logger. +func Debug(args ...interface{}) { + std.Debug(args...) +} + +// Print logs a message at level Info on the standard logger. +func Print(args ...interface{}) { + std.Print(args...) +} + +// Info logs a message at level Info on the standard logger. +func Info(args ...interface{}) { + std.Info(args...) +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(args ...interface{}) { + std.Warn(args...) +} + +// Warning logs a message at level Warn on the standard logger. +func Warning(args ...interface{}) { + std.Warning(args...) +} + +// Error logs a message at level Error on the standard logger. +func Error(args ...interface{}) { + std.Error(args...) +} + +// Panic logs a message at level Panic on the standard logger. +func Panic(args ...interface{}) { + std.Panic(args...) +} + +// Fatal logs a message at level Fatal on the standard logger. +func Fatal(args ...interface{}) { + std.Fatal(args...) +} + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +// Printf logs a message at level Info on the standard logger. +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +// Infof logs a message at level Info on the standard logger. +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + std.Warnf(format, args...) +} + +// Warningf logs a message at level Warn on the standard logger. +func Warningf(format string, args ...interface{}) { + std.Warningf(format, args...) +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +// Panicf logs a message at level Panic on the standard logger. +func Panicf(format string, args ...interface{}) { + std.Panicf(format, args...) +} + +// Fatalf logs a message at level Fatal on the standard logger. +func Fatalf(format string, args ...interface{}) { + std.Fatalf(format, args...) +} + +// Debugln logs a message at level Debug on the standard logger. +func Debugln(args ...interface{}) { + std.Debugln(args...) +} + +// Println logs a message at level Info on the standard logger. +func Println(args ...interface{}) { + std.Println(args...) +} + +// Infoln logs a message at level Info on the standard logger. +func Infoln(args ...interface{}) { + std.Infoln(args...) +} + +// Warnln logs a message at level Warn on the standard logger. +func Warnln(args ...interface{}) { + std.Warnln(args...) +} + +// Warningln logs a message at level Warn on the standard logger. +func Warningln(args ...interface{}) { + std.Warningln(args...) +} + +// Errorln logs a message at level Error on the standard logger. +func Errorln(args ...interface{}) { + std.Errorln(args...) +} + +// Panicln logs a message at level Panic on the standard logger. +func Panicln(args ...interface{}) { + std.Panicln(args...) +} + +// Fatalln logs a message at level Fatal on the standard logger. +func Fatalln(args ...interface{}) { + std.Fatalln(args...) +} diff --git a/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go new file mode 100644 index 000000000..b183ff5b1 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/formatter.go @@ -0,0 +1,45 @@ +package logrus + +import "time" + +const defaultTimestampFormat = time.RFC3339 + +// The Formatter interface is used to implement a custom Formatter. It takes an +// `Entry`. It exposes all the fields, including the default ones: +// +// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +// * `entry.Data["time"]`. The timestamp. +// * `entry.Data["level"]. The level the entry was logged at. +// +// Any additional fields added with `WithField` or `WithFields` are also in +// `entry.Data`. Format is expected to return an array of bytes which are then +// logged to `logger.Out`. +type Formatter interface { + Format(*Entry) ([]byte, error) +} + +// This is to not silently overwrite `time`, `msg` and `level` fields when +// dumping it. If this code wasn't there doing: +// +// logrus.WithField("level", 1).Info("hello") +// +// Would just silently drop the user provided level. Instead with this code +// it'll logged as: +// +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// +// It's not exported because it's still using Data in an opinionated way. It's to +// avoid code duplication between the two default formatters. +func prefixFieldClashes(data Fields) { + if t, ok := data["time"]; ok { + data["fields.time"] = t + } + + if m, ok := data["msg"]; ok { + data["fields.msg"] = m + } + + if l, ok := data["level"]; ok { + data["fields.level"] = l + } +} diff --git a/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go new file mode 100644 index 000000000..d9481589f --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go @@ -0,0 +1,101 @@ +package logrus + +import ( + "fmt" + "testing" + "time" +) + +// smallFields is a small size data set for benchmarking +var smallFields = Fields{ + "foo": "bar", + "baz": "qux", + "one": "two", + "three": "four", +} + +// largeFields is a large size data set for benchmarking +var largeFields = Fields{ + "foo": "bar", + "baz": "qux", + "one": "two", + "three": "four", + "five": "six", + "seven": "eight", + "nine": "ten", + "eleven": "twelve", + "thirteen": "fourteen", + "fifteen": "sixteen", + "seventeen": "eighteen", + "nineteen": "twenty", + "a": "b", + "c": "d", + "e": "f", + "g": "h", + "i": "j", + "k": "l", + "m": "n", + "o": "p", + "q": "r", + "s": "t", + "u": "v", + "w": "x", + "y": "z", + "this": "will", + "make": "thirty", + "entries": "yeah", +} + +var errorFields = Fields{ + "foo": fmt.Errorf("bar"), + "baz": fmt.Errorf("qux"), +} + +func BenchmarkErrorTextFormatter(b *testing.B) { + doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) +} + +func BenchmarkSmallTextFormatter(b *testing.B) { + doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) +} + +func BenchmarkLargeTextFormatter(b *testing.B) { + doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) +} + +func BenchmarkSmallColoredTextFormatter(b *testing.B) { + doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) +} + +func BenchmarkLargeColoredTextFormatter(b *testing.B) { + doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) +} + +func BenchmarkSmallJSONFormatter(b *testing.B) { + doBenchmark(b, &JSONFormatter{}, smallFields) +} + +func BenchmarkLargeJSONFormatter(b *testing.B) { + doBenchmark(b, &JSONFormatter{}, largeFields) +} + +func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { + logger := New() + + entry := &Entry{ + Time: time.Time{}, + Level: InfoLevel, + Message: "message", + Data: fields, + Logger: logger, + } + var d []byte + var err error + for i := 0; i < b.N; i++ { + d, err = formatter.Format(entry) + if err != nil { + b.Fatal(err) + } + b.SetBytes(int64(len(d))) + } +} diff --git a/vendor/github.com/Sirupsen/logrus/hook_test.go b/vendor/github.com/Sirupsen/logrus/hook_test.go new file mode 100644 index 000000000..4fea7514e --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hook_test.go @@ -0,0 +1,144 @@ +package logrus + +import ( + "sync" + "testing" + + "github.com/stretchr/testify/assert" +) + +type TestHook struct { + Fired bool +} + +func (hook *TestHook) Fire(entry *Entry) error { + hook.Fired = true + return nil +} + +func (hook *TestHook) Levels() []Level { + return []Level{ + DebugLevel, + InfoLevel, + WarnLevel, + ErrorLevel, + FatalLevel, + PanicLevel, + } +} + +func TestHookFires(t *testing.T) { + hook := new(TestHook) + + LogAndAssertJSON(t, func(log *Logger) { + log.Hooks.Add(hook) + assert.Equal(t, hook.Fired, false) + + log.Print("test") + }, func(fields Fields) { + assert.Equal(t, hook.Fired, true) + }) +} + +type ModifyHook struct { +} + +func (hook *ModifyHook) Fire(entry *Entry) error { + entry.Data["wow"] = "whale" + return nil +} + +func (hook *ModifyHook) Levels() []Level { + return []Level{ + DebugLevel, + InfoLevel, + WarnLevel, + ErrorLevel, + FatalLevel, + PanicLevel, + } +} + +func TestHookCanModifyEntry(t *testing.T) { + hook := new(ModifyHook) + + LogAndAssertJSON(t, func(log *Logger) { + log.Hooks.Add(hook) + log.WithField("wow", "elephant").Print("test") + }, func(fields Fields) { + assert.Equal(t, fields["wow"], "whale") + }) +} + +func TestCanFireMultipleHooks(t *testing.T) { + hook1 := new(ModifyHook) + hook2 := new(TestHook) + + LogAndAssertJSON(t, func(log *Logger) { + log.Hooks.Add(hook1) + log.Hooks.Add(hook2) + + log.WithField("wow", "elephant").Print("test") + }, func(fields Fields) { + assert.Equal(t, fields["wow"], "whale") + assert.Equal(t, hook2.Fired, true) + }) +} + +type ErrorHook struct { + Fired bool +} + +func (hook *ErrorHook) Fire(entry *Entry) error { + hook.Fired = true + return nil +} + +func (hook *ErrorHook) Levels() []Level { + return []Level{ + ErrorLevel, + } +} + +func TestErrorHookShouldntFireOnInfo(t *testing.T) { + hook := new(ErrorHook) + + LogAndAssertJSON(t, func(log *Logger) { + log.Hooks.Add(hook) + log.Info("test") + }, func(fields Fields) { + assert.Equal(t, hook.Fired, false) + }) +} + +func TestErrorHookShouldFireOnError(t *testing.T) { + hook := new(ErrorHook) + + LogAndAssertJSON(t, func(log *Logger) { + log.Hooks.Add(hook) + log.Error("test") + }, func(fields Fields) { + assert.Equal(t, hook.Fired, true) + }) +} + +func TestAddHookRace(t *testing.T) { + var wg sync.WaitGroup + wg.Add(2) + hook := new(ErrorHook) + LogAndAssertJSON(t, func(log *Logger) { + go func() { + defer wg.Done() + log.AddHook(hook) + }() + go func() { + defer wg.Done() + log.Error("test") + }() + wg.Wait() + }, func(fields Fields) { + // the line may have been logged + // before the hook was added, so we can't + // actually assert on the hook + }) +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go new file mode 100644 index 000000000..3f151cdc3 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks.go @@ -0,0 +1,34 @@ +package logrus + +// A hook to be fired when logging on the logging levels returned from +// `Levels()` on your implementation of the interface. Note that this is not +// fired in a goroutine or a channel with workers, you should handle such +// functionality yourself if your call is non-blocking and you don't wish for +// the logging calls for levels returned from `Levels()` to block. +type Hook interface { + Levels() []Level + Fire(*Entry) error +} + +// Internal type for storing the hooks on a logger instance. +type LevelHooks map[Level][]Hook + +// Add a hook to an instance of logger. This is called with +// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +func (hooks LevelHooks) Add(hook Hook) { + for _, level := range hook.Levels() { + hooks[level] = append(hooks[level], hook) + } +} + +// Fire all the hooks for the passed level. Used by `entry.log` to fire +// appropriate hooks for a log entry. +func (hooks LevelHooks) Fire(level Level, entry *Entry) error { + for _, hook := range hooks[level] { + if err := hook.Fire(entry); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md b/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md new file mode 100644 index 000000000..1bbc0f72d --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md @@ -0,0 +1,39 @@ +# Syslog Hooks for Logrus :walrus: + +## Usage + +```go +import ( + "log/syslog" + "github.com/sirupsen/logrus" + lSyslog "github.com/sirupsen/logrus/hooks/syslog" +) + +func main() { + log := logrus.New() + hook, err := lSyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + + if err == nil { + log.Hooks.Add(hook) + } +} +``` + +If you want to connect to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). Just assign empty string to the first two parameters of `NewSyslogHook`. It should look like the following. + +```go +import ( + "log/syslog" + "github.com/sirupsen/logrus" + lSyslog "github.com/sirupsen/logrus/hooks/syslog" +) + +func main() { + log := logrus.New() + hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "") + + if err == nil { + log.Hooks.Add(hook) + } +} +``` diff --git a/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go b/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go new file mode 100644 index 000000000..329ce0d60 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go @@ -0,0 +1,55 @@ +// +build !windows,!nacl,!plan9 + +package syslog + +import ( + "fmt" + "log/syslog" + "os" + + "github.com/sirupsen/logrus" +) + +// SyslogHook to send logs via syslog. +type SyslogHook struct { + Writer *syslog.Writer + SyslogNetwork string + SyslogRaddr string +} + +// Creates a hook to be added to an instance of logger. This is called with +// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` +// `if err == nil { log.Hooks.Add(hook) }` +func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) { + w, err := syslog.Dial(network, raddr, priority, tag) + return &SyslogHook{w, network, raddr}, err +} + +func (hook *SyslogHook) Fire(entry *logrus.Entry) error { + line, err := entry.String() + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err) + return err + } + + switch entry.Level { + case logrus.PanicLevel: + return hook.Writer.Crit(line) + case logrus.FatalLevel: + return hook.Writer.Crit(line) + case logrus.ErrorLevel: + return hook.Writer.Err(line) + case logrus.WarnLevel: + return hook.Writer.Warning(line) + case logrus.InfoLevel: + return hook.Writer.Info(line) + case logrus.DebugLevel: + return hook.Writer.Debug(line) + default: + return nil + } +} + +func (hook *SyslogHook) Levels() []logrus.Level { + return logrus.AllLevels +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go new file mode 100644 index 000000000..5ec3a4445 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go @@ -0,0 +1,27 @@ +package syslog + +import ( + "log/syslog" + "testing" + + "github.com/sirupsen/logrus" +) + +func TestLocalhostAddAndPrint(t *testing.T) { + log := logrus.New() + hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + + if err != nil { + t.Errorf("Unable to connect to local syslog.") + } + + log.Hooks.Add(hook) + + for _, level := range hook.Levels() { + if len(log.Hooks[level]) != 1 { + t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level])) + } + } + + log.Info("Congratulations!") +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks/test/test.go b/vendor/github.com/Sirupsen/logrus/hooks/test/test.go new file mode 100644 index 000000000..62c4845df --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks/test/test.go @@ -0,0 +1,95 @@ +// The Test package is used for testing logrus. It is here for backwards +// compatibility from when logrus' organization was upper-case. Please use +// lower-case logrus and the `null` package instead of this one. +package test + +import ( + "io/ioutil" + "sync" + + "github.com/sirupsen/logrus" +) + +// Hook is a hook designed for dealing with logs in test scenarios. +type Hook struct { + // Entries is an array of all entries that have been received by this hook. + // For safe access, use the AllEntries() method, rather than reading this + // value directly. + Entries []*logrus.Entry + mu sync.RWMutex +} + +// NewGlobal installs a test hook for the global logger. +func NewGlobal() *Hook { + + hook := new(Hook) + logrus.AddHook(hook) + + return hook + +} + +// NewLocal installs a test hook for a given local logger. +func NewLocal(logger *logrus.Logger) *Hook { + + hook := new(Hook) + logger.Hooks.Add(hook) + + return hook + +} + +// NewNullLogger creates a discarding logger and installs the test hook. +func NewNullLogger() (*logrus.Logger, *Hook) { + + logger := logrus.New() + logger.Out = ioutil.Discard + + return logger, NewLocal(logger) + +} + +func (t *Hook) Fire(e *logrus.Entry) error { + t.mu.Lock() + defer t.mu.Unlock() + t.Entries = append(t.Entries, e) + return nil +} + +func (t *Hook) Levels() []logrus.Level { + return logrus.AllLevels +} + +// LastEntry returns the last entry that was logged or nil. +func (t *Hook) LastEntry() *logrus.Entry { + t.mu.RLock() + defer t.mu.RUnlock() + i := len(t.Entries) - 1 + if i < 0 { + return nil + } + // Make a copy, for safety + e := *t.Entries[i] + return &e +} + +// AllEntries returns all entries that were logged. +func (t *Hook) AllEntries() []*logrus.Entry { + t.mu.RLock() + defer t.mu.RUnlock() + // Make a copy so the returned value won't race with future log requests + entries := make([]*logrus.Entry, len(t.Entries)) + for i, entry := range t.Entries { + // Make a copy, for safety + e := *entry + entries[i] = &e + } + return entries +} + +// Reset removes all Entries from this test hook. +func (t *Hook) Reset() { + t.mu.Lock() + defer t.mu.Unlock() + t.Entries = make([]*logrus.Entry, 0) +} diff --git a/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go b/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go new file mode 100644 index 000000000..3f55cfe31 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go @@ -0,0 +1,39 @@ +package test + +import ( + "testing" + + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" +) + +func TestAllHooks(t *testing.T) { + + assert := assert.New(t) + + logger, hook := NewNullLogger() + assert.Nil(hook.LastEntry()) + assert.Equal(0, len(hook.Entries)) + + logger.Error("Hello error") + assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal("Hello error", hook.LastEntry().Message) + assert.Equal(1, len(hook.Entries)) + + logger.Warn("Hello warning") + assert.Equal(logrus.WarnLevel, hook.LastEntry().Level) + assert.Equal("Hello warning", hook.LastEntry().Message) + assert.Equal(2, len(hook.Entries)) + + hook.Reset() + assert.Nil(hook.LastEntry()) + assert.Equal(0, len(hook.Entries)) + + hook = NewGlobal() + + logrus.Error("Hello error") + assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal("Hello error", hook.LastEntry().Message) + assert.Equal(1, len(hook.Entries)) + +} diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go new file mode 100644 index 000000000..fb01c1b10 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/json_formatter.go @@ -0,0 +1,79 @@ +package logrus + +import ( + "encoding/json" + "fmt" +) + +type fieldKey string + +// FieldMap allows customization of the key names for default fields. +type FieldMap map[fieldKey]string + +// Default key names for the default fields +const ( + FieldKeyMsg = "msg" + FieldKeyLevel = "level" + FieldKeyTime = "time" +) + +func (f FieldMap) resolve(key fieldKey) string { + if k, ok := f[key]; ok { + return k + } + + return string(key) +} + +// JSONFormatter formats logs into parsable json +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + TimestampFormat string + + // DisableTimestamp allows disabling automatic timestamps in output + DisableTimestamp bool + + // FieldMap allows users to customize the names of keys for default fields. + // As an example: + // formatter := &JSONFormatter{ + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message", + // }, + // } + FieldMap FieldMap +} + +// Format renders a single log entry +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields, len(entry.Data)+3) + for k, v := range entry.Data { + switch v := v.(type) { + case error: + // Otherwise errors are ignored by `encoding/json` + // https://github.com/sirupsen/logrus/issues/137 + data[k] = v.Error() + default: + data[k] = v + } + } + prefixFieldClashes(data) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + + if !f.DisableTimestamp { + data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + } + data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message + data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() + + serialized, err := json.Marshal(data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter_test.go b/vendor/github.com/Sirupsen/logrus/json_formatter_test.go new file mode 100644 index 000000000..51093a79b --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/json_formatter_test.go @@ -0,0 +1,199 @@ +package logrus + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestErrorNotLost(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + if entry["error"] != "wild walrus" { + t.Fatal("Error field not set") + } +} + +func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + if entry["omg"] != "wild walrus" { + t.Fatal("Error field not set") + } +} + +func TestFieldClashWithTime(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("time", "right now!")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + if entry["fields.time"] != "right now!" { + t.Fatal("fields.time not set to original time field") + } + + if entry["time"] != "0001-01-01T00:00:00Z" { + t.Fatal("time field not set to current time, was: ", entry["time"]) + } +} + +func TestFieldClashWithMsg(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("msg", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + if entry["fields.msg"] != "something" { + t.Fatal("fields.msg not set to original msg field") + } +} + +func TestFieldClashWithLevel(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + entry := make(map[string]interface{}) + err = json.Unmarshal(b, &entry) + if err != nil { + t.Fatal("Unable to unmarshal formatted entry: ", err) + } + + if entry["fields.level"] != "something" { + t.Fatal("fields.level not set to original level field") + } +} + +func TestJSONEntryEndsWithNewline(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + + if b[len(b)-1] != '\n' { + t.Fatal("Expected JSON log entry to end with a newline") + } +} + +func TestJSONMessageKey(t *testing.T) { + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyMsg: "message", + }, + } + + b, err := formatter.Format(&Entry{Message: "oh hai"}) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !(strings.Contains(s, "message") && strings.Contains(s, "oh hai")) { + t.Fatal("Expected JSON to format message key") + } +} + +func TestJSONLevelKey(t *testing.T) { + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyLevel: "somelevel", + }, + } + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, "somelevel") { + t.Fatal("Expected JSON to format level key") + } +} + +func TestJSONTimeKey(t *testing.T) { + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyTime: "timeywimey", + }, + } + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, "timeywimey") { + t.Fatal("Expected JSON to format time key") + } +} + +func TestJSONDisableTimestamp(t *testing.T) { + formatter := &JSONFormatter{ + DisableTimestamp: true, + } + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if strings.Contains(s, FieldKeyTime) { + t.Error("Did not prevent timestamp", s) + } +} + +func TestJSONEnableTimestamp(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, FieldKeyTime) { + t.Error("Timestamp not present", s) + } +} diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go new file mode 100644 index 000000000..fdaf8a653 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logger.go @@ -0,0 +1,323 @@ +package logrus + +import ( + "io" + "os" + "sync" + "sync/atomic" +) + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stderr`. You can also set this to + // something more adventorous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. + Level Level + // Used to sync writing to the log. Locking is enabled by Default + mu MutexWrap + // Reusable empty entry + entryPool sync.Pool +} + +type MutexWrap struct { + lock sync.Mutex + disabled bool +} + +func (mw *MutexWrap) Lock() { + if !mw.disabled { + mw.lock.Lock() + } +} + +func (mw *MutexWrap) Unlock() { + if !mw.disabled { + mw.lock.Unlock() + } +} + +func (mw *MutexWrap) Disable() { + mw.disabled = true +} + +// Creates a new logger. Configuration should be set by changing `Formatter`, +// `Out` and `Hooks` directly on the default logger instance. You can also just +// instantiate your own: +// +// var log = &Logger{ +// Out: os.Stderr, +// Formatter: new(JSONFormatter), +// Hooks: make(LevelHooks), +// Level: logrus.DebugLevel, +// } +// +// It's recommended to make this a global instance called `log`. +func New() *Logger { + return &Logger{ + Out: os.Stderr, + Formatter: new(TextFormatter), + Hooks: make(LevelHooks), + Level: InfoLevel, + } +} + +func (logger *Logger) newEntry() *Entry { + entry, ok := logger.entryPool.Get().(*Entry) + if ok { + return entry + } + return NewEntry(logger) +} + +func (logger *Logger) releaseEntry(entry *Entry) { + logger.entryPool.Put(entry) +} + +// Adds a field to the log entry, note that it doesn't log until you call +// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. +// If you want multiple fields, use `WithFields`. +func (logger *Logger) WithField(key string, value interface{}) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithField(key, value) +} + +// Adds a struct of fields to the log entry. All it does is call `WithField` for +// each `Field`. +func (logger *Logger) WithFields(fields Fields) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithFields(fields) +} + +// Add an error as single field to the log entry. All it does is call +// `WithError` for the given `error`. +func (logger *Logger) WithError(err error) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithError(err) +} + +func (logger *Logger) Debugf(format string, args ...interface{}) { + if logger.level() >= DebugLevel { + entry := logger.newEntry() + entry.Debugf(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Infof(format string, args ...interface{}) { + if logger.level() >= InfoLevel { + entry := logger.newEntry() + entry.Infof(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Printf(format string, args ...interface{}) { + entry := logger.newEntry() + entry.Printf(format, args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnf(format string, args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warnf(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Warningf(format string, args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warnf(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Errorf(format string, args ...interface{}) { + if logger.level() >= ErrorLevel { + entry := logger.newEntry() + entry.Errorf(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Fatalf(format string, args ...interface{}) { + if logger.level() >= FatalLevel { + entry := logger.newEntry() + entry.Fatalf(format, args...) + logger.releaseEntry(entry) + } + Exit(1) +} + +func (logger *Logger) Panicf(format string, args ...interface{}) { + if logger.level() >= PanicLevel { + entry := logger.newEntry() + entry.Panicf(format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Debug(args ...interface{}) { + if logger.level() >= DebugLevel { + entry := logger.newEntry() + entry.Debug(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Info(args ...interface{}) { + if logger.level() >= InfoLevel { + entry := logger.newEntry() + entry.Info(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Print(args ...interface{}) { + entry := logger.newEntry() + entry.Info(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warn(args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warn(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Warning(args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warn(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Error(args ...interface{}) { + if logger.level() >= ErrorLevel { + entry := logger.newEntry() + entry.Error(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Fatal(args ...interface{}) { + if logger.level() >= FatalLevel { + entry := logger.newEntry() + entry.Fatal(args...) + logger.releaseEntry(entry) + } + Exit(1) +} + +func (logger *Logger) Panic(args ...interface{}) { + if logger.level() >= PanicLevel { + entry := logger.newEntry() + entry.Panic(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Debugln(args ...interface{}) { + if logger.level() >= DebugLevel { + entry := logger.newEntry() + entry.Debugln(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Infoln(args ...interface{}) { + if logger.level() >= InfoLevel { + entry := logger.newEntry() + entry.Infoln(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Println(args ...interface{}) { + entry := logger.newEntry() + entry.Println(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnln(args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warnln(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Warningln(args ...interface{}) { + if logger.level() >= WarnLevel { + entry := logger.newEntry() + entry.Warnln(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Errorln(args ...interface{}) { + if logger.level() >= ErrorLevel { + entry := logger.newEntry() + entry.Errorln(args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Fatalln(args ...interface{}) { + if logger.level() >= FatalLevel { + entry := logger.newEntry() + entry.Fatalln(args...) + logger.releaseEntry(entry) + } + Exit(1) +} + +func (logger *Logger) Panicln(args ...interface{}) { + if logger.level() >= PanicLevel { + entry := logger.newEntry() + entry.Panicln(args...) + logger.releaseEntry(entry) + } +} + +//When file is opened with appending mode, it's safe to +//write concurrently to a file (within 4k message on Linux). +//In these cases user can choose to disable the lock. +func (logger *Logger) SetNoLock() { + logger.mu.Disable() +} + +func (logger *Logger) level() Level { + return Level(atomic.LoadUint32((*uint32)(&logger.Level))) +} + +func (logger *Logger) SetLevel(level Level) { + atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) +} + +func (logger *Logger) AddHook(hook Hook) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Hooks.Add(hook) +} diff --git a/vendor/github.com/Sirupsen/logrus/logger_bench_test.go b/vendor/github.com/Sirupsen/logrus/logger_bench_test.go new file mode 100644 index 000000000..dd23a3535 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logger_bench_test.go @@ -0,0 +1,61 @@ +package logrus + +import ( + "os" + "testing" +) + +// smallFields is a small size data set for benchmarking +var loggerFields = Fields{ + "foo": "bar", + "baz": "qux", + "one": "two", + "three": "four", +} + +func BenchmarkDummyLogger(b *testing.B) { + nullf, err := os.OpenFile("/dev/null", os.O_WRONLY, 0666) + if err != nil { + b.Fatalf("%v", err) + } + defer nullf.Close() + doLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields) +} + +func BenchmarkDummyLoggerNoLock(b *testing.B) { + nullf, err := os.OpenFile("/dev/null", os.O_WRONLY|os.O_APPEND, 0666) + if err != nil { + b.Fatalf("%v", err) + } + defer nullf.Close() + doLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields) +} + +func doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) { + logger := Logger{ + Out: out, + Level: InfoLevel, + Formatter: formatter, + } + entry := logger.WithFields(fields) + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + entry.Info("aaa") + } + }) +} + +func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) { + logger := Logger{ + Out: out, + Level: InfoLevel, + Formatter: formatter, + } + logger.SetNoLock() + entry := logger.WithFields(fields) + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + entry.Info("aaa") + } + }) +} diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go new file mode 100644 index 000000000..dd3899974 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logrus.go @@ -0,0 +1,143 @@ +package logrus + +import ( + "fmt" + "log" + "strings" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Level type +type Level uint32 + +// Convert the Level to a string. E.g. PanicLevel becomes "panic". +func (level Level) String() string { + switch level { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warning" + case ErrorLevel: + return "error" + case FatalLevel: + return "fatal" + case PanicLevel: + return "panic" + } + + return "unknown" +} + +// ParseLevel takes a string level and returns the Logrus log level constant. +func ParseLevel(lvl string) (Level, error) { + switch strings.ToLower(lvl) { + case "panic": + return PanicLevel, nil + case "fatal": + return FatalLevel, nil + case "error": + return ErrorLevel, nil + case "warn", "warning": + return WarnLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid logrus Level: %q", lvl) +} + +// A constant exposing all logging levels +var AllLevels = []Level{ + PanicLevel, + FatalLevel, + ErrorLevel, + WarnLevel, + InfoLevel, + DebugLevel, +} + +// These are the different logging levels. You can set the logging level to log +// on your instance of logger, obtained with `logrus.New()`. +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel +) + +// Won't compile if StdLogger can't be realized by a log.Logger +var ( + _ StdLogger = &log.Logger{} + _ StdLogger = &Entry{} + _ StdLogger = &Logger{} +) + +// StdLogger is what your logrus-enabled library should take, that way +// it'll accept a stdlib logger and a logrus logger. There's no standard +// interface, this is the closest we get, unfortunately. +type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +} + +// The FieldLogger interface generalizes the Entry and Logger types +type FieldLogger interface { + WithField(key string, value interface{}) *Entry + WithFields(fields Fields) *Entry + WithError(err error) *Entry + + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Printf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Panicf(format string, args ...interface{}) + + Debug(args ...interface{}) + Info(args ...interface{}) + Print(args ...interface{}) + Warn(args ...interface{}) + Warning(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Panic(args ...interface{}) + + Debugln(args ...interface{}) + Infoln(args ...interface{}) + Println(args ...interface{}) + Warnln(args ...interface{}) + Warningln(args ...interface{}) + Errorln(args ...interface{}) + Fatalln(args ...interface{}) + Panicln(args ...interface{}) +} diff --git a/vendor/github.com/Sirupsen/logrus/logrus_test.go b/vendor/github.com/Sirupsen/logrus/logrus_test.go new file mode 100644 index 000000000..78cbc2825 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/logrus_test.go @@ -0,0 +1,386 @@ +package logrus + +import ( + "bytes" + "encoding/json" + "strconv" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" +) + +func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { + var buffer bytes.Buffer + var fields Fields + + logger := New() + logger.Out = &buffer + logger.Formatter = new(JSONFormatter) + + log(logger) + + err := json.Unmarshal(buffer.Bytes(), &fields) + assert.Nil(t, err) + + assertions(fields) +} + +func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { + var buffer bytes.Buffer + + logger := New() + logger.Out = &buffer + logger.Formatter = &TextFormatter{ + DisableColors: true, + } + + log(logger) + + fields := make(map[string]string) + for _, kv := range strings.Split(buffer.String(), " ") { + if !strings.Contains(kv, "=") { + continue + } + kvArr := strings.Split(kv, "=") + key := strings.TrimSpace(kvArr[0]) + val := kvArr[1] + if kvArr[1][0] == '"' { + var err error + val, err = strconv.Unquote(val) + assert.NoError(t, err) + } + fields[key] = val + } + assertions(fields) +} + +func TestPrint(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Print("test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test") + assert.Equal(t, fields["level"], "info") + }) +} + +func TestInfo(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Info("test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test") + assert.Equal(t, fields["level"], "info") + }) +} + +func TestWarn(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Warn("test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test") + assert.Equal(t, fields["level"], "warning") + }) +} + +func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Infoln("test", "test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test test") + }) +} + +func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Infoln("test", 10) + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test 10") + }) +} + +func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Infoln(10, 10) + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "10 10") + }) +} + +func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Infoln(10, 10) + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "10 10") + }) +} + +func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Info("test", 10) + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test10") + }) +} + +func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.Info("test", "test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "testtest") + }) +} + +func TestWithFieldsShouldAllowAssignments(t *testing.T) { + var buffer bytes.Buffer + var fields Fields + + logger := New() + logger.Out = &buffer + logger.Formatter = new(JSONFormatter) + + localLog := logger.WithFields(Fields{ + "key1": "value1", + }) + + localLog.WithField("key2", "value2").Info("test") + err := json.Unmarshal(buffer.Bytes(), &fields) + assert.Nil(t, err) + + assert.Equal(t, "value2", fields["key2"]) + assert.Equal(t, "value1", fields["key1"]) + + buffer = bytes.Buffer{} + fields = Fields{} + localLog.Info("test") + err = json.Unmarshal(buffer.Bytes(), &fields) + assert.Nil(t, err) + + _, ok := fields["key2"] + assert.Equal(t, false, ok) + assert.Equal(t, "value1", fields["key1"]) +} + +func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.WithField("msg", "hello").Info("test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test") + }) +} + +func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.WithField("msg", "hello").Info("test") + }, func(fields Fields) { + assert.Equal(t, fields["msg"], "test") + assert.Equal(t, fields["fields.msg"], "hello") + }) +} + +func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.WithField("time", "hello").Info("test") + }, func(fields Fields) { + assert.Equal(t, fields["fields.time"], "hello") + }) +} + +func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { + LogAndAssertJSON(t, func(log *Logger) { + log.WithField("level", 1).Info("test") + }, func(fields Fields) { + assert.Equal(t, fields["level"], "info") + assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only + }) +} + +func TestDefaultFieldsAreNotPrefixed(t *testing.T) { + LogAndAssertText(t, func(log *Logger) { + ll := log.WithField("herp", "derp") + ll.Info("hello") + ll.Info("bye") + }, func(fields map[string]string) { + for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { + if _, ok := fields[fieldName]; ok { + t.Fatalf("should not have prefixed %q: %v", fieldName, fields) + } + } + }) +} + +func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { + + var buffer bytes.Buffer + var fields Fields + + logger := New() + logger.Out = &buffer + logger.Formatter = new(JSONFormatter) + + llog := logger.WithField("context", "eating raw fish") + + llog.Info("looks delicious") + + err := json.Unmarshal(buffer.Bytes(), &fields) + assert.NoError(t, err, "should have decoded first message") + assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") + assert.Equal(t, fields["msg"], "looks delicious") + assert.Equal(t, fields["context"], "eating raw fish") + + buffer.Reset() + + llog.Warn("omg it is!") + + err = json.Unmarshal(buffer.Bytes(), &fields) + assert.NoError(t, err, "should have decoded second message") + assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") + assert.Equal(t, fields["msg"], "omg it is!") + assert.Equal(t, fields["context"], "eating raw fish") + assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") + +} + +func TestConvertLevelToString(t *testing.T) { + assert.Equal(t, "debug", DebugLevel.String()) + assert.Equal(t, "info", InfoLevel.String()) + assert.Equal(t, "warning", WarnLevel.String()) + assert.Equal(t, "error", ErrorLevel.String()) + assert.Equal(t, "fatal", FatalLevel.String()) + assert.Equal(t, "panic", PanicLevel.String()) +} + +func TestParseLevel(t *testing.T) { + l, err := ParseLevel("panic") + assert.Nil(t, err) + assert.Equal(t, PanicLevel, l) + + l, err = ParseLevel("PANIC") + assert.Nil(t, err) + assert.Equal(t, PanicLevel, l) + + l, err = ParseLevel("fatal") + assert.Nil(t, err) + assert.Equal(t, FatalLevel, l) + + l, err = ParseLevel("FATAL") + assert.Nil(t, err) + assert.Equal(t, FatalLevel, l) + + l, err = ParseLevel("error") + assert.Nil(t, err) + assert.Equal(t, ErrorLevel, l) + + l, err = ParseLevel("ERROR") + assert.Nil(t, err) + assert.Equal(t, ErrorLevel, l) + + l, err = ParseLevel("warn") + assert.Nil(t, err) + assert.Equal(t, WarnLevel, l) + + l, err = ParseLevel("WARN") + assert.Nil(t, err) + assert.Equal(t, WarnLevel, l) + + l, err = ParseLevel("warning") + assert.Nil(t, err) + assert.Equal(t, WarnLevel, l) + + l, err = ParseLevel("WARNING") + assert.Nil(t, err) + assert.Equal(t, WarnLevel, l) + + l, err = ParseLevel("info") + assert.Nil(t, err) + assert.Equal(t, InfoLevel, l) + + l, err = ParseLevel("INFO") + assert.Nil(t, err) + assert.Equal(t, InfoLevel, l) + + l, err = ParseLevel("debug") + assert.Nil(t, err) + assert.Equal(t, DebugLevel, l) + + l, err = ParseLevel("DEBUG") + assert.Nil(t, err) + assert.Equal(t, DebugLevel, l) + + l, err = ParseLevel("invalid") + assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) +} + +func TestGetSetLevelRace(t *testing.T) { + wg := sync.WaitGroup{} + for i := 0; i < 100; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + if i%2 == 0 { + SetLevel(InfoLevel) + } else { + GetLevel() + } + }(i) + + } + wg.Wait() +} + +func TestLoggingRace(t *testing.T) { + logger := New() + + var wg sync.WaitGroup + wg.Add(100) + + for i := 0; i < 100; i++ { + go func() { + logger.Info("info") + wg.Done() + }() + } + wg.Wait() +} + +// Compile test +func TestLogrusInterface(t *testing.T) { + var buffer bytes.Buffer + fn := func(l FieldLogger) { + b := l.WithField("key", "value") + b.Debug("Test") + } + // test logger + logger := New() + logger.Out = &buffer + fn(logger) + + // test Entry + e := logger.WithField("another", "value") + fn(e) +} + +// Implements io.Writer using channels for synchronization, so we can wait on +// the Entry.Writer goroutine to write in a non-racey way. This does assume that +// there is a single call to Logger.Out for each message. +type channelWriter chan []byte + +func (cw channelWriter) Write(p []byte) (int, error) { + cw <- p + return len(p), nil +} + +func TestEntryWriter(t *testing.T) { + cw := channelWriter(make(chan []byte, 1)) + log := New() + log.Out = cw + log.Formatter = new(JSONFormatter) + log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n")) + + bs := <-cw + var fields Fields + err := json.Unmarshal(bs, &fields) + assert.Nil(t, err) + assert.Equal(t, fields["foo"], "bar") + assert.Equal(t, fields["level"], "warning") +} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go new file mode 100644 index 000000000..d7b3893f3 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go @@ -0,0 +1,10 @@ +// +build darwin freebsd openbsd netbsd dragonfly +// +build !appengine + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TIOCGETA + +type Termios unix.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go new file mode 100644 index 000000000..88d7298e2 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/terminal_linux.go @@ -0,0 +1,14 @@ +// Based on ssh/terminal: +// 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 !appengine + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TCGETS + +type Termios unix.Termios diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go new file mode 100644 index 000000000..be412aa94 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/text_formatter.go @@ -0,0 +1,191 @@ +package logrus + +import ( + "bytes" + "fmt" + "io" + "os" + "sort" + "strings" + "sync" + "time" + + "golang.org/x/crypto/ssh/terminal" +) + +const ( + nocolor = 0 + red = 31 + green = 32 + yellow = 33 + blue = 36 + gray = 37 +) + +var ( + baseTimestamp time.Time +) + +func init() { + baseTimestamp = time.Now() +} + +// TextFormatter formats logs into text +type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool + + // QuoteEmptyFields will wrap empty fields in quotes if true + QuoteEmptyFields bool + + // Whether the logger's out is to a terminal + isTerminal bool + + sync.Once +} + +func (f *TextFormatter) init(entry *Entry) { + if entry.Logger != nil { + f.isTerminal = f.checkIfTerminal(entry.Logger.Out) + } +} + +func (f *TextFormatter) checkIfTerminal(w io.Writer) bool { + switch v := w.(type) { + case *os.File: + return terminal.IsTerminal(int(v.Fd())) + default: + return false + } +} + +// Format renders a single log entry +func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { + var b *bytes.Buffer + keys := make([]string, 0, len(entry.Data)) + for k := range entry.Data { + keys = append(keys, k) + } + + if !f.DisableSorting { + sort.Strings(keys) + } + if entry.Buffer != nil { + b = entry.Buffer + } else { + b = &bytes.Buffer{} + } + + prefixFieldClashes(entry.Data) + + f.Do(func() { f.init(entry) }) + + isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + if isColored { + f.printColored(b, entry, keys, timestampFormat) + } else { + if !f.DisableTimestamp { + f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) + } + f.appendKeyValue(b, "level", entry.Level.String()) + if entry.Message != "" { + f.appendKeyValue(b, "msg", entry.Message) + } + for _, key := range keys { + f.appendKeyValue(b, key, entry.Data[key]) + } + } + + b.WriteByte('\n') + return b.Bytes(), nil +} + +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { + var levelColor int + switch entry.Level { + case DebugLevel: + levelColor = gray + case WarnLevel: + levelColor = yellow + case ErrorLevel, FatalLevel, PanicLevel: + levelColor = red + default: + levelColor = blue + } + + levelText := strings.ToUpper(entry.Level.String())[0:4] + + if f.DisableTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) + } else if !f.FullTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message) + } else { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) + } + for _, k := range keys { + v := entry.Data[k] + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) + f.appendValue(b, v) + } +} + +func (f *TextFormatter) needsQuoting(text string) bool { + if f.QuoteEmptyFields && len(text) == 0 { + return true + } + for _, ch := range text { + if !((ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { + return true + } + } + return false +} + +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { + if b.Len() > 0 { + b.WriteByte(' ') + } + b.WriteString(key) + b.WriteByte('=') + f.appendValue(b, value) +} + +func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { + stringVal, ok := value.(string) + if !ok { + stringVal = fmt.Sprint(value) + } + + if !f.needsQuoting(stringVal) { + b.WriteString(stringVal) + } else { + b.WriteString(fmt.Sprintf("%q", stringVal)) + } +} diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter_test.go b/vendor/github.com/Sirupsen/logrus/text_formatter_test.go new file mode 100644 index 000000000..d93b931e5 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/text_formatter_test.go @@ -0,0 +1,141 @@ +package logrus + +import ( + "bytes" + "errors" + "fmt" + "strings" + "testing" + "time" +) + +func TestFormatting(t *testing.T) { + tf := &TextFormatter{DisableColors: true} + + testCases := []struct { + value string + expected string + }{ + {`foo`, "time=\"0001-01-01T00:00:00Z\" level=panic test=foo\n"}, + } + + for _, tc := range testCases { + b, _ := tf.Format(WithField("test", tc.value)) + + if string(b) != tc.expected { + t.Errorf("formatting expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected) + } + } +} + +func TestQuoting(t *testing.T) { + tf := &TextFormatter{DisableColors: true} + + checkQuoting := func(q bool, value interface{}) { + b, _ := tf.Format(WithField("test", value)) + idx := bytes.Index(b, ([]byte)("test=")) + cont := bytes.Contains(b[idx+5:], []byte("\"")) + if cont != q { + if q { + t.Errorf("quoting expected for: %#v", value) + } else { + t.Errorf("quoting not expected for: %#v", value) + } + } + } + + checkQuoting(false, "") + checkQuoting(false, "abcd") + checkQuoting(false, "v1.0") + checkQuoting(false, "1234567890") + checkQuoting(false, "/foobar") + checkQuoting(false, "foo_bar") + checkQuoting(false, "foo@bar") + checkQuoting(false, "foobar^") + checkQuoting(false, "+/-_^@f.oobar") + checkQuoting(true, "foobar$") + checkQuoting(true, "&foobar") + checkQuoting(true, "x y") + checkQuoting(true, "x,y") + checkQuoting(false, errors.New("invalid")) + checkQuoting(true, errors.New("invalid argument")) + + // Test for quoting empty fields. + tf.QuoteEmptyFields = true + checkQuoting(true, "") + checkQuoting(false, "abcd") + checkQuoting(true, errors.New("invalid argument")) +} + +func TestEscaping(t *testing.T) { + tf := &TextFormatter{DisableColors: true} + + testCases := []struct { + value string + expected string + }{ + {`ba"r`, `ba\"r`}, + {`ba'r`, `ba'r`}, + } + + for _, tc := range testCases { + b, _ := tf.Format(WithField("test", tc.value)) + if !bytes.Contains(b, []byte(tc.expected)) { + t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected) + } + } +} + +func TestEscaping_Interface(t *testing.T) { + tf := &TextFormatter{DisableColors: true} + + ts := time.Now() + + testCases := []struct { + value interface{} + expected string + }{ + {ts, fmt.Sprintf("\"%s\"", ts.String())}, + {errors.New("error: something went wrong"), "\"error: something went wrong\""}, + } + + for _, tc := range testCases { + b, _ := tf.Format(WithField("test", tc.value)) + if !bytes.Contains(b, []byte(tc.expected)) { + t.Errorf("escaping expected for %q (result was %q instead of %q)", tc.value, string(b), tc.expected) + } + } +} + +func TestTimestampFormat(t *testing.T) { + checkTimeStr := func(format string) { + customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} + customStr, _ := customFormatter.Format(WithField("test", "test")) + timeStart := bytes.Index(customStr, ([]byte)("time=")) + timeEnd := bytes.Index(customStr, ([]byte)("level=")) + timeStr := customStr[timeStart+5+len("\"") : timeEnd-1-len("\"")] + if format == "" { + format = time.RFC3339 + } + _, e := time.Parse(format, (string)(timeStr)) + if e != nil { + t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) + } + } + + checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") + checkTimeStr("Mon Jan _2 15:04:05 2006") + checkTimeStr("") +} + +func TestDisableTimestampWithColoredOutput(t *testing.T) { + tf := &TextFormatter{DisableTimestamp: true, ForceColors: true} + + b, _ := tf.Format(WithField("test", "test")) + if strings.Contains(string(b), "[0000]") { + t.Error("timestamp not expected when DisableTimestamp is true") + } +} + +// TODO add tests for sorting etc., this requires a parser for the text +// formatter output. diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go new file mode 100644 index 000000000..7bdebedc6 --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/writer.go @@ -0,0 +1,62 @@ +package logrus + +import ( + "bufio" + "io" + "runtime" +) + +func (logger *Logger) Writer() *io.PipeWriter { + return logger.WriterLevel(InfoLevel) +} + +func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { + return NewEntry(logger).WriterLevel(level) +} + +func (entry *Entry) Writer() *io.PipeWriter { + return entry.WriterLevel(InfoLevel) +} + +func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { + reader, writer := io.Pipe() + + var printFunc func(args ...interface{}) + + switch level { + case DebugLevel: + printFunc = entry.Debug + case InfoLevel: + printFunc = entry.Info + case WarnLevel: + printFunc = entry.Warn + case ErrorLevel: + printFunc = entry.Error + case FatalLevel: + printFunc = entry.Fatal + case PanicLevel: + printFunc = entry.Panic + default: + printFunc = entry.Print + } + + go entry.writerScanner(reader, printFunc) + runtime.SetFinalizer(writer, writerFinalizer) + + return writer +} + +func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + printFunc(scanner.Text()) + } + if err := scanner.Err(); err != nil { + entry.Errorf("Error while reading from Writer: %s", err) + } + reader.Close() +} + +func writerFinalizer(writer *io.PipeWriter) { + writer.Close() +} diff --git a/vendor/github.com/apache/thrift/.gitignore b/vendor/github.com/apache/thrift/.gitignore index bdb84ea59..3fd7826e5 100644 --- a/vendor/github.com/apache/thrift/.gitignore +++ b/vendor/github.com/apache/thrift/.gitignore @@ -21,6 +21,7 @@ *.swp *.hi *~ +tags .*project junit*.properties @@ -36,6 +37,7 @@ node_modules compile test-driver erl_crash.dump +package-lock.json project.lock.json .sonar @@ -116,6 +118,7 @@ project.lock.json /lib/cpp/test/TFileTransportTest /lib/cpp/test/TInterruptTest /lib/cpp/test/TNonblockingServerTest +/lib/cpp/test/TNonblockingSSLServerTest /lib/cpp/test/TPipedTransportTest /lib/cpp/test/TServerIntegrationTest /lib/cpp/test/TSocketInterruptTest @@ -221,6 +224,7 @@ project.lock.json /lib/java/build /lib/js/dist /lib/js/doc +/lib/js/package-lock.json /lib/js/test/build /lib/netcore/**/.vs /lib/netcore/**/bin @@ -265,6 +269,8 @@ project.lock.json /lib/php/test/packages/ /lib/py/dist/ /lib/erl/logs/ +/lib/go/pkg +/lib/go/src /lib/go/test/gopath/ /lib/go/test/ThriftTest.thrift /lib/rs/target/ @@ -299,13 +305,16 @@ project.lock.json /test/log/ /test/test.log /test/erl/.generated +/test/erl/.rebar /test/erl/ebin /test/go/bin/ /test/go/ThriftTest.thrift /test/go/gopath /test/go/pkg/ /test/go/src/code.google.com/ +/test/go/src/common/mock_handler.go /test/go/src/github.com/golang/ +/test/go/src/golang.org/ /test/go/src/gen/ /test/go/src/thrift /test/haxe/bin @@ -348,11 +357,13 @@ project.lock.json /tutorial/delphi/DelphiClient/*.identcache /tutorial/delphi/DelphiServer/*.identcache /tutorial/delphi/DelphiServer/*.local +/tutorial/go/gopath /tutorial/go/go-tutorial /tutorial/go/calculator-remote /tutorial/go/src/shared /tutorial/go/src/tutorial /tutorial/go/src/git.apache.org +/tutorial/go/src/golang.org /tutorial/haxe/bin /tutorial/hs/dist/ /tutorial/java/build/ diff --git a/vendor/github.com/apache/thrift/.travis.yml b/vendor/github.com/apache/thrift/.travis.yml index 6b0b9afd5..443960bee 100644 --- a/vendor/github.com/apache/thrift/.travis.yml +++ b/vendor/github.com/apache/thrift/.travis.yml @@ -38,96 +38,54 @@ env: - SCRIPT="cmake.sh" - BUILD_ARG="" - BUILD_ENV="-e CC=clang -e CXX=clang++" - - DISTRO=ubuntu + - DISTRO=ubuntu-xenial - BUILD_LIBS="CPP C_GLIB HASKELL JAVA PYTHON TESTING TUTORIALS" # only meaningful for CMake builds matrix: - - TEST_NAME="Cross Language Tests (Header, Multiplexed and JSON Protocols)" + - TEST_NAME="Cross Language Tests (Binary, Header, JSON Protocols)" SCRIPT="cross-test.sh" - BUILD_ARG="-'(header|multiplexed|json)'" + BUILD_ARG="-'(binary|header|json)'" BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - - TEST_NAME="Cross Language Tests (Binary Protocol)" + - TEST_NAME="Cross Language Tests (Compact and Multiplexed Protocols)" SCRIPT="cross-test.sh" - BUILD_ARG="-'(binary)'" + BUILD_ARG="-'(compact|multiplexed)'" BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - - TEST_NAME="Cross Language Tests (Compact Protocol)" - SCRIPT="cross-test.sh" - BUILD_ARG="-'(compact)'" - BUILD_ENV="-e CC=clang -e CXX=clang++ -e THRIFT_CROSSTEST_CONCURRENCY=4" - - # TODO: Remove them once migrated to CMake # Autotools builds - - TEST_NAME="C C++ C# D Erlang Haxe Go (automake)" + # TODO: Remove them once migrated to CMake + - TEST_NAME="Autotools (CentOS 7.3)" + DISTRO=centos-7.3 SCRIPT="autotools.sh" - BUILD_ARG="--without-dart --without-haskell --without-java --without-lua --without-nodejs --without-perl --without-php --without-php_extension --without-python --without-ruby --without-rust" - - - TEST_NAME="C C++ Plugin Haskell Perl - GCC (automake)" - SCRIPT="autotools.sh" - BUILD_ARG="--enable-plugin --without-csharp --without-java --without-erlang --without-nodejs --without-lua --without-python --without-perl --without-php --without-php_extension --without-dart --without-ruby --without-haskell --without-go --without-haxe --without-d --without-rust" BUILD_ENV="-e CC=gcc -e CXX=g++" + BUILD_ARG="--without-cpp --without-csharp --without-c_glib --without-d -without-dart --without-erlang --without-go --without-haskell --without-haxe" - - TEST_NAME="Java Lua PHP Ruby Dart Node.js Python Rust (automake)" + - TEST_NAME="Autotools (Ubuntu Xenial)" SCRIPT="autotools.sh" - BUILD_ARG="--without-cpp --without-c_glib --without-csharp --without-d --without-erlang --without-go --without-haxe" + BUILD_ENV="-e CC=gcc -e CXX=g++" + BUILD_ARG="--enable-plugin --without-java --without-lua --without-nodejs --without-perl --without-php --without-php_extension --without-python --without-py3 --without-ruby --without-rust" # CMake builds - - TEST_NAME="All (Debian)" - DISTRO=debian + - TEST_NAME="CMake (CentOS 7.3)" + DISTRO=centos-7.3 - - TEST_NAME="C C++ - GCC" - BUILD_LIBS="CPP C_GLIB TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" + - TEST_NAME="CMake (Ubuntu Xenial)" - - TEST_NAME="C++ (Boost Thread - GCC)" + # C++ specific options: compiler plug-in, threading model + - TEST_NAME="C++ (Boost Thread)" BUILD_LIBS="CPP TESTING TUTORIALS" BUILD_ARG="-DWITH_BOOSTTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - TEST_NAME="C++ Plugin (Std Thread)" BUILD_LIBS="CPP TESTING TUTORIALS" BUILD_ARG="-DWITH_PLUGIN=ON -DWITH_STDTHREADS=ON -DWITH_PYTHON=OFF -DWITH_C_GLIB=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - - TEST_NAME="Compiler (mingw)" - BUILD_LIBS="" - BUILD_ARG="-DCMAKE_TOOLCHAIN_FILE=../build/cmake/mingw32-toolchain.cmake -DBUILD_COMPILER=ON -DBUILD_LIBRARIES=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF" - BUILD_ENV="" - - - TEST_NAME="All - GCC (CentOS)" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=centos - - - TEST_NAME="C C++ - Clang (CentOS)" - BUILD_LIBS="CPP C_GLIB TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - DISTRO=centos - - - TEST_NAME="Python 2.6 (CentOS 6)" - BUILD_LIBS="PYTHON TESTING TUTORIALS" - BUILD_ARG="-DWITH_PYTHON=ON -DWITH_CPP=OFF -DWITH_JAVA=OFF -DWITH_HASKELL=OFF" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=centos6 - # Distribution - TEST_NAME="make dist" SCRIPT="make-dist.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - TEST_NAME="Debian Packages" SCRIPT="dpkg.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - - - TEST_NAME="make dist (Debian)" - SCRIPT="make-dist.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=debian - - - TEST_NAME="Debian Packages (Debian)" - SCRIPT="dpkg.sh" - BUILD_ENV="-e CC=gcc -e CXX=g++" - DISTRO=debian # C and C++ undefined behavior. This wraps autotools.sh, but each binary crashes if # undefined behavior occurs. Skips the known flaky tests. diff --git a/vendor/github.com/apache/thrift/aclocal/ax_boost_base.m4 b/vendor/github.com/apache/thrift/aclocal/ax_boost_base.m4 index b496020e4..19c71b675 100644 --- a/vendor/github.com/apache/thrift/aclocal/ax_boost_base.m4 +++ b/vendor/github.com/apache/thrift/aclocal/ax_boost_base.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_boost_base.html +# https://www.gnu.org/software/autoconf-archive/ax_boost_base.html # =========================================================================== # # SYNOPSIS @@ -33,7 +33,15 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 23 +#serial 42 + +# example boost program (need to pass version) +m4_define([_AX_BOOST_BASE_PROGRAM], + [AC_LANG_PROGRAM([[ +#include +]],[[ +(void) ((void)sizeof(char[1 - 2*!!((BOOST_VERSION) < ($1))])); +]])]) AC_DEFUN([AX_BOOST_BASE], [ @@ -44,101 +52,121 @@ AC_ARG_WITH([boost], or disable it (ARG=no) @<:@ARG=yes@:>@ ])], [ - if test "$withval" = "no"; then - want_boost="no" - elif test "$withval" = "yes"; then - want_boost="yes" - ac_boost_path="" - else - want_boost="yes" - ac_boost_path="$withval" - fi + AS_CASE([$withval], + [no],[want_boost="no";_AX_BOOST_BASE_boost_path=""], + [yes],[want_boost="yes";_AX_BOOST_BASE_boost_path=""], + [want_boost="yes";_AX_BOOST_BASE_boost_path="$withval"]) ], [want_boost="yes"]) AC_ARG_WITH([boost-libdir], - AS_HELP_STRING([--with-boost-libdir=LIB_DIR], - [Force given directory for boost libraries. Note that this will override library path detection, so use this parameter only if default library detection fails and you know exactly where your boost libraries are located.]), - [ - if test -d "$withval" - then - ac_boost_lib_path="$withval" - else - AC_MSG_ERROR(--with-boost-libdir expected directory name) - fi - ], - [ac_boost_lib_path=""] -) + [AS_HELP_STRING([--with-boost-libdir=LIB_DIR], + [Force given directory for boost libraries. + Note that this will override library path detection, + so use this parameter only if default library detection fails + and you know exactly where your boost libraries are located.])], + [ + AS_IF([test -d "$withval"], + [_AX_BOOST_BASE_boost_lib_path="$withval"], + [AC_MSG_ERROR([--with-boost-libdir expected directory name])]) + ], + [_AX_BOOST_BASE_boost_lib_path=""]) -if test "x$want_boost" = "xyes"; then - boost_lib_version_req=ifelse([$1], ,1.20.0,$1) - boost_lib_version_req_shorten=`expr $boost_lib_version_req : '\([[0-9]]*\.[[0-9]]*\)'` - boost_lib_version_req_major=`expr $boost_lib_version_req : '\([[0-9]]*\)'` - boost_lib_version_req_minor=`expr $boost_lib_version_req : '[[0-9]]*\.\([[0-9]]*\)'` - boost_lib_version_req_sub_minor=`expr $boost_lib_version_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'` - if test "x$boost_lib_version_req_sub_minor" = "x" ; then - boost_lib_version_req_sub_minor="0" - fi - WANT_BOOST_VERSION=`expr $boost_lib_version_req_major \* 100000 \+ $boost_lib_version_req_minor \* 100 \+ $boost_lib_version_req_sub_minor` - AC_MSG_CHECKING(for boostlib >= $boost_lib_version_req) +BOOST_LDFLAGS="" +BOOST_CPPFLAGS="" +AS_IF([test "x$want_boost" = "xyes"], + [_AX_BOOST_BASE_RUNDETECT([$1],[$2],[$3])]) +AC_SUBST(BOOST_CPPFLAGS) +AC_SUBST(BOOST_LDFLAGS) +]) + + +# convert a version string in $2 to numeric and affect to polymorphic var $1 +AC_DEFUN([_AX_BOOST_BASE_TONUMERICVERSION],[ + AS_IF([test "x$2" = "x"],[_AX_BOOST_BASE_TONUMERICVERSION_req="1.20.0"],[_AX_BOOST_BASE_TONUMERICVERSION_req="$2"]) + _AX_BOOST_BASE_TONUMERICVERSION_req_shorten=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\.[[0-9]]*\)'` + _AX_BOOST_BASE_TONUMERICVERSION_req_major=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '\([[0-9]]*\)'` + AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_major" = "x"], + [AC_MSG_ERROR([You should at least specify libboost major version])]) + _AX_BOOST_BASE_TONUMERICVERSION_req_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.\([[0-9]]*\)'` + AS_IF([test "x$_AX_BOOST_BASE_TONUMERICVERSION_req_minor" = "x"], + [_AX_BOOST_BASE_TONUMERICVERSION_req_minor="0"]) + _AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req : '[[0-9]]*\.[[0-9]]*\.\([[0-9]]*\)'` + AS_IF([test "X$_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor" = "X"], + [_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor="0"]) + _AX_BOOST_BASE_TONUMERICVERSION_RET=`expr $_AX_BOOST_BASE_TONUMERICVERSION_req_major \* 100000 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_minor \* 100 \+ $_AX_BOOST_BASE_TONUMERICVERSION_req_sub_minor` + AS_VAR_SET($1,$_AX_BOOST_BASE_TONUMERICVERSION_RET) +]) + +dnl Run the detection of boost should be run only if $want_boost +AC_DEFUN([_AX_BOOST_BASE_RUNDETECT],[ + _AX_BOOST_BASE_TONUMERICVERSION(WANT_BOOST_VERSION,[$1]) succeeded=no + + AC_REQUIRE([AC_CANONICAL_HOST]) dnl On 64-bit systems check for system libraries in both lib64 and lib. dnl The former is specified by FHS, but e.g. Debian does not adhere to dnl this (as it rises problems for generic multi-arch support). dnl The last entry in the list is chosen by default when no libraries dnl are found, e.g. when only header-only libraries are installed! - libsubdirs="lib" - ax_arch=`uname -m` - case $ax_arch in - x86_64|ppc64|s390x|sparc64|aarch64) - libsubdirs="lib64 lib lib64" - ;; - esac + AS_CASE([${host_cpu}], + [x86_64],[libsubdirs="lib64 libx32 lib lib64"], + [ppc64|s390x|sparc64|aarch64|ppc64le],[libsubdirs="lib64 lib lib64"], + [libsubdirs="lib"], + ) dnl allow for real multi-arch paths e.g. /usr/lib/x86_64-linux-gnu. Give dnl them priority over the other paths since, if libs are found there, they dnl are almost assuredly the ones desired. - AC_REQUIRE([AC_CANONICAL_HOST]) - libsubdirs="lib/${host_cpu}-${host_os} $libsubdirs" - - case ${host_cpu} in - i?86) - libsubdirs="lib/i386-${host_os} $libsubdirs" - ;; - esac + AS_CASE([${host_cpu}], + [i?86],[multiarch_libsubdir="lib/i386-${host_os}"], + [multiarch_libsubdir="lib/${host_cpu}-${host_os}"] + ) dnl first we check the system location for boost libraries dnl this location ist chosen if boost libraries are installed with the --layout=system option dnl or if you install boost with RPM - if test "$ac_boost_path" != ""; then - BOOST_CPPFLAGS="-I$ac_boost_path/include" - for ac_boost_path_tmp in $libsubdirs; do - if test -d "$ac_boost_path"/"$ac_boost_path_tmp" ; then - BOOST_LDFLAGS="-L$ac_boost_path/$ac_boost_path_tmp" - break - fi - done - elif test "$cross_compiling" != yes; then - for ac_boost_path_tmp in $lt_sysroot/usr $lt_sysroot/usr/local $lt_sysroot/opt $lt_sysroot/opt/local ; do - if test -d "$ac_boost_path_tmp/include/boost" && test -r "$ac_boost_path_tmp/include/boost"; then - for libsubdir in $libsubdirs ; do - if ls "$ac_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi + AS_IF([test "x$_AX_BOOST_BASE_boost_path" != "x"],[ + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) includes in "$_AX_BOOST_BASE_boost_path/include"]) + AS_IF([test -d "$_AX_BOOST_BASE_boost_path/include" && test -r "$_AX_BOOST_BASE_boost_path/include"],[ + AC_MSG_RESULT([yes]) + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include" + for _AX_BOOST_BASE_boost_path_tmp in $multiarch_libsubdir $libsubdirs; do + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION) lib path in "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp"]) + AS_IF([test -d "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" && test -r "$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp" ],[ + AC_MSG_RESULT([yes]) + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$_AX_BOOST_BASE_boost_path_tmp"; + break; + ], + [AC_MSG_RESULT([no])]) + done],[ + AC_MSG_RESULT([no])]) + ],[ + if test X"$cross_compiling" = Xyes; then + search_libsubdirs=$multiarch_libsubdir + else + search_libsubdirs="$multiarch_libsubdir $libsubdirs" + fi + for _AX_BOOST_BASE_boost_path_tmp in /usr /usr/local /opt /opt/local ; do + if test -d "$_AX_BOOST_BASE_boost_path_tmp/include/boost" && test -r "$_AX_BOOST_BASE_boost_path_tmp/include/boost" ; then + for libsubdir in $search_libsubdirs ; do + if ls "$_AX_BOOST_BASE_boost_path_tmp/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done - BOOST_LDFLAGS="-L$ac_boost_path_tmp/$libsubdir" - BOOST_CPPFLAGS="-I$ac_boost_path_tmp/include" + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path_tmp/$libsubdir" + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path_tmp/include" break; fi done - fi + ]) dnl overwrite ld flags if we have required special directory with dnl --with-boost-libdir parameter - if test "$ac_boost_lib_path" != ""; then - BOOST_LDFLAGS="-L$ac_boost_lib_path" - fi + AS_IF([test "x$_AX_BOOST_BASE_boost_lib_path" != "x"], + [BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_lib_path"]) + AC_MSG_CHECKING([for boostlib >= $1 ($WANT_BOOST_VERSION)]) CPPFLAGS_SAVED="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" export CPPFLAGS @@ -149,15 +177,7 @@ if test "x$want_boost" = "xyes"; then AC_REQUIRE([AC_PROG_CXX]) AC_LANG_PUSH(C++) - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - @%:@include - ]], [[ - #if BOOST_VERSION >= $WANT_BOOST_VERSION - // Everything is okay - #else - # error Boost version is too old - #endif - ]])],[ + AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes @@ -169,30 +189,50 @@ if test "x$want_boost" = "xyes"; then dnl if we found no boost with system layout we search for boost libraries dnl built and installed without the --layout=system option or for a staged(not installed) version - if test "x$succeeded" != "xyes"; then + if test "x$succeeded" != "xyes" ; then + CPPFLAGS="$CPPFLAGS_SAVED" + LDFLAGS="$LDFLAGS_SAVED" + BOOST_CPPFLAGS= + if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then + BOOST_LDFLAGS= + fi _version=0 - if test "$ac_boost_path" != ""; then - if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then - for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do - _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` + if test -n "$_AX_BOOST_BASE_boost_path" ; then + if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path"; then + for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do + _version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` - if test "$V_CHECK" = "1" ; then + if test "x$V_CHECK" = "x1" ; then _version=$_version_tmp fi VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` - BOOST_CPPFLAGS="-I$ac_boost_path/include/boost-$VERSION_UNDERSCORE" + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path/include/boost-$VERSION_UNDERSCORE" done + dnl if nothing found search for layout used in Windows distributions + if test -z "$BOOST_CPPFLAGS"; then + if test -d "$_AX_BOOST_BASE_boost_path/boost" && test -r "$_AX_BOOST_BASE_boost_path/boost"; then + BOOST_CPPFLAGS="-I$_AX_BOOST_BASE_boost_path" + fi + fi + dnl if we found something and BOOST_LDFLAGS was unset before + dnl (because "$_AX_BOOST_BASE_boost_lib_path" = ""), set it here. + if test -n "$BOOST_CPPFLAGS" && test -z "$BOOST_LDFLAGS"; then + for libsubdir in $libsubdirs ; do + if ls "$_AX_BOOST_BASE_boost_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi + done + BOOST_LDFLAGS="-L$_AX_BOOST_BASE_boost_path/$libsubdir" + fi fi else - if test "$cross_compiling" != yes; then - for ac_boost_path in $lt_sysroot/usr $lt_sysroot/usr/local $lt_sysroot/opt $lt_sysroot/opt/local ; do - if test -d "$ac_boost_path" && test -r "$ac_boost_path"; then - for i in `ls -d $ac_boost_path/include/boost-* 2>/dev/null`; do - _version_tmp=`echo $i | sed "s#$ac_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` + if test "x$cross_compiling" != "xyes" ; then + for _AX_BOOST_BASE_boost_path in /usr /usr/local /opt /opt/local ; do + if test -d "$_AX_BOOST_BASE_boost_path" && test -r "$_AX_BOOST_BASE_boost_path" ; then + for i in `ls -d $_AX_BOOST_BASE_boost_path/include/boost-* 2>/dev/null`; do + _version_tmp=`echo $i | sed "s#$_AX_BOOST_BASE_boost_path##" | sed 's/\/include\/boost-//' | sed 's/_/./'` V_CHECK=`expr $_version_tmp \> $_version` - if test "$V_CHECK" = "1" ; then + if test "x$V_CHECK" = "x1" ; then _version=$_version_tmp - best_path=$ac_boost_path + best_path=$_AX_BOOST_BASE_boost_path fi done fi @@ -200,7 +240,7 @@ if test "x$want_boost" = "xyes"; then VERSION_UNDERSCORE=`echo $_version | sed 's/\./_/'` BOOST_CPPFLAGS="-I$best_path/include/boost-$VERSION_UNDERSCORE" - if test "$ac_boost_lib_path" = ""; then + if test -z "$_AX_BOOST_BASE_boost_lib_path" ; then for libsubdir in $libsubdirs ; do if ls "$best_path/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done @@ -208,7 +248,7 @@ if test "x$want_boost" = "xyes"; then fi fi - if test "x$BOOST_ROOT" != "x"; then + if test -n "$BOOST_ROOT" ; then for libsubdir in $libsubdirs ; do if ls "$BOOST_ROOT/stage/$libsubdir/libboost_"* >/dev/null 2>&1 ; then break; fi done @@ -217,7 +257,7 @@ if test "x$want_boost" = "xyes"; then stage_version=`echo $version_dir | sed 's/boost_//' | sed 's/_/./g'` stage_version_shorten=`expr $stage_version : '\([[0-9]]*\.[[0-9]]*\)'` V_CHECK=`expr $stage_version_shorten \>\= $_version` - if test "$V_CHECK" = "1" -a "$ac_boost_lib_path" = "" ; then + if test "x$V_CHECK" = "x1" && test -z "$_AX_BOOST_BASE_boost_lib_path" ; then AC_MSG_NOTICE(We will use a staged boost library from $BOOST_ROOT) BOOST_CPPFLAGS="-I$BOOST_ROOT" BOOST_LDFLAGS="-L$BOOST_ROOT/stage/$libsubdir" @@ -232,15 +272,7 @@ if test "x$want_boost" = "xyes"; then export LDFLAGS AC_LANG_PUSH(C++) - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - @%:@include - ]], [[ - #if BOOST_VERSION >= $WANT_BOOST_VERSION - // Everything is okay - #else - # error Boost version is too old - #endif - ]])],[ + AC_COMPILE_IFELSE([_AX_BOOST_BASE_PROGRAM($WANT_BOOST_VERSION)],[ AC_MSG_RESULT(yes) succeeded=yes found_system=yes @@ -249,17 +281,15 @@ if test "x$want_boost" = "xyes"; then AC_LANG_POP([C++]) fi - if test "$succeeded" != "yes" ; then - if test "$_version" = "0" ; then - AC_MSG_NOTICE([[We could not detect the boost libraries (version $boost_lib_version_req_shorten or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in . See http://randspringer.de/boost for more documentation.]]) + if test "x$succeeded" != "xyes" ; then + if test "x$_version" = "x0" ; then + AC_MSG_NOTICE([[We could not detect the boost libraries (version $1 or higher). If you have a staged boost library (still not installed) please specify \$BOOST_ROOT in your environment and do not give a PATH to --with-boost option. If you are sure you have boost installed, then check your version number looking in . See http://randspringer.de/boost for more documentation.]]) else AC_MSG_NOTICE([Your boost libraries seems to old (version $_version).]) fi # execute ACTION-IF-NOT-FOUND (if present): ifelse([$3], , :, [$3]) else - AC_SUBST(BOOST_CPPFLAGS) - AC_SUBST(BOOST_LDFLAGS) AC_DEFINE(HAVE_BOOST,,[define if the Boost library is available]) # execute ACTION-IF-FOUND (if present): ifelse([$2], , :, [$2]) @@ -267,6 +297,5 @@ if test "x$want_boost" = "xyes"; then CPPFLAGS="$CPPFLAGS_SAVED" LDFLAGS="$LDFLAGS_SAVED" -fi ]) diff --git a/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx.m4 b/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx.m4 new file mode 100644 index 000000000..5032bba80 --- /dev/null +++ b/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx.m4 @@ -0,0 +1,982 @@ +# =========================================================================== +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) +# +# DESCRIPTION +# +# Check for baseline language coverage in the compiler for the specified +# version of the C++ standard. If necessary, add switches to CXX and +# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) +# or '14' (for the C++14 standard). +# +# The second argument, if specified, indicates whether you insist on an +# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. +# -std=c++11). If neither is specified, you get whatever works, with +# preference for an extended mode. +# +# The third argument, if specified 'mandatory' or if left unspecified, +# indicates that baseline support for the specified C++ standard is +# required and that the macro should error out if no mode with that +# support is found. If specified 'optional', then configuration proceeds +# regardless, after defining HAVE_CXX${VERSION} if and only if a +# supporting mode is found. +# +# LICENSE +# +# Copyright (c) 2008 Benjamin Kosnik +# Copyright (c) 2012 Zack Weinberg +# Copyright (c) 2013 Roy Stogner +# Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov +# Copyright (c) 2015 Paul Norman +# Copyright (c) 2015 Moritz Klammler +# Copyright (c) 2016 Krzesimir Nowak +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice +# and this notice are preserved. This file is offered as-is, without any +# warranty. + +#serial 7 + +dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro +dnl (serial version number 13). + +AX_REQUIRE_DEFINED([AC_MSG_WARN]) +AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl + m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], + [$1], [14], [ax_cxx_compile_alternatives="14 1y"], + [$1], [17], [ax_cxx_compile_alternatives="17 1z"], + [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$2], [], [], + [$2], [ext], [], + [$2], [noext], [], + [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl + m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], + [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], + [$3], [optional], [ax_cxx_compile_cxx$1_required=false], + [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) + AC_LANG_PUSH([C++])dnl + ac_success=no + AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, + ax_cv_cxx_compile_cxx$1, + [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [ax_cv_cxx_compile_cxx$1=yes], + [ax_cv_cxx_compile_cxx$1=no])]) + if test x$ax_cv_cxx_compile_cxx$1 = xyes; then + ac_success=yes + fi + + m4_if([$2], [noext], [], [dnl + if test x$ac_success = xno; then + for alternative in ${ax_cxx_compile_alternatives}; do + switch="-std=gnu++${alternative}" + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + fi]) + + m4_if([$2], [ext], [], [dnl + if test x$ac_success = xno; then + dnl HP's aCC needs +std=c++11 according to: + dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf + dnl Cray's crayCC needs "-h std=c++11" + for alternative in ${ax_cxx_compile_alternatives}; do + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, + $cachevar, + [ac_save_CXX="$CXX" + CXX="$CXX $switch" + AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], + [eval $cachevar=yes], + [eval $cachevar=no]) + CXX="$ac_save_CXX"]) + if eval test x\$$cachevar = xyes; then + CXX="$CXX $switch" + if test -n "$CXXCPP" ; then + CXXCPP="$CXXCPP $switch" + fi + ac_success=yes + break + fi + done + if test x$ac_success = xyes; then + break + fi + done + fi]) + AC_LANG_POP([C++]) + if test x$ax_cxx_compile_cxx$1_required = xtrue; then + if test x$ac_success = xno; then + AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) + fi + fi + if test x$ac_success = xno; then + HAVE_CXX$1=0 + AC_MSG_NOTICE([No compiler with C++$1 support was found]) + else + HAVE_CXX$1=1 + AC_DEFINE(HAVE_CXX$1,1, + [define if the compiler supports basic C++$1 syntax]) + fi + AC_SUBST(HAVE_CXX$1) + m4_if([$1], [17], [AC_MSG_WARN([C++17 is not yet standardized, so the checks may change in incompatible ways anytime])]) +]) + + +dnl Test body for checking C++11 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 +) + + +dnl Test body for checking C++14 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 +) + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], + _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 +) + +dnl Tests for new features in C++11 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ + +// If the compiler admits that it is not ready for C++11, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201103L + +#error "This is not a C++11 compiler" + +#else + +namespace cxx11 +{ + + namespace test_static_assert + { + + template + struct check + { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); + }; + + } + + namespace test_final_override + { + + struct Base + { + virtual void f() {} + }; + + struct Derived : public Base + { + virtual void f() override {} + }; + + } + + namespace test_double_right_angle_brackets + { + + template < typename T > + struct check {}; + + typedef check single_type; + typedef check> double_type; + typedef check>> triple_type; + typedef check>>> quadruple_type; + + } + + namespace test_decltype + { + + int + f() + { + int a = 1; + decltype(a) b = 2; + return a + b; + } + + } + + namespace test_type_deduction + { + + template < typename T1, typename T2 > + struct is_same + { + static const bool value = false; + }; + + template < typename T > + struct is_same + { + static const bool value = true; + }; + + template < typename T1, typename T2 > + auto + add(T1 a1, T2 a2) -> decltype(a1 + a2) + { + return a1 + a2; + } + + int + test(const int c, volatile int v) + { + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == false, ""); + auto ac = c; + auto av = v; + auto sumi = ac + av + 'x'; + auto sumf = ac + av + 1.0; + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == true, ""); + static_assert(is_same::value == false, ""); + static_assert(is_same::value == true, ""); + return (sumf > 0.0) ? sumi : add(c, v); + } + + } + + namespace test_noexcept + { + + int f() { return 0; } + int g() noexcept { return 0; } + + static_assert(noexcept(f()) == false, ""); + static_assert(noexcept(g()) == true, ""); + + } + + namespace test_constexpr + { + + template < typename CharT > + unsigned long constexpr + strlen_c_r(const CharT *const s, const unsigned long acc) noexcept + { + return *s ? strlen_c_r(s + 1, acc + 1) : acc; + } + + template < typename CharT > + unsigned long constexpr + strlen_c(const CharT *const s) noexcept + { + return strlen_c_r(s, 0UL); + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("1") == 1UL, ""); + static_assert(strlen_c("example") == 7UL, ""); + static_assert(strlen_c("another\0example") == 7UL, ""); + + } + + namespace test_rvalue_references + { + + template < int N > + struct answer + { + static constexpr int value = N; + }; + + answer<1> f(int&) { return answer<1>(); } + answer<2> f(const int&) { return answer<2>(); } + answer<3> f(int&&) { return answer<3>(); } + + void + test() + { + int i = 0; + const int c = 0; + static_assert(decltype(f(i))::value == 1, ""); + static_assert(decltype(f(c))::value == 2, ""); + static_assert(decltype(f(0))::value == 3, ""); + } + + } + + namespace test_uniform_initialization + { + + struct test + { + static const int zero {}; + static const int one {1}; + }; + + static_assert(test::zero == 0, ""); + static_assert(test::one == 1, ""); + + } + + namespace test_lambdas + { + + void + test1() + { + auto lambda1 = [](){}; + auto lambda2 = lambda1; + lambda1(); + lambda2(); + } + + int + test2() + { + auto a = [](int i, int j){ return i + j; }(1, 2); + auto b = []() -> int { return '0'; }(); + auto c = [=](){ return a + b; }(); + auto d = [&](){ return c; }(); + auto e = [a, &b](int x) mutable { + const auto identity = [](int y){ return y; }; + for (auto i = 0; i < a; ++i) + a += b--; + return x + identity(a + b); + }(0); + return a + b + c + d + e; + } + + int + test3() + { + const auto nullary = [](){ return 0; }; + const auto unary = [](int x){ return x; }; + using nullary_t = decltype(nullary); + using unary_t = decltype(unary); + const auto higher1st = [](nullary_t f){ return f(); }; + const auto higher2nd = [unary](nullary_t f1){ + return [unary, f1](unary_t f2){ return f2(unary(f1())); }; + }; + return higher1st(nullary) + higher2nd(nullary)(unary); + } + + } + + namespace test_variadic_templates + { + + template + struct sum; + + template + struct sum + { + static constexpr auto value = N0 + sum::value; + }; + + template <> + struct sum<> + { + static constexpr auto value = 0; + }; + + static_assert(sum<>::value == 0, ""); + static_assert(sum<1>::value == 1, ""); + static_assert(sum<23>::value == 23, ""); + static_assert(sum<1, 2>::value == 3, ""); + static_assert(sum<5, 5, 11>::value == 21, ""); + static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); + + } + + // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae + // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function + // because of this. + namespace test_template_alias_sfinae + { + + struct foo {}; + + template + using member = typename T::member_type; + + template + void func(...) {} + + template + void func(member*) {} + + void test(); + + void test() { func(0); } + + } + +} // namespace cxx11 + +#endif // __cplusplus >= 201103L + +]]) + + +dnl Tests for new features in C++14 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ + +// If the compiler admits that it is not ready for C++14, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus < 201402L + +#error "This is not a C++14 compiler" + +#else + +namespace cxx14 +{ + + namespace test_polymorphic_lambdas + { + + int + test() + { + const auto lambda = [](auto&&... args){ + const auto istiny = [](auto x){ + return (sizeof(x) == 1UL) ? 1 : 0; + }; + const int aretiny[] = { istiny(args)... }; + return aretiny[0]; + }; + return lambda(1, 1L, 1.0f, '1'); + } + + } + + namespace test_binary_literals + { + + constexpr auto ivii = 0b0000000000101010; + static_assert(ivii == 42, "wrong value"); + + } + + namespace test_generalized_constexpr + { + + template < typename CharT > + constexpr unsigned long + strlen_c(const CharT *const s) noexcept + { + auto length = 0UL; + for (auto p = s; *p; ++p) + ++length; + return length; + } + + static_assert(strlen_c("") == 0UL, ""); + static_assert(strlen_c("x") == 1UL, ""); + static_assert(strlen_c("test") == 4UL, ""); + static_assert(strlen_c("another\0test") == 7UL, ""); + + } + + namespace test_lambda_init_capture + { + + int + test() + { + auto x = 0; + const auto lambda1 = [a = x](int b){ return a + b; }; + const auto lambda2 = [a = lambda1(x)](){ return a; }; + return lambda2(); + } + + } + + namespace test_digit_separators + { + + constexpr auto ten_million = 100'000'000; + static_assert(ten_million == 100000000, ""); + + } + + namespace test_return_type_deduction + { + + auto f(int& x) { return x; } + decltype(auto) g(int& x) { return x; } + + template < typename T1, typename T2 > + struct is_same + { + static constexpr auto value = false; + }; + + template < typename T > + struct is_same + { + static constexpr auto value = true; + }; + + int + test() + { + auto x = 0; + static_assert(is_same::value, ""); + static_assert(is_same::value, ""); + return x; + } + + } + +} // namespace cxx14 + +#endif // __cplusplus >= 201402L + +]]) + + +dnl Tests for new features in C++17 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ + +// If the compiler admits that it is not ready for C++17, why torture it? +// Hopefully, this will speed up the test. + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif __cplusplus <= 201402L + +#error "This is not a C++17 compiler" + +#else + +#if defined(__clang__) + #define REALLY_CLANG +#else + #if defined(__GNUC__) + #define REALLY_GCC + #endif +#endif + +#include +#include +#include + +namespace cxx17 +{ + +#if !defined(REALLY_CLANG) + namespace test_constexpr_lambdas + { + + // TODO: test it with clang++ from git + + constexpr int foo = [](){return 42;}(); + + } +#endif // !defined(REALLY_CLANG) + + namespace test::nested_namespace::definitions + { + + } + + namespace test_fold_expression + { + + template + int multiply(Args... args) + { + return (args * ... * 1); + } + + template + bool all(Args... args) + { + return (args && ...); + } + + } + + namespace test_extended_static_assert + { + + static_assert (true); + + } + + namespace test_auto_brace_init_list + { + + auto foo = {5}; + auto bar {5}; + + static_assert(std::is_same, decltype(foo)>::value); + static_assert(std::is_same::value); + } + + namespace test_typename_in_template_template_parameter + { + + template typename X> struct D; + + } + + namespace test_fallthrough_nodiscard_maybe_unused_attributes + { + + int f1() + { + return 42; + } + + [[nodiscard]] int f2() + { + [[maybe_unused]] auto unused = f1(); + + switch (f1()) + { + case 17: + f1(); + [[fallthrough]]; + case 42: + f1(); + } + return f1(); + } + + } + + namespace test_extended_aggregate_initialization + { + + struct base1 + { + int b1, b2 = 42; + }; + + struct base2 + { + base2() { + b3 = 42; + } + int b3; + }; + + struct derived : base1, base2 + { + int d; + }; + + derived d1 {{1, 2}, {}, 4}; // full initialization + derived d2 {{}, {}, 4}; // value-initialized bases + + } + + namespace test_general_range_based_for_loop + { + + struct iter + { + int i; + + int& operator* () + { + return i; + } + + const int& operator* () const + { + return i; + } + + iter& operator++() + { + ++i; + return *this; + } + }; + + struct sentinel + { + int i; + }; + + bool operator== (const iter& i, const sentinel& s) + { + return i.i == s.i; + } + + bool operator!= (const iter& i, const sentinel& s) + { + return !(i == s); + } + + struct range + { + iter begin() const + { + return {0}; + } + + sentinel end() const + { + return {5}; + } + }; + + void f() + { + range r {}; + + for (auto i : r) + { + [[maybe_unused]] auto v = i; + } + } + + } + + namespace test_lambda_capture_asterisk_this_by_value + { + + struct t + { + int i; + int foo() + { + return [*this]() + { + return i; + }(); + } + }; + + } + + namespace test_enum_class_construction + { + + enum class byte : unsigned char + {}; + + byte foo {42}; + + } + + namespace test_constexpr_if + { + + template + int f () + { + if constexpr(cond) + { + return 13; + } + else + { + return 42; + } + } + + } + + namespace test_selection_statement_with_initializer + { + + int f() + { + return 13; + } + + int f2() + { + if (auto i = f(); i > 0) + { + return 3; + } + + switch (auto i = f(); i + 4) + { + case 17: + return 2; + + default: + return 1; + } + } + + } + +#if !defined(REALLY_CLANG) + namespace test_template_argument_deduction_for_class_templates + { + + // TODO: test it with clang++ from git + + template + struct pair + { + pair (T1 p1, T2 p2) + : m1 {p1}, + m2 {p2} + {} + + T1 m1; + T2 m2; + }; + + void f() + { + [[maybe_unused]] auto p = pair{13, 42u}; + } + + } +#endif // !defined(REALLY_CLANG) + + namespace test_non_type_auto_template_parameters + { + + template + struct B + {}; + + B<5> b1; + B<'a'> b2; + + } + +#if !defined(REALLY_CLANG) + namespace test_structured_bindings + { + + // TODO: test it with clang++ from git + + int arr[2] = { 1, 2 }; + std::pair pr = { 1, 2 }; + + auto f1() -> int(&)[2] + { + return arr; + } + + auto f2() -> std::pair& + { + return pr; + } + + struct S + { + int x1 : 2; + volatile double y1; + }; + + S f3() + { + return {}; + } + + auto [ x1, y1 ] = f1(); + auto& [ xr1, yr1 ] = f1(); + auto [ x2, y2 ] = f2(); + auto& [ xr2, yr2 ] = f2(); + const auto [ x3, y3 ] = f3(); + + } +#endif // !defined(REALLY_CLANG) + +#if !defined(REALLY_CLANG) + namespace test_exception_spec_type_system + { + + // TODO: test it with clang++ from git + + struct Good {}; + struct Bad {}; + + void g1() noexcept; + void g2(); + + template + Bad + f(T*, T*); + + template + Good + f(T1*, T2*); + + static_assert (std::is_same_v); + + } +#endif // !defined(REALLY_CLANG) + + namespace test_inline_variables + { + + template void f(T) + {} + + template inline T g(T) + { + return T{}; + } + + template<> inline void f<>(int) + {} + + template<> int g<>(int) + { + return 5; + } + + } + +} // namespace cxx17 + +#endif // __cplusplus <= 201402L + +]]) diff --git a/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx_11.m4 b/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx_11.m4 index a9a8f584f..1733fd85f 100644 --- a/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx_11.m4 +++ b/vendor/github.com/apache/thrift/aclocal/ax_cxx_compile_stdcxx_11.m4 @@ -1,26 +1,23 @@ -# ============================================================================ -# http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html -# ============================================================================ +# ============================================================================= +# https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html +# ============================================================================= # # SYNOPSIS # -# AX_CXX_COMPILE_STDCXX_11([ext|noext],[mandatory|optional]) +# AX_CXX_COMPILE_STDCXX_11([ext|noext], [mandatory|optional]) # # DESCRIPTION # # Check for baseline language coverage in the compiler for the C++11 -# standard; if necessary, add switches to CXXFLAGS to enable support. +# standard; if necessary, add switches to CXX and CXXCPP to enable +# support. # -# The first argument, if specified, indicates whether you insist on an -# extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. -# -std=c++11). If neither is specified, you get whatever works, with -# preference for an extended mode. -# -# The second argument, if specified 'mandatory' or if left unspecified, -# indicates that baseline C++11 support is required and that the macro -# should error out if no mode with that support is found. If specified -# 'optional', then configuration proceeds regardless, after defining -# HAVE_CXX11 if and only if a supporting mode is found. +# This macro is a convenience alias for calling the AX_CXX_COMPILE_STDCXX +# macro with the version set to C++11. The two optional arguments are +# forwarded literally as the second and third argument respectively. +# Please see the documentation for the AX_CXX_COMPILE_STDCXX macro for +# more information. If you want to use this macro, you also need to +# download the ax_cxx_compile_stdcxx.m4 file. # # LICENSE # @@ -28,138 +25,15 @@ # Copyright (c) 2012 Zack Weinberg # Copyright (c) 2013 Roy Stogner # Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov +# Copyright (c) 2015 Paul Norman +# Copyright (c) 2015 Moritz Klammler # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 10 +#serial 18 -m4_define([_AX_CXX_COMPILE_STDCXX_11_testbody], [[ - template - struct check - { - static_assert(sizeof(int) <= sizeof(T), "not big enough"); - }; - - struct Base { - virtual void f() {} - }; - struct Child : public Base { - virtual void f() override {} - }; - - typedef check> right_angle_brackets; - - int a; - decltype(a) b; - - typedef check check_type; - check_type c; - check_type&& cr = static_cast(c); - - auto d = a; - auto l = [](){}; - // Prevent Clang error: unused variable 'l' [-Werror,-Wunused-variable] - struct use_l { use_l() { l(); } }; - - // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae - // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function because of this - namespace test_template_alias_sfinae { - struct foo {}; - - template - using member = typename T::member_type; - - template - void func(...) {} - - template - void func(member*) {} - - void test(); - - void test() { - func(0); - } - } -]]) - -AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl - m4_if([$1], [], [], - [$1], [ext], [], - [$1], [noext], [], - [m4_fatal([invalid argument `$1' to AX_CXX_COMPILE_STDCXX_11])])dnl - m4_if([$2], [], [ax_cxx_compile_cxx11_required=true], - [$2], [mandatory], [ax_cxx_compile_cxx11_required=true], - [$2], [optional], [ax_cxx_compile_cxx11_required=false], - [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX_11])]) - AC_LANG_PUSH([C++])dnl - ac_success=no - AC_CACHE_CHECK(whether $CXX supports C++11 features by default, - ax_cv_cxx_compile_cxx11, - [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [ax_cv_cxx_compile_cxx11=yes], - [ax_cv_cxx_compile_cxx11=no])]) - if test x$ax_cv_cxx_compile_cxx11 = xyes; then - ac_success=yes - fi - - m4_if([$1], [noext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=gnu++11 -std=gnu++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - ac_success=yes - break - fi - done - fi]) - - m4_if([$1], [ext], [], [dnl - if test x$ac_success = xno; then - for switch in -std=c++11 -std=c++0x; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) - AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, - $cachevar, - [ac_save_CXXFLAGS="$CXXFLAGS" - CXXFLAGS="$CXXFLAGS $switch" - AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], - [eval $cachevar=yes], - [eval $cachevar=no]) - CXXFLAGS="$ac_save_CXXFLAGS"]) - if eval test x\$$cachevar = xyes; then - CXXFLAGS="$CXXFLAGS $switch" - ac_success=yes - break - fi - done - fi]) - AC_LANG_POP([C++]) - if test x$ax_cxx_compile_cxx11_required = xtrue; then - if test x$ac_success = xno; then - AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) - fi - else - if test x$ac_success = xno; then - HAVE_CXX11=0 - AC_MSG_NOTICE([No compiler with C++11 support was found]) - else - HAVE_CXX11=1 - AC_DEFINE(HAVE_CXX11,1, - [define if the compiler supports basic C++11 syntax]) - fi - - AC_SUBST(HAVE_CXX11) - fi -]) +AX_REQUIRE_DEFINED([AX_CXX_COMPILE_STDCXX]) +AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [AX_CXX_COMPILE_STDCXX([11], [$1], [$2])]) diff --git a/vendor/github.com/apache/thrift/build/docker/README.md b/vendor/github.com/apache/thrift/build/docker/README.md index 85cb3b2ae..eda8279fb 100644 --- a/vendor/github.com/apache/thrift/build/docker/README.md +++ b/vendor/github.com/apache/thrift/build/docker/README.md @@ -1,27 +1,81 @@ # Apache Thrift Docker containers -A set of docker containers used to build and test Apache Thrift +Docker containers used to build and test Apache Thrift for a variety of platforms. -### Available Containers +## Available Containers -* Ubuntu - based on ubuntu:trusty (14.04) -* Centos - based on centos:6.6 +### CentOS +* 7.3 (current) + +### Debian +* jessie +* stretch (current) + +### Ubuntu +* trusty +* xenial (current) ## Dependencies - -* A working Docker environment. A Vagrantfile is provided which will setup an Ubuntu host and working Docker environment as well as build the Apache Thrift Docker container for testing and development +* A working Docker environment. A Vagrantfile is provided which will setup an Ubuntu host and working Docker environment as well as build the Apache Thrift Docker container for testing and development. ## Usage -From the Apache Thrift code base root +From the Apache Thrift code base root: * Build - docker build -t thrift build/docker/ubuntu + docker build -t thrift build/docker/ubuntu-xenial or - docker build -t thrift build/docker/centos + docker build -t thrift build/docker/centos-7.3 * Run docker run -v $(pwd):/thrift/src -it thrift /bin/bash +## Core Tool Versions per Dockerfile + | Tool | centos-7.3 | debian-stretch | ubuntu-xenial | + |-----------|------------|----------------|---------------| + | ant | 1.9.2 | 1.9.9 | 1.9.6 | + | autoconf | 2.69 | 2.69 | 2.69 | + | automake | 1.13.4 | 1.15 | 1.15 | + | bison | 2.7 | 3.0.4 | 3.0.4 | + | boost | 1.53.0 | 1.62.0 | 1.58.0 | + | cmake | 3.6.3 | 3.7.2 | 3.5.1 | + | flex | 2.5.37 | 2.6.1 | 2.6.0 | + | glibc | 2.17 | 2.24 | 2.23 | + | libevent | 2.0.21 | 2.0.21 | 2.0.21 | + | libstdc++ | 4.8.5 | 6.3.0 | 5.4.0 | + | make | 3.82 | 4.1 | 4.1 | + | openssl | 1.0.1e | 1.1.0f | 1.0.2g | + +## Language Versions per Dockerfile + | Language | centos-7.3 | debian-stretch | ubuntu-xenial | + |-----------|------------|----------------|---------------| + | as3 | | | | + | C++-gcc | 4.8.5 | 6.3.0 | 5.4.0 | + | C++-clang | 3.4.2 | 3.8.1 | 3.8 | + | C# (mono) | 4.6.2 | 4.6.2.7 | 5.2.0.215 | + | c_glib | 2.46.2 | 2.50.3 | 2.48.2 | + | cocoa | | | | + | d | 2.076.0 | 2.075.1 | 2.075.1 | + | dart | 1.24.2 | 1.24.2 | 1.24.2 | + | delphi | | | | + | dotnet | | | | + | erlang | 20 | 19.2 | 18.3 | + | go | 1.9 | 1.7.4 | 1.6.2 | + | haskell | 7.6.3 | 8.0.1 | 7.10.3 | + | haxe | | 3.2.1 | 3.2.1 | + | java | 1.8.0_141 | 1.8.0_141 | 1.8.0_131 | + | js | | | | + | lua | 5.3.4 | 5.2.4 | 5.2.4 | + | nodejs | 6.11.1 | 8.4.0 | 8.4.0 | + | ocaml | 4.01.0 | 4.02.3 | 4.02.3 | + | perl | 5.16.3 | 5.24.1 | 5.22.1 | + | php | 5.4.16 | 7.0.19 | 7.0.22 | + | python2 | 2.7.5 | 2.7.13 | 2.7.12 | + | python3 | 3.4.5 | 3.5.3 | 3.5.2 | + | ruby | 2.0.0p648 | 2.3.3p222 | 2.3.1p112 | + | rust | 1.17.0 | 1.14.0 | 1.15.1 | + | smalltalk | | | | + | swift | | | | + diff --git a/vendor/github.com/apache/thrift/build/docker/centos-7.3/Dockerfile b/vendor/github.com/apache/thrift/build/docker/centos-7.3/Dockerfile new file mode 100644 index 000000000..f79939c72 --- /dev/null +++ b/vendor/github.com/apache/thrift/build/docker/centos-7.3/Dockerfile @@ -0,0 +1,197 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Apache Thrift Docker build environment for Centos +# +# Known missing client libraries: +# - dotnet (will update to 2.0.0 separately) +# - haxe (not in debian stretch) + +FROM centos:7.3.1611 +MAINTAINER Apache Thrift + +RUN yum install -y epel-release + +# General dependencies +RUN yum install -y \ + autoconf \ + bison \ + bison-devel \ + clang \ + clang-analyzer \ + cmake3 \ + curl \ + flex \ + gcc \ + gcc-c++ \ + git \ + libtool \ + m4 \ + make \ + tar \ + unzip \ + wget && \ + ln -s /usr/bin/cmake3 /usr/bin/cmake && \ + ln -s /usr/bin/cpack3 /usr/bin/cpack && \ + ln -s /usr/bin/ctest3 /usr/bin/ctest + +# C++ dependencies +RUN yum install -y \ + boost-devel-static \ + zlib-devel \ + openssl-devel \ + libevent-devel && \ + cd /usr/lib64 && \ + ln -s libboost_thread-mt.a libboost_thread.a + +# C# Dependencies +RUN yum install -y \ + mono-core \ + mono-devel \ + mono-web-devel \ + mono-extras + +# D Dependencies +RUN yum install -y http://downloads.dlang.org/releases/2.x/2.076.0/dmd-2.076.0-0.fedora.x86_64.rpm xdg-utils +RUN curl -sSL https://github.com/D-Programming-Deimos/openssl/archive/master.tar.gz| tar xz && \ + curl -sSL https://github.com/D-Programming-Deimos/libevent/archive/master.tar.gz| tar xz && \ + mkdir -p /usr/include/dmd/druntime/import/deimos /usr/include/dmd/druntime/import/C && \ + mv libevent-master/deimos/* openssl-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ + mv libevent-master/C/* openssl-master/C/* /usr/include/dmd/druntime/import/C/ && \ + rm -rf libevent-master openssl-master + +# Dart +RUN cd /usr/local && \ + wget -q https://storage.googleapis.com/dart-archive/channels/stable/release/1.24.2/sdk/dartsdk-linux-x64-release.zip && \ + unzip -q dartsdk-linux-x64-release.zip && \ + rm dartsdk-linux-x64-release.zip +ENV PATH /usr/local/dart-sdk/bin:$PATH + +# Erlang Dependencies +RUN curl -sSL http://packages.erlang-solutions.com/rpm/centos/erlang_solutions.repo -o /etc/yum.repos.d/erlang_solutions.repo && \ + yum install -y \ + erlang-kernel \ + erlang-erts \ + erlang-stdlib \ + erlang-eunit \ + erlang-rebar \ + erlang-tools + +# GLibC Dependencies +RUN yum install -y glib2-devel + +# Go Dependencies +RUN curl -sSL https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz | tar -C /usr/local/ -xz +ENV PATH /usr/local/go/bin:$PATH + +# Haskell Dependencies +RUN yum -y install haskell-platform + +# Haxe Dependencies +# Not in debian/stretch + +# Java Dependencies +RUN yum install -y \ + ant \ + junit \ + ant-junit \ + java-1.8.0-openjdk-devel + +# Lua Dependencies +# Lua in epel is too old (5.1.4, need 5.2) so we get the latest +RUN yum install -y readline-devel && \ + wget -q http://www.lua.org/ftp/lua-5.3.4.tar.gz && \ + tar xzf lua-5.3.4.tar.gz && \ + cd lua-5.3.4 && \ + sed -i 's/CFLAGS= /CFLAGS= -fPIC /g' src/Makefile && \ + make linux && \ + make install && \ + cd .. && \ + rm -rf lua-5* + +# MinGW Dependencies +RUN yum install -y \ + mingw32-binutils \ + mingw32-crt \ + mingw32-nsis + +# Node.js Dependencies +# Work around epel issue where they removed http-parser that nodejs depends on! +RUN yum -y install https://opensource.enda.eu/packages/http-parser-2.7.1-3.el7.x86_64.rpm +RUN yum install -y \ + nodejs \ + npm + +# Ocaml Dependencies +RUN yum install -y \ + ocaml \ + ocaml-ocamldoc && \ + wget -q https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin && \ + opam init --yes && \ + opam install --yes oasis && \ + echo '. /root/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true' >> ~/.bashrc + +# Perl Dependencies +RUN yum install -y \ + perl \ + perl-version \ + perl-Bit-Vector \ + perl-Class-Accessor \ + perl-ExtUtils-MakeMaker \ + perl-Test-Simple \ + perl-IO-Socket-SSL \ + perl-Net-SSLeay \ + perl-Crypt-SSLeay + +# PHP Dependencies +RUN yum install -y \ + php \ + php-devel \ + php-pear \ + re2c \ + php-phpunit-PHPUnit \ + bzip2 + +# Python Dependencies +RUN yum install -y \ + python \ + python-devel \ + python-pip \ + python-setuptools \ + python34 \ + python34-devel \ + python34-pip \ + python34-setuptools +RUN pip2 install --upgrade pip +RUN pip2 install --upgrade backports.ssl_match_hostname ipaddress setuptools six tornado tornado-testing twisted virtualenv zope-interface +RUN pip3 install --upgrade pip +RUN pip3 install --upgrade backports.ssl_match_hostname ipaddress setuptools six tornado tornado-testing twisted virtualenv zope-interface + +# Ruby Dependencies +RUN yum install -y \ + ruby \ + ruby-devel \ + rubygems && \ + gem install bundler rake + +# Rust +RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain 1.17.0 +ENV PATH /root/.cargo/bin:$PATH + +# Clean up +RUN rm -rf /tmp/* && \ + yum clean all + +ENV THRIFT_ROOT /thrift +RUN mkdir -p $THRIFT_ROOT/src +COPY Dockerfile $THRIFT_ROOT/ +WORKDIR $THRIFT_ROOT/src diff --git a/vendor/github.com/apache/thrift/build/docker/centos/Dockerfile b/vendor/github.com/apache/thrift/build/docker/centos/Dockerfile deleted file mode 100644 index 1881343ee..000000000 --- a/vendor/github.com/apache/thrift/build/docker/centos/Dockerfile +++ /dev/null @@ -1,146 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Apache Thrift Docker build environment for Centos -# -# Known missing client libraries: -# - D -# - Haxe -# - Lua -# - -FROM centos:7 -MAINTAINER Apache Thrift - -RUN yum install -y epel-release - -# General dependencies -RUN yum install -y \ - tar \ - m4 \ - perl \ - clang \ - gcc \ - gcc-c++ \ - git \ - libtool \ - autoconf \ - make \ - bison \ - bison-devel \ - flex - -# C++ dependencies -RUN yum install -y \ - boost-devel-static \ - zlib-devel \ - openssl-devel \ - libevent-devel - -# Java Dependencies -RUN yum install -y \ - ant \ - junit \ - ant-junit \ - java-1.7.0-openjdk-devel - -# Python Dependencies -RUN yum install -y \ - python-devel \ - python-pip \ - python-setuptools \ - python-six \ - python-twisted-web && \ - pip install -U backports.ssl_match_hostname ipaddress tornado - -# Ruby Dependencies -RUN yum install -y \ - ruby \ - ruby-devel \ - rubygems && \ - gem install bundler rake - -# Perl Dependencies -RUN yum install -y \ - perl-Bit-Vector \ - perl-Class-Accessor \ - perl-ExtUtils-MakeMaker \ - perl-Test-Simple \ - perl-IO-Socket-SSL \ - perl-Net-SSLeay \ - perl-Crypt-SSLeay - -# PHP Dependencies -RUN yum install -y \ - php \ - php-devel \ - php-pear \ - re2c \ - php-phpunit-PHPUnit \ - bzip2 - -# GLibC Dependencies -RUN yum install -y glib2-devel - -# Erlang Dependencies -RUN curl -sSL http://packages.erlang-solutions.com/rpm/centos/erlang_solutions.repo -o /etc/yum.repos.d/erlang_solutions.repo && \ - yum install -y \ - erlang-kernel \ - erlang-erts \ - erlang-stdlib \ - erlang-eunit \ - erlang-rebar \ - erlang-tools - -# Go Dependencies -RUN curl -sSL https://storage.googleapis.com/golang/go1.4.3.linux-amd64.tar.gz | tar -C /usr/local/ -xz -ENV PATH /usr/local/go/bin:$PATH - -# Haskell Dependencies -RUN yum -y install haskell-platform - -# Node.js Dependencies -RUN yum install -y \ - nodejs \ - nodejs-devel \ - npm - -# C# Dependencies -RUN yum install -y \ - mono-core \ - mono-devel \ - mono-web-devel \ - mono-extras - -# Rust -RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain 1.17.0 -ENV PATH /root/.cargo/bin:$PATH - -# MinGW Dependencies -RUN yum install -y \ - mingw32-binutils \ - mingw32-crt \ - mingw32-nsis - -# CMake -RUN curl -sSL https://cmake.org/files/v3.4/cmake-3.4.0.tar.gz | tar -xz && \ - cd cmake-3.4.0 && ./bootstrap && make -j4 && make install && \ - cd .. && rm -rf cmake-3.4.0 - -# Clean up -RUN rm -rf /tmp/* && \ - yum clean all - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/github.com/apache/thrift/build/docker/centos6/Dockerfile b/vendor/github.com/apache/thrift/build/docker/centos6/Dockerfile deleted file mode 100644 index 5567ab7a4..000000000 --- a/vendor/github.com/apache/thrift/build/docker/centos6/Dockerfile +++ /dev/null @@ -1,56 +0,0 @@ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Apache Thrift Docker build environment for Centos 6 -# -# This file is intended for testing old packages that are not available for -# latest Ubuntu LTS/Debian/CentOS. Currently, it is only used for Python 2.6. -# - -FROM centos:6 -MAINTAINER Apache Thrift - -RUN yum install -y epel-release && \ - yum install -y \ - autoconf \ - bison \ - bison-devel \ - clang \ - flex \ - gcc \ - gcc-c++ \ - git \ - libtool \ - m4 \ - make \ - perl \ - tar \ - python-devel \ - python-setuptools \ - python-twisted-web \ - python-pip \ - && yum clean all - -# optional dependencies -# skipping ipaddress and backports.ssl_match_hostname to test legacy callback -# RUN pip install ipaddress backports.ssl_match_hostname tornado -RUN pip install tornado - -# CMake -RUN curl -sSL https://cmake.org/files/v3.4/cmake-3.4.1.tar.gz | tar -xz && \ - cd cmake-3.4.1 && ./bootstrap && make -j4 && make install && \ - cd .. && rm -rf cmake-3.4.1 - -ENV THRIFT_ROOT /thrift -RUN mkdir -p $THRIFT_ROOT/src -COPY Dockerfile $THRIFT_ROOT/ -WORKDIR $THRIFT_ROOT/src diff --git a/vendor/github.com/apache/thrift/build/docker/debian/Dockerfile b/vendor/github.com/apache/thrift/build/docker/debian-jessie/Dockerfile similarity index 100% rename from vendor/github.com/apache/thrift/build/docker/debian/Dockerfile rename to vendor/github.com/apache/thrift/build/docker/debian-jessie/Dockerfile diff --git a/vendor/github.com/apache/thrift/build/docker/debian-stretch/Dockerfile b/vendor/github.com/apache/thrift/build/docker/debian-stretch/Dockerfile new file mode 100644 index 000000000..70309fbe0 --- /dev/null +++ b/vendor/github.com/apache/thrift/build/docker/debian-stretch/Dockerfile @@ -0,0 +1,230 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Apache Thrift Docker build environment for Debian Stretch +# +# Known issues: +# - d: deimos for libevent and openssl disabled - build errors +# - dotnetcore, because netcore is for 1.0.0-preview and 2.0.0 is out +# - rust: cargo not in debian repo - perhaps not needed? + +FROM buildpack-deps:stretch-scm +MAINTAINER Apache Thrift + +ENV DEBIAN_FRONTEND noninteractive + +### Add apt repos + +RUN apt-get update && apt-get install -y --no-install-recommends apt apt-transport-https curl wget apt-utils + +# D +RUN wget http://master.dl.sourceforge.net/project/d-apt/files/d-apt.list -O /etc/apt/sources.list.d/d-apt.list && \ + apt-get update && apt-get -y --allow-unauthenticated install --reinstall d-apt-keyring + +# Dart +RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ + curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list && \ + sed -i /etc/apt/sources.list.d/dart_stable.list -e 's/https:/http:/g' + +# dotnet (core) 2.0.0 - project isn't ready for this yet: +# RUN curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg && \ +# echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt/sources.list.d/dotnetdev.list + +# node.js (this step runs apt-get update internally) +RUN curl -sL https://deb.nodesource.com/setup_8.x | bash + + +### install general dependencies +RUN apt-get install -y --no-install-recommends \ +`# General dependencies` \ + bash-completion \ + bison \ + build-essential \ + clang \ + cmake \ + debhelper \ + flex \ + gdb \ + ninja-build \ + pkg-config \ + vim + + +### languages + +RUN apt-get install -y --no-install-recommends \ +`# C++ dependencies` \ + libboost-dev \ + libboost-filesystem-dev \ + libboost-program-options-dev \ + libboost-system-dev \ + libboost-test-dev \ + libboost-thread-dev \ + libevent-dev \ + libssl-dev \ + qt5-default \ + qtbase5-dev \ + qtbase5-dev-tools + +RUN apt-get install -y --no-install-recommends \ +`# csharp (mono) dependencies` \ + mono-devel + +RUN apt-get install -y --no-install-recommends \ +`# D dependencies` \ + dmd-bin \ + libevent-dev \ + libssl-dev \ + xdg-utils +# libevent deimos disabled - build errors +# RUN mkdir -p /usr/include/dmd/druntime/import/deimos /usr/include/dmd/druntime/import/C && \ +# curl -sSL https://github.com/D-Programming-Deimos/libevent/archive/master.tar.gz| tar xz && \ +# mv libevent-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ +# mv libevent-master/C/* /usr/include/dmd/druntime/import/C/ && \ +# rm -rf libevent-master +# openssl deimos doesn't work with openssl-1.1.0 - disabling it for now: +# RUN curl -sSL https://github.com/D-Programming-Deimos/openssl/archive/master.tar.gz| tar xz && \ +# mv openssl-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ +# mv openssl-master/C/* /usr/include/dmd/druntime/import/C/ && \ +# rm -rf openssl-master + +RUN apt-get install -y --no-install-recommends \ +`# Dart dependencies` \ + dart +ENV PATH /usr/lib/dart/bin:$PATH + +# project isn't ready for this quite yet: +# RUN apt-get install -y --no-install-recommends \ +# `# dotnet core dependencies` \ +# dotnet-sdk-2.0.0 + +RUN apt-get install -y --no-install-recommends \ +`# Erlang dependencies` \ + erlang-base \ + erlang-eunit \ + erlang-dev \ + erlang-tools \ + rebar + +RUN apt-get install -y --no-install-recommends \ +`# GlibC dependencies` \ + libglib2.0-dev + +RUN apt-get install -y --no-install-recommends \ +`# golang (go) dependencies` \ + golang-go + +RUN apt-get install -y --no-install-recommends \ +`# Haskell dependencies` \ + ghc \ + cabal-install + +RUN apt-get install -y --no-install-recommends \ +`# Haxe dependencies` \ + haxe \ + neko \ + neko-dev +RUN haxelib setup --always /usr/share/haxe/lib && \ + haxelib install --always hxcpp + +RUN apt-get install -y --no-install-recommends \ +`# Java dependencies` \ + ant \ + ant-optional \ + openjdk-8-jdk \ + maven + +RUN apt-get install -y --no-install-recommends \ +`# Lua dependencies` \ + lua5.2 \ + lua5.2-dev +# https://bugs.launchpad.net/ubuntu/+source/lua5.3/+bug/1707212 +# same for debian stretch +# lua5.3 does not install alternatives so stick with 5.2 here + +RUN apt-get install -y --no-install-recommends \ +`# Node.js dependencies` \ + nodejs + +RUN apt-get install -y --no-install-recommends \ +`# OCaml dependencies` \ + ocaml \ + opam && \ + opam init --yes && \ + opam install --yes oasis + +RUN apt-get install -y --no-install-recommends \ +`# Perl dependencies` \ + libbit-vector-perl \ + libclass-accessor-class-perl \ + libcrypt-ssleay-perl \ + libio-socket-ssl-perl \ + libnet-ssleay-perl + +RUN apt-get install -y --no-install-recommends \ +`# Php dependencies` \ + php7.0 \ + php7.0-cli \ + php7.0-dev \ + php-pear \ + re2c \ + phpunit + +RUN apt-get install -y --no-install-recommends \ +`# Python dependencies` \ + python-all \ + python-all-dbg \ + python-all-dev \ + python-backports.ssl-match-hostname \ + python-ipaddress \ + python-pip \ + python-setuptools \ + python-six \ + python-tornado \ + python-twisted \ + python-wheel \ + python-zope.interface \ + python3-all \ + python3-all-dbg \ + python3-all-dev \ + python3-setuptools \ + python3-six \ + python3-tornado \ + python3-twisted \ + python3-wheel \ + python3-zope.interface && \ + pip install --upgrade backports.ssl_match_hostname + +RUN apt-get install -y --no-install-recommends \ +`# Ruby dependencies` \ + ruby \ + ruby-dev \ + ruby-bundler +RUN gem install bundler --no-ri --no-rdoc + +RUN apt-get install -y --no-install-recommends \ +`# Rust dependencies` \ + rustc + +# Update anything else left hanging +RUN apt-get dist-upgrade -y + +# Clean up +RUN rm -rf /var/cache/apt/* && \ + rm -rf /var/lib/apt/lists/* && \ + rm -rf /tmp/* && \ + rm -rf /var/tmp/* + +ENV THRIFT_ROOT /thrift +RUN mkdir -p $THRIFT_ROOT/src +COPY Dockerfile $THRIFT_ROOT/ +WORKDIR $THRIFT_ROOT/src diff --git a/vendor/github.com/apache/thrift/build/docker/scripts/cmake.sh b/vendor/github.com/apache/thrift/build/docker/scripts/cmake.sh index 6508e7108..ccc311e44 100755 --- a/vendor/github.com/apache/thrift/build/docker/scripts/cmake.sh +++ b/vendor/github.com/apache/thrift/build/docker/scripts/cmake.sh @@ -19,5 +19,5 @@ for LIB in $BUILD_LIBS; do done $MAKEPROG -j3 cpack -ctest -VV -# was: -E "(concurrency_test|processor_test)" +ctest -VV -E "(python_test)" +# disabled cmake python_test for now since it fails in travis under centos diff --git a/vendor/github.com/apache/thrift/build/docker/scripts/ubsan.sh b/vendor/github.com/apache/thrift/build/docker/scripts/ubsan.sh index d39cc8361..e1e82c9c5 100755 --- a/vendor/github.com/apache/thrift/build/docker/scripts/ubsan.sh +++ b/vendor/github.com/apache/thrift/build/docker/scripts/ubsan.sh @@ -5,12 +5,6 @@ set -ex # Wraps autotools.sh, but each binary crashes if it exhibits undefined behavior. See # http://releases.llvm.org/3.8.0/tools/clang/docs/UndefinedBehaviorSanitizer.html -# Install a more recent clang than default: -sudo apt-get update -sudo apt-get install -y --no-install-recommends clang-3.8 llvm-3.8-dev -export CC=clang-3.8 -export CXX=clang++-3.8 - # Set the undefined behavior flags. This crashes on all undefined behavior except for # undefined casting, aka "vptr". # diff --git a/vendor/github.com/apache/thrift/build/docker/ubuntu/Dockerfile b/vendor/github.com/apache/thrift/build/docker/ubuntu-trusty/Dockerfile similarity index 100% rename from vendor/github.com/apache/thrift/build/docker/ubuntu/Dockerfile rename to vendor/github.com/apache/thrift/build/docker/ubuntu-trusty/Dockerfile diff --git a/vendor/github.com/apache/thrift/build/docker/ubuntu-xenial/Dockerfile b/vendor/github.com/apache/thrift/build/docker/ubuntu-xenial/Dockerfile new file mode 100644 index 000000000..6bad6a94c --- /dev/null +++ b/vendor/github.com/apache/thrift/build/docker/ubuntu-xenial/Dockerfile @@ -0,0 +1,236 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Apache Thrift Docker build environment for Ubuntu Xenial +# +# Known missing or disabled libraries: +# - d: deimos for libevent and openssl omitted - not compatible / build errors +# - dotnetcore, because netcore is for 1.0.0-preview and 2.0.0 is out + +FROM buildpack-deps:xenial-scm +MAINTAINER Apache Thrift + +ENV DEBIAN_FRONTEND noninteractive + +### Add apt repos + +RUN apt-get update && apt-get install -y --no-install-recommends apt apt-transport-https curl wget apt-utils + +# csharp (mono) +RUN echo "deb http://download.mono-project.com/repo/debian xenial main" | tee /etc/apt/sources.list.d/mono.list && \ + apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A6A19B38D3D831EF + +# D +RUN wget http://master.dl.sourceforge.net/project/d-apt/files/d-apt.list -O /etc/apt/sources.list.d/d-apt.list && \ + apt-get update && apt-get -y --allow-unauthenticated install --reinstall d-apt-keyring + +# Dart +RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ + curl https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list && \ + sed -i /etc/apt/sources.list.d/dart_stable.list -e 's/https:/http:/g' + +# dotnet (core) 2.0.0 - project isn't ready for this yet: +# RUN curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg && \ +# echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt/sources.list.d/dotnetdev.list + +# node.js (this step runs apt-get update internally) +RUN curl -sL https://deb.nodesource.com/setup_8.x | bash + + +### install general dependencies +RUN apt-get install -y --no-install-recommends \ +`# General dependencies` \ + bash-completion \ + bison \ + build-essential \ + clang \ + cmake \ + debhelper \ + flex \ + gdb \ + llvm \ + ninja-build \ + pkg-config \ + vim +ENV PATH /usr/lib/llvm-3.8/bin:$PATH + +### languages + +RUN apt-get install -y --no-install-recommends \ +`# C++ dependencies` \ + libboost-dev \ + libboost-filesystem-dev \ + libboost-program-options-dev \ + libboost-system-dev \ + libboost-test-dev \ + libboost-thread-dev \ + libevent-dev \ + libssl-dev \ + qt5-default \ + qtbase5-dev \ + qtbase5-dev-tools + +RUN apt-get install -y --no-install-recommends \ +`# csharp (mono) dependencies` \ + mono-devel + +RUN apt-get install -y --no-install-recommends \ +`# D dependencies` \ + dmd-bin \ + libevent-dev \ + libssl-dev \ + xdg-utils +# libevent deimos doesn't seem to work so disabling it: +# RUN mkdir -p /usr/include/dmd/druntime/import/deimos /usr/include/dmd/druntime/import/C && \ +# curl -sSL https://github.com/D-Programming-Deimos/libevent/archive/master.tar.gz| tar xz && \ +# mv libevent-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ +# mv libevent-master/C/* /usr/include/dmd/druntime/import/C/ && \ +# rm -rf libevent-master +# openssl deimos doesn't work with openssl-1.0.2 so disabling it: +# RUN curl -sSL https://github.com/D-Programming-Deimos/openssl/archive/master.tar.gz| tar xz && \ +# mv openssl-master/deimos/* /usr/include/dmd/druntime/import/deimos/ && \ +# mv openssl-master/C/* /usr/include/dmd/druntime/import/C/ && \ +# rm -rf openssl-master + +RUN apt-get install -y --no-install-recommends \ +`# Dart dependencies` \ + dart +ENV PATH /usr/lib/dart/bin:$PATH + +# project isn't ready for this quite yet: +# RUN apt-get install -y --no-install-recommends \ +# `# dotnet core dependencies` \ +# dotnet-sdk-2.0.0 + +RUN apt-get install -y --no-install-recommends \ +`# Erlang dependencies` \ + erlang-base \ + erlang-eunit \ + erlang-dev \ + erlang-tools \ + rebar + +RUN apt-get install -y --no-install-recommends \ +`# GlibC dependencies` \ + libglib2.0-dev + +RUN apt-get install -y --no-install-recommends \ +`# golang (go) dependencies` \ + golang-go \ + golang-race-detector-runtime + +RUN apt-get install -y --no-install-recommends \ +`# Haskell dependencies` \ + ghc \ + cabal-install + +RUN apt-get install -y --no-install-recommends \ +`# Haxe dependencies` \ + haxe \ + neko \ + neko-dev \ + libneko0 +RUN haxelib setup --always /usr/share/haxe/lib && \ + haxelib install --always hxcpp + +RUN apt-get install -y --no-install-recommends \ +`# Java dependencies` \ + ant \ + ant-optional \ + openjdk-8-jdk \ + maven + +RUN apt-get install -y --no-install-recommends \ +`# Lua dependencies` \ + lua5.2 \ + lua5.2-dev +# https://bugs.launchpad.net/ubuntu/+source/lua5.3/+bug/1707212 +# lua5.3 does not install alternatives so stick with 5.2 here + +RUN apt-get install -y --no-install-recommends \ +`# Node.js dependencies` \ + nodejs + +RUN apt-get install -y --no-install-recommends \ +`# OCaml dependencies` \ + ocaml \ + opam && \ + opam init --yes && \ + opam install --yes oasis + +RUN apt-get install -y --no-install-recommends \ +`# Perl dependencies` \ + libbit-vector-perl \ + libclass-accessor-class-perl \ + libcrypt-ssleay-perl \ + libio-socket-ssl-perl \ + libnet-ssleay-perl + +RUN apt-get install -y --no-install-recommends \ +`# Php dependencies` \ + php7.0 \ + php7.0-cli \ + php7.0-dev \ + php-pear \ + re2c \ + phpunit + +RUN apt-get install -y --no-install-recommends \ +`# Python dependencies` \ + python-all \ + python-all-dbg \ + python-all-dev \ + python-backports.ssl-match-hostname \ + python-ipaddress \ + python-pip \ + python-setuptools \ + python-six \ + python-tornado \ + python-twisted \ + python-wheel \ + python-zope.interface \ + python3-all \ + python3-all-dbg \ + python3-all-dev \ + python3-setuptools \ + python3-six \ + python3-tornado \ + python3-twisted \ + python3-wheel \ + python3-zope.interface && \ + pip install --upgrade backports.ssl_match_hostname + +RUN apt-get install -y --no-install-recommends \ +`# Ruby dependencies` \ + ruby \ + ruby-dev \ + ruby-bundler +RUN gem install bundler --no-ri --no-rdoc + +RUN apt-get install -y --no-install-recommends \ +`# Rust dependencies` \ + cargo \ + rustc + +# Update anything else left hanging +RUN apt-get dist-upgrade -y + +# Clean up +RUN rm -rf /var/cache/apt/* && \ + rm -rf /var/lib/apt/lists/* && \ + rm -rf /tmp/* && \ + rm -rf /var/tmp/* + +ENV THRIFT_ROOT /thrift +RUN mkdir -p $THRIFT_ROOT/src +COPY Dockerfile $THRIFT_ROOT/ +WORKDIR $THRIFT_ROOT/src diff --git a/vendor/github.com/apache/thrift/compiler/cpp/CMakeLists.txt b/vendor/github.com/apache/thrift/compiler/cpp/CMakeLists.txt index 8e861e41c..5da28aad4 100644 --- a/vendor/github.com/apache/thrift/compiler/cpp/CMakeLists.txt +++ b/vendor/github.com/apache/thrift/compiler/cpp/CMakeLists.txt @@ -23,6 +23,7 @@ if(MSVC) # The winflexbison generator outputs some macros that conflict with the Visual Studio 2010 copy of stdint.h # This might be fixed in later versions of Visual Studio, but an easy solution is to include stdint.h first if(HAVE_STDINT_H) + add_definitions(-D__STDC_FORMAT_MACROS) add_definitions(-D__STDC_LIMIT_MACROS) add_definitions(/FI"stdint.h") endif(HAVE_STDINT_H) diff --git a/vendor/github.com/apache/thrift/compiler/cpp/README.md b/vendor/github.com/apache/thrift/compiler/cpp/README.md index 77cb23421..2fff0d846 100644 --- a/vendor/github.com/apache/thrift/compiler/cpp/README.md +++ b/vendor/github.com/apache/thrift/compiler/cpp/README.md @@ -79,7 +79,7 @@ Open compiler.sln and remove the Pre-build commands under the project's From a command prompt: ``` cd thrift/compiler/cpp -flex -osrc\thrift\thriftl.cc src\thrift\thriftl.ll +flex -o src\thrift\thriftl.cc src\thrift\thriftl.ll ``` In the generated thriftl.cc, comment out #include diff --git a/vendor/github.com/apache/thrift/configure.ac b/vendor/github.com/apache/thrift/configure.ac index bb036f00c..df716bd0b 100755 --- a/vendor/github.com/apache/thrift/configure.ac +++ b/vendor/github.com/apache/thrift/configure.ac @@ -120,6 +120,7 @@ if test "$enable_libs" = "no"; then with_java="no" with_csharp="no" with_python="no" + with_py3="no" with_ruby="no" with_haskell="no" with_haxe="no" @@ -303,6 +304,7 @@ AM_CONDITIONAL(WITH_TWISTED_TEST, [test "$have_trial" = "yes"]) # Find "python3" executable. # It's distro specific and far from ideal but needed to cross test py2-3 at once. # TODO: find "python2" if it's 3.x +have_py3="no" if python --version 2>&1 | grep -q "Python 2"; then AC_PATH_PROGS([PYTHON3], [python3 python3.5 python35 python3.4 python34]) if test -n "$PYTHON3"; then @@ -657,7 +659,7 @@ AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_TYPE_UINT8_T -AC_CHECK_TYPES([ptrdiff_t], [], [exit 1]) +AC_CHECK_TYPES([ptrdiff_t], [], [echo "ptrdiff_t not found or g++ not installed - cannot continue" && exit 1]) AC_STRUCT_TM @@ -899,107 +901,42 @@ AC_OUTPUT echo echo "$PACKAGE $VERSION" echo -echo "Building Plugin Support ...... : $have_plugin" -echo "Building C++ Library ......... : $have_cpp" echo "Building C (GLib) Library .... : $have_c_glib" -echo "Building Java Library ........ : $have_java" -echo "Building C# Library .......... : $have_csharp" -echo "Building .NET Core Library ... : $have_dotnetcore" -echo "Building Python Library ...... : $have_python" -echo "Building Ruby Library ........ : $have_ruby" -echo "Building Haxe Library ........ : $have_haxe" -echo "Building Haskell Library ..... : $have_haskell" -echo "Building Perl Library ........ : $have_perl" -echo "Building PHP Library ......... : $have_php" +echo "Building C# (Mono) Library ... : $have_csharp" +echo "Building C++ Library ......... : $have_cpp" +echo "Building D Library ........... : $have_d" echo "Building Dart Library ........ : $have_dart" +echo "Building dotnetcore Library .. : $have_dotnetcore" echo "Building Erlang Library ...... : $have_erlang" echo "Building Go Library .......... : $have_go" -echo "Building D Library ........... : $have_d" -echo "Building NodeJS Library ...... : $have_nodejs" +echo "Building Haskell Library ..... : $have_haskell" +echo "Building Haxe Library ........ : $have_haxe" +echo "Building Java Library ........ : $have_java" echo "Building Lua Library ......... : $have_lua" +echo "Building NodeJS Library ...... : $have_nodejs" +echo "Building Perl Library ........ : $have_perl" +echo "Building PHP Library ......... : $have_php" +echo "Building Plugin Support ...... : $have_plugin" +echo "Building Python Library ...... : $have_python" +echo "Building Py3 Library ......... : $have_py3" +echo "Building Ruby Library ........ : $have_ruby" echo "Building Rust Library ........ : $have_rs" -if test "$have_cpp" = "yes" ; then - echo - echo "C++ Library:" - echo " Build TZlibTransport ...... : $have_zlib" - echo " Build TNonblockingServer .. : $have_libevent" - echo " Build TQTcpServer (Qt4) ... : $have_qt" - echo " Build TQTcpServer (Qt5) ... : $have_qt5" -fi -if test "$have_java" = "yes" ; then - echo - echo "Java Library:" - echo " Using javac ............... : $JAVAC" - echo " Using java ................ : $JAVA" - echo " Using ant ................. : $ANT" -fi if test "$have_csharp" = "yes" ; then echo echo "C# Library:" echo " Using .NET 3.5 ............ : $net_3_5" + echo " Using mono version ........ : $($MCS --version | head -1)" fi -if test "$have_dotnetcore" = "yes" ; then +if test "$have_cpp" = "yes" ; then echo - echo ".NET Core Library:" - echo " Using .NET Core ........... : $DOTNETCORE" - echo " Using .NET Core version ... : $DOTNETCORE_VERSION" -fi -if test "$have_python" = "yes" ; then - echo - echo "Python Library:" - echo " Using Python .............. : $PYTHON" - if test "$have_py3" = "yes" ; then - echo " Using Python3 ............. : $PYTHON3" - fi - if test "$have_trial" = "yes"; then - echo " Using trial ............... : $TRIAL" - fi -fi -if test "$have_php" = "yes" ; then - echo - echo "PHP Library:" - echo " Using php-config .......... : $PHP_CONFIG" -fi -if test "$have_dart" = "yes" ; then - echo - echo "Dart Library:" - echo " Using Dart ................ : $DART" - echo " Using Pub ................. : $DARTPUB" -fi -if test "$have_ruby" = "yes" ; then - echo - echo "Ruby Library:" - echo " Using Ruby ................ : $RUBY" -fi -if test "$have_haskell" = "yes" ; then - echo - echo "Haskell Library:" - echo " Using Haskell ............. : $RUNHASKELL" - echo " Using Cabal ............... : $CABAL" -fi -if test "$have_haxe" = "yes" ; then - echo - echo "Haxe Library:" - echo " Using Haxe ................ : $HAXE" - echo " Using Haxe version ........ : $HAXE_VERSION" -fi -if test "$have_perl" = "yes" ; then - echo - echo "Perl Library:" - echo " Using Perl ................ : $PERL" -fi -if test "$have_erlang" = "yes" ; then - echo - echo "Erlang Library:" - echo " Using erlc ................ : $ERLC" - echo " Using rebar ............... : $REBAR" -fi -if test "$have_go" = "yes" ; then - echo - echo "Go Library:" - echo " Using Go................... : $GO" - echo " Using Go version........... : $($GO version)" + echo "C++ Library:" + echo " C++ compiler .............. : $CXX" + echo " Build TZlibTransport ...... : $have_zlib" + echo " Build TNonblockingServer .. : $have_libevent" + echo " Build TQTcpServer (Qt4) ... : $have_qt" + echo " Build TQTcpServer (Qt5) ... : $have_qt5" + echo " C++ compiler version ...... : $($CXX --version | head -1)" fi if test "$have_d" = "yes" ; then echo @@ -1007,6 +944,61 @@ if test "$have_d" = "yes" ; then echo " Using D Compiler .......... : $DMD" echo " Building D libevent tests . : $with_d_event_tests" echo " Building D SSL tests ...... : $with_d_ssl_tests" + echo " Using D version ........... : $($DMD --version | head -1)" +fi +if test "$have_dart" = "yes" ; then + echo + echo "Dart Library:" + echo " Using Dart ................ : $DART" + echo " Using Pub ................. : $DARTPUB" + echo " Using Dart version ........ : $($DART --version 2>&1)" +fi +if test "$have_dotnetcore" = "yes" ; then + echo + echo ".NET Core Library:" + echo " Using .NET Core ........... : $DOTNETCORE" + echo " Using .NET Core version ... : $DOTNETCORE_VERSION" +fi +if test "$have_erlang" = "yes" ; then + echo + echo "Erlang Library:" + echo " Using erlc ................ : $ERLC" + echo " Using rebar ............... : $REBAR" + echo " Using erlc version ........ : $($ERL -eval 'erlang:display(erlang:system_info(otp_release)), halt().' -noshell | tr -d '\"')" +fi +if test "$have_go" = "yes" ; then + echo + echo "Go Library:" + echo " Using Go................... : $GO" + echo " Using Go version........... : $($GO version)" +fi +if test "$have_haskell" = "yes" ; then + echo + echo "Haskell Library:" + echo " Using Cabal ............... : $CABAL" + echo " Using Haskell ............. : $RUNHASKELL" + echo " Using Haskell version ..... : $($RUNHASKELL --version)" +fi +if test "$have_haxe" = "yes" ; then + echo + echo "Haxe Library:" + echo " Using Haxe ................ : $HAXE" + echo " Using Haxe version ........ : $HAXE_VERSION" +fi +if test "$have_java" = "yes" ; then + echo + echo "Java Library:" + echo " Using ant ................. : $ANT" + echo " Using java ................ : $JAVA" + echo " Using javac ............... : $JAVAC" + echo " Using ant version ......... : $($ANT -version 2>&1)" + echo " Using java version ........ : $($JAVA -version 2>&1 | grep 'version ')" +fi +if test "$have_lua" = "yes" ; then + echo + echo "Lua Library:" + echo " Using Lua ................. : $LUA" + echo " Using Lua version.......... : $($LUA -v)" fi if test "$have_nodejs" = "yes" ; then echo @@ -1014,10 +1006,36 @@ if test "$have_nodejs" = "yes" ; then echo " Using NodeJS .............. : $NODEJS" echo " Using NodeJS version....... : $($NODEJS --version)" fi -if test "$have_lua" = "yes" ; then +if test "$have_perl" = "yes" ; then echo - echo "Lua Library:" - echo " Using Lua ................. : $LUA" + echo "Perl Library:" + echo " Using Perl ................ : $PERL" + echo " Using Perl version ........ : $($PERL -v | grep 'version ')" +fi +if test "$have_php" = "yes" ; then + echo + echo "PHP Library:" + echo " Using php-config .......... : $PHP_CONFIG" + echo " Using php version ......... : $($PHP --version | head -1)" +fi +if test "$have_python" = "yes" ; then + echo + echo "Python Library:" + echo " Using Python .............. : $PYTHON" + echo " Using Python version ...... : $($PYTHON --version 2>&1)" + if test "$have_py3" = "yes" ; then + echo " Using Python3 ............. : $PYTHON3" + echo " Using Python3 version ..... : $($PYTHON3 --version)" + fi + if test "$have_trial" = "yes"; then + echo " Using trial ............... : $TRIAL" + fi +fi +if test "$have_ruby" = "yes" ; then + echo + echo "Ruby Library:" + echo " Using Ruby ................ : $RUBY" + echo " Using Ruby version ........ : $($RUBY --version)" fi if test "$have_rs" = "yes" ; then echo @@ -1030,3 +1048,4 @@ echo echo "If something is missing that you think should be present," echo "please skim the output of configure to find the missing" echo "component. Details are present in config.log." +echo diff --git a/vendor/github.com/apache/thrift/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c b/vendor/github.com/apache/thrift/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c index 1de4a4327..be8637df3 100644 --- a/vendor/github.com/apache/thrift/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c +++ b/vendor/github.com/apache/thrift/lib/c_glib/src/thrift/c_glib/transport/thrift_ssl_socket.c @@ -383,17 +383,16 @@ gboolean thrift_ssl_load_cert_from_buffer(ThriftSSLSocket *ssl_socket, const cha X509_STORE *cert_store = SSL_CTX_get_cert_store(ssl_socket->ctx); if(cert_store!=NULL){ - int index = 0; - while ((cacert = PEM_read_bio_X509(mem, NULL, 0, NULL))!=NULL) { - if(cacert) { - g_debug("Our certificate name is %s", cacert->name); - X509_STORE_add_cert(cert_store, cacert); - X509_free(cacert); - cacert=NULL; - } /* Free immediately */ - index++; - } - retval=TRUE; + int index = 0; + while ((cacert = PEM_read_bio_X509(mem, NULL, 0, NULL))!=NULL) { + if(cacert) { + X509_STORE_add_cert(cert_store, cacert); + X509_free(cacert); + cacert=NULL; + } /* Free immediately */ + index++; + } + retval=TRUE; } BIO_free(mem); return retval; diff --git a/vendor/github.com/apache/thrift/lib/cpp/Makefile.am b/vendor/github.com/apache/thrift/lib/cpp/Makefile.am index 77d4d6c98..4441fba4c 100755 --- a/vendor/github.com/apache/thrift/lib/cpp/Makefile.am +++ b/vendor/github.com/apache/thrift/lib/cpp/Makefile.am @@ -62,7 +62,7 @@ pkgconfig_DATA += thrift-qt5.pc endif AM_CXXFLAGS = -Wall -Wextra -pedantic -AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(OPENSSL_INCLUDES) -I$(srcdir)/src -D__STDC_LIMIT_MACROS +AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(OPENSSL_INCLUDES) -I$(srcdir)/src -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS # Define the source files for the module diff --git a/vendor/github.com/apache/thrift/lib/cpp/test/CMakeLists.txt b/vendor/github.com/apache/thrift/lib/cpp/test/CMakeLists.txt index 1a6062d32..5c5ed180a 100644 --- a/vendor/github.com/apache/thrift/lib/cpp/test/CMakeLists.txt +++ b/vendor/github.com/apache/thrift/lib/cpp/test/CMakeLists.txt @@ -19,6 +19,7 @@ include_directories(SYSTEM "${Boost_INCLUDE_DIRS}") +add_definitions("-D__STDC_FORMAT_MACROS") add_definitions("-D__STDC_LIMIT_MACROS") if (WITH_DYN_LINK_TEST) diff --git a/vendor/github.com/apache/thrift/lib/cpp/test/Makefile.am b/vendor/github.com/apache/thrift/lib/cpp/test/Makefile.am index feff93062..95d9889ee 100755 --- a/vendor/github.com/apache/thrift/lib/cpp/test/Makefile.am +++ b/vendor/github.com/apache/thrift/lib/cpp/test/Makefile.am @@ -389,7 +389,7 @@ gen-cpp/SecondService.cpp gen-cpp/ThriftTest_constants.cpp gen-cpp/ThriftTest.cp gen-cpp/ChildService.cpp gen-cpp/ChildService.h gen-cpp/ParentService.cpp gen-cpp/ParentService.h gen-cpp/proc_types.cpp gen-cpp/proc_types.h: processor/proc.thrift $(THRIFT) --gen cpp:templates,cob_style $< -AM_CPPFLAGS = $(BOOST_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -D__STDC_LIMIT_MACROS -I. +AM_CPPFLAGS = $(BOOST_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I. AM_LDFLAGS = $(BOOST_LDFLAGS) AM_CXXFLAGS = -Wall -Wextra -pedantic diff --git a/vendor/github.com/apache/thrift/lib/d/Makefile.am b/vendor/github.com/apache/thrift/lib/d/Makefile.am index 5c529bae3..2a8121856 100644 --- a/vendor/github.com/apache/thrift/lib/d/Makefile.am +++ b/vendor/github.com/apache/thrift/lib/d/Makefile.am @@ -177,7 +177,7 @@ unittest/.directory: touch $@ unittest/debug/%: src/%.d $(all_targets) unittest/emptymain.d - $(DMD) -gc -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ + $(DMD) -g -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ unittest/release/%: src/%.d $(all_targets) unittest/emptymain.d $(DMD) -O -release -of$(subst /,$(DMD_OF_DIRSEP),$@) $(d_test_flags) $^ diff --git a/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/http.d b/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/http.d index c7d1f5094..0e58deeb6 100644 --- a/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/http.d +++ b/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/http.d @@ -330,7 +330,7 @@ protected: "Host: " ~ host_ ~ "\r\n" ~ "Content-Type: application/x-thrift\r\n" ~ "Content-Length: " ~ to!string(dataLength) ~ "\r\n" ~ - "Accept: application/x-thrift\r\n" + "Accept: application/x-thrift\r\n" ~ "User-Agent: Thrift/" ~ VERSION ~ " (D/TClientHttpTransport)\r\n" ~ "\r\n"; } diff --git a/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/socket.d b/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/socket.d index 38b567a07..228abf004 100644 --- a/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/socket.d +++ b/vendor/github.com/apache/thrift/lib/d/src/thrift/transport/socket.d @@ -79,8 +79,8 @@ abstract class TSocketBase : TBaseTransport { version (none) assert(written <= buf.length, text("Implementation wrote " ~ "more data than requested to?! (", written, " vs. ", buf.length, ")")); } body { - assert(0, "DMD bug? – Why would contracts work for interfaces, but not " - "for abstract methods? " + assert(0, "DMD bug? – Why would contracts work for interfaces, but not " ~ + "for abstract methods? " ~ "(Error: function […] in and out contracts require function body"); } diff --git a/vendor/github.com/apache/thrift/lib/hs/Thrift.cabal b/vendor/github.com/apache/thrift/lib/hs/thrift.cabal similarity index 100% rename from vendor/github.com/apache/thrift/lib/hs/Thrift.cabal rename to vendor/github.com/apache/thrift/lib/hs/thrift.cabal diff --git a/vendor/github.com/apache/thrift/lib/nodejs/lib/thrift/multiplexed_protocol.js b/vendor/github.com/apache/thrift/lib/nodejs/lib/thrift/multiplexed_protocol.js index 9caf6ab52..d078aa226 100644 --- a/vendor/github.com/apache/thrift/lib/nodejs/lib/thrift/multiplexed_protocol.js +++ b/vendor/github.com/apache/thrift/lib/nodejs/lib/thrift/multiplexed_protocol.js @@ -52,17 +52,17 @@ Multiplexer.prototype.createClient = function(serviceName, ServiceClient, connec if (ServiceClient.Client) { ServiceClient = ServiceClient.Client; } - var self = this; - ServiceClient.prototype.new_seqid = function() { - self.seqid += 1; - return self.seqid; - }; var writeCb = function(buf, seqid) { connection.write(buf,seqid); }; var transport = new connection.transport(undefined, writeCb); var protocolWrapper = new Wrapper(serviceName, connection.protocol, connection); var client = new ServiceClient(transport, protocolWrapper); + var self = this; + client.new_seqid = function() { + self.seqid += 1; + return self.seqid; + }; if (typeof connection.client !== 'object') { connection.client = {}; diff --git a/vendor/github.com/apache/thrift/lib/php/lib/Thrift/Transport/TSocket.php b/vendor/github.com/apache/thrift/lib/php/lib/Thrift/Transport/TSocket.php index dd87039d0..a1872b98b 100644 --- a/vendor/github.com/apache/thrift/lib/php/lib/Thrift/Transport/TSocket.php +++ b/vendor/github.com/apache/thrift/lib/php/lib/Thrift/Transport/TSocket.php @@ -242,8 +242,10 @@ class TSocket extends TTransport throw new TException($error); } - $socket = socket_import_stream($this->handle_); - socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); + if (function_exists('socket_import_stream') && function_exists('socket_set_option')) { + $socket = socket_import_stream($this->handle_); + socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); + } } /** diff --git a/vendor/github.com/apache/thrift/lib/py/src/ext/types.h b/vendor/github.com/apache/thrift/lib/py/src/ext/types.h index 2fc9d9cc7..5cd8dda9e 100644 --- a/vendor/github.com/apache/thrift/lib/py/src/ext/types.h +++ b/vendor/github.com/apache/thrift/lib/py/src/ext/types.h @@ -23,6 +23,7 @@ #include #ifdef _MSC_VER +#define __STDC_FORMAT_MACROS #define __STDC_LIMIT_MACROS #endif #include diff --git a/vendor/github.com/apache/thrift/test/cpp/Makefile.am b/vendor/github.com/apache/thrift/test/cpp/Makefile.am index 82dc5187d..e2c21f5dd 100755 --- a/vendor/github.com/apache/thrift/test/cpp/Makefile.am +++ b/vendor/github.com/apache/thrift/test/cpp/Makefile.am @@ -107,7 +107,7 @@ gen-cpp/StressTest_types.cpp gen-cpp/StressTest_constants.cpp gen-cpp/Service.cp $(THRIFT) --gen cpp $< AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(LIBEVENT_CPPFLAGS) -I$(top_srcdir)/lib/cpp/src -Igen-cpp -AM_CXXFLAGS = -Wall -Wextra -pedantic -D__STDC_LIMIT_MACROS +AM_CXXFLAGS = -Wall -Wextra -pedantic -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS AM_LDFLAGS = $(BOOST_LDFLAGS) $(LIBEVENT_LDFLAGS) $(ZLIB_LIBS) clean-local: diff --git a/vendor/github.com/apache/thrift/test/go/src/common/mock_handler.go b/vendor/github.com/apache/thrift/test/go/src/common/mock_handler.go deleted file mode 100644 index 3960e1ab7..000000000 --- a/vendor/github.com/apache/thrift/test/go/src/common/mock_handler.go +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -// Automatically generated by MockGen. DO NOT EDIT! -// Source: gen/thrifttest (interfaces: ThriftTest) - -package common - -import ( - thrifttest "gen/thrifttest" - gomock "github.com/golang/mock/gomock" - context "golang.org/x/net/context" -) - -// MockThriftTest is a mock of ThriftTest interface -type MockThriftTest struct { - ctrl *gomock.Controller - recorder *MockThriftTestMockRecorder -} - -// MockThriftTestMockRecorder is the mock recorder for MockThriftTest -type MockThriftTestMockRecorder struct { - mock *MockThriftTest -} - -// NewMockThriftTest creates a new mock instance -func NewMockThriftTest(ctrl *gomock.Controller) *MockThriftTest { - mock := &MockThriftTest{ctrl: ctrl} - mock.recorder = &MockThriftTestMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (_m *MockThriftTest) EXPECT() *MockThriftTestMockRecorder { - return _m.recorder -} - -// TestBinary mocks base method -func (_m *MockThriftTest) TestBinary(_param0 context.Context, _param1 []byte) ([]byte, error) { - ret := _m.ctrl.Call(_m, "TestBinary", _param0, _param1) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestBinary indicates an expected call of TestBinary -func (_mr *MockThriftTestMockRecorder) TestBinary(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBinary", arg0, arg1) -} - -// TestBool mocks base method -func (_m *MockThriftTest) TestBool(_param0 context.Context, _param1 bool) (bool, error) { - ret := _m.ctrl.Call(_m, "TestBool", _param0, _param1) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestBool indicates an expected call of TestBool -func (_mr *MockThriftTestMockRecorder) TestBool(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestBool", arg0, arg1) -} - -// TestByte mocks base method -func (_m *MockThriftTest) TestByte(_param0 context.Context, _param1 int8) (int8, error) { - ret := _m.ctrl.Call(_m, "TestByte", _param0, _param1) - ret0, _ := ret[0].(int8) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestByte indicates an expected call of TestByte -func (_mr *MockThriftTestMockRecorder) TestByte(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestByte", arg0, arg1) -} - -// TestDouble mocks base method -func (_m *MockThriftTest) TestDouble(_param0 context.Context, _param1 float64) (float64, error) { - ret := _m.ctrl.Call(_m, "TestDouble", _param0, _param1) - ret0, _ := ret[0].(float64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestDouble indicates an expected call of TestDouble -func (_mr *MockThriftTestMockRecorder) TestDouble(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestDouble", arg0, arg1) -} - -// TestEnum mocks base method -func (_m *MockThriftTest) TestEnum(_param0 context.Context, _param1 thrifttest.Numberz) (thrifttest.Numberz, error) { - ret := _m.ctrl.Call(_m, "TestEnum", _param0, _param1) - ret0, _ := ret[0].(thrifttest.Numberz) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestEnum indicates an expected call of TestEnum -func (_mr *MockThriftTestMockRecorder) TestEnum(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestEnum", arg0, arg1) -} - -// TestException mocks base method -func (_m *MockThriftTest) TestException(_param0 context.Context, _param1 string) error { - ret := _m.ctrl.Call(_m, "TestException", _param0, _param1) - ret0, _ := ret[0].(error) - return ret0 -} - -// TestException indicates an expected call of TestException -func (_mr *MockThriftTestMockRecorder) TestException(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestException", arg0, arg1) -} - -// TestI32 mocks base method -func (_m *MockThriftTest) TestI32(_param0 context.Context, _param1 int32) (int32, error) { - ret := _m.ctrl.Call(_m, "TestI32", _param0, _param1) - ret0, _ := ret[0].(int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestI32 indicates an expected call of TestI32 -func (_mr *MockThriftTestMockRecorder) TestI32(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI32", arg0, arg1) -} - -// TestI64 mocks base method -func (_m *MockThriftTest) TestI64(_param0 context.Context, _param1 int64) (int64, error) { - ret := _m.ctrl.Call(_m, "TestI64", _param0, _param1) - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestI64 indicates an expected call of TestI64 -func (_mr *MockThriftTestMockRecorder) TestI64(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestI64", arg0, arg1) -} - -// TestInsanity mocks base method -func (_m *MockThriftTest) TestInsanity(_param0 context.Context, _param1 *thrifttest.Insanity) (map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity, error) { - ret := _m.ctrl.Call(_m, "TestInsanity", _param0, _param1) - ret0, _ := ret[0].(map[thrifttest.UserId]map[thrifttest.Numberz]*thrifttest.Insanity) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestInsanity indicates an expected call of TestInsanity -func (_mr *MockThriftTestMockRecorder) TestInsanity(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestInsanity", arg0, arg1) -} - -// TestList mocks base method -func (_m *MockThriftTest) TestList(_param0 context.Context, _param1 []int32) ([]int32, error) { - ret := _m.ctrl.Call(_m, "TestList", _param0, _param1) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestList indicates an expected call of TestList -func (_mr *MockThriftTestMockRecorder) TestList(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestList", arg0, arg1) -} - -// TestMap mocks base method -func (_m *MockThriftTest) TestMap(_param0 context.Context, _param1 map[int32]int32) (map[int32]int32, error) { - ret := _m.ctrl.Call(_m, "TestMap", _param0, _param1) - ret0, _ := ret[0].(map[int32]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestMap indicates an expected call of TestMap -func (_mr *MockThriftTestMockRecorder) TestMap(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMap", arg0, arg1) -} - -// TestMapMap mocks base method -func (_m *MockThriftTest) TestMapMap(_param0 context.Context, _param1 int32) (map[int32]map[int32]int32, error) { - ret := _m.ctrl.Call(_m, "TestMapMap", _param0, _param1) - ret0, _ := ret[0].(map[int32]map[int32]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestMapMap indicates an expected call of TestMapMap -func (_mr *MockThriftTestMockRecorder) TestMapMap(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMapMap", arg0, arg1) -} - -// TestMulti mocks base method -func (_m *MockThriftTest) TestMulti(_param0 context.Context, _param1 int8, _param2 int32, _param3 int64, _param4 map[int16]string, _param5 thrifttest.Numberz, _param6 thrifttest.UserId) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestMulti", _param0, _param1, _param2, _param3, _param4, _param5, _param6) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestMulti indicates an expected call of TestMulti -func (_mr *MockThriftTestMockRecorder) TestMulti(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMulti", arg0, arg1, arg2, arg3, arg4, arg5, arg6) -} - -// TestMultiException mocks base method -func (_m *MockThriftTest) TestMultiException(_param0 context.Context, _param1 string, _param2 string) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestMultiException", _param0, _param1, _param2) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestMultiException indicates an expected call of TestMultiException -func (_mr *MockThriftTestMockRecorder) TestMultiException(arg0, arg1, arg2 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestMultiException", arg0, arg1, arg2) -} - -// TestNest mocks base method -func (_m *MockThriftTest) TestNest(_param0 context.Context, _param1 *thrifttest.Xtruct2) (*thrifttest.Xtruct2, error) { - ret := _m.ctrl.Call(_m, "TestNest", _param0, _param1) - ret0, _ := ret[0].(*thrifttest.Xtruct2) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestNest indicates an expected call of TestNest -func (_mr *MockThriftTestMockRecorder) TestNest(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestNest", arg0, arg1) -} - -// TestOneway mocks base method -func (_m *MockThriftTest) TestOneway(_param0 context.Context, _param1 int32) error { - ret := _m.ctrl.Call(_m, "TestOneway", _param0, _param1) - ret0, _ := ret[0].(error) - return ret0 -} - -// TestOneway indicates an expected call of TestOneway -func (_mr *MockThriftTestMockRecorder) TestOneway(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestOneway", arg0, arg1) -} - -// TestSet mocks base method -func (_m *MockThriftTest) TestSet(_param0 context.Context, _param1 []int32) ([]int32, error) { - ret := _m.ctrl.Call(_m, "TestSet", _param0, _param1) - ret0, _ := ret[0].([]int32) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestSet indicates an expected call of TestSet -func (_mr *MockThriftTestMockRecorder) TestSet(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestSet", arg0, arg1) -} - -// TestString mocks base method -func (_m *MockThriftTest) TestString(_param0 context.Context, _param1 string) (string, error) { - ret := _m.ctrl.Call(_m, "TestString", _param0, _param1) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestString indicates an expected call of TestString -func (_mr *MockThriftTestMockRecorder) TestString(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestString", arg0, arg1) -} - -// TestStringMap mocks base method -func (_m *MockThriftTest) TestStringMap(_param0 context.Context, _param1 map[string]string) (map[string]string, error) { - ret := _m.ctrl.Call(_m, "TestStringMap", _param0, _param1) - ret0, _ := ret[0].(map[string]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestStringMap indicates an expected call of TestStringMap -func (_mr *MockThriftTestMockRecorder) TestStringMap(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStringMap", arg0, arg1) -} - -// TestStruct mocks base method -func (_m *MockThriftTest) TestStruct(_param0 context.Context, _param1 *thrifttest.Xtruct) (*thrifttest.Xtruct, error) { - ret := _m.ctrl.Call(_m, "TestStruct", _param0, _param1) - ret0, _ := ret[0].(*thrifttest.Xtruct) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestStruct indicates an expected call of TestStruct -func (_mr *MockThriftTestMockRecorder) TestStruct(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestStruct", arg0, arg1) -} - -// TestTypedef mocks base method -func (_m *MockThriftTest) TestTypedef(_param0 context.Context, _param1 thrifttest.UserId) (thrifttest.UserId, error) { - ret := _m.ctrl.Call(_m, "TestTypedef", _param0, _param1) - ret0, _ := ret[0].(thrifttest.UserId) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// TestTypedef indicates an expected call of TestTypedef -func (_mr *MockThriftTestMockRecorder) TestTypedef(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestTypedef", arg0, arg1) -} - -// TestVoid mocks base method -func (_m *MockThriftTest) TestVoid(_param0 context.Context) error { - ret := _m.ctrl.Call(_m, "TestVoid", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -// TestVoid indicates an expected call of TestVoid -func (_mr *MockThriftTestMockRecorder) TestVoid(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "TestVoid", arg0) -} diff --git a/vendor/github.com/apache/thrift/test/py.twisted/test_suite.py b/vendor/github.com/apache/thrift/test/py.twisted/test_suite.py index 43149a4c9..886de44d2 100755 --- a/vendor/github.com/apache/thrift/test/py.twisted/test_suite.py +++ b/vendor/github.com/apache/thrift/test/py.twisted/test_suite.py @@ -36,12 +36,11 @@ from twisted.trial import unittest from twisted.internet import defer, reactor from twisted.internet.protocol import ClientCreator -from zope.interface import implements +from zope.interface import implementer +@implementer(ThriftTest.Iface) class TestHandler: - implements(ThriftTest.Iface) - def __init__(self): self.onewaysQueue = defer.DeferredQueue() diff --git a/vendor/github.com/apache/thrift/test/tests.json b/vendor/github.com/apache/thrift/test/tests.json index 818982e02..2b846018b 100644 --- a/vendor/github.com/apache/thrift/test/tests.json +++ b/vendor/github.com/apache/thrift/test/tests.json @@ -160,7 +160,7 @@ ] }, "client": { - "timeout": 2.9, + "timeout": 6, "command": [ "node", "client.js", diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go index 1ff1529a8..b699e4449 100644 --- a/vendor/github.com/asaskevich/govalidator/validator.go +++ b/vendor/github.com/asaskevich/govalidator/validator.go @@ -595,7 +595,7 @@ func ValidateStruct(s interface{}) (bool, error) { continue // Private field } structResult := true - if valueField.Kind() == reflect.Struct { + if valueField.Kind() == reflect.Struct && typeField.Tag.Get(tagName) != "-" { var err error structResult, err = ValidateStruct(valueField.Interface()) if err != nil { diff --git a/vendor/github.com/cactus/go-statsd-client/.travis.yml b/vendor/github.com/cactus/go-statsd-client/.travis.yml index ddcb85ce8..c6419e6d2 100644 --- a/vendor/github.com/cactus/go-statsd-client/.travis.yml +++ b/vendor/github.com/cactus/go-statsd-client/.travis.yml @@ -2,8 +2,9 @@ language: go sudo: false script: go test -v -cpu=1,2 ./... go: - - 1.3 - 1.4 - 1.5 - 1.6 - 1.7 + - 1.8 + - 1.9 diff --git a/vendor/github.com/ccirello/supervisor/.gitignore b/vendor/github.com/ccirello/supervisor/.gitignore deleted file mode 100644 index a1ab3d994..000000000 --- a/vendor/github.com/ccirello/supervisor/.gitignore +++ /dev/null @@ -1 +0,0 @@ -supervisor.test diff --git a/vendor/github.com/ccirello/supervisor/.travis.yml b/vendor/github.com/ccirello/supervisor/.travis.yml deleted file mode 100644 index b4c79c339..000000000 --- a/vendor/github.com/ccirello/supervisor/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: go -go_import_path: cirello.io/supervisor -go: - - 1.7.5 - - 1.8 - - tip diff --git a/vendor/github.com/ccirello/supervisor/README.md b/vendor/github.com/ccirello/supervisor/README.md deleted file mode 100644 index 91aa96402..000000000 --- a/vendor/github.com/ccirello/supervisor/README.md +++ /dev/null @@ -1,5 +0,0 @@ -[![Build Status](https://travis-ci.org/ucirello/supervisor.png?branch=master)](https://travis-ci.org/ucirello/supervisor) - -go get [-u] cirello.io/supervisor - -http://godoc.org/cirello.io/supervisor diff --git a/vendor/github.com/ccirello/supervisor/anon.go b/vendor/github.com/ccirello/supervisor/anon.go deleted file mode 100644 index c737a1742..000000000 --- a/vendor/github.com/ccirello/supervisor/anon.go +++ /dev/null @@ -1,40 +0,0 @@ -package supervisor - -import ( - "context" - "fmt" - "sync" -) - -var ( - universalAnonSvcMu sync.Mutex - universalAnonSvc uint64 -) - -func getUniversalAnonSvc() uint64 { - universalAnonSvcMu.Lock() - universalAnonSvc++ - v := universalAnonSvc - universalAnonSvcMu.Unlock() - return v -} - -type anonymousService struct { - id uint64 - f func(context.Context) -} - -func newAnonymousService(f func(context.Context)) *anonymousService { - return &anonymousService{ - id: getUniversalAnonSvc(), - f: f, - } -} - -func (a anonymousService) Serve(ctx context.Context) { - a.f(ctx) -} - -func (a anonymousService) String() string { - return fmt.Sprintf("anonymous service %d", a.id) -} diff --git a/vendor/github.com/ccirello/supervisor/doc.go b/vendor/github.com/ccirello/supervisor/doc.go deleted file mode 100644 index 4effe3b0d..000000000 --- a/vendor/github.com/ccirello/supervisor/doc.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Package supervisor provides supervisor trees for Go applications. - -This package implements supervisor trees, similar to what Erlang runtime offers. -It is built on top of context package, with all of its advantages, namely the -possibility trickle down context-related values and cancelation signals. - -A supervisor tree can be composed either of services or other supervisors - each -supervisor can have its own set of configurations. Any instance of -supervisor.Service can be added to a tree. - - Supervisor - ├─▶ Supervisor (if one service dies, only one is restarted) - │ ├─▶ Service - │ └─▶ Service - ├─▶ Group (if one service dies, all others are restarted too) - │ └─▶ Service - │ Service - │ Service - └─▶ Service - -Example: - package main - - import ( - "fmt" - "os" - "os/signal" - "time" - - "cirello.io/supervisor" - "context" - ) - - type Simpleservice int - - func (s *Simpleservice) String() string { - return fmt.Sprintf("simple service %d", int(*s)) - } - - func (s *Simpleservice) Serve(ctx context.Context) { - for { - select { - case <-ctx.Done(): - return - default: - fmt.Println("do something...") - time.Sleep(500 * time.Millisecond) - } - } - } - - func main(){ - svc := Simpleservice(1) - supervisor.Add(&svc) - - // Simply, if not special context is needed: - // supervisor.Serve() - // Or, using context.Context to propagate behavior: - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) - ctx, cancel := context.WithCancel(context.Background()) - go func(){ - <-c - fmt.Println("halting supervisor...") - cancel() - }() - supervisor.ServeContext(ctx) - } - -TheJerf's blog post about Suture is a very good and helpful read to understand -how this package has been implemented. - -This is package is inspired by github.com/thejerf/suture - -http://www.jerf.org/iri/post/2930 -*/ -package supervisor // import "cirello.io/supervisor" diff --git a/vendor/github.com/ccirello/supervisor/group.go b/vendor/github.com/ccirello/supervisor/group.go deleted file mode 100644 index 025755165..000000000 --- a/vendor/github.com/ccirello/supervisor/group.go +++ /dev/null @@ -1,69 +0,0 @@ -package supervisor - -import ( - "context" - "sync" -) - -// Group is a superset of Supervisor datastructure responsible for offering a -// supervisor tree whose all services are restarted whenever one of them fail or -// is restarted. It assumes that all services rely on each other. It implements -// Service, therefore it can be nested if necessary either with other Group or -// Supervisor. When passing the Group around, remind to do it as reference -// (&group). -type Group struct { - *Supervisor -} - -// Serve starts the Group tree. It can be started only once at a time. If -// stopped (canceled), it can be restarted. In case of concurrent calls, it will -// hang until the current call is completed. -func (g *Group) Serve(ctx context.Context) { - if g.Supervisor == nil { - panic("Supervisor missing for this Group.") - } - g.Supervisor.prepare() - restartCtx, cancel := context.WithCancel(ctx) - - var ( - mu sync.Mutex - processingFailure bool - ) - processFailure := func() { - mu.Lock() - if processingFailure { - mu.Unlock() - return - } - processingFailure = true - mu.Unlock() - - if !g.shouldRestart() { - cancel() - return - } - - g.mu.Lock() - g.log("halting all services after failure") - for _, c := range g.terminations { - c() - } - - g.cancelations = make(map[string]context.CancelFunc) - g.mu.Unlock() - - go func() { - g.log("waiting for all services termination") - g.runningServices.Wait() - g.log("waiting for all services termination - completed") - - mu.Lock() - processingFailure = false - mu.Unlock() - - g.log("triggering group restart") - g.added <- struct{}{} - }() - } - serve(g.Supervisor, restartCtx, processFailure) -} diff --git a/vendor/github.com/ccirello/supervisor/helpers.go b/vendor/github.com/ccirello/supervisor/helpers.go deleted file mode 100644 index f11fe9e67..000000000 --- a/vendor/github.com/ccirello/supervisor/helpers.go +++ /dev/null @@ -1,101 +0,0 @@ -package supervisor - -import ( - "context" - "fmt" - "sync" -) - -func serve(s *Supervisor, ctx context.Context, processFailure processFailure) { - s.running.Lock() - defer s.running.Unlock() - - startServices(s, ctx, processFailure) - var wg sync.WaitGroup - wg.Add(1) - go func() { - for { - select { - case <-s.added: - startServices(s, ctx, processFailure) - - case <-ctx.Done(): - wg.Done() - return - } - } - }() - <-ctx.Done() - - wg.Wait() - s.runningServices.Wait() - - s.mu.Lock() - s.cancelations = make(map[string]context.CancelFunc) - s.mu.Unlock() -} - -func startServices(s *Supervisor, supervisorCtx context.Context, processFailure processFailure) { - s.mu.Lock() - defer s.mu.Unlock() - - var wg sync.WaitGroup - for _, name := range s.svcorder { - svc := s.services[name] - if _, ok := s.cancelations[name]; ok { - continue - } - - wg.Add(1) - - terminateCtx, terminate := context.WithCancel(supervisorCtx) - s.cancelations[name] = terminate - s.terminations[name] = terminate - - go func(name string, svc service) { - s.runningServices.Add(1) - defer s.runningServices.Done() - wg.Done() - retry := true - for retry { - retry = svc.svctype == Permanent - s.log(fmt.Sprintf("%s starting", name)) - func() { - defer func() { - if r := recover(); r != nil { - s.log(fmt.Sprintf("%s panic: %v", name, r)) - retry = svc.svctype == Permanent || svc.svctype == Transient - } - }() - ctx, cancel := context.WithCancel(terminateCtx) - s.mu.Lock() - s.cancelations[name] = cancel - s.mu.Unlock() - svc.svc.Serve(ctx) - }() - if retry { - processFailure() - } - select { - case <-terminateCtx.Done(): - s.log(fmt.Sprintf("%s restart aborted (terminated)", name)) - return - case <-supervisorCtx.Done(): - s.log(fmt.Sprintf("%s restart aborted (supervisor halted)", name)) - return - default: - } - switch svc.svctype { - case Temporary: - s.log(fmt.Sprintf("%s exited (temporary)", name)) - return - case Transient: - s.log(fmt.Sprintf("%s exited (transient)", name)) - default: - s.log(fmt.Sprintf("%s exited (permanent)", name)) - } - } - }(name, svc) - } - wg.Wait() -} diff --git a/vendor/github.com/ccirello/supervisor/stdsupervisor.go b/vendor/github.com/ccirello/supervisor/stdsupervisor.go deleted file mode 100644 index 1156177c4..000000000 --- a/vendor/github.com/ccirello/supervisor/stdsupervisor.go +++ /dev/null @@ -1,108 +0,0 @@ -package supervisor - -import ( - "context" - "sync" -) - -var ( - defaultSupervisor Supervisor - running sync.Mutex - defaultContext = context.Background() -) - -func init() { - defaultSupervisor.Name = "default supervisor" -} - -// Add inserts new service into the default supervisor. If it is already -// started, it will launch it automatically. -func Add(service Service) { - defaultSupervisor.Add(service) -} - -// AddFunc inserts new anonymous service into the default supervisor. If it is -// already started, it will launch it automatically. -func AddFunc(f func(context.Context)) { - defaultSupervisor.AddFunc(f) -} - -// Cancelations return a list of services names of default supervisor and their -// cancelation calls. These calls be used to force a service restart. -func Cancelations() map[string]context.CancelFunc { - return defaultSupervisor.Cancelations() -} - -// Remove stops the service in the default supervisor tree and remove from it. -func Remove(name string) { - defaultSupervisor.Remove(name) -} - -// Serve starts the default supervisor tree. It can be started only once at a -// time. If stopped (canceled), it can be restarted. In case of concurrent -// calls, it will hang until the current call is completed. It can run only one -// per package-level. If you need many, use -// supervisor.Supervisor/supervisor.Group instead of supervisor.Serve{,Group}. -// After its conclusion, its internal state is reset. -func Serve() { - running.Lock() - defaultSupervisor.Serve(defaultContext) - defaultSupervisor.reset() - defaultContext = context.Background() - running.Unlock() -} - -// ServeContext starts the default upervisor tree with a custom context.Context. -// It can be started only once at a time. If stopped (canceled), it can be -// restarted. In case of concurrent calls, it will hang until the current call -// is completed. After its conclusion, its internal state is reset. -func ServeContext(ctx context.Context) { - running.Lock() - defaultSupervisor.Serve(ctx) - defaultSupervisor.reset() - running.Unlock() -} - -// ServeGroup starts the default supervisor tree within a Group. It can be -// started only once at a time. If stopped (canceled), it can be restarted. -// In case of concurrent calls, it will hang until the current call is -// completed. It can run only one per package-level. If you need many, use -// supervisor.ServeContext/supervisor.ServeGroupContext instead of -// supervisor.Serve/supervisor.ServeGroup. After its conclusion, its internal -// state is reset. -func ServeGroup() { - running.Lock() - var group Group - group.Supervisor = &defaultSupervisor - group.Serve(defaultContext) - defaultSupervisor.reset() - defaultContext = context.Background() - running.Unlock() -} - -// ServeGroupContext starts the defaultSupervisor tree with a custom -// context.Context. It can be started only once at a time. If stopped -// (canceled), it can be restarted. In case of concurrent calls, it will hang -// until the current call is completed. After its conclusion, its internal -// state is reset. -func ServeGroupContext(ctx context.Context) { - running.Lock() - var group Group - group.Supervisor = &defaultSupervisor - group.Serve(ctx) - defaultSupervisor.reset() - running.Unlock() -} - -// Services return a list of services of default supervisor. -func Services() map[string]Service { - return defaultSupervisor.Services() -} - -// SetDefaultContext allows to change the context used for supervisor.Serve() -// and supervisor.ServeGroup(). -func SetDefaultContext(ctx context.Context) { - running.Lock() - defaultContext = ctx - running.Unlock() -} diff --git a/vendor/github.com/ccirello/supervisor/stdsupervisor_example_test.go b/vendor/github.com/ccirello/supervisor/stdsupervisor_example_test.go deleted file mode 100644 index 427cd713c..000000000 --- a/vendor/github.com/ccirello/supervisor/stdsupervisor_example_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package supervisor_test - -import ( - "context" - "fmt" - "sync" - - "cirello.io/supervisor" -) - -type Simpleservice struct { - id int - sync.WaitGroup -} - -func (s *Simpleservice) Serve(ctx context.Context) { - fmt.Println(s.String()) - s.Done() - <-ctx.Done() -} - -func (s *Simpleservice) String() string { - return fmt.Sprintf("simple service %d", s.id) -} - -func ExampleAddFunc() { - var svc sync.WaitGroup - - svc.Add(1) - supervisor.AddFunc(func(ctx context.Context) { - fmt.Println("anonymous service") - svc.Done() - <-ctx.Done() - }) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.ServeContext(ctx) - wg.Done() - }() - - svc.Wait() - cancel() - wg.Wait() - - // output: - // anonymous service -} - -func ExampleServeContext() { - svc := &Simpleservice{id: 1} - svc.Add(1) - supervisor.Add(svc) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.ServeContext(ctx) - wg.Done() - }() - - svc.Wait() - cancel() - wg.Wait() - - // output: - // simple service 1 -} - -func ExampleServeGroupContext() { - svc1 := &Simpleservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &Simpleservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.ServeGroupContext(ctx) - wg.Done() - }() - - svc1.Wait() - svc2.Wait() - cancel() - wg.Wait() - - // unordered output: - // simple service 1 - // simple service 2 -} - -func ExampleServe() { - svc := &Simpleservice{id: 1} - svc.Add(1) - supervisor.Add(svc) - - var cancel context.CancelFunc - ctx, cancel := context.WithCancel(context.Background()) - supervisor.SetDefaultContext(ctx) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve() - wg.Done() - }() - - svc.Wait() - cancel() - wg.Wait() - - // output: - // simple service 1 -} - -func ExampleServeGroup() { - svc1 := &Simpleservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &Simpleservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - supervisor.SetDefaultContext(ctx) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.ServeGroup() - wg.Done() - }() - - svc1.Wait() - svc2.Wait() - cancel() - wg.Wait() - - // unordered output: - // simple service 1 - // simple service 2 -} diff --git a/vendor/github.com/ccirello/supervisor/stdsupervisor_test.go b/vendor/github.com/ccirello/supervisor/stdsupervisor_test.go deleted file mode 100644 index ffc6366a8..000000000 --- a/vendor/github.com/ccirello/supervisor/stdsupervisor_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package supervisor - -import ( - "context" - "sync" - "testing" -) - -func TestAddFunc(t *testing.T) { - t.Parallel() - - universalAnonSvcMu.Lock() - oldCount := universalAnonSvc - universalAnonSvc = 0 - universalAnonSvcMu.Unlock() - defer func() { - universalAnonSvcMu.Lock() - universalAnonSvc = oldCount - universalAnonSvcMu.Unlock() - }() - - var ( - runCount int - wg sync.WaitGroup - ) - - wg.Add(1) - AddFunc(func(ctx context.Context) { - runCount++ - wg.Done() - <-ctx.Done() - }) - - ctx, cancel := context.WithCancel(context.Background()) - go ServeContext(ctx) - - svcs := Services() - if _, ok := svcs["anonymous service 1"]; !ok { - t.Errorf("anonymous service was not found in service list") - } - - wg.Wait() - cancel() - - if runCount == 0 { - t.Errorf("anonymous service should have been started") - } -} - -func TestDefaultSupevisorAndGroup(t *testing.T) { - t.Parallel() - - svc := &holdingservice{id: 1} - svc.Add(1) - - ctx, cancel := context.WithCancel(context.Background()) - SetDefaultContext(ctx) - Add(svc) - if len(defaultSupervisor.services) != 1 { - t.Errorf("%s should have been added", svc.String()) - } - - Remove(svc.String()) - if len(defaultSupervisor.services) != 0 { - t.Errorf("%s should have been removed. services: %#v", svc.String(), defaultSupervisor.services) - } - - Add(svc) - - svcs := Services() - if _, ok := svcs[svc.String()]; !ok { - t.Errorf("%s should have been found", svc.String()) - } - - var wg sync.WaitGroup - wg.Add(1) - go func() { - Serve() - wg.Done() - }() - - svc.Wait() - - cs := Cancelations() - if _, ok := cs[svc.String()]; !ok { - t.Errorf("%s's cancelation should have been found. %#v", svc.String(), cs) - } - - cancel() - wg.Wait() - - ctx, cancel = context.WithCancel(context.Background()) - SetDefaultContext(ctx) - svc.Add(1) - Add(svc) - if len(defaultSupervisor.services) != 1 { - t.Errorf("%s should have been added", svc.String()) - } - - wg.Add(1) - go func() { - ServeGroup() - wg.Done() - }() - - svc.Wait() - cancel() - wg.Wait() -} diff --git a/vendor/github.com/ccirello/supervisor/supervisor.go b/vendor/github.com/ccirello/supervisor/supervisor.go deleted file mode 100644 index c66d2b2c8..000000000 --- a/vendor/github.com/ccirello/supervisor/supervisor.go +++ /dev/null @@ -1,245 +0,0 @@ -package supervisor - -import ( - "context" - "fmt" - "log" - "sync" - "time" -) - -type service struct { - svc Service - svctype ServiceType -} - -type processFailure func() - -// AlwaysRestart adjusts the supervisor to never halt in face of failures. -const AlwaysRestart = -1 - -// ServiceType defines the restart strategy for a service. -type ServiceType int - -const ( - // Permanent services are always restarted - Permanent ServiceType = iota - // Transient services are restarted only when panic. - Transient - // Temporary services are never restarted. - Temporary -) - -// Service is the public interface expected by a Supervisor. -// -// This will be internally named after the result of fmt.Stringer, if available. -// Otherwise it is going to use an internal representation for the service -// name. -type Service interface { - // Serve is called by a Supervisor to start the service. It expects the - // service to honor the passed context and its lifetime. Observe - // <-ctx.Done() and ctx.Err(). If the service is stopped by anything - // but the Supervisor, it will get started again. Be careful with shared - // state among restarts. - Serve(ctx context.Context) -} - -// Supervisor is the basic datastructure responsible for offering a supervisor -// tree. It implements Service, therefore it can be nested if necessary. When -// passing the Supervisor around, remind to do it as reference (&supervisor). -// Once the supervisor is started, its attributes are frozen. -type Supervisor struct { - // Name for this supervisor tree, used for logging. - Name string - name string - - // MaxRestarts is the number of maximum restarts given MaxTime. If more - // than MaxRestarts occur in the last MaxTime, then the supervisor - // stops all services and halts. Set this to AlwaysRestart to prevent - // supervisor halt. - MaxRestarts int - maxrestarts int - - - // MaxTime is the time period on which the internal restart count will - // be reset. - MaxTime time.Duration - maxtime time.Duration - - // Log is a replaceable function used for overall logging. - // Default: log.Printf. - Log func(interface{}) - log func(interface{}) - - // indicates that supervisor is ready for use. - prepared sync.Once - - // signals that a new service has just been added, so the started - // supervisor picks it up. - added chan struct{} - - // indicates that supervisor has running services. - running sync.Mutex - runningServices sync.WaitGroup - - mu sync.Mutex - svcorder []string // order in which services must be started - services map[string]service // added services - cancelations map[string]context.CancelFunc // each service cancelation - terminations map[string]context.CancelFunc // each service termination call - lastRestart time.Time - restarts int -} - -func (s *Supervisor) prepare() { - s.prepared.Do(s.reset) -} - -func (s *Supervisor) reset() { - s.mu.Lock() - if s.Name == "" { - s.Name = "supervisor" - } - if s.MaxRestarts == 0 { - s.MaxRestarts = 5 - } - if s.MaxTime == 0 { - s.MaxTime = 15 * time.Second - } - if s.Log == nil { - s.Log = func(msg interface{}) { - log.Printf("%s: %v", s.Name, msg) - } - } - - s.name = s.Name - s.maxrestarts = s.MaxRestarts - s.maxtime = s.MaxTime - s.log = s.Log - - s.added = make(chan struct{}) - s.cancelations = make(map[string]context.CancelFunc) - s.services = make(map[string]service) - s.terminations = make(map[string]context.CancelFunc) - s.mu.Unlock() -} - -func (s *Supervisor) shouldRestart() bool { - if s.maxrestarts == AlwaysRestart { - return true - } - - s.mu.Lock() - defer s.mu.Unlock() - if time.Since(s.lastRestart) > s.maxtime { - s.restarts = 0 - } - s.lastRestart = time.Now() - s.restarts++ - return s.restarts < s.maxrestarts -} - -// Cancelations return a list of services names and their cancelation calls. -// These calls be used to force a service restart. -func (s *Supervisor) Cancelations() map[string]context.CancelFunc { - svclist := make(map[string]context.CancelFunc) - s.mu.Lock() - for k, v := range s.cancelations { - svclist[k] = v - } - s.mu.Unlock() - return svclist -} - -// Add inserts into the Supervisor tree a new permanent service. If the -// Supervisor is already started, it will start it automatically. -func (s *Supervisor) Add(service Service) { - s.AddService(service, Permanent) -} - -// AddFunc inserts into the Supervisor tree a new permanent anonymous service. -// If the Supervisor is already started, it will start it automatically. -func (s *Supervisor) AddFunc(f func(context.Context)) { - s.AddService(newAnonymousService(f), Permanent) -} - -// AddService inserts into the Supervisor tree a new service of ServiceType. If -// the Supervisor is already started, it will start it automatically. If the -// same service is added more than once, it will reset its backoff mechanism and -// force a service restart. -func (s *Supervisor) AddService(svc Service, svctype ServiceType) { - s.prepare() - - name := fmt.Sprintf("%s", svc) - s.mu.Lock() - s.services[name] = service{ - svc: svc, - svctype: svctype, - } - s.svcorder = append(s.svcorder, name) - s.mu.Unlock() - - go func() { - s.added <- struct{}{} - }() -} - -// Remove stops the service in the Supervisor tree and remove from it. -func (s *Supervisor) Remove(name string) { - s.prepare() - - s.mu.Lock() - defer s.mu.Unlock() - if _, ok := s.services[name]; !ok { - return - } - - delete(s.services, name) - - for i, n := range s.svcorder { - if name == n { - s.svcorder = append(s.svcorder[:i], s.svcorder[i+1:]...) - break - } - } - - if c, ok := s.terminations[name]; ok { - delete(s.terminations, name) - c() - } - - if _, ok := s.cancelations[name]; ok { - delete(s.cancelations, name) - } -} - -// Serve starts the Supervisor tree. It can be started only once at a time. If -// stopped (canceled), it can be restarted. In case of concurrent calls, it will -// hang until the current call is completed. -func (s *Supervisor) Serve(ctx context.Context) { - s.prepare() - restartCtx, cancel := context.WithCancel(ctx) - processFailure := func() { - restart := s.shouldRestart() - if !restart { - cancel() - } - } - serve(s, restartCtx, processFailure) -} - -// Services return a list of services -func (s *Supervisor) Services() map[string]Service { - svclist := make(map[string]Service) - s.mu.Lock() - for k, v := range s.services { - svclist[k] = v.svc - } - s.mu.Unlock() - return svclist -} - -func (s *Supervisor) String() string { - s.prepare() - return s.name -} diff --git a/vendor/github.com/ccirello/supervisor/supervisor_example_test.go b/vendor/github.com/ccirello/supervisor/supervisor_example_test.go deleted file mode 100644 index 2606c1a9d..000000000 --- a/vendor/github.com/ccirello/supervisor/supervisor_example_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package supervisor_test - -import ( - "context" - "time" - - "cirello.io/supervisor" -) - -func ExampleSupervisor() { - var supervisor supervisor.Supervisor - - svc := &Simpleservice{id: 1} - svc.Add(1) - supervisor.Add(svc) - - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - go supervisor.Serve(ctx) - - svc.Wait() - cancel() -} - -func ExampleGroup() { - supervisor := supervisor.Group{ - Supervisor: &supervisor.Supervisor{}, - } - - svc1 := &Simpleservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &Simpleservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) - go supervisor.Serve(ctx) - - svc1.Wait() - svc2.Wait() - cancel() -} diff --git a/vendor/github.com/ccirello/supervisor/supervisor_test.go b/vendor/github.com/ccirello/supervisor/supervisor_test.go deleted file mode 100644 index fd44f108d..000000000 --- a/vendor/github.com/ccirello/supervisor/supervisor_test.go +++ /dev/null @@ -1,1072 +0,0 @@ -package supervisor - -import ( - "context" - "fmt" - "io/ioutil" - "log" - "sync" - "testing" - "time" -) - -func init() { - log.SetOutput(ioutil.Discard) -} - -func TestAddFuncSupervisor(t *testing.T) { - t.Parallel() - - var ( - runCount int - wg sync.WaitGroup - ) - - wg.Add(1) - var svr Supervisor - svr.AddFunc(func(ctx context.Context) { - runCount++ - wg.Done() - <-ctx.Done() - }) - - ctx, cancel := context.WithCancel(context.Background()) - go svr.Serve(ctx) - - wg.Wait() - cancel() - - if runCount == 0 { - t.Errorf("anonymous service should have been started") - } -} - -func TestAddServiceAfterServe(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestAddServiceAfterServe supervisor" - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - - svc1.Wait() - - svc2 := &holdingservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - svc2.Wait() - - cancel() - <-ctx.Done() - wg.Wait() - - if count := getServiceCount(&supervisor); count != 2 { - t.Errorf("unexpected service count: %v", count) - } -} - -func TestAlwaysRestart(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestAlwaysRestart supervisor", - MaxRestarts: AlwaysRestart, - Log: func(msg interface{}) { - t.Log("supervisor log (always restart):", msg) - }, - } - svc1 := failingservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - - for svc1.Count() < 2 { - } - - cancel() -} - -func TestCascaded(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestCascaded root" - svc1 := waitservice{id: 1} - supervisor.Add(&svc1) - svc2 := waitservice{id: 2} - supervisor.Add(&svc2) - - var childSupervisor Supervisor - childSupervisor.Name = "TestCascaded child" - svc3 := waitservice{id: 3} - childSupervisor.Add(&svc3) - svc4 := waitservice{id: 4} - childSupervisor.Add(&svc4) - supervisor.Add(&childSupervisor) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - for svc1.Count() == 0 || svc3.Count() == 0 { - } - - cancel() - - if count := getServiceCount(&supervisor); count != 3 { - t.Errorf("unexpected service count: %v", count) - } - - switch { - case svc1.count != 1, svc2.count != 1, svc3.count != 1, svc4.count != 1: - t.Errorf("services should have been executed only once. %d %d %d %d", - svc1.count, svc2.count, svc3.count, svc4.count) - } -} - -func TestFailing(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestFailing supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (failing):", msg) - }, - } - svc1 := failingservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - - for svc1.Count() == 0 { - } - - cancel() - - if svc1.count != 1 { - t.Errorf("the failed service should have been started just once. Got: %d", svc1.count) - } -} - -func TestGroupMaxRestart(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Group{ - Supervisor: &Supervisor{ - Name: "TestMaxRestartGroup supervisor", - MaxRestarts: 1, - Log: func(msg interface{}) { - t.Log("supervisor log (max restart group):", msg) - }, - }, - } - svc1 := failingservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - - wg.Wait() - cancel() - - if svc1.count > 1 { - t.Error("the panic service should have not been started more than once.") - } -} - -func TestHaltAfterFailure(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestHaltAfterFailure supervisor", - MaxRestarts: 1, - Log: func(msg interface{}) { - t.Log("supervisor log (halt after failure):", msg) - }, - } - svc1 := failingservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - - for svc1.Count() == 0 { - } - - cancel() - - if svc1.count != 1 { - t.Errorf("the failed service should have been started just once. Got: %d", svc1.count) - } -} - -func TestHaltAfterPanic(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestHaltAfterPanic supervisor", - MaxRestarts: AlwaysRestart, - Log: func(msg interface{}) { - t.Log("supervisor log (halt after panic):", msg) - }, - } - - ctx, cancel := context.WithCancel(context.Background()) - - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - svc1.Wait() - - svc2 := &panicabortsupervisorservice{id: 2, cancel: cancel, supervisor: &supervisor} - supervisor.Add(svc2) - - wg.Wait() - - if svc1.count > 1 { - t.Error("the holding service should have not been started more than once.") - } -} - -func TestInvalidGroup(t *testing.T) { - t.Parallel() - defer func() { - if r := recover(); r == nil { - t.Error("defer called, but not because of panic") - } - }() - var group Group - ctx, cancel := context.WithCancel(context.Background()) - group.Serve(ctx) - t.Error("this group is invalid and should have had panic()'d") - cancel() -} - -func TestLog(t *testing.T) { - t.Parallel() - - supervisor := Supervisor{ - Name: "TestLog", - } - svc1 := panicservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - for svc1.Count() == 0 { - } - - cancel() -} - -func TestManualCancelation(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestManualCancelation supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (restartable):", msg) - }, - } - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := restartableservice{id: 2, restarted: make(chan struct{})} - supervisor.Add(&svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - - svc1.Wait() - - // Testing restart - <-svc2.restarted - svcs := supervisor.Cancelations() - svcancel := svcs[svc2.String()] - svcancel() - <-svc2.restarted - - cancel() - <-ctx.Done() - wg.Wait() -} - -func TestMaxRestart(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := &Supervisor{ - Name: "TestMaxRestart supervisor", - MaxRestarts: 1, - Log: func(msg interface{}) { - t.Log("supervisor log (max restart):", msg) - }, - } - svc1 := failingservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - - wg.Wait() - cancel() - - if svc1.count > 1 { - t.Error("the panic service should have not been started more than once.") - } -} - -func TestPanic(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestPanic supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (panic):", msg) - }, - } - svc1 := panicservice{id: 1} - supervisor.Add(&svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - for svc1.Count() == 0 { - } - cancel() - if svc1.count == 0 { - t.Errorf("the failed service should have been started at least once. Got: %d", svc1.count) - } -} - -func TestRemovePanicService(t *testing.T) { - t.Parallel() - - supervisor := Group{ - Supervisor: &Supervisor{ - Name: "TestRemovePanicService supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (panic bug):", msg) - }, - }, - } - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - - svc1 := waitservice{id: 1} - supervisor.Add(&svc1) - svc2 := quickpanicservice{id: 2} - supervisor.Add(&svc2) - - supervisor.Remove(svc2.String()) - cancel() - - svcs := supervisor.Services() - if _, ok := svcs[svc2.String()]; ok { - t.Errorf("%s should have been removed.", &svc2) - } -} - -func TestRemoveServiceAfterServe(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestRemoveServiceAfterServe supervisor" - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &holdingservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - - lbefore := getServiceCount(&supervisor) - supervisor.Remove("unknown service") - lafter := getServiceCount(&supervisor) - - if lbefore != lafter { - t.Error("the removal of an unknown service shouldn't happen") - } - - svc1.Wait() - svc2.Wait() - - supervisor.Remove(svc1.String()) - lremoved := getServiceCount(&supervisor) - if lbefore == lremoved { - t.Error("the removal of a service should have affected the supervisor:", lbefore, lremoved) - } - - cancel() - <-ctx.Done() - wg.Wait() -} - -func TestRemoveServiceAfterServeBug(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestRemoveServiceAfterServeBug supervisor" - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - - svc1.Wait() - supervisor.Remove(svc1.String()) - cancel() - - if svc1.count > 1 { - t.Errorf("the removal of a service should have terminated it. It was started %v times", svc1.count) - } -} - -func TestServiceList(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestServiceList supervisor" - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - }() - svc1.Wait() - - svcs := supervisor.Services() - if svc, ok := svcs[svc1.String()]; !ok || svc1 != svc.(*holdingservice) { - t.Errorf("could not find service when listing them. %s missing", svc1.String()) - } - - cancel() - <-ctx.Done() - wg.Done() -} - -func TestServices(t *testing.T) { - t.Parallel() - - var supervisor Supervisor - supervisor.Name = "TestServices supervisor" - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &holdingservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - }() - svc1.Wait() - svc2.Wait() - - svcs := supervisor.Services() - for _, svcname := range []string{svc1.String(), svc2.String()} { - if _, ok := svcs[svcname]; !ok { - t.Errorf("expected service not found: %s", svcname) - } - } - - cancel() - <-ctx.Done() - wg.Done() -} - -func TestString(t *testing.T) { - t.Parallel() - - const expected = "test" - var supervisor Supervisor - supervisor.Name = expected - - if got := fmt.Sprintf("%s", &supervisor); got != expected { - t.Errorf("error getting supervisor name: %s", got) - } -} - -func TestStringDefaultName(t *testing.T) { - t.Parallel() - - const expected = "supervisor" - var supervisor Supervisor - supervisor.prepare() - - if got := fmt.Sprintf("%s", &supervisor); got != expected { - t.Errorf("error getting supervisor name: %s", got) - } -} - -func TestSupervisorAbortRestart(t *testing.T) { - t.Parallel() - supervisor := Supervisor{ - Name: "TestAbortRestart supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (abort restart):", msg) - }, - } - - svc1 := &holdingservice{id: 1} - svc1.Add(1) - supervisor.Add(svc1) - svc2 := &restartableservice{id: 2} - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - svc1.Wait() - - for svc2.Count() < 3 { - } - - cancel() - wg.Wait() - - if svc2.count < 3 { - t.Errorf("the restartable service should have been started twice. Got: %d", svc2.count) - } -} - -func TestTemporaryService(t *testing.T) { - t.Parallel() - supervisor := Supervisor{ - Name: "TestTemporaryService supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (termination abort restart):", msg) - }, - } - - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - svc1 := &temporaryservice{id: 1} - supervisor.AddService(svc1, Temporary) - - for svc1.Count() < 1 { - } - - svc2 := &temporaryservice{id: 2} - supervisor.AddService(svc2, Temporary) - cancel() - - if svc1.count != 1 { - t.Error("the temporary service should have been started just once.", svc1.count) - } -} - -func TestTerminationAfterPanic(t *testing.T) { - t.Parallel() - - defer func() { - if r := recover(); r != nil { - t.Errorf("unexpected panic: %v", r) - } - }() - - supervisor := Supervisor{ - Name: "TestTerminationAfterPanic supervisor", - MaxRestarts: AlwaysRestart, - Log: func(msg interface{}) { - t.Log("supervisor log (termination after panic):", msg) - }, - } - svc1 := &triggerpanicservice{id: 1} - supervisor.Add(svc1) - svc2 := &holdingservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - svc2.Wait() - - svc3 := &holdingservice{id: 3} - svc3.Add(1) - supervisor.Add(svc3) - svc3.Wait() - - supervisor.Remove(svc1.String()) - - svc4 := &holdingservice{id: 4} - svc4.Add(1) - supervisor.Add(svc4) - svc4.Wait() - - cancel() - - wg.Wait() - - if svc1.count > 1 { - t.Error("the panic service should have not been started more than once.") - } -} - -func TestTransientService(t *testing.T) { - t.Parallel() - supervisor := Supervisor{ - Name: "TestTemporaryService supervisor", - Log: func(msg interface{}) { - t.Log("supervisor log (termination abort restart):", msg) - }, - } - - svc1 := &transientservice{id: 1} - svc1.Add(1) - supervisor.AddService(svc1, Transient) - svc2 := &holdingservice{id: 2} - svc2.Add(1) - supervisor.Add(svc2) - - ctx, cancel := context.WithCancel(context.Background()) - var wg sync.WaitGroup - wg.Add(1) - go func() { - supervisor.Serve(ctx) - wg.Done() - }() - svc1.Wait() - svc2.Wait() - - cancel() - wg.Wait() - - if svc1.count != 2 { - t.Error("the transient service should have been started just twice.") - } -} - -func TestValidGroup(t *testing.T) { - t.Parallel() - - supervisor := &Group{ - Supervisor: &Supervisor{ - Name: "TestValidGroup supervisor", - Log: func(msg interface{}) { - t.Log("group log:", msg) - }, - }, - } - ctx, cancel := context.WithCancel(context.Background()) - go supervisor.Serve(ctx) - t.Log("supervisor started") - - trigger1 := make(chan struct{}) - listening1 := make(chan struct{}) - svc1 := &triggerfailservice{id: 1, trigger: trigger1, listening: listening1, log: t.Logf} - supervisor.Add(svc1) - t.Log("svc1 added") - - trigger2 := make(chan struct{}) - listening2 := make(chan struct{}) - svc2 := &triggerfailservice{id: 2, trigger: trigger2, listening: listening2, log: t.Logf} - supervisor.Add(svc2) - t.Log("svc2 added") - - <-listening1 - <-listening2 - trigger1 <- struct{}{} - - <-listening1 - <-listening2 - - if !(svc1.count == svc2.count && svc1.count == 1) { - t.Errorf("both services should have the same start count") - } - - t.Log("stopping supervisor") - cancel() -} - -func getServiceCount(s *Supervisor) int { - s.mu.Lock() - l := len(s.services) - s.mu.Unlock() - return l -} - -type simpleservice int - -func (s *simpleservice) Serve(ctx context.Context) { - for { - select { - case <-ctx.Done(): - return - default: - time.Sleep(500 * time.Millisecond) - } - } -} - -func (s *simpleservice) String() string { - return fmt.Sprintf("simple service %d", int(*s)) -} - -type failingservice struct { - id int - mu sync.Mutex - count int -} - -func (s *failingservice) Serve(ctx context.Context) { - select { - case <-ctx.Done(): - return - default: - time.Sleep(100 * time.Millisecond) - s.mu.Lock() - s.count++ - s.mu.Unlock() - return - } -} - -func (s *failingservice) String() string { - return fmt.Sprintf("failing service %v", s.id) -} - -func (s *failingservice) Count() int { - s.mu.Lock() - c := s.count - s.mu.Unlock() - return c -} - -type holdingservice struct { - id int - mu sync.Mutex - count int - sync.WaitGroup -} - -func (s *holdingservice) Serve(ctx context.Context) { - s.mu.Lock() - s.count++ - s.mu.Unlock() - s.Done() - <-ctx.Done() -} - -func (s *holdingservice) String() string { - return fmt.Sprintf("holding service %v", s.id) -} - -type panicservice struct { - id int - mu sync.Mutex - count int -} - -func (s *panicservice) Serve(ctx context.Context) { - for { - select { - case <-ctx.Done(): - return - default: - time.Sleep(100 * time.Millisecond) - s.mu.Lock() - s.count++ - s.mu.Unlock() - panic("forcing panic") - } - } -} - -func (s *panicservice) String() string { - return fmt.Sprintf("panic service %v", s.id) -} - -func (s *panicservice) Count() int { - s.mu.Lock() - c := s.count - s.mu.Unlock() - return c -} - -type quickpanicservice struct { - id, count int -} - -func (s *quickpanicservice) Serve(ctx context.Context) { - for { - select { - case <-ctx.Done(): - return - default: - s.count++ - panic("forcing panic") - } - } -} - -func (s *quickpanicservice) String() string { - return fmt.Sprintf("panic service %v", s.id) -} - -type restartableservice struct { - id int - restarted chan struct{} - mu sync.Mutex - count int -} - -func (s *restartableservice) Serve(ctx context.Context) { - for { - s.mu.Lock() - s.count++ - s.mu.Unlock() - select { - case <-ctx.Done(): - return - default: - time.Sleep(500 * time.Millisecond) - select { - case s.restarted <- struct{}{}: - default: - } - } - } -} - -func (s *restartableservice) Count() int { - s.mu.Lock() - c := s.count - s.mu.Unlock() - return c -} - -func (s *restartableservice) String() string { - return fmt.Sprintf("restartable service %v", s.id) -} - -type waitservice struct { - id int - mu sync.Mutex - count int -} - -func (s *waitservice) Serve(ctx context.Context) { - s.mu.Lock() - s.count++ - s.mu.Unlock() - <-ctx.Done() -} - -func (s *waitservice) String() string { - return fmt.Sprintf("wait service %v", s.id) -} - -func (s *waitservice) Count() int { - s.mu.Lock() - c := s.count - s.mu.Unlock() - return c -} - -type temporaryservice struct { - id int - mu sync.Mutex - count int -} - -func (s *temporaryservice) Serve(ctx context.Context) { - s.mu.Lock() - s.count++ - s.mu.Unlock() -} - -func (s *temporaryservice) Count() int { - s.mu.Lock() - c := s.count - s.mu.Unlock() - return c -} - -func (s *temporaryservice) String() string { - return fmt.Sprintf("temporary service %v", s.id) -} - -type triggerpanicservice struct { - id, count int -} - -func (s *triggerpanicservice) Serve(ctx context.Context) { - <-ctx.Done() - s.count++ - panic("forcing panic") -} - -func (s *triggerpanicservice) String() string { - return fmt.Sprintf("iterative panic service %v", s.id) -} - -type panicabortsupervisorservice struct { - id int - cancel context.CancelFunc - supervisor *Supervisor -} - -func (s *panicabortsupervisorservice) Serve(ctx context.Context) { - s.supervisor.mu.Lock() - defer s.supervisor.mu.Unlock() - s.supervisor.terminations = nil - s.cancel() - panic("forcing panic") -} - -func (s *panicabortsupervisorservice) String() string { - return fmt.Sprintf("super panic service %v", s.id) -} - -type transientservice struct { - id int - mu sync.Mutex - count int - sync.WaitGroup -} - -func (s *transientservice) Serve(ctx context.Context) { - s.mu.Lock() - defer s.mu.Unlock() - s.count++ - if s.count == 1 { - panic("panic once") - } - s.Done() - <-ctx.Done() -} - -func (s *transientservice) String() string { - return fmt.Sprintf("transient service %v", s.id) -} - -type triggerfailservice struct { - id int - trigger chan struct{} - listening chan struct{} - log func(msg string, args ...interface{}) - count int -} - -func (s *triggerfailservice) Serve(ctx context.Context) { - s.listening <- struct{}{} - s.log("listening %d", s.id) - select { - case <-s.trigger: - s.log("triggered %d", s.id) - s.count++ - case <-ctx.Done(): - s.log("context done %d", s.id) - s.count++ - } -} - -func (s *triggerfailservice) String() string { - return fmt.Sprintf("trigger fail service %v", s.id) -} diff --git a/vendor/github.com/cloudflare/cfssl/cli/version/version.go b/vendor/github.com/cloudflare/cfssl/cli/version/version.go index 1c1c867ac..9e309813f 100644 --- a/vendor/github.com/cloudflare/cfssl/cli/version/version.go +++ b/vendor/github.com/cloudflare/cfssl/cli/version/version.go @@ -27,9 +27,14 @@ Usage of version: cfssl version ` +// FormatVersion returns the formatted version string. +func FormatVersion() string { + return fmt.Sprintf("Version: %s\nRevision: %s\nRuntime: %s\n", versionString(), version.Revision, runtime.Version()) +} + // The main functionality of 'cfssl version' is to print out the version info. func versionMain(args []string, c cli.Config) (err error) { - fmt.Printf("Version: %s\nRevision: %s\nRuntime: %s\n", versionString(), version.Revision, runtime.Version()) + fmt.Printf("%s", FormatVersion()) return nil } diff --git a/vendor/github.com/cloudflare/cfssl/cmd/cfssljson/cfssljson.go b/vendor/github.com/cloudflare/cfssl/cmd/cfssljson/cfssljson.go index 9063ead96..deafbb624 100644 --- a/vendor/github.com/cloudflare/cfssl/cmd/cfssljson/cfssljson.go +++ b/vendor/github.com/cloudflare/cfssl/cmd/cfssljson/cfssljson.go @@ -9,6 +9,8 @@ import ( "fmt" "io/ioutil" "os" + + "github.com/cloudflare/cfssl/cli/version" ) func readFile(filespec string) ([]byte, error) { @@ -51,8 +53,14 @@ func main() { bare := flag.Bool("bare", false, "the response from CFSSL is not wrapped in the API standard response") inFile := flag.String("f", "-", "JSON input") output := flag.Bool("stdout", false, "output the response instead of saving to a file") + printVersion := flag.Bool("version", false, "print version and exit") flag.Parse() + if *printVersion { + fmt.Printf("%s", version.FormatVersion()) + return + } + var baseName string if flag.NArg() == 0 { baseName = "cert" diff --git a/vendor/github.com/coreos/etcd/.travis.yml b/vendor/github.com/coreos/etcd/.travis.yml index fb8e9b832..6e0c66810 100644 --- a/vendor/github.com/coreos/etcd/.travis.yml +++ b/vendor/github.com/coreos/etcd/.travis.yml @@ -4,7 +4,7 @@ go_import_path: github.com/coreos/etcd sudo: false go: - - 1.8.3 + - 1.9 - tip notifications: @@ -56,6 +56,7 @@ before_install: - go get -v -u honnef.co/go/tools/cmd/unused - go get -v -u honnef.co/go/tools/cmd/staticcheck - ./scripts/install-marker.sh amd64 + - export GOROOT=$(go env GOROOT) # disable godep restore override install: diff --git a/vendor/github.com/coreos/etcd/Documentation/learning/data_model.md b/vendor/github.com/coreos/etcd/Documentation/learning/data_model.md index ab5935dc1..e497238f2 100644 --- a/vendor/github.com/coreos/etcd/Documentation/learning/data_model.md +++ b/vendor/github.com/coreos/etcd/Documentation/learning/data_model.md @@ -10,7 +10,7 @@ The store’s logical view is a flat binary key space. The key space has a lexic The key space maintains multiple revisions. Each atomic mutative operation (e.g., a transaction operation may contain multiple operations) creates a new revision on the key space. All data held by previous revisions remains unchanged. Old versions of key can still be accessed through previous revisions. Likewise, revisions are indexed as well; ranging over revisions with watchers is efficient. If the store is compacted to save space, revisions before the compact revision will be removed. -A key’s lifetime spans a generation, denoted by its version. Each key may have one or multiple generations. Creating a key increments the version of that key, starting at 1 if the key never existed. Deleting a key generates a key tombstone, concluding the key’s current generation by resetting its version. Each modification of a key creates a new generation of the key and increases its version. Once a compaction happens, any version ended before the given revision will be removed and values set before the compaction revision except the latest one will be removed. +A key’s lifetime spans a generation, denoted by its version. Each key may have one or multiple generations. Creating a key increments the version of that key, starting at 1 if the key never existed. Deleting a key generates a key tombstone, concluding the key’s current generation by resetting its version. Each modification of a key increments its version. Once a compaction happens, any version ended before the given revision will be removed and values set before the compaction revision except the latest one will be removed. ### Physical view diff --git a/vendor/github.com/coreos/etcd/Documentation/v2/implementation-faq.md b/vendor/github.com/coreos/etcd/Documentation/v2/implementation-faq.md deleted file mode 100644 index 027c47aaf..000000000 --- a/vendor/github.com/coreos/etcd/Documentation/v2/implementation-faq.md +++ /dev/null @@ -1,70 +0,0 @@ -**This is the documentation for etcd2 releases. Read [etcd3 doc][v3-docs] for etcd3 releases.** - -[v3-docs]: ../docs.md#documentation - - -# FAQ - -## Initial Bootstrapping UX - -etcd initial bootstrapping is done via command line flags such as -`--initial-cluster` or `--discovery`. These flags can safely be left on the -command line after your cluster is running but they will be ignored if you have -a non-empty data dir. So, why did we decide to have this sort of odd UX? - -One of the design goals of etcd is easy bringup of clusters using a one-shot -static configuration like AWS Cloud Formation, PXE booting, etc. Essentially we -want to describe several virtual machines and bring them all up at once into an -etcd cluster. - -To achieve this sort of hands-free cluster bootstrap we had two other options: - -**API to bootstrap** - -This is problematic because it cannot be coordinated from a single service file -and we didn't want to have the etcd socket listening but unresponsive to -clients for an unbound period of time. - -It would look something like this: - -``` -ExecStart=/usr/bin/etcd -ExecStartPost/usr/bin/etcd init localhost:2379 --cluster= -``` - -**etcd init subcommand** - -``` -etcd init --cluster='default=http://localhost:2380,default=http://localhost:7001'... -etcd init --discovery https://discovery-example.etcd.io/193e4 -``` - -Then after running an init step you would execute `etcd`. This however -introduced problems: we now have to define a hand-off protocol between the etcd -init process and the etcd binary itself. This is hard to coordinate in a single -service file such as: - -``` -ExecStartPre=/usr/bin/etcd init --cluster=.... -ExecStart=/usr/bin/etcd -``` - -There are several error cases: - -0) Init has already run and the data directory is already configured -1) Discovery fails because of network timeout, etc -2) Discovery fails because the cluster is already full and etcd needs to fall back to proxy -3) Static cluster configuration fails because of conflict, misconfiguration or timeout - -In hindsight we could have made this work by doing: - -``` -rc status -0 Init already ran -1 Discovery fails on network timeout, etc -0 Discovery fails for cluster full, coordinate via proxy state file -1 Static cluster configuration failed -``` - -Perhaps we can add the init command in a future version and deprecate if the UX -continues to confuse people. diff --git a/vendor/github.com/coreos/etcd/NEWS b/vendor/github.com/coreos/etcd/NEWS index 6327cad18..922ee8e3b 100644 --- a/vendor/github.com/coreos/etcd/NEWS +++ b/vendor/github.com/coreos/etcd/NEWS @@ -1,3 +1,8 @@ +etcd v3.2.7 (2017-09-01) +- fix server-side auth so concurrent auth operations do not return old revision error +- fix concurrency/stm Put with serializable snapshot + - use store revision from first fetch to resolve write conflicts instead of modified revision + etcd v3.2.6 (2017-08-21) - fix watch restore from snapshot - fix etcd_debugging_mvcc_keys_total inconsistency diff --git a/vendor/github.com/coreos/etcd/README.md b/vendor/github.com/coreos/etcd/README.md index 8ab28492c..55ee92bd7 100644 --- a/vendor/github.com/coreos/etcd/README.md +++ b/vendor/github.com/coreos/etcd/README.md @@ -1,6 +1,7 @@ # etcd [![Go Report Card](https://goreportcard.com/badge/github.com/coreos/etcd)](https://goreportcard.com/report/github.com/coreos/etcd) +[![Coverage](https://codecov.io/gh/coreos/etcd/branch/master/graph/badge.svg)](https://codecov.io/gh/coreos/etcd) [![Build Status](https://travis-ci.org/coreos/etcd.svg?branch=master)](https://travis-ci.org/coreos/etcd) [![Build Status](https://semaphoreci.com/api/v1/coreos/etcd/branches/master/shields_badge.svg)](https://semaphoreci.com/coreos/etcd) [![Docker Repository on Quay.io](https://quay.io/repository/coreos/etcd-git/status "Docker Repository on Quay.io")](https://quay.io/repository/coreos/etcd-git) diff --git a/vendor/github.com/coreos/etcd/clientv3/README.md b/vendor/github.com/coreos/etcd/clientv3/README.md index 643d0e2f0..376bfba76 100644 --- a/vendor/github.com/coreos/etcd/clientv3/README.md +++ b/vendor/github.com/coreos/etcd/clientv3/README.md @@ -1,6 +1,6 @@ # etcd/clientv3 -[![Godoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/coreos/etcd/clientv3) +[![Godoc](https://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/coreos/etcd/clientv3) `etcd/clientv3` is the official Go etcd client for v3. diff --git a/vendor/github.com/coreos/etcd/e2e/cluster_test.go b/vendor/github.com/coreos/etcd/e2e/cluster_test.go index 991fb13dc..0ea7bd24b 100644 --- a/vendor/github.com/coreos/etcd/e2e/cluster_test.go +++ b/vendor/github.com/coreos/etcd/e2e/cluster_test.go @@ -212,6 +212,7 @@ func (cfg *etcdProcessClusterConfig) etcdServerProcessConfigs() []*etcdServerPro "--data-dir", dataDirPath, "--snapshot-count", fmt.Sprintf("%d", cfg.snapCount), } + args = addV2Args(args) if cfg.forceNewCluster { args = append(args, "--force-new-cluster") } diff --git a/vendor/github.com/coreos/etcd/e2e/docker/Dockerfile b/vendor/github.com/coreos/etcd/e2e/docker/Dockerfile index c94e1612a..195bdd91a 100644 --- a/vendor/github.com/coreos/etcd/e2e/docker/Dockerfile +++ b/vendor/github.com/coreos/etcd/e2e/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.8.3-stretch +FROM golang:1.9-stretch LABEL Description="Image for etcd DNS testing" RUN apt update -y RUN go get github.com/mattn/goreman diff --git a/vendor/github.com/coreos/etcd/e2e/v2_test.go b/vendor/github.com/coreos/etcd/e2e/v2_test.go new file mode 100644 index 000000000..ad59211ec --- /dev/null +++ b/vendor/github.com/coreos/etcd/e2e/v2_test.go @@ -0,0 +1,19 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !v2v3 + +package e2e + +func addV2Args(args []string) []string { return args } diff --git a/vendor/github.com/coreos/etcd/e2e/v2v3_test.go b/vendor/github.com/coreos/etcd/e2e/v2v3_test.go new file mode 100644 index 000000000..b9c69466a --- /dev/null +++ b/vendor/github.com/coreos/etcd/e2e/v2v3_test.go @@ -0,0 +1,21 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build v2v3 + +package e2e + +func addV2Args(args []string) []string { + return append(args, "--experimental-enable-v2v3", "v2/") +} diff --git a/vendor/github.com/coreos/etcd/embed/config.go b/vendor/github.com/coreos/etcd/embed/config.go index 9f1516b65..8d429cb0a 100644 --- a/vendor/github.com/coreos/etcd/embed/config.go +++ b/vendor/github.com/coreos/etcd/embed/config.go @@ -145,6 +145,7 @@ type Config struct { // Experimental flags ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"` + ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"` } // configYAML holds the config suitable for yaml parsing diff --git a/vendor/github.com/coreos/etcd/embed/etcd.go b/vendor/github.com/coreos/etcd/embed/etcd.go index 5959f4059..6ceb55b79 100644 --- a/vendor/github.com/coreos/etcd/embed/etcd.go +++ b/vendor/github.com/coreos/etcd/embed/etcd.go @@ -29,6 +29,8 @@ import ( "github.com/coreos/etcd/etcdserver" "github.com/coreos/etcd/etcdserver/api/etcdhttp" "github.com/coreos/etcd/etcdserver/api/v2http" + "github.com/coreos/etcd/etcdserver/api/v2v3" + "github.com/coreos/etcd/etcdserver/api/v3client" "github.com/coreos/etcd/etcdserver/api/v3rpc" "github.com/coreos/etcd/pkg/cors" "github.com/coreos/etcd/pkg/debugutil" @@ -409,7 +411,12 @@ func (e *Etcd) serve() (err error) { // Start a client server goroutine for each listen address var h http.Handler if e.Config().EnableV2 { - h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()) + if len(e.Config().ExperimentalEnableV2V3) > 0 { + srv := v2v3.NewServer(v3client.New(e.Server), e.cfg.ExperimentalEnableV2V3) + h = v2http.NewClientHandler(srv, e.Server.Cfg.ReqTimeout()) + } else { + h = v2http.NewClientHandler(e.Server, e.Server.Cfg.ReqTimeout()) + } } else { mux := http.NewServeMux() etcdhttp.HandleBasic(mux, e.Server) diff --git a/vendor/github.com/coreos/etcd/etcdctl/ctlv3/command/migrate_command.go b/vendor/github.com/coreos/etcd/etcdctl/ctlv3/command/migrate_command.go index 634ebb944..48c17c8ab 100644 --- a/vendor/github.com/coreos/etcd/etcdctl/ctlv3/command/migrate_command.go +++ b/vendor/github.com/coreos/etcd/etcdctl/ctlv3/command/migrate_command.go @@ -218,8 +218,9 @@ func applyConf(cc raftpb.ConfChange, cl *membership.RaftCluster) { } } -func applyRequest(r *pb.Request, applyV2 etcdserver.ApplierV2) { - toTTLOptions(r) +func applyRequest(req *pb.Request, applyV2 etcdserver.ApplierV2) { + r := (*etcdserver.RequestV2)(req) + r.TTLOptions() switch r.Method { case "POST": applyV2.Post(r) @@ -236,15 +237,6 @@ func applyRequest(r *pb.Request, applyV2 etcdserver.ApplierV2) { } } -func toTTLOptions(r *pb.Request) store.TTLOptionSet { - refresh, _ := pbutil.GetBool(r.Refresh) - ttlOptions := store.TTLOptionSet{Refresh: refresh} - if r.Expiration != 0 { - ttlOptions.ExpireTime = time.Unix(0, r.Expiration) - } - return ttlOptions -} - func writeStore(w io.Writer, st store.Store) uint64 { all, err := st.Get("/1", true, true) if err != nil { diff --git a/vendor/github.com/coreos/etcd/etcdctl/ctlv3/ctl_cov.go b/vendor/github.com/coreos/etcd/etcdctl/ctlv3/ctl_cov.go index 1ce1f524a..6908113a7 100644 --- a/vendor/github.com/coreos/etcd/etcdctl/ctlv3/ctl_cov.go +++ b/vendor/github.com/coreos/etcd/etcdctl/ctlv3/ctl_cov.go @@ -27,6 +27,7 @@ func Start() { // ETCDCTL_ARGS=etcdctl_test arg1 arg2... // SetArgs() takes arg1 arg2... rootCmd.SetArgs(strings.Split(os.Getenv("ETCDCTL_ARGS"), "\xe7\xcd")[1:]) + os.Unsetenv("ETCDCTL_ARGS") if err := rootCmd.Execute(); err != nil { command.ExitWithError(command.ExitError, err) } diff --git a/vendor/github.com/coreos/etcd/etcdmain/config.go b/vendor/github.com/coreos/etcd/etcdmain/config.go index 4b72649b0..614112923 100644 --- a/vendor/github.com/coreos/etcd/etcdmain/config.go +++ b/vendor/github.com/coreos/etcd/etcdmain/config.go @@ -110,8 +110,8 @@ func newConfig() *config { embed.ClusterStateFlagExisting, ), fallback: flags.NewStringsFlag( - fallbackFlagExit, fallbackFlagProxy, + fallbackFlagExit, ), proxy: flags.NewStringsFlag( proxyFlagOff, @@ -149,28 +149,20 @@ func newConfig() *config { fs.Var(flags.NewURLsValue(embed.DefaultAdvertiseClientURLs), "advertise-client-urls", "List of this member's client URLs to advertise to the public.") fs.StringVar(&cfg.Durl, "discovery", cfg.Durl, "Discovery URL used to bootstrap the cluster.") fs.Var(cfg.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %s", strings.Join(cfg.fallback.Values, ", "))) - if err := cfg.fallback.Set(fallbackFlagProxy); err != nil { - // Should never happen. - plog.Panicf("unexpected error setting up discovery-fallback flag: %v", err) - } + fs.StringVar(&cfg.Dproxy, "discovery-proxy", cfg.Dproxy, "HTTP proxy to use for traffic to discovery service.") fs.StringVar(&cfg.DNSCluster, "discovery-srv", cfg.DNSCluster, "DNS domain used to bootstrap initial cluster.") fs.StringVar(&cfg.InitialCluster, "initial-cluster", cfg.InitialCluster, "Initial cluster configuration for bootstrapping.") fs.StringVar(&cfg.InitialClusterToken, "initial-cluster-token", cfg.InitialClusterToken, "Initial cluster token for the etcd cluster during bootstrap.") fs.Var(cfg.clusterState, "initial-cluster-state", "Initial cluster state ('new' or 'existing').") - if err := cfg.clusterState.Set(embed.ClusterStateFlagNew); err != nil { - // Should never happen. - plog.Panicf("unexpected error setting up clusterStateFlag: %v", err) - } + fs.BoolVar(&cfg.StrictReconfigCheck, "strict-reconfig-check", cfg.StrictReconfigCheck, "Reject reconfiguration requests that would cause quorum loss.") fs.BoolVar(&cfg.EnableV2, "enable-v2", true, "Accept etcd V2 client requests.") + fs.StringVar(&cfg.ExperimentalEnableV2V3, "experimental-enable-v2v3", cfg.ExperimentalEnableV2V3, "v3 prefix for serving emulated v2 state.") // proxy fs.Var(cfg.proxy, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(cfg.proxy.Values, ", "))) - if err := cfg.proxy.Set(proxyFlagOff); err != nil { - // Should never happen. - plog.Panicf("unexpected error setting up proxyFlag: %v", err) - } + fs.UintVar(&cfg.ProxyFailureWaitMs, "proxy-failure-wait", cfg.ProxyFailureWaitMs, "Time (in milliseconds) an endpoint will be held in a failed state.") fs.UintVar(&cfg.ProxyRefreshIntervalMs, "proxy-refresh-interval", cfg.ProxyRefreshIntervalMs, "Time (in milliseconds) of the endpoints refresh interval.") fs.UintVar(&cfg.ProxyDialTimeoutMs, "proxy-dial-timeout", cfg.ProxyDialTimeoutMs, "Time (in milliseconds) for a dial to timeout.") diff --git a/vendor/github.com/coreos/etcd/etcdmain/help.go b/vendor/github.com/coreos/etcd/etcdmain/help.go index 152fbb649..37a670abd 100644 --- a/vendor/github.com/coreos/etcd/etcdmain/help.go +++ b/vendor/github.com/coreos/etcd/etcdmain/help.go @@ -183,5 +183,7 @@ auth flags: experimental flags: --experimental-corrupt-check-time '0s' duration of time between cluster corruption check passes. + --experimental-enable-v2v3 '' + serve v2 requests through the v3 backend under a given prefix. ` ) diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/cluster.go b/vendor/github.com/coreos/etcd/etcdserver/api/cluster.go index 87face4a1..654c25804 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/cluster.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/cluster.go @@ -33,9 +33,6 @@ type Cluster interface { // Member retrieves a particular member based on ID, or nil if the // member does not exist in the cluster Member(id types.ID) *membership.Member - // IsIDRemoved checks whether the given ID has been removed from this - // cluster at some point in the past - IsIDRemoved(id types.ID) bool // Version is the cluster-wide minimum major.minor version. Version() *semver.Version } diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/base.go b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/base.go index e7dc144f6..f0d3b0bd3 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/base.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/base.go @@ -43,7 +43,7 @@ const ( // HandleBasic adds handlers to a mux for serving JSON etcd client requests // that do not access the v2 store. -func HandleBasic(mux *http.ServeMux, server *etcdserver.EtcdServer) { +func HandleBasic(mux *http.ServeMux, server etcdserver.ServerPeer) { mux.HandleFunc(varsPath, serveVars) mux.HandleFunc(configPath+"/local/log", logHandleFunc) HandleMetricsHealth(mux, server) diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/metrics.go b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/metrics.go index 81b636056..23e7aff86 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/metrics.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/metrics.go @@ -33,7 +33,7 @@ const ( ) // HandleMetricsHealth registers metrics and health handlers. -func HandleMetricsHealth(mux *http.ServeMux, srv *etcdserver.EtcdServer) { +func HandleMetricsHealth(mux *http.ServeMux, srv etcdserver.ServerV2) { mux.Handle(pathMetrics, prometheus.Handler()) mux.Handle(PathHealth, NewHealthHandler(func() Health { return checkHealth(srv) })) } @@ -44,7 +44,7 @@ func HandlePrometheus(mux *http.ServeMux) { } // HandleHealth registers health handler on '/health'. -func HandleHealth(mux *http.ServeMux, srv *etcdserver.EtcdServer) { +func HandleHealth(mux *http.ServeMux, srv etcdserver.ServerV2) { mux.Handle(PathHealth, NewHealthHandler(func() Health { return checkHealth(srv) })) } @@ -74,7 +74,7 @@ type Health struct { Errors []string `json:"errors,omitempty"` } -func checkHealth(srv *etcdserver.EtcdServer) Health { +func checkHealth(srv etcdserver.ServerV2) Health { h := Health{Health: false} as := srv.Alarms() diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer.go b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer.go index 721bae3c6..0a9213b01 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer.go @@ -29,13 +29,8 @@ const ( ) // NewPeerHandler generates an http.Handler to handle etcd peer requests. -func NewPeerHandler(s *etcdserver.EtcdServer) http.Handler { - var lh http.Handler - l := s.Lessor() - if l != nil { - lh = leasehttp.NewHandler(l, func() <-chan struct{} { return s.ApplyWait() }) - } - return newPeerHandler(s.Cluster(), s.RaftHandler(), lh) +func NewPeerHandler(s etcdserver.ServerPeer) http.Handler { + return newPeerHandler(s.Cluster(), s.RaftHandler(), s.LeaseHandler()) } func newPeerHandler(cluster api.Cluster, raftHandler http.Handler, leaseHandler http.Handler) http.Handler { diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer_test.go b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer_test.go index c2b14f195..40dbef8ae 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer_test.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/etcdhttp/peer_test.go @@ -47,7 +47,6 @@ func (c *fakeCluster) Members() []*membership.Member { return []*membership.Member(ms) } func (c *fakeCluster) Member(id types.ID) *membership.Member { return c.members[uint64(id)] } -func (c *fakeCluster) IsIDRemoved(id types.ID) bool { return false } func (c *fakeCluster) Version() *semver.Version { return nil } // TestNewPeerHandlerOnRaftPrefix tests that NewPeerHandler returns a handler that diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client.go index aa1e71ec3..c9d86508e 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client.go @@ -50,22 +50,21 @@ const ( ) // NewClientHandler generates a muxed http.Handler with the given parameters to serve etcd client requests. -func NewClientHandler(server *etcdserver.EtcdServer, timeout time.Duration) http.Handler { +func NewClientHandler(server etcdserver.ServerPeer, timeout time.Duration) http.Handler { mux := http.NewServeMux() etcdhttp.HandleBasic(mux, server) handleV2(mux, server, timeout) return requestLogger(mux) } -func handleV2(mux *http.ServeMux, server *etcdserver.EtcdServer, timeout time.Duration) { +func handleV2(mux *http.ServeMux, server etcdserver.ServerV2, timeout time.Duration) { sec := auth.NewStore(server, timeout) kh := &keysHandler{ sec: sec, server: server, cluster: server.Cluster(), - timer: server, timeout: timeout, - clientCertAuthEnabled: server.Cfg.ClientCertAuthEnabled, + clientCertAuthEnabled: server.ClientCertAuthEnabled(), } sh := &statsHandler{ @@ -78,7 +77,7 @@ func handleV2(mux *http.ServeMux, server *etcdserver.EtcdServer, timeout time.Du cluster: server.Cluster(), timeout: timeout, clock: clockwork.NewRealClock(), - clientCertAuthEnabled: server.Cfg.ClientCertAuthEnabled, + clientCertAuthEnabled: server.ClientCertAuthEnabled(), } mah := &machinesHandler{cluster: server.Cluster()} @@ -86,7 +85,7 @@ func handleV2(mux *http.ServeMux, server *etcdserver.EtcdServer, timeout time.Du sech := &authHandler{ sec: sec, cluster: server.Cluster(), - clientCertAuthEnabled: server.Cfg.ClientCertAuthEnabled, + clientCertAuthEnabled: server.ClientCertAuthEnabled(), } mux.HandleFunc("/", http.NotFound) mux.Handle(keysPrefix, kh) @@ -102,9 +101,8 @@ func handleV2(mux *http.ServeMux, server *etcdserver.EtcdServer, timeout time.Du type keysHandler struct { sec auth.Store - server etcdserver.Server + server etcdserver.ServerV2 cluster api.Cluster - timer etcdserver.RaftTimer timeout time.Duration clientCertAuthEnabled bool } @@ -142,7 +140,7 @@ func (h *keysHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } switch { case resp.Event != nil: - if err := writeKeyEvent(w, resp.Event, noValueOnSuccess, h.timer); err != nil { + if err := writeKeyEvent(w, resp, noValueOnSuccess); err != nil { // Should never be reached plog.Errorf("error writing event (%v)", err) } @@ -150,7 +148,7 @@ func (h *keysHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { case resp.Watcher != nil: ctx, cancel := context.WithTimeout(context.Background(), defaultWatchTimeout) defer cancel() - handleKeyWatch(ctx, w, resp.Watcher, rr.Stream, h.timer) + handleKeyWatch(ctx, w, resp, rr.Stream) default: writeKeyError(w, errors.New("received response with no Event/Watcher!")) } @@ -170,7 +168,7 @@ func (h *machinesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { type membersHandler struct { sec auth.Store - server etcdserver.Server + server etcdserver.ServerV2 cluster api.Cluster timeout time.Duration clock clockwork.Clock @@ -503,14 +501,15 @@ func parseKeyRequest(r *http.Request, clock clockwork.Clock) (etcdserverpb.Reque // writeKeyEvent trims the prefix of key path in a single Event under // StoreKeysPrefix, serializes it and writes the resulting JSON to the given // ResponseWriter, along with the appropriate headers. -func writeKeyEvent(w http.ResponseWriter, ev *store.Event, noValueOnSuccess bool, rt etcdserver.RaftTimer) error { +func writeKeyEvent(w http.ResponseWriter, resp etcdserver.Response, noValueOnSuccess bool) error { + ev := resp.Event if ev == nil { return errors.New("cannot write empty Event!") } w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex)) - w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index())) - w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term())) + w.Header().Set("X-Raft-Index", fmt.Sprint(resp.Index)) + w.Header().Set("X-Raft-Term", fmt.Sprint(resp.Term)) if ev.IsCreated() { w.WriteHeader(http.StatusCreated) @@ -552,7 +551,8 @@ func writeKeyError(w http.ResponseWriter, err error) { } } -func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher, stream bool, rt etcdserver.RaftTimer) { +func handleKeyWatch(ctx context.Context, w http.ResponseWriter, resp etcdserver.Response, stream bool) { + wa := resp.Watcher defer wa.Remove() ech := wa.EventChan() var nch <-chan bool @@ -562,8 +562,8 @@ func handleKeyWatch(ctx context.Context, w http.ResponseWriter, wa store.Watcher w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Etcd-Index", fmt.Sprint(wa.StartIndex())) - w.Header().Set("X-Raft-Index", fmt.Sprint(rt.Index())) - w.Header().Set("X-Raft-Term", fmt.Sprint(rt.Term())) + w.Header().Set("X-Raft-Index", fmt.Sprint(resp.Index)) + w.Header().Set("X-Raft-Term", fmt.Sprint(resp.Term)) w.WriteHeader(http.StatusOK) // Ensure headers are flushed early, in case of long polling diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client_test.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client_test.go index 896021b22..0a58082a4 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client_test.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/client_test.go @@ -30,6 +30,7 @@ import ( etcdErr "github.com/coreos/etcd/error" "github.com/coreos/etcd/etcdserver" + "github.com/coreos/etcd/etcdserver/api" "github.com/coreos/etcd/etcdserver/api/v2http/httptypes" "github.com/coreos/etcd/etcdserver/etcdserverpb" "github.com/coreos/etcd/etcdserver/membership" @@ -87,14 +88,26 @@ func mustNewMethodRequest(t *testing.T, m, p string) *http.Request { } } +type fakeServer struct { + dummyRaftTimer + dummyStats +} + +func (s *fakeServer) Leader() types.ID { return types.ID(1) } +func (s *fakeServer) Alarms() []*etcdserverpb.AlarmMember { return nil } +func (s *fakeServer) Cluster() api.Cluster { return nil } +func (s *fakeServer) ClusterVersion() *semver.Version { return nil } +func (s *fakeServer) RaftHandler() http.Handler { return nil } +func (s *fakeServer) Do(ctx context.Context, r etcdserverpb.Request) (rr etcdserver.Response, err error) { + return +} +func (s *fakeServer) ClientCertAuthEnabled() bool { return false } + type serverRecorder struct { + fakeServer actions []action } -func (s *serverRecorder) Start() {} -func (s *serverRecorder) Stop() {} -func (s *serverRecorder) Leader() types.ID { return types.ID(1) } -func (s *serverRecorder) ID() types.ID { return types.ID(1) } func (s *serverRecorder) Do(_ context.Context, r etcdserverpb.Request) (etcdserver.Response, error) { s.actions = append(s.actions, action{name: "Do", params: []interface{}{r}}) return etcdserver.Response{}, nil @@ -117,8 +130,6 @@ func (s *serverRecorder) UpdateMember(_ context.Context, m membership.Member) ([ return nil, nil } -func (s *serverRecorder) ClusterVersion() *semver.Version { return nil } - type action struct { name string params []interface{} @@ -138,13 +149,10 @@ func (fr *flushingRecorder) Flush() { // resServer implements the etcd.Server interface for testing. // It returns the given response from any Do calls, and nil error type resServer struct { + fakeServer res etcdserver.Response } -func (rs *resServer) Start() {} -func (rs *resServer) Stop() {} -func (rs *resServer) ID() types.ID { return types.ID(1) } -func (rs *resServer) Leader() types.ID { return types.ID(1) } func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) { return rs.res, nil } @@ -158,7 +166,6 @@ func (rs *resServer) RemoveMember(_ context.Context, _ uint64) ([]*membership.Me func (rs *resServer) UpdateMember(_ context.Context, _ membership.Member) ([]*membership.Member, error) { return nil, nil } -func (rs *resServer) ClusterVersion() *semver.Version { return nil } func boolp(b bool) *bool { return &b } @@ -874,7 +881,7 @@ func TestServeMembersUpdate(t *testing.T) { func TestServeMembersFail(t *testing.T) { tests := []struct { req *http.Request - server etcdserver.Server + server etcdserver.ServerV2 wcode int }{ @@ -941,7 +948,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - errors.New("Error while adding a member"), + err: errors.New("Error while adding a member"), }, http.StatusInternalServerError, @@ -955,7 +962,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - membership.ErrIDExists, + err: membership.ErrIDExists, }, http.StatusConflict, @@ -969,7 +976,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - membership.ErrPeerURLexists, + err: membership.ErrPeerURLexists, }, http.StatusConflict, @@ -981,7 +988,7 @@ func TestServeMembersFail(t *testing.T) { Method: "DELETE", }, &errServer{ - errors.New("Error while removing member"), + err: errors.New("Error while removing member"), }, http.StatusInternalServerError, @@ -993,7 +1000,7 @@ func TestServeMembersFail(t *testing.T) { Method: "DELETE", }, &errServer{ - membership.ErrIDRemoved, + err: membership.ErrIDRemoved, }, http.StatusGone, @@ -1005,7 +1012,7 @@ func TestServeMembersFail(t *testing.T) { Method: "DELETE", }, &errServer{ - membership.ErrIDNotFound, + err: membership.ErrIDNotFound, }, http.StatusNotFound, @@ -1075,7 +1082,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - errors.New("blah"), + err: errors.New("blah"), }, http.StatusInternalServerError, @@ -1089,7 +1096,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - membership.ErrPeerURLexists, + err: membership.ErrPeerURLexists, }, http.StatusConflict, @@ -1103,7 +1110,7 @@ func TestServeMembersFail(t *testing.T) { Header: map[string][]string{"Content-Type": {"application/json"}}, }, &errServer{ - membership.ErrIDNotFound, + err: membership.ErrIDNotFound, }, http.StatusNotFound, @@ -1153,7 +1160,7 @@ func TestServeMembersFail(t *testing.T) { func TestWriteEvent(t *testing.T) { // nil event should not panic rec := httptest.NewRecorder() - writeKeyEvent(rec, nil, false, dummyRaftTimer{}) + writeKeyEvent(rec, etcdserver.Response{}, false) h := rec.Header() if len(h) > 0 { t.Fatalf("unexpected non-empty headers: %#v", h) @@ -1199,7 +1206,8 @@ func TestWriteEvent(t *testing.T) { for i, tt := range tests { rw := httptest.NewRecorder() - writeKeyEvent(rw, tt.ev, tt.noValue, dummyRaftTimer{}) + resp := etcdserver.Response{Event: tt.ev, Term: 5, Index: 100} + writeKeyEvent(rw, resp, tt.noValue) if gct := rw.Header().Get("Content-Type"); gct != "application/json" { t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct) } @@ -1411,7 +1419,7 @@ func TestServeStoreStats(t *testing.T) { func TestBadServeKeys(t *testing.T) { testBadCases := []struct { req *http.Request - server etcdserver.Server + server etcdserver.ServerV2 wcode int wbody string @@ -1451,7 +1459,7 @@ func TestBadServeKeys(t *testing.T) { // etcdserver.Server error mustNewRequest(t, "foo"), &errServer{ - errors.New("Internal Server Error"), + err: errors.New("Internal Server Error"), }, http.StatusInternalServerError, @@ -1461,7 +1469,7 @@ func TestBadServeKeys(t *testing.T) { // etcdserver.Server etcd error mustNewRequest(t, "foo"), &errServer{ - etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/1/pant", 0), + err: etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/1/pant", 0), }, http.StatusNotFound, @@ -1471,7 +1479,7 @@ func TestBadServeKeys(t *testing.T) { // non-event/watcher response from etcdserver.Server mustNewRequest(t, "foo"), &resServer{ - etcdserver.Response{}, + res: etcdserver.Response{}, }, http.StatusInternalServerError, @@ -1529,7 +1537,7 @@ func TestServeKeysGood(t *testing.T) { }, } server := &resServer{ - etcdserver.Response{ + res: etcdserver.Response{ Event: &store.Event{ Action: store.Get, Node: &store.NodeExtern{}, @@ -1540,7 +1548,6 @@ func TestServeKeysGood(t *testing.T) { h := &keysHandler{ timeout: time.Hour, server: server, - timer: &dummyRaftTimer{}, cluster: &fakeCluster{id: 1}, } rw := httptest.NewRecorder() @@ -1597,7 +1604,6 @@ func TestServeKeysEvent(t *testing.T) { timeout: time.Hour, server: server, cluster: &fakeCluster{id: 1}, - timer: &dummyRaftTimer{}, } for _, tt := range tests { @@ -1632,7 +1638,7 @@ func TestServeKeysWatch(t *testing.T) { echan: ec, } server := &resServer{ - etcdserver.Response{ + res: etcdserver.Response{ Watcher: dw, }, } @@ -1640,7 +1646,6 @@ func TestServeKeysWatch(t *testing.T) { timeout: time.Hour, server: server, cluster: &fakeCluster{id: 1}, - timer: &dummyRaftTimer{}, } go func() { ec <- &store.Event{ @@ -1764,7 +1769,8 @@ func TestHandleWatch(t *testing.T) { } tt.doToChan(wa.echan) - handleKeyWatch(tt.getCtx(), rw, wa, false, dummyRaftTimer{}) + resp := etcdserver.Response{Term: 5, Index: 100, Watcher: wa} + handleKeyWatch(tt.getCtx(), rw, resp, false) wcode := http.StatusOK wct := "application/json" @@ -1808,7 +1814,8 @@ func TestHandleWatchStreaming(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { - handleKeyWatch(ctx, rw, wa, true, dummyRaftTimer{}) + resp := etcdserver.Response{Watcher: wa} + handleKeyWatch(ctx, rw, resp, true) close(done) }() diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/http_test.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/http_test.go index 61225409e..5b68a49a5 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v2http/http_test.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2http/http_test.go @@ -48,19 +48,15 @@ func (c *fakeCluster) Members() []*membership.Member { return []*membership.Member(ms) } func (c *fakeCluster) Member(id types.ID) *membership.Member { return c.members[uint64(id)] } -func (c *fakeCluster) IsIDRemoved(id types.ID) bool { return false } func (c *fakeCluster) Version() *semver.Version { return nil } // errServer implements the etcd.Server interface for testing. // It returns the given error from any Do/Process/AddMember/RemoveMember calls. type errServer struct { err error + fakeServer } -func (fs *errServer) Start() {} -func (fs *errServer) Stop() {} -func (fs *errServer) ID() types.ID { return types.ID(1) } -func (fs *errServer) Leader() types.ID { return types.ID(1) } func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) { return etcdserver.Response{}, fs.err } @@ -77,8 +73,6 @@ func (fs *errServer) UpdateMember(ctx context.Context, m membership.Member) ([]* return nil, fs.err } -func (fs *errServer) ClusterVersion() *semver.Version { return nil } - func TestWriteError(t *testing.T) { // nil error should not panic rec := httptest.NewRecorder() diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/cluster.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/cluster.go new file mode 100644 index 000000000..b53e6d7c8 --- /dev/null +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/cluster.go @@ -0,0 +1,31 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v2v3 + +import ( + "github.com/coreos/etcd/etcdserver/membership" + "github.com/coreos/etcd/pkg/types" + + "github.com/coreos/go-semver/semver" +) + +func (s *v2v3Server) ID() types.ID { + // TODO: use an actual member ID + return types.ID(0xe7cd2f00d) +} +func (s *v2v3Server) ClientURLs() []string { panic("STUB") } +func (s *v2v3Server) Members() []*membership.Member { panic("STUB") } +func (s *v2v3Server) Member(id types.ID) *membership.Member { panic("STUB") } +func (s *v2v3Server) Version() *semver.Version { panic("STUB") } diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/doc.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/doc.go new file mode 100644 index 000000000..2ff372f18 --- /dev/null +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/doc.go @@ -0,0 +1,16 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package v2v3 provides a ServerV2 implementation backed by clientv3.Client. +package v2v3 diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/server.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/server.go new file mode 100644 index 000000000..dae457ccf --- /dev/null +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/server.go @@ -0,0 +1,117 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v2v3 + +import ( + "net/http" + "time" + + "github.com/coreos/etcd/clientv3" + "github.com/coreos/etcd/etcdserver" + "github.com/coreos/etcd/etcdserver/api" + pb "github.com/coreos/etcd/etcdserver/etcdserverpb" + "github.com/coreos/etcd/etcdserver/membership" + "github.com/coreos/etcd/pkg/types" + + "github.com/coreos/go-semver/semver" + "golang.org/x/net/context" // TODO: replace with context in go1.9 +) + +type fakeStats struct{} + +func (s *fakeStats) SelfStats() []byte { return nil } +func (s *fakeStats) LeaderStats() []byte { return nil } +func (s *fakeStats) StoreStats() []byte { return nil } + +type v2v3Server struct { + c *clientv3.Client + store *v2v3Store + fakeStats +} + +func NewServer(c *clientv3.Client, pfx string) etcdserver.ServerPeer { + return &v2v3Server{c: c, store: newStore(c, pfx)} +} + +func (s *v2v3Server) ClientCertAuthEnabled() bool { return false } + +func (s *v2v3Server) LeaseHandler() http.Handler { panic("STUB: lease handler") } +func (s *v2v3Server) RaftHandler() http.Handler { panic("STUB: raft handler") } + +func (s *v2v3Server) Leader() types.ID { + ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second) + defer cancel() + resp, err := s.c.Status(ctx, s.c.Endpoints()[0]) + if err != nil { + return 0 + } + return types.ID(resp.Leader) +} + +func (s *v2v3Server) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) { + resp, err := s.c.MemberAdd(ctx, memb.PeerURLs) + if err != nil { + return nil, err + } + return v3MembersToMembership(resp.Members), nil +} + +func (s *v2v3Server) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) { + resp, err := s.c.MemberRemove(ctx, id) + if err != nil { + return nil, err + } + return v3MembersToMembership(resp.Members), nil +} + +func (s *v2v3Server) UpdateMember(ctx context.Context, m membership.Member) ([]*membership.Member, error) { + resp, err := s.c.MemberUpdate(ctx, uint64(m.ID), m.PeerURLs) + if err != nil { + return nil, err + } + return v3MembersToMembership(resp.Members), nil +} + +func v3MembersToMembership(v3membs []*pb.Member) []*membership.Member { + membs := make([]*membership.Member, len(v3membs)) + for i, m := range v3membs { + membs[i] = &membership.Member{ + ID: types.ID(m.ID), + RaftAttributes: membership.RaftAttributes{ + PeerURLs: m.PeerURLs, + }, + Attributes: membership.Attributes{ + Name: m.Name, + ClientURLs: m.ClientURLs, + }, + } + } + return membs +} + +func (s *v2v3Server) ClusterVersion() *semver.Version { return s.Version() } +func (s *v2v3Server) Cluster() api.Cluster { return s } +func (s *v2v3Server) Alarms() []*pb.AlarmMember { return nil } + +func (s *v2v3Server) Do(ctx context.Context, r pb.Request) (etcdserver.Response, error) { + applier := etcdserver.NewApplierV2(s.store, nil) + reqHandler := etcdserver.NewStoreRequestV2Handler(s.store, applier) + req := (*etcdserver.RequestV2)(&r) + resp, err := req.Handle(ctx, reqHandler) + if resp.Err != nil { + return resp, resp.Err + } + return resp, err +} diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/store.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/store.go new file mode 100644 index 000000000..22227f8aa --- /dev/null +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/store.go @@ -0,0 +1,621 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v2v3 + +import ( + "context" + "fmt" + "path" + "strings" + "time" + + "github.com/coreos/etcd/clientv3" + "github.com/coreos/etcd/clientv3/concurrency" + etcdErr "github.com/coreos/etcd/error" + "github.com/coreos/etcd/mvcc/mvccpb" + "github.com/coreos/etcd/store" +) + +// store implements the Store interface for V2 using +// a v3 client. +type v2v3Store struct { + c *clientv3.Client + // pfx is the v3 prefix where keys should be stored. + pfx string + ctx context.Context +} + +const maxPathDepth = 63 + +var errUnsupported = fmt.Errorf("TTLs are unsupported") + +func NewStore(c *clientv3.Client, pfx string) store.Store { return newStore(c, pfx) } + +func newStore(c *clientv3.Client, pfx string) *v2v3Store { return &v2v3Store{c, pfx, c.Ctx()} } + +func (s *v2v3Store) Index() uint64 { panic("STUB") } + +func (s *v2v3Store) Get(nodePath string, recursive, sorted bool) (*store.Event, error) { + key := s.mkPath(nodePath) + resp, err := s.c.Txn(s.ctx).Then( + clientv3.OpGet(key+"/"), + clientv3.OpGet(key), + ).Commit() + if err != nil { + return nil, err + } + + if kvs := resp.Responses[0].GetResponseRange().Kvs; len(kvs) != 0 || isRoot(nodePath) { + nodes, err := s.getDir(nodePath, recursive, sorted, resp.Header.Revision) + if err != nil { + return nil, err + } + cidx, midx := uint64(0), uint64(0) + if len(kvs) > 0 { + cidx, midx = mkV2Rev(kvs[0].CreateRevision), mkV2Rev(kvs[0].ModRevision) + } + return &store.Event{ + Action: store.Get, + Node: &store.NodeExtern{ + Key: nodePath, + Dir: true, + Nodes: nodes, + CreatedIndex: cidx, + ModifiedIndex: midx, + }, + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil + } + + kvs := resp.Responses[1].GetResponseRange().Kvs + if len(kvs) == 0 { + return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision)) + } + + return &store.Event{ + Action: store.Get, + Node: s.mkV2Node(kvs[0]), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) getDir(nodePath string, recursive, sorted bool, rev int64) ([]*store.NodeExtern, error) { + rootNodes, err := s.getDirDepth(nodePath, 1, rev) + if err != nil || !recursive { + return rootNodes, err + } + nextNodes := rootNodes + nodes := make(map[string]*store.NodeExtern) + // Breadth walk the subdirectories + for i := 2; len(nextNodes) > 0; i++ { + for _, n := range nextNodes { + nodes[n.Key] = n + if parent := nodes[path.Dir(n.Key)]; parent != nil { + parent.Nodes = append(parent.Nodes, n) + } + } + if nextNodes, err = s.getDirDepth(nodePath, i, rev); err != nil { + return nil, err + } + } + return rootNodes, nil +} + +func (s *v2v3Store) getDirDepth(nodePath string, depth int, rev int64) ([]*store.NodeExtern, error) { + pd := s.mkPathDepth(nodePath, depth) + resp, err := s.c.Get(s.ctx, pd, clientv3.WithPrefix(), clientv3.WithRev(rev)) + if err != nil { + return nil, err + } + + nodes := make([]*store.NodeExtern, len(resp.Kvs)) + for i, kv := range resp.Kvs { + nodes[i] = s.mkV2Node(kv) + } + return nodes, nil +} + +func (s *v2v3Store) Set( + nodePath string, + dir bool, + value string, + expireOpts store.TTLOptionSet, +) (*store.Event, error) { + if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() { + return nil, errUnsupported + } + + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + + ecode := 0 + applyf := func(stm concurrency.STM) error { + parent := path.Dir(nodePath) + if !isRoot(parent) && stm.Rev(s.mkPath(parent)+"/") == 0 { + ecode = etcdErr.EcodeKeyNotFound + return nil + } + + key := s.mkPath(nodePath) + if dir { + if stm.Rev(key) != 0 { + // exists as non-dir + ecode = etcdErr.EcodeNotDir + return nil + } + key = key + "/" + } else if stm.Rev(key+"/") != 0 { + ecode = etcdErr.EcodeNotFile + return nil + } + stm.Put(key, value, clientv3.WithPrevKV()) + stm.Put(s.mkActionKey(), store.Set) + return nil + } + + resp, err := s.newSTM(applyf) + if err != nil { + return nil, err + } + if ecode != 0 { + return nil, etcdErr.NewError(ecode, nodePath, mkV2Rev(resp.Header.Revision)) + } + + createRev := resp.Header.Revision + var pn *store.NodeExtern + if pkv := prevKeyFromPuts(resp); pkv != nil { + pn = s.mkV2Node(pkv) + createRev = pkv.CreateRevision + } + + vp := &value + if dir { + vp = nil + } + return &store.Event{ + Action: store.Set, + Node: &store.NodeExtern{ + Key: nodePath, + Value: vp, + Dir: dir, + ModifiedIndex: mkV2Rev(resp.Header.Revision), + CreatedIndex: mkV2Rev(createRev), + }, + PrevNode: pn, + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) Update(nodePath, newValue string, expireOpts store.TTLOptionSet) (*store.Event, error) { + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + + if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() { + return nil, errUnsupported + } + + key := s.mkPath(nodePath) + ecode := 0 + applyf := func(stm concurrency.STM) error { + if rev := stm.Rev(key + "/"); rev != 0 { + ecode = etcdErr.EcodeNotFile + return nil + } + if rev := stm.Rev(key); rev == 0 { + ecode = etcdErr.EcodeKeyNotFound + return nil + } + stm.Put(key, newValue, clientv3.WithPrevKV()) + stm.Put(s.mkActionKey(), store.Update) + return nil + } + + resp, err := s.newSTM(applyf) + if err != nil { + return nil, err + } + if ecode != 0 { + return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision)) + } + + pkv := prevKeyFromPuts(resp) + return &store.Event{ + Action: store.Update, + Node: &store.NodeExtern{ + Key: nodePath, + Value: &newValue, + ModifiedIndex: mkV2Rev(resp.Header.Revision), + CreatedIndex: mkV2Rev(pkv.CreateRevision), + }, + PrevNode: s.mkV2Node(pkv), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) Create( + nodePath string, + dir bool, + value string, + unique bool, + expireOpts store.TTLOptionSet, +) (*store.Event, error) { + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() { + return nil, errUnsupported + } + ecode := 0 + applyf := func(stm concurrency.STM) error { + ecode = 0 + key := s.mkPath(nodePath) + if unique { + // append unique item under the node path + for { + key = nodePath + "/" + fmt.Sprintf("%020s", time.Now()) + key = path.Clean(path.Join("/", key)) + key = s.mkPath(key) + if stm.Rev(key) == 0 { + break + } + } + } + if stm.Rev(key) > 0 || stm.Rev(key+"/") > 0 { + ecode = etcdErr.EcodeNodeExist + return nil + } + // build path if any directories in path do not exist + dirs := []string{} + for p := path.Dir(nodePath); !isRoot(p); p = path.Dir(p) { + pp := s.mkPath(p) + if stm.Rev(pp) > 0 { + ecode = etcdErr.EcodeNotDir + return nil + } + if stm.Rev(pp+"/") == 0 { + dirs = append(dirs, pp+"/") + } + } + for _, d := range dirs { + stm.Put(d, "") + } + + if dir { + // directories marked with extra slash in key name + key += "/" + } + stm.Put(key, value) + stm.Put(s.mkActionKey(), store.Create) + return nil + } + + resp, err := s.newSTM(applyf) + if err != nil { + return nil, err + } + if ecode != 0 { + return nil, etcdErr.NewError(ecode, nodePath, mkV2Rev(resp.Header.Revision)) + } + + var v *string + if !dir { + v = &value + } + + return &store.Event{ + Action: store.Create, + Node: &store.NodeExtern{ + Key: nodePath, + Value: v, + Dir: dir, + ModifiedIndex: mkV2Rev(resp.Header.Revision), + CreatedIndex: mkV2Rev(resp.Header.Revision), + }, + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) CompareAndSwap( + nodePath string, + prevValue string, + prevIndex uint64, + value string, + expireOpts store.TTLOptionSet, +) (*store.Event, error) { + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + if expireOpts.Refresh || !expireOpts.ExpireTime.IsZero() { + return nil, errUnsupported + } + + key := s.mkPath(nodePath) + resp, err := s.c.Txn(s.ctx).If( + s.mkCompare(nodePath, prevValue, prevIndex)..., + ).Then( + clientv3.OpPut(key, value, clientv3.WithPrevKV()), + clientv3.OpPut(s.mkActionKey(), store.CompareAndSwap), + ).Else( + clientv3.OpGet(key), + clientv3.OpGet(key+"/"), + ).Commit() + + if err != nil { + return nil, err + } + if !resp.Succeeded { + return nil, compareFail(nodePath, prevValue, prevIndex, resp) + } + + pkv := resp.Responses[0].GetResponsePut().PrevKv + return &store.Event{ + Action: store.CompareAndSwap, + Node: &store.NodeExtern{ + Key: nodePath, + Value: &value, + CreatedIndex: mkV2Rev(pkv.CreateRevision), + ModifiedIndex: mkV2Rev(resp.Header.Revision), + }, + PrevNode: s.mkV2Node(pkv), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) Delete(nodePath string, dir, recursive bool) (*store.Event, error) { + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + if !dir && !recursive { + return s.deleteNode(nodePath) + } + dir = true + if !recursive { + return s.deleteEmptyDir(nodePath) + } + + dels := make([]clientv3.Op, maxPathDepth+1) + dels[0] = clientv3.OpDelete(s.mkPath(nodePath)+"/", clientv3.WithPrevKV()) + for i := 1; i < maxPathDepth; i++ { + dels[i] = clientv3.OpDelete(s.mkPathDepth(nodePath, i), clientv3.WithPrefix()) + } + dels[maxPathDepth] = clientv3.OpPut(s.mkActionKey(), store.Delete) + + resp, err := s.c.Txn(s.ctx).If( + clientv3.Compare(clientv3.Version(s.mkPath(nodePath)+"/"), ">", 0), + clientv3.Compare(clientv3.Version(s.mkPathDepth(nodePath, maxPathDepth)+"/"), "=", 0), + ).Then( + dels..., + ).Commit() + if err != nil { + return nil, err + } + if !resp.Succeeded { + return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, mkV2Rev(resp.Header.Revision)) + } + dresp := resp.Responses[0].GetResponseDeleteRange() + return &store.Event{ + Action: store.Delete, + PrevNode: s.mkV2Node(dresp.PrevKvs[0]), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) deleteEmptyDir(nodePath string) (*store.Event, error) { + resp, err := s.c.Txn(s.ctx).If( + clientv3.Compare(clientv3.Version(s.mkPathDepth(nodePath, 1)), "=", 0).WithPrefix(), + ).Then( + clientv3.OpDelete(s.mkPath(nodePath)+"/", clientv3.WithPrevKV()), + clientv3.OpPut(s.mkActionKey(), store.Delete), + ).Commit() + if err != nil { + return nil, err + } + if !resp.Succeeded { + return nil, etcdErr.NewError(etcdErr.EcodeDirNotEmpty, nodePath, mkV2Rev(resp.Header.Revision)) + } + dresp := resp.Responses[0].GetResponseDeleteRange() + if len(dresp.PrevKvs) == 0 { + return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, mkV2Rev(resp.Header.Revision)) + } + return &store.Event{ + Action: store.Delete, + PrevNode: s.mkV2Node(dresp.PrevKvs[0]), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) deleteNode(nodePath string) (*store.Event, error) { + resp, err := s.c.Txn(s.ctx).If( + clientv3.Compare(clientv3.Version(s.mkPath(nodePath)+"/"), "=", 0), + ).Then( + clientv3.OpDelete(s.mkPath(nodePath), clientv3.WithPrevKV()), + clientv3.OpPut(s.mkActionKey(), store.Delete), + ).Commit() + if err != nil { + return nil, err + } + if !resp.Succeeded { + return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision)) + } + pkvs := resp.Responses[0].GetResponseDeleteRange().PrevKvs + if len(pkvs) == 0 { + return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision)) + } + pkv := pkvs[0] + return &store.Event{ + Action: store.Delete, + Node: &store.NodeExtern{ + Key: nodePath, + CreatedIndex: mkV2Rev(pkv.CreateRevision), + ModifiedIndex: mkV2Rev(resp.Header.Revision), + }, + PrevNode: s.mkV2Node(pkv), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func (s *v2v3Store) CompareAndDelete(nodePath, prevValue string, prevIndex uint64) (*store.Event, error) { + if isRoot(nodePath) { + return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, nodePath, 0) + } + + key := s.mkPath(nodePath) + resp, err := s.c.Txn(s.ctx).If( + s.mkCompare(nodePath, prevValue, prevIndex)..., + ).Then( + clientv3.OpDelete(key, clientv3.WithPrevKV()), + clientv3.OpPut(s.mkActionKey(), store.CompareAndDelete), + ).Else( + clientv3.OpGet(key), + clientv3.OpGet(key+"/"), + ).Commit() + + if err != nil { + return nil, err + } + if !resp.Succeeded { + return nil, compareFail(nodePath, prevValue, prevIndex, resp) + } + + // len(pkvs) > 1 since txn only succeeds when key exists + pkv := resp.Responses[0].GetResponseDeleteRange().PrevKvs[0] + return &store.Event{ + Action: store.CompareAndDelete, + Node: &store.NodeExtern{ + Key: nodePath, + CreatedIndex: mkV2Rev(pkv.CreateRevision), + ModifiedIndex: mkV2Rev(resp.Header.Revision), + }, + PrevNode: s.mkV2Node(pkv), + EtcdIndex: mkV2Rev(resp.Header.Revision), + }, nil +} + +func compareFail(nodePath, prevValue string, prevIndex uint64, resp *clientv3.TxnResponse) error { + if dkvs := resp.Responses[1].GetResponseRange().Kvs; len(dkvs) > 0 { + return etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, mkV2Rev(resp.Header.Revision)) + } + kvs := resp.Responses[0].GetResponseRange().Kvs + if len(kvs) == 0 { + return etcdErr.NewError(etcdErr.EcodeKeyNotFound, nodePath, mkV2Rev(resp.Header.Revision)) + } + kv := kvs[0] + indexMatch := (prevIndex == 0 || kv.ModRevision == int64(prevIndex)) + valueMatch := (prevValue == "" || string(kv.Value) == prevValue) + cause := "" + switch { + case indexMatch && !valueMatch: + cause = fmt.Sprintf("[%v != %v]", prevValue, string(kv.Value)) + case valueMatch && !indexMatch: + cause = fmt.Sprintf("[%v != %v]", prevIndex, kv.ModRevision) + default: + cause = fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, string(kv.Value), prevIndex, kv.ModRevision) + } + return etcdErr.NewError(etcdErr.EcodeTestFailed, cause, mkV2Rev(resp.Header.Revision)) +} + +func (s *v2v3Store) mkCompare(nodePath, prevValue string, prevIndex uint64) []clientv3.Cmp { + key := s.mkPath(nodePath) + cmps := []clientv3.Cmp{clientv3.Compare(clientv3.Version(key), ">", 0)} + if prevIndex != 0 { + cmps = append(cmps, clientv3.Compare(clientv3.ModRevision(key), "=", mkV3Rev(prevIndex))) + } + if prevValue != "" { + cmps = append(cmps, clientv3.Compare(clientv3.Value(key), "=", prevValue)) + } + return cmps +} + +func (s *v2v3Store) JsonStats() []byte { panic("STUB") } +func (s *v2v3Store) DeleteExpiredKeys(cutoff time.Time) { panic("STUB") } + +func (s *v2v3Store) Version() int { return 2 } + +// TODO: move this out of the Store interface? + +func (s *v2v3Store) Save() ([]byte, error) { panic("STUB") } +func (s *v2v3Store) Recovery(state []byte) error { panic("STUB") } +func (s *v2v3Store) Clone() store.Store { panic("STUB") } +func (s *v2v3Store) SaveNoCopy() ([]byte, error) { panic("STUB") } +func (s *v2v3Store) HasTTLKeys() bool { panic("STUB") } + +func (s *v2v3Store) mkPath(nodePath string) string { return s.mkPathDepth(nodePath, 0) } + +func (s *v2v3Store) mkNodePath(p string) string { + return path.Clean(p[len(s.pfx)+len("/k/000/"):]) +} + +// mkPathDepth makes a path to a key that encodes its directory depth +// for fast directory listing. If a depth is provided, it is added +// to the computed depth. +func (s *v2v3Store) mkPathDepth(nodePath string, depth int) string { + normalForm := path.Clean(path.Join("/", nodePath)) + n := strings.Count(normalForm, "/") + depth + return fmt.Sprintf("%s/%03d/k/%s", s.pfx, n, normalForm) +} + +func (s *v2v3Store) mkActionKey() string { return s.pfx + "/act" } + +func isRoot(s string) bool { return len(s) == 0 || s == "/" || s == "/0" || s == "/1" } + +func mkV2Rev(v3Rev int64) uint64 { + if v3Rev == 0 { + return 0 + } + return uint64(v3Rev - 1) +} + +func mkV3Rev(v2Rev uint64) int64 { + if v2Rev == 0 { + return 0 + } + return int64(v2Rev + 1) +} + +// mkV2Node creates a V2 NodeExtern from a V3 KeyValue +func (s *v2v3Store) mkV2Node(kv *mvccpb.KeyValue) *store.NodeExtern { + if kv == nil { + return nil + } + n := &store.NodeExtern{ + Key: string(s.mkNodePath(string(kv.Key))), + Dir: kv.Key[len(kv.Key)-1] == '/', + CreatedIndex: mkV2Rev(kv.CreateRevision), + ModifiedIndex: mkV2Rev(kv.ModRevision), + } + if !n.Dir { + v := string(kv.Value) + n.Value = &v + } + return n +} + +// prevKeyFromPuts gets the prev key that is being put; ignores +// the put action response. +func prevKeyFromPuts(resp *clientv3.TxnResponse) *mvccpb.KeyValue { + for _, r := range resp.Responses { + pkv := r.GetResponsePut().PrevKv + if pkv != nil && pkv.CreateRevision > 0 { + return pkv + } + } + return nil +} + +func (s *v2v3Store) newSTM(applyf func(concurrency.STM) error) (*clientv3.TxnResponse, error) { + return concurrency.NewSTM(s.c, applyf, concurrency.WithIsolation(concurrency.Serializable)) +} diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/watcher.go b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/watcher.go new file mode 100644 index 000000000..1c2680e74 --- /dev/null +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v2v3/watcher.go @@ -0,0 +1,140 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v2v3 + +import ( + "context" + "strings" + + "github.com/coreos/etcd/clientv3" + etcdErr "github.com/coreos/etcd/error" + "github.com/coreos/etcd/store" +) + +func (s *v2v3Store) Watch(prefix string, recursive, stream bool, sinceIndex uint64) (store.Watcher, error) { + ctx, cancel := context.WithCancel(s.ctx) + wch := s.c.Watch( + ctx, + // TODO: very pricey; use a single store-wide watch in future + s.pfx, + clientv3.WithPrefix(), + clientv3.WithRev(int64(sinceIndex)), + clientv3.WithCreatedNotify(), + clientv3.WithPrevKV()) + resp, ok := <-wch + if err := resp.Err(); err != nil || !ok { + cancel() + return nil, etcdErr.NewError(etcdErr.EcodeRaftInternal, prefix, 0) + } + + evc, donec := make(chan *store.Event), make(chan struct{}) + go func() { + defer func() { + close(evc) + close(donec) + }() + for resp := range wch { + for _, ev := range s.mkV2Events(resp) { + k := ev.Node.Key + if recursive { + if !strings.HasPrefix(k, prefix) { + continue + } + // accept events on hidden keys given in prefix + k = strings.Replace(k, prefix, "/", 1) + // ignore hidden keys deeper than prefix + if strings.Contains(k, "/_") { + continue + } + } + if !recursive && k != prefix { + continue + } + select { + case evc <- ev: + case <-ctx.Done(): + return + } + if !stream { + return + } + } + } + }() + + return &v2v3Watcher{ + startRev: resp.Header.Revision, + evc: evc, + donec: donec, + cancel: cancel, + }, nil +} + +func (s *v2v3Store) mkV2Events(wr clientv3.WatchResponse) (evs []*store.Event) { + ak := s.mkActionKey() + for _, rev := range mkRevs(wr) { + var act, key *clientv3.Event + for _, ev := range rev { + if string(ev.Kv.Key) == ak { + act = ev + } else if key != nil && len(key.Kv.Key) < len(ev.Kv.Key) { + // use longest key to ignore intermediate new + // directories from Create. + key = ev + } else if key == nil { + key = ev + } + } + v2ev := &store.Event{ + Action: string(act.Kv.Value), + Node: s.mkV2Node(key.Kv), + PrevNode: s.mkV2Node(key.PrevKv), + EtcdIndex: mkV2Rev(wr.Header.Revision), + } + evs = append(evs, v2ev) + } + return evs +} + +func mkRevs(wr clientv3.WatchResponse) (revs [][]*clientv3.Event) { + var curRev []*clientv3.Event + for _, ev := range wr.Events { + if curRev != nil && ev.Kv.ModRevision != curRev[0].Kv.ModRevision { + revs = append(revs, curRev) + curRev = nil + } + curRev = append(curRev, ev) + } + if curRev != nil { + revs = append(revs, curRev) + } + return revs +} + +type v2v3Watcher struct { + startRev int64 + evc chan *store.Event + donec chan struct{} + cancel context.CancelFunc +} + +func (w *v2v3Watcher) StartIndex() uint64 { return mkV2Rev(w.startRev) } + +func (w *v2v3Watcher) Remove() { + w.cancel() + <-w.donec +} + +func (w *v2v3Watcher) EventChan() chan *store.Event { return w.evc } diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/grpc.go b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/grpc.go index 19943ff52..3f7cea8ee 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/grpc.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/grpc.go @@ -31,6 +31,7 @@ import ( const ( grpcOverheadBytes = 512 * 1024 maxStreams = math.MaxUint32 + maxSendBytes = math.MaxInt32 ) func init() { @@ -45,7 +46,8 @@ func Server(s *etcdserver.EtcdServer, tls *tls.Config) *grpc.Server { } opts = append(opts, grpc.UnaryInterceptor(newUnaryInterceptor(s))) opts = append(opts, grpc.StreamInterceptor(newStreamInterceptor(s))) - opts = append(opts, grpc.MaxMsgSize(int(s.Cfg.MaxRequestBytes+grpcOverheadBytes))) + opts = append(opts, grpc.MaxRecvMsgSize(int(s.Cfg.MaxRequestBytes+grpcOverheadBytes))) + opts = append(opts, grpc.MaxSendMsgSize(maxSendBytes)) opts = append(opts, grpc.MaxConcurrentStreams(maxStreams)) grpcServer := grpc.NewServer(opts...) diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/maintenance.go b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/maintenance.go index fdbb118ce..a88aec995 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/maintenance.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/maintenance.go @@ -46,8 +46,7 @@ type LeaderTransferrer interface { } type RaftStatusGetter interface { - Index() uint64 - Term() uint64 + etcdserver.RaftTimer ID() types.ID Leader() types.ID } diff --git a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/member.go b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/member.go index 91a59389b..ff271e8dd 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/member.go +++ b/vendor/github.com/coreos/etcd/etcdserver/api/v3rpc/member.go @@ -27,16 +27,14 @@ import ( ) type ClusterServer struct { - cluster api.Cluster - server etcdserver.Server - raftTimer etcdserver.RaftTimer + cluster api.Cluster + server etcdserver.ServerV3 } -func NewClusterServer(s *etcdserver.EtcdServer) *ClusterServer { +func NewClusterServer(s etcdserver.ServerV3) *ClusterServer { return &ClusterServer{ - cluster: s.Cluster(), - server: s, - raftTimer: s, + cluster: s.Cluster(), + server: s, } } @@ -86,7 +84,7 @@ func (cs *ClusterServer) MemberList(ctx context.Context, r *pb.MemberListRequest } func (cs *ClusterServer) header() *pb.ResponseHeader { - return &pb.ResponseHeader{ClusterId: uint64(cs.cluster.ID()), MemberId: uint64(cs.server.ID()), RaftTerm: cs.raftTimer.Term()} + return &pb.ResponseHeader{ClusterId: uint64(cs.cluster.ID()), MemberId: uint64(cs.server.ID()), RaftTerm: cs.server.Term()} } func membersToProtoMembers(membs []*membership.Member) []*pb.Member { diff --git a/vendor/github.com/coreos/etcd/etcdserver/apply_v2.go b/vendor/github.com/coreos/etcd/etcdserver/apply_v2.go index f278efca8..aefe19d26 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/apply_v2.go +++ b/vendor/github.com/coreos/etcd/etcdserver/apply_v2.go @@ -20,7 +20,6 @@ import ( "time" "github.com/coreos/etcd/etcdserver/api" - pb "github.com/coreos/etcd/etcdserver/etcdserverpb" "github.com/coreos/etcd/etcdserver/membership" "github.com/coreos/etcd/pkg/pbutil" "github.com/coreos/etcd/store" @@ -29,11 +28,11 @@ import ( // ApplierV2 is the interface for processing V2 raft messages type ApplierV2 interface { - Delete(r *pb.Request) Response - Post(r *pb.Request) Response - Put(r *pb.Request) Response - QGet(r *pb.Request) Response - Sync(r *pb.Request) Response + Delete(r *RequestV2) Response + Post(r *RequestV2) Response + Put(r *RequestV2) Response + QGet(r *RequestV2) Response + Sync(r *RequestV2) Response } func NewApplierV2(s store.Store, c *membership.RaftCluster) ApplierV2 { @@ -45,7 +44,7 @@ type applierV2store struct { cluster *membership.RaftCluster } -func (a *applierV2store) Delete(r *pb.Request) Response { +func (a *applierV2store) Delete(r *RequestV2) Response { switch { case r.PrevIndex > 0 || r.PrevValue != "": return toResponse(a.store.CompareAndDelete(r.Path, r.PrevValue, r.PrevIndex)) @@ -54,12 +53,12 @@ func (a *applierV2store) Delete(r *pb.Request) Response { } } -func (a *applierV2store) Post(r *pb.Request) Response { - return toResponse(a.store.Create(r.Path, r.Dir, r.Val, true, toTTLOptions(r))) +func (a *applierV2store) Post(r *RequestV2) Response { + return toResponse(a.store.Create(r.Path, r.Dir, r.Val, true, r.TTLOptions())) } -func (a *applierV2store) Put(r *pb.Request) Response { - ttlOptions := toTTLOptions(r) +func (a *applierV2store) Put(r *RequestV2) Response { + ttlOptions := r.TTLOptions() exists, existsSet := pbutil.GetBool(r.PrevExist) switch { case existsSet: @@ -96,19 +95,18 @@ func (a *applierV2store) Put(r *pb.Request) Response { } } -func (a *applierV2store) QGet(r *pb.Request) Response { +func (a *applierV2store) QGet(r *RequestV2) Response { return toResponse(a.store.Get(r.Path, r.Recursive, r.Sorted)) } -func (a *applierV2store) Sync(r *pb.Request) Response { +func (a *applierV2store) Sync(r *RequestV2) Response { a.store.DeleteExpiredKeys(time.Unix(0, r.Time)) return Response{} } // applyV2Request interprets r as a call to store.X and returns a Response interpreted // from store.Event -func (s *EtcdServer) applyV2Request(r *pb.Request) Response { - toTTLOptions(r) +func (s *EtcdServer) applyV2Request(r *RequestV2) Response { switch r.Method { case "POST": return s.applyV2.Post(r) @@ -122,11 +120,11 @@ func (s *EtcdServer) applyV2Request(r *pb.Request) Response { return s.applyV2.Sync(r) default: // This should never be reached, but just in case: - return Response{err: ErrUnknownMethod} + return Response{Err: ErrUnknownMethod} } } -func toTTLOptions(r *pb.Request) store.TTLOptionSet { +func (r *RequestV2) TTLOptions() store.TTLOptionSet { refresh, _ := pbutil.GetBool(r.Refresh) ttlOptions := store.TTLOptionSet{Refresh: refresh} if r.Expiration != 0 { @@ -136,5 +134,5 @@ func toTTLOptions(r *pb.Request) store.TTLOptionSet { } func toResponse(ev *store.Event, err error) Response { - return Response{Event: ev, err: err} + return Response{Event: ev, Err: err} } diff --git a/vendor/github.com/coreos/etcd/etcdserver/server.go b/vendor/github.com/coreos/etcd/etcdserver/server.go index ac7601ecb..ffeaf88cc 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/server.go +++ b/vendor/github.com/coreos/etcd/etcdserver/server.go @@ -38,6 +38,7 @@ import ( "github.com/coreos/etcd/etcdserver/membership" "github.com/coreos/etcd/etcdserver/stats" "github.com/coreos/etcd/lease" + "github.com/coreos/etcd/lease/leasehttp" "github.com/coreos/etcd/mvcc" "github.com/coreos/etcd/mvcc/backend" "github.com/coreos/etcd/pkg/fileutil" @@ -108,29 +109,33 @@ func init() { } type Response struct { + Term uint64 + Index uint64 Event *store.Event Watcher store.Watcher - err error + Err error } -type Server interface { - // Start performs any initialization of the Server necessary for it to - // begin serving requests. It must be called before Do or Process. - // Start must be non-blocking; any long-running server functionality - // should be implemented in goroutines. - Start() - // Stop terminates the Server and performs any necessary finalization. - // Do and Process cannot be called after Stop has been invoked. - Stop() - // ID returns the ID of the Server. +type ServerV2 interface { + Server + // Do takes a V2 request and attempts to fulfill it, returning a Response. + Do(ctx context.Context, r pb.Request) (Response, error) + stats.Stats + ClientCertAuthEnabled() bool +} + +type ServerV3 interface { + Server ID() types.ID + RaftTimer +} + +func (s *EtcdServer) ClientCertAuthEnabled() bool { return s.Cfg.ClientCertAuthEnabled } + +type Server interface { // Leader returns the ID of the leader Server. Leader() types.ID - // Do takes a request and attempts to fulfill it, returning a Response. - Do(ctx context.Context, r pb.Request) (Response, error) - // Process takes a raft message and applies it to the server's raft state - // machine, respecting any timeout of the given context. - Process(ctx context.Context, m raftpb.Message) error + // AddMember attempts to add a member into the cluster. It will return // ErrIDRemoved if member ID is removed from the cluster, or return // ErrIDExists if member ID exists in the cluster. @@ -139,7 +144,6 @@ type Server interface { // return ErrIDRemoved if member ID is removed from the cluster, or return // ErrIDNotFound if member ID is not in the cluster. RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) - // UpdateMember attempts to update an existing member in the cluster. It will // return ErrIDNotFound if the member ID does not exist. UpdateMember(ctx context.Context, updateMemb membership.Member) ([]*membership.Member, error) @@ -159,6 +163,8 @@ type Server interface { // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since // this feature is introduced post 2.0. ClusterVersion() *semver.Version + Cluster() api.Cluster + Alarms() []*pb.AlarmMember } // EtcdServer is the production implementation of the Server interface @@ -514,9 +520,10 @@ func NewServer(cfg ServerConfig) (srv *EtcdServer, err error) { return srv, nil } -// Start prepares and starts server in a new goroutine. It is no longer safe to -// modify a server's fields after it has been sent to Start. -// It also starts a goroutine to publish its server information. +// Start performs any initialization of the Server necessary for it to +// begin serving requests. It must be called before Do or Process. +// Start must be non-blocking; any long-running server functionality +// should be implemented in goroutines. func (s *EtcdServer) Start() { s.start() s.goAttach(func() { s.publish(s.Cfg.ReqTimeout()) }) @@ -576,14 +583,27 @@ func (s *EtcdServer) purgeFile() { func (s *EtcdServer) ID() types.ID { return s.id } -func (s *EtcdServer) Cluster() *membership.RaftCluster { return s.cluster } - -func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() } - -func (s *EtcdServer) Lessor() lease.Lessor { return s.lessor } +func (s *EtcdServer) Cluster() api.Cluster { return s.cluster } func (s *EtcdServer) ApplyWait() <-chan struct{} { return s.applyWait.Wait(s.getCommittedIndex()) } +type ServerPeer interface { + ServerV2 + RaftHandler() http.Handler + LeaseHandler() http.Handler +} + +func (s *EtcdServer) LeaseHandler() http.Handler { + if s.lessor == nil { + return nil + } + return leasehttp.NewHandler(s.lessor, s.ApplyWait) +} + +func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() } + +// Process takes a raft message and applies it to the server's raft state +// machine, respecting any timeout of the given context. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error { if s.cluster.IsIDRemoved(types.ID(m.From)) { plog.Warningf("reject message from removed member %s", types.ID(m.From).String()) @@ -992,6 +1012,8 @@ func (s *EtcdServer) HardStop() { // Stop should be called after a Start(s), otherwise it will block forever. // When stopping leader, Stop transfers its leadership to one of its peers // before stopping the server. +// Stop terminates the Server and performs any necessary finalization. +// Do and Process cannot be called after Stop has been invoked. func (s *EtcdServer) Stop() { if err := s.TransferLeadership(); err != nil { plog.Warningf("%s failed to transfer leadership (%v)", s.ID(), err) @@ -1322,12 +1344,13 @@ func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) { var raftReq pb.InternalRaftRequest if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible var r pb.Request - pbutil.MustUnmarshal(&r, e.Data) - s.w.Trigger(r.ID, s.applyV2Request(&r)) + rp := &r + pbutil.MustUnmarshal(rp, e.Data) + s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp))) return } if raftReq.V2 != nil { - req := raftReq.V2 + req := (*RequestV2)(raftReq.V2) s.w.Trigger(req.ID, s.applyV2Request(req)) return } diff --git a/vendor/github.com/coreos/etcd/etcdserver/server_test.go b/vendor/github.com/coreos/etcd/etcdserver/server_test.go index 66c99247b..c2bd0045f 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/server_test.go +++ b/vendor/github.com/coreos/etcd/etcdserver/server_test.go @@ -441,7 +441,7 @@ func TestApplyRequest(t *testing.T) { // Unknown method - error { pb.Request{Method: "BADMETHOD", ID: 1}, - Response{err: ErrUnknownMethod}, + Response{Err: ErrUnknownMethod}, []testutil.Action{}, }, } @@ -450,7 +450,7 @@ func TestApplyRequest(t *testing.T) { st := mockstore.NewRecorder() srv := &EtcdServer{store: st} srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster} - resp := srv.applyV2Request(&tt.req) + resp := srv.applyV2Request((*RequestV2)(&tt.req)) if !reflect.DeepEqual(resp, tt.wresp) { t.Errorf("#%d: resp = %+v, want %+v", i, resp, tt.wresp) @@ -476,7 +476,7 @@ func TestApplyRequestOnAdminMemberAttributes(t *testing.T) { Path: membership.MemberAttributesStorePath(1), Val: `{"Name":"abc","ClientURLs":["http://127.0.0.1:2379"]}`, } - srv.applyV2Request(&req) + srv.applyV2Request((*RequestV2)(&req)) w := membership.Attributes{Name: "abc", ClientURLs: []string{"http://127.0.0.1:2379"}} if g := cl.Member(1).Attributes; !reflect.DeepEqual(g, w) { t.Errorf("attributes = %v, want %v", g, w) @@ -701,7 +701,8 @@ func TestDoProposal(t *testing.T) { if err != nil { t.Fatalf("#%d: err = %v, want nil", i, err) } - wresp := Response{Event: &store.Event{}} + // resp.Index is set in Do() based on the raft state; may either be 0 or 1 + wresp := Response{Event: &store.Event{}, Index: resp.Index} if !reflect.DeepEqual(resp, wresp) { t.Errorf("#%d: resp = %v, want %v", i, resp, wresp) } diff --git a/vendor/github.com/coreos/etcd/etcdserver/v2_server.go b/vendor/github.com/coreos/etcd/etcdserver/v2_server.go index 72c4eb7c5..6c4aa8baf 100644 --- a/vendor/github.com/coreos/etcd/etcdserver/v2_server.go +++ b/vendor/github.com/coreos/etcd/etcdserver/v2_server.go @@ -18,38 +18,83 @@ import ( "time" pb "github.com/coreos/etcd/etcdserver/etcdserverpb" + "github.com/coreos/etcd/store" "golang.org/x/net/context" ) -type v2API interface { - Post(ctx context.Context, r *pb.Request) (Response, error) - Put(ctx context.Context, r *pb.Request) (Response, error) - Delete(ctx context.Context, r *pb.Request) (Response, error) - QGet(ctx context.Context, r *pb.Request) (Response, error) - Get(ctx context.Context, r *pb.Request) (Response, error) - Head(ctx context.Context, r *pb.Request) (Response, error) +type RequestV2 pb.Request + +type RequestV2Handler interface { + Post(ctx context.Context, r *RequestV2) (Response, error) + Put(ctx context.Context, r *RequestV2) (Response, error) + Delete(ctx context.Context, r *RequestV2) (Response, error) + QGet(ctx context.Context, r *RequestV2) (Response, error) + Get(ctx context.Context, r *RequestV2) (Response, error) + Head(ctx context.Context, r *RequestV2) (Response, error) } -type v2apiStore struct{ s *EtcdServer } +type reqV2HandlerEtcdServer struct { + reqV2HandlerStore + s *EtcdServer +} -func (a *v2apiStore) Post(ctx context.Context, r *pb.Request) (Response, error) { +type reqV2HandlerStore struct { + store store.Store + applier ApplierV2 +} + +func NewStoreRequestV2Handler(s store.Store, applier ApplierV2) RequestV2Handler { + return &reqV2HandlerStore{s, applier} +} + +func (a *reqV2HandlerStore) Post(ctx context.Context, r *RequestV2) (Response, error) { + return a.applier.Post(r), nil +} + +func (a *reqV2HandlerStore) Put(ctx context.Context, r *RequestV2) (Response, error) { + return a.applier.Put(r), nil +} + +func (a *reqV2HandlerStore) Delete(ctx context.Context, r *RequestV2) (Response, error) { + return a.applier.Delete(r), nil +} + +func (a *reqV2HandlerStore) QGet(ctx context.Context, r *RequestV2) (Response, error) { + return a.applier.QGet(r), nil +} + +func (a *reqV2HandlerStore) Get(ctx context.Context, r *RequestV2) (Response, error) { + if r.Wait { + wc, err := a.store.Watch(r.Path, r.Recursive, r.Stream, r.Since) + return Response{Watcher: wc}, err + } + ev, err := a.store.Get(r.Path, r.Recursive, r.Sorted) + return Response{Event: ev}, err +} + +func (a *reqV2HandlerStore) Head(ctx context.Context, r *RequestV2) (Response, error) { + ev, err := a.store.Get(r.Path, r.Recursive, r.Sorted) + return Response{Event: ev}, err +} + +func (a *reqV2HandlerEtcdServer) Post(ctx context.Context, r *RequestV2) (Response, error) { return a.processRaftRequest(ctx, r) } -func (a *v2apiStore) Put(ctx context.Context, r *pb.Request) (Response, error) { +func (a *reqV2HandlerEtcdServer) Put(ctx context.Context, r *RequestV2) (Response, error) { return a.processRaftRequest(ctx, r) } -func (a *v2apiStore) Delete(ctx context.Context, r *pb.Request) (Response, error) { +func (a *reqV2HandlerEtcdServer) Delete(ctx context.Context, r *RequestV2) (Response, error) { return a.processRaftRequest(ctx, r) } -func (a *v2apiStore) QGet(ctx context.Context, r *pb.Request) (Response, error) { +func (a *reqV2HandlerEtcdServer) QGet(ctx context.Context, r *RequestV2) (Response, error) { return a.processRaftRequest(ctx, r) } -func (a *v2apiStore) processRaftRequest(ctx context.Context, r *pb.Request) (Response, error) { - data, err := r.Marshal() +func (a *reqV2HandlerEtcdServer) processRaftRequest(ctx context.Context, r *RequestV2) (Response, error) { + data, err := ((*pb.Request)(r)).Marshal() if err != nil { return Response{}, err } @@ -63,7 +108,7 @@ func (a *v2apiStore) processRaftRequest(ctx context.Context, r *pb.Request) (Res select { case x := <-ch: resp := x.(Response) - return resp, resp.err + return resp, resp.Err case <-ctx.Done(): proposalsFailed.Inc() a.s.w.Trigger(r.ID, nil) // GC wait @@ -73,53 +118,43 @@ func (a *v2apiStore) processRaftRequest(ctx context.Context, r *pb.Request) (Res return Response{}, ErrStopped } -func (a *v2apiStore) Get(ctx context.Context, r *pb.Request) (Response, error) { - if r.Wait { - wc, err := a.s.store.Watch(r.Path, r.Recursive, r.Stream, r.Since) - if err != nil { - return Response{}, err - } - return Response{Watcher: wc}, nil +func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) { + r.ID = s.reqIDGen.Next() + h := &reqV2HandlerEtcdServer{ + reqV2HandlerStore: reqV2HandlerStore{ + store: s.store, + applier: s.applyV2, + }, + s: s, } - ev, err := a.s.store.Get(r.Path, r.Recursive, r.Sorted) - if err != nil { - return Response{}, err - } - return Response{Event: ev}, nil + rp := &r + resp, err := ((*RequestV2)(rp)).Handle(ctx, h) + resp.Term, resp.Index = s.Term(), s.Index() + return resp, err } -func (a *v2apiStore) Head(ctx context.Context, r *pb.Request) (Response, error) { - ev, err := a.s.store.Get(r.Path, r.Recursive, r.Sorted) - if err != nil { - return Response{}, err - } - return Response{Event: ev}, nil -} - -// Do interprets r and performs an operation on s.store according to r.Method +// Handle interprets r and performs an operation on s.store according to r.Method // and other fields. If r.Method is "POST", "PUT", "DELETE", or a "GET" with // Quorum == true, r will be sent through consensus before performing its // respective operation. Do will block until an action is performed or there is // an error. -func (s *EtcdServer) Do(ctx context.Context, r pb.Request) (Response, error) { - r.ID = s.reqIDGen.Next() +func (r *RequestV2) Handle(ctx context.Context, v2api RequestV2Handler) (Response, error) { if r.Method == "GET" && r.Quorum { r.Method = "QGET" } - v2api := (v2API)(&v2apiStore{s}) switch r.Method { case "POST": - return v2api.Post(ctx, &r) + return v2api.Post(ctx, r) case "PUT": - return v2api.Put(ctx, &r) + return v2api.Put(ctx, r) case "DELETE": - return v2api.Delete(ctx, &r) + return v2api.Delete(ctx, r) case "QGET": - return v2api.QGet(ctx, &r) + return v2api.QGet(ctx, r) case "GET": - return v2api.Get(ctx, &r) + return v2api.Get(ctx, r) case "HEAD": - return v2api.Head(ctx, &r) + return v2api.Head(ctx, r) } return Response{}, ErrUnknownMethod } diff --git a/vendor/github.com/coreos/etcd/hack/benchmark/bench.sh b/vendor/github.com/coreos/etcd/hack/benchmark/bench.sh old mode 100644 new mode 100755 index 3955d9e6e..d72efd3e2 --- a/vendor/github.com/coreos/etcd/hack/benchmark/bench.sh +++ b/vendor/github.com/coreos/etcd/hack/benchmark/bench.sh @@ -1,8 +1,8 @@ #!/bin/bash -e -leader=http://10.240.201.15:2379 +leader=http://localhost:2379 # assume three servers -servers=( http://10.240.201.15:2379 http://10.240.212.209:2379 http://10.240.95.3:2379 ) +servers=( http://localhost:2379 http://localhost:22379 http://localhost:32379 ) keyarray=( 64 256 ) diff --git a/vendor/github.com/coreos/etcd/integration/cluster.go b/vendor/github.com/coreos/etcd/integration/cluster.go index 7dcfdcdd4..01a2aa6ad 100644 --- a/vendor/github.com/coreos/etcd/integration/cluster.go +++ b/vendor/github.com/coreos/etcd/integration/cluster.go @@ -303,10 +303,11 @@ func (c *cluster) removeMember(t *testing.T, id uint64) error { cc := MustNewHTTPClient(t, c.URLs(), c.cfg.ClientTLS) ma := client.NewMembersAPI(cc) ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) - if err := ma.Remove(ctx, types.ID(id).String()); err != nil { + err := ma.Remove(ctx, types.ID(id).String()) + cancel() + if err != nil { return err } - cancel() newMembers := make([]*member, 0) for _, m := range c.Members { if uint64(m.s.ID()) != id { diff --git a/vendor/github.com/coreos/etcd/integration/cluster_test.go b/vendor/github.com/coreos/etcd/integration/cluster_test.go index 5907d6841..14549dac0 100644 --- a/vendor/github.com/coreos/etcd/integration/cluster_test.go +++ b/vendor/github.com/coreos/etcd/integration/cluster_test.go @@ -151,7 +151,15 @@ func testDecreaseClusterSize(t *testing.T, size int) { // TODO: remove the last but one member for i := 0; i < size-1; i++ { id := c.Members[len(c.Members)-1].s.ID() - c.RemoveMember(t, uint64(id)) + // may hit second leader election on slow machines + if err := c.removeMember(t, uint64(id)); err != nil { + if strings.Contains(err.Error(), "no leader") { + t.Logf("got leader error (%v)", err) + i-- + continue + } + t.Fatal(err) + } c.waitLeader(t, c.Members) } clusterMustProgress(t, c.Members) diff --git a/vendor/github.com/coreos/etcd/integration/v3_auth_test.go b/vendor/github.com/coreos/etcd/integration/v3_auth_test.go index d0965a789..03ea88cd9 100644 --- a/vendor/github.com/coreos/etcd/integration/v3_auth_test.go +++ b/vendor/github.com/coreos/etcd/integration/v3_auth_test.go @@ -15,6 +15,8 @@ package integration import ( + "fmt" + "sync" "testing" "time" @@ -292,3 +294,41 @@ func TestV3AuthNonAuthorizedRPCs(t *testing.T) { t.Fatalf("could put key (%v), it should cause an error of permission denied", respput) } } + +func TestV3AuthOldRevConcurrent(t *testing.T) { + defer testutil.AfterTest(t) + clus := NewClusterV3(t, &ClusterConfig{Size: 1}) + defer clus.Terminate(t) + + authSetupRoot(t, toGRPC(clus.Client(0)).Auth) + + c, cerr := clientv3.New(clientv3.Config{ + Endpoints: clus.Client(0).Endpoints(), + DialTimeout: 5 * time.Second, + Username: "root", + Password: "123", + }) + testutil.AssertNil(t, cerr) + defer c.Close() + + var wg sync.WaitGroup + f := func(i int) { + defer wg.Done() + role, user := fmt.Sprintf("test-role-%d", i), fmt.Sprintf("test-user-%d", i) + _, err := c.RoleAdd(context.TODO(), role) + testutil.AssertNil(t, err) + _, err = c.RoleGrantPermission(context.TODO(), role, "", clientv3.GetPrefixRangeEnd(""), clientv3.PermissionType(clientv3.PermReadWrite)) + testutil.AssertNil(t, err) + _, err = c.UserAdd(context.TODO(), user, "123") + testutil.AssertNil(t, err) + _, err = c.Put(context.TODO(), "a", "b") + testutil.AssertNil(t, err) + } + // needs concurrency to trigger + numRoles := 2 + wg.Add(numRoles) + for i := 0; i < numRoles; i++ { + go f(i) + } + wg.Wait() +} diff --git a/vendor/github.com/coreos/etcd/integration/v3_watch_test.go b/vendor/github.com/coreos/etcd/integration/v3_watch_test.go index c6570d0c2..92fc98ef3 100644 --- a/vendor/github.com/coreos/etcd/integration/v3_watch_test.go +++ b/vendor/github.com/coreos/etcd/integration/v3_watch_test.go @@ -223,20 +223,24 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { cresp, err := wStream.Recv() if err != nil { t.Errorf("#%d: wStream.Recv error: %v", i, err) + clus.Terminate(t) continue } if !cresp.Created { t.Errorf("#%d: did not create watchid, got %+v", i, cresp) + clus.Terminate(t) continue } if cresp.Canceled { t.Errorf("#%d: canceled watcher on create %+v", i, cresp) + clus.Terminate(t) continue } createdWatchId := cresp.WatchId if cresp.Header == nil || cresp.Header.Revision != 1 { t.Errorf("#%d: header revision got +%v, wanted revison 1", i, cresp) + clus.Terminate(t) continue } diff --git a/vendor/github.com/coreos/etcd/mvcc/index.go b/vendor/github.com/coreos/etcd/mvcc/index.go index 53b3ebc66..13a350c19 100644 --- a/vendor/github.com/coreos/etcd/mvcc/index.go +++ b/vendor/github.com/coreos/etcd/mvcc/index.go @@ -85,6 +85,21 @@ func (ti *treeIndex) keyIndex(keyi *keyIndex) *keyIndex { return nil } +func (ti *treeIndex) visit(key, end []byte, f func(ki *keyIndex)) { + keyi, endi := &keyIndex{key: key}, &keyIndex{key: end} + + ti.RLock() + defer ti.RUnlock() + + ti.tree.AscendGreaterOrEqual(keyi, func(item btree.Item) bool { + if len(endi.key) > 0 && !item.Less(endi) { + return false + } + f(item.(*keyIndex)) + return true + }) +} + func (ti *treeIndex) Revisions(key, end []byte, atRev int64) (revs []revision) { if end == nil { rev, _, _, err := ti.Get(key, atRev) @@ -93,8 +108,12 @@ func (ti *treeIndex) Revisions(key, end []byte, atRev int64) (revs []revision) { } return []revision{rev} } - _, rev := ti.Range(key, end, atRev) - return rev + ti.visit(key, end, func(ki *keyIndex) { + if rev, _, _, err := ki.get(atRev); err == nil { + revs = append(revs, rev) + } + }) + return revs } func (ti *treeIndex) Range(key, end []byte, atRev int64) (keys [][]byte, revs []revision) { @@ -105,27 +124,12 @@ func (ti *treeIndex) Range(key, end []byte, atRev int64) (keys [][]byte, revs [] } return [][]byte{key}, []revision{rev} } - - keyi := &keyIndex{key: key} - endi := &keyIndex{key: end} - - ti.RLock() - defer ti.RUnlock() - - ti.tree.AscendGreaterOrEqual(keyi, func(item btree.Item) bool { - if len(endi.key) > 0 && !item.Less(endi) { - return false + ti.visit(key, end, func(ki *keyIndex) { + if rev, _, _, err := ki.get(atRev); err == nil { + revs = append(revs, rev) + keys = append(keys, ki.key) } - curKeyi := item.(*keyIndex) - rev, _, _, err := curKeyi.get(atRev) - if err != nil { - return true - } - revs = append(revs, rev) - keys = append(keys, curKeyi.key) - return true }) - return keys, revs } diff --git a/vendor/github.com/coreos/etcd/mvcc/kvstore_bench_test.go b/vendor/github.com/coreos/etcd/mvcc/kvstore_bench_test.go index 92f3d6d50..a64a3c5a5 100644 --- a/vendor/github.com/coreos/etcd/mvcc/kvstore_bench_test.go +++ b/vendor/github.com/coreos/etcd/mvcc/kvstore_bench_test.go @@ -45,22 +45,34 @@ func BenchmarkStorePut(b *testing.B) { } } -func BenchmarkStoreRangeOneKey(b *testing.B) { +func BenchmarkStoreRangeKey1(b *testing.B) { benchmarkStoreRange(b, 1) } +func BenchmarkStoreRangeKey100(b *testing.B) { benchmarkStoreRange(b, 100) } + +func benchmarkStoreRange(b *testing.B, n int) { var i fakeConsistentIndex be, tmpPath := backend.NewDefaultTmpBackend() s := NewStore(be, &lease.FakeLessor{}, &i) defer cleanup(s, be, tmpPath) // 64 byte key/val - key, val := createBytesSlice(64, 1), createBytesSlice(64, 1) - s.Put(key[0], val[0], lease.NoLease) + keys, val := createBytesSlice(64, n), createBytesSlice(64, 1) + for i := range keys { + s.Put(keys[i], val[0], lease.NoLease) + } // Force into boltdb tx instead of backend read tx. s.Commit() + var begin, end []byte + if n == 1 { + begin, end = keys[0], nil + } else { + begin, end = []byte{}, []byte{} + } + b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - s.Range(key[0], nil, RangeOptions{}) + s.Range(begin, end, RangeOptions{}) } } diff --git a/vendor/github.com/coreos/etcd/mvcc/watchable_store.go b/vendor/github.com/coreos/etcd/mvcc/watchable_store.go index b9664bd81..2d8545942 100644 --- a/vendor/github.com/coreos/etcd/mvcc/watchable_store.go +++ b/vendor/github.com/coreos/etcd/mvcc/watchable_store.go @@ -144,7 +144,6 @@ func (s *watchableStore) watch(key, end []byte, startRev int64, id WatchID, ch c func (s *watchableStore) cancelWatcher(wa *watcher) { for { s.mu.Lock() - if s.unsynced.delete(wa) { slowWatcherGauge.Dec() break @@ -152,6 +151,9 @@ func (s *watchableStore) cancelWatcher(wa *watcher) { break } else if wa.compacted { break + } else if wa.ch == nil { + // already canceled (e.g., cancel/close race) + break } if !wa.victim { @@ -177,6 +179,7 @@ func (s *watchableStore) cancelWatcher(wa *watcher) { } watcherGauge.Dec() + wa.ch = nil s.mu.Unlock() } @@ -425,7 +428,6 @@ func (s *watchableStore) notify(rev int64, evs []mvccpb.Event) { if eb.revs != 1 { plog.Panicf("unexpected multiple revisions in notification") } - if w.send(WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}) { pendingEventsGauge.Add(float64(len(eb.evs))) } else { diff --git a/vendor/github.com/coreos/etcd/mvcc/watchable_store_test.go b/vendor/github.com/coreos/etcd/mvcc/watchable_store_test.go index 93c7cc954..52e1b90c0 100644 --- a/vendor/github.com/coreos/etcd/mvcc/watchable_store_test.go +++ b/vendor/github.com/coreos/etcd/mvcc/watchable_store_test.go @@ -539,3 +539,49 @@ func TestWatchVictims(t *testing.T) { default: } } + +// TestStressWatchCancelClose tests closing a watch stream while +// canceling its watches. +func TestStressWatchCancelClose(t *testing.T) { + b, tmpPath := backend.NewDefaultTmpBackend() + s := newWatchableStore(b, &lease.FakeLessor{}, nil) + + defer func() { + s.store.Close() + os.Remove(tmpPath) + }() + + testKey, testValue := []byte("foo"), []byte("bar") + var wg sync.WaitGroup + readyc := make(chan struct{}) + wg.Add(100) + for i := 0; i < 100; i++ { + go func() { + defer wg.Done() + w := s.NewWatchStream() + ids := make([]WatchID, 10) + for i := range ids { + ids[i] = w.Watch(testKey, nil, 0) + } + <-readyc + wg.Add(1 + len(ids)/2) + for i := range ids[:len(ids)/2] { + go func(n int) { + defer wg.Done() + w.Cancel(ids[n]) + }(i) + } + go func() { + defer wg.Done() + w.Close() + }() + }() + } + + close(readyc) + for i := 0; i < 100; i++ { + s.Put(testKey, testValue, lease.NoLease) + } + + wg.Wait() +} diff --git a/vendor/github.com/coreos/etcd/mvcc/watcher.go b/vendor/github.com/coreos/etcd/mvcc/watcher.go index 9468d4269..bc0c6322f 100644 --- a/vendor/github.com/coreos/etcd/mvcc/watcher.go +++ b/vendor/github.com/coreos/etcd/mvcc/watcher.go @@ -129,16 +129,25 @@ func (ws *watchStream) Chan() <-chan WatchResponse { func (ws *watchStream) Cancel(id WatchID) error { ws.mu.Lock() cancel, ok := ws.cancels[id] + w := ws.watchers[id] ok = ok && !ws.closed - if ok { - delete(ws.cancels, id) - delete(ws.watchers, id) - } ws.mu.Unlock() + if !ok { return ErrWatcherNotExist } cancel() + + ws.mu.Lock() + // The watch isn't removed until cancel so that if Close() is called, + // it will wait for the cancel. Otherwise, Close() could close the + // watch channel while the store is still posting events. + if ww := ws.watchers[id]; ww == w { + delete(ws.cancels, id) + delete(ws.watchers, id) + } + ws.mu.Unlock() + return nil } diff --git a/vendor/github.com/coreos/etcd/pkg/flags/strings.go b/vendor/github.com/coreos/etcd/pkg/flags/strings.go index 21ff916a6..40ee43253 100644 --- a/vendor/github.com/coreos/etcd/pkg/flags/strings.go +++ b/vendor/github.com/coreos/etcd/pkg/flags/strings.go @@ -18,8 +18,11 @@ import "errors" // NewStringsFlag creates a new string flag for which any one of the given // strings is a valid value, and any other value is an error. +// +// valids[0] will be default value. Caller must be sure len(valids)!=0 or +// it will panic. func NewStringsFlag(valids ...string) *StringsFlag { - return &StringsFlag{Values: valids} + return &StringsFlag{Values: valids, val: valids[0]} } // StringsFlag implements the flag.Value interface. diff --git a/vendor/github.com/coreos/etcd/pkg/flags/strings_test.go b/vendor/github.com/coreos/etcd/pkg/flags/strings_test.go index 351085a31..b699961e3 100644 --- a/vendor/github.com/coreos/etcd/pkg/flags/strings_test.go +++ b/vendor/github.com/coreos/etcd/pkg/flags/strings_test.go @@ -32,11 +32,14 @@ func TestStringsSet(t *testing.T) { // unrecognized values {[]string{"abc", "def"}, "ghi", false}, {[]string{"on", "off"}, "", false}, - {[]string{}, "asdf", false}, } for i, tt := range tests { sf := NewStringsFlag(tt.vals...) + if sf.val != tt.vals[0] { + t.Errorf("#%d: want default val=%v,but got %v", i, tt.vals[0], sf.val) + } + err := sf.Set(tt.val) if tt.pass != (err == nil) { t.Errorf("#%d: want pass=%t, but got err=%v", i, tt.pass, err) diff --git a/vendor/github.com/coreos/etcd/pkg/netutil/netutil_test.go b/vendor/github.com/coreos/etcd/pkg/netutil/netutil_test.go index 82abe6d12..e748a0a75 100644 --- a/vendor/github.com/coreos/etcd/pkg/netutil/netutil_test.go +++ b/vendor/github.com/coreos/etcd/pkg/netutil/netutil_test.go @@ -178,6 +178,21 @@ func TestURLsEqual(t *testing.T) { b: []url.URL{{Scheme: "http", Host: "10.0.10.1:2379"}}, expect: true, }, + { + a: []url.URL{{Scheme: "http", Host: "example.com:2379"}}, + b: []url.URL{{Scheme: "https", Host: "10.0.10.1:2379"}}, + expect: false, + }, + { + a: []url.URL{{Scheme: "https", Host: "example.com:2379"}}, + b: []url.URL{{Scheme: "http", Host: "10.0.10.1:2379"}}, + expect: false, + }, + { + a: []url.URL{{Scheme: "unix", Host: "abc:2379"}}, + b: []url.URL{{Scheme: "unix", Host: "abc:2379"}}, + expect: true, + }, { a: []url.URL{{Scheme: "http", Host: "127.0.0.1:2379"}, {Scheme: "http", Host: "127.0.0.1:2380"}}, b: []url.URL{{Scheme: "http", Host: "127.0.0.1:2379"}, {Scheme: "http", Host: "127.0.0.1:2380"}}, diff --git a/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil_test.go b/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil_test.go index fd361ec50..5a8dd9a17 100644 --- a/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil_test.go +++ b/vendor/github.com/coreos/etcd/pkg/pbutil/pbutil_test.go @@ -24,7 +24,7 @@ func TestMarshaler(t *testing.T) { data := []byte("test data") m := &fakeMarshaler{data: data} if g := MustMarshal(m); !reflect.DeepEqual(g, data) { - t.Errorf("data = %s, want %s", g, m) + t.Errorf("data = %s, want %s", g, m.data) } } @@ -43,7 +43,7 @@ func TestUnmarshaler(t *testing.T) { m := &fakeUnmarshaler{} MustUnmarshal(m, data) if !reflect.DeepEqual(m.data, data) { - t.Errorf("data = %s, want %s", m.data, m) + t.Errorf("data = %s, want %s", m.data, data) } } diff --git a/vendor/github.com/coreos/etcd/pkg/srv/srv.go b/vendor/github.com/coreos/etcd/pkg/srv/srv.go index fefcbcb4b..600061ce8 100644 --- a/vendor/github.com/coreos/etcd/pkg/srv/srv.go +++ b/vendor/github.com/coreos/etcd/pkg/srv/srv.go @@ -71,9 +71,10 @@ func GetCluster(service, name, dns string, apurls types.URLs) ([]string, error) // SRV records have a trailing dot but URL shouldn't. shortHost := strings.TrimSuffix(srv.Target, ".") urlHost := net.JoinHostPort(shortHost, port) - stringParts = append(stringParts, fmt.Sprintf("%s=%s://%s", n, scheme, urlHost)) if ok && url.Scheme != scheme { err = fmt.Errorf("bootstrap at %s from DNS for %s has scheme mismatch with expected peer %s", scheme+"://"+urlHost, service, url.String()) + } else { + stringParts = append(stringParts, fmt.Sprintf("%s=%s://%s", n, scheme, urlHost)) } } if len(stringParts) == 0 { diff --git a/vendor/github.com/coreos/etcd/pkg/srv/srv_test.go b/vendor/github.com/coreos/etcd/pkg/srv/srv_test.go index 0386c9d2a..17faa8548 100644 --- a/vendor/github.com/coreos/etcd/pkg/srv/srv_test.go +++ b/vendor/github.com/coreos/etcd/pkg/srv/srv_test.go @@ -86,7 +86,14 @@ func TestSRVGetCluster(t *testing.T) { "dnsClusterTest=https://1.example.com:2480,0=https://2.example.com:2480,1=https://3.example.com:2480", }, - // invalid + // reject if apurls are TLS but SRV is only http + { + nil, + srvAll, + []string{"https://10.0.0.1:2480"}, + + "0=http://2.example.com:2480,1=http://3.example.com:2480", + }, } resolveTCPAddr = func(network, addr string) (*net.TCPAddr, error) { diff --git a/vendor/github.com/coreos/etcd/pkg/testutil/assert.go b/vendor/github.com/coreos/etcd/pkg/testutil/assert.go index 8bd3922ee..9cf03457d 100644 --- a/vendor/github.com/coreos/etcd/pkg/testutil/assert.go +++ b/vendor/github.com/coreos/etcd/pkg/testutil/assert.go @@ -54,5 +54,9 @@ func AssertFalse(t *testing.T, v bool, msg ...string) { } func isNil(v interface{}) bool { - return v == nil || reflect.ValueOf(v).IsNil() + if v == nil { + return true + } + rv := reflect.ValueOf(v) + return rv.Kind() != reflect.Struct && rv.IsNil() } diff --git a/vendor/github.com/coreos/etcd/pkg/wait/wait.go b/vendor/github.com/coreos/etcd/pkg/wait/wait.go index 34fa237e8..9b1df419e 100644 --- a/vendor/github.com/coreos/etcd/pkg/wait/wait.go +++ b/vendor/github.com/coreos/etcd/pkg/wait/wait.go @@ -34,7 +34,7 @@ type Wait interface { } type list struct { - l sync.Mutex + l sync.RWMutex m map[uint64]chan interface{} } @@ -68,8 +68,8 @@ func (w *list) Trigger(id uint64, x interface{}) { } func (w *list) IsRegistered(id uint64) bool { - w.l.Lock() - defer w.l.Unlock() + w.l.RLock() + defer w.l.RUnlock() _, ok := w.m[id] return ok } diff --git a/vendor/github.com/coreos/etcd/raft/README.md b/vendor/github.com/coreos/etcd/raft/README.md index f485b8397..4702fd80c 100644 --- a/vendor/github.com/coreos/etcd/raft/README.md +++ b/vendor/github.com/coreos/etcd/raft/README.md @@ -112,7 +112,7 @@ After creating a Node, the user has a few responsibilities: First, read from the Node.Ready() channel and process the updates it contains. These steps may be performed in parallel, except as noted in step 2. -1. Write HardState, Entries, and Snapshot to persistent storage if they are not empty. Note that when writing an Entry with Index i, any previously-persisted entries with Index >= i must be discarded. +1. Write Entries, HardState and Snapshot to persistent storage in order, i.e. Entries first, then HardState and Snapshot if they are not empty. If persistent storage supports atomic writes then all of them can be written together. Note that when writing an Entry with Index i, any previously-persisted entries with Index >= i must be discarded. 2. Send all Messages to the nodes named in the To field. It is important that no messages be sent until the latest HardState has been persisted to disk, and all Entries written by any previous Ready batch (Messages may be sent while entries from the same batch are being persisted). To reduce the I/O latency, an optimization can be applied to make leader write to disk in parallel with its followers (as explained at section 10.2.1 in Raft thesis). If any Message has type MsgSnap, call Node.ReportSnapshot() after it has been sent (these messages may be large). Note: Marshalling messages is not thread-safe; it is important to make sure that no new entries are persisted while marshalling. The easiest way to achieve this is to serialise the messages directly inside the main raft loop. diff --git a/vendor/github.com/coreos/etcd/store/metrics.go b/vendor/github.com/coreos/etcd/store/metrics.go index 26404ba72..08cd4f030 100644 --- a/vendor/github.com/coreos/etcd/store/metrics.go +++ b/vendor/github.com/coreos/etcd/store/metrics.go @@ -86,7 +86,11 @@ const ( ) func init() { - prometheus.MustRegister(readCounter) + if prometheus.Register(readCounter) != nil { + // Tests will try to double register sicne the tests use both + // store and store_test packages; ignore second attempts. + return + } prometheus.MustRegister(writeCounter) prometheus.MustRegister(expireCounter) prometheus.MustRegister(watchRequests) diff --git a/vendor/github.com/coreos/etcd/store/store_test.go b/vendor/github.com/coreos/etcd/store/store_test.go index 49f6fc620..44f72efe4 100644 --- a/vendor/github.com/coreos/etcd/store/store_test.go +++ b/vendor/github.com/coreos/etcd/store/store_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package store +package store_test import ( "testing" @@ -20,11 +20,17 @@ import ( etcdErr "github.com/coreos/etcd/error" "github.com/coreos/etcd/pkg/testutil" - "github.com/jonboulle/clockwork" + "github.com/coreos/etcd/store" ) +type StoreCloser interface { + store.Store + Close() +} + func TestNewStoreWithNamespaces(t *testing.T) { - s := newStore("/0", "/1") + s := newTestStore(t, "/0", "/1") + defer s.Close() _, err := s.Get("/0", false, false) testutil.AssertNil(t, err) @@ -34,8 +40,10 @@ func TestNewStoreWithNamespaces(t *testing.T) { // Ensure that the store can retrieve an existing value. func TestStoreGetValue(t *testing.T) { - s := newStore() - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) var eidx uint64 = 1 e, err := s.Get("/foo", false, false) testutil.AssertNil(t, err) @@ -45,90 +53,23 @@ func TestStoreGetValue(t *testing.T) { testutil.AssertEqual(t, *e.Node.Value, "bar") } -// Ensure that any TTL <= minExpireTime becomes Permanent -func TestMinExpireTime(t *testing.T) { - s := newStore() - fc := clockwork.NewFakeClock() - s.clock = fc - // FakeClock starts at 0, so minExpireTime should be far in the future.. but just in case - testutil.AssertTrue(t, minExpireTime.After(fc.Now()), "minExpireTime should be ahead of FakeClock!") - s.Create("/foo", false, "Y", false, TTLOptionSet{ExpireTime: fc.Now().Add(3 * time.Second)}) - fc.Advance(5 * time.Second) - // Ensure it hasn't expired - s.DeleteExpiredKeys(fc.Now()) - var eidx uint64 = 1 - e, err := s.Get("/foo", true, false) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "get") - testutil.AssertEqual(t, e.Node.Key, "/foo") - testutil.AssertEqual(t, e.Node.TTL, int64(0)) -} - -// Ensure that the store can recursively retrieve a directory listing. -// Note that hidden files should not be returned. -func TestStoreGetDirectory(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/bar", false, "X", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/_hidden", false, "*", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/baz", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/baz/bat", false, "Y", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/baz/_hidden", false, "*", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/baz/ttl", false, "Y", false, TTLOptionSet{ExpireTime: fc.Now().Add(time.Second * 3)}) - var eidx uint64 = 7 - e, err := s.Get("/foo", true, false) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "get") - testutil.AssertEqual(t, e.Node.Key, "/foo") - testutil.AssertEqual(t, len(e.Node.Nodes), 2) - var bazNodes NodeExterns - for _, node := range e.Node.Nodes { - switch node.Key { - case "/foo/bar": - testutil.AssertEqual(t, *node.Value, "X") - testutil.AssertEqual(t, node.Dir, false) - case "/foo/baz": - testutil.AssertEqual(t, node.Dir, true) - testutil.AssertEqual(t, len(node.Nodes), 2) - bazNodes = node.Nodes - default: - t.Errorf("key = %s, not matched", node.Key) - } - } - for _, node := range bazNodes { - switch node.Key { - case "/foo/baz/bat": - testutil.AssertEqual(t, *node.Value, "Y") - testutil.AssertEqual(t, node.Dir, false) - case "/foo/baz/ttl": - testutil.AssertEqual(t, *node.Value, "Y") - testutil.AssertEqual(t, node.Dir, false) - testutil.AssertEqual(t, node.TTL, int64(3)) - default: - t.Errorf("key = %s, not matched", node.Key) - } - } -} - // Ensure that the store can retrieve a directory in sorted order. func TestStoreGetSorted(t *testing.T) { - s := newStore() - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/x", false, "0", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/z", false, "0", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/y", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/y/a", false, "0", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/y/b", false, "0", false, TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/x", false, "0", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/z", false, "0", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/y", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/y/a", false, "0", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/y/b", false, "0", false, store.TTLOptionSet{ExpireTime: store.Permanent}) var eidx uint64 = 6 e, err := s.Get("/foo", true, true) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) - var yNodes NodeExterns + var yNodes store.NodeExterns sortedStrings := []string{"/foo/x", "/foo/y", "/foo/z"} for i := range e.Node.Nodes { node := e.Node.Nodes[i] @@ -150,11 +91,12 @@ func TestStoreGetSorted(t *testing.T) { } func TestSet(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() // Set /foo="" var eidx uint64 = 1 - e, err := s.Set("/foo", false, "", TTLOptionSet{ExpireTime: Permanent}) + e, err := s.Set("/foo", false, "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "set") @@ -168,7 +110,7 @@ func TestSet(t *testing.T) { // Set /foo="bar" eidx = 2 - e, err = s.Set("/foo", false, "bar", TTLOptionSet{ExpireTime: Permanent}) + e, err = s.Set("/foo", false, "bar", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "set") @@ -186,7 +128,7 @@ func TestSet(t *testing.T) { testutil.AssertEqual(t, e.PrevNode.ModifiedIndex, uint64(1)) // Set /foo="baz" (for testing prevNode) eidx = 3 - e, err = s.Set("/foo", false, "baz", TTLOptionSet{ExpireTime: Permanent}) + e, err = s.Set("/foo", false, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "set") @@ -205,7 +147,7 @@ func TestSet(t *testing.T) { // Set /dir as a directory eidx = 4 - e, err = s.Set("/dir", true, "", TTLOptionSet{ExpireTime: Permanent}) + e, err = s.Set("/dir", true, "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "set") @@ -220,10 +162,12 @@ func TestSet(t *testing.T) { // Ensure that the store can create a new key if it doesn't already exist. func TestStoreCreateValue(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + // Create /foo=bar var eidx uint64 = 1 - e, err := s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + e, err := s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") @@ -237,7 +181,7 @@ func TestStoreCreateValue(t *testing.T) { // Create /empty="" eidx = 2 - e, err = s.Create("/empty", false, "", false, TTLOptionSet{ExpireTime: Permanent}) + e, err = s.Create("/empty", false, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") @@ -253,9 +197,11 @@ func TestStoreCreateValue(t *testing.T) { // Ensure that the store can create a new directory if it doesn't already exist. func TestStoreCreateDirectory(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 1 - e, err := s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + e, err := s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") @@ -265,12 +211,14 @@ func TestStoreCreateDirectory(t *testing.T) { // Ensure that the store fails to create a key if it already exists. func TestStoreCreateFailsIfExists(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + // create /foo as dir - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) // create /foo as dir again - e, _err := s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + e, _err := s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeNodeExist) testutil.AssertEqual(t, err.Message, "Key already exists") @@ -281,12 +229,14 @@ func TestStoreCreateFailsIfExists(t *testing.T) { // Ensure that the store can update a key if it already exists. func TestStoreUpdateValue(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + // create /foo=bar - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) // update /foo="bzr" var eidx uint64 = 2 - e, err := s.Update("/foo", "baz", TTLOptionSet{ExpireTime: Permanent}) + e, err := s.Update("/foo", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "update") @@ -307,7 +257,7 @@ func TestStoreUpdateValue(t *testing.T) { // update /foo="" eidx = 3 - e, err = s.Update("/foo", "", TTLOptionSet{ExpireTime: Permanent}) + e, err = s.Update("/foo", "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "update") @@ -329,9 +279,11 @@ func TestStoreUpdateValue(t *testing.T) { // Ensure that the store cannot update a directory. func TestStoreUpdateFailsIfDirectory(t *testing.T) { - s := newStore() - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - e, _err := s.Update("/foo", "baz", TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e, _err := s.Update("/foo", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeNotFile) testutil.AssertEqual(t, err.Message, "Not a file") @@ -339,55 +291,13 @@ func TestStoreUpdateFailsIfDirectory(t *testing.T) { testutil.AssertNil(t, e) } -// Ensure that the store can update the TTL on a value. -func TestStoreUpdateValueTTL(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - _, err := s.Update("/foo", "baz", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - testutil.AssertNil(t, err) - e, _ := s.Get("/foo", false, false) - testutil.AssertEqual(t, *e.Node.Value, "baz") - testutil.AssertEqual(t, e.EtcdIndex, eidx) - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - e, err = s.Get("/foo", false, false) - testutil.AssertNil(t, e) - testutil.AssertEqual(t, err.(*etcdErr.Error).ErrorCode, etcdErr.EcodeKeyNotFound) -} - -// Ensure that the store can update the TTL on a directory. -func TestStoreUpdateDirTTL(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 3 - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) - e, err := s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, e.Node.Dir, true) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - e, _ = s.Get("/foo/bar", false, false) - testutil.AssertEqual(t, *e.Node.Value, "baz") - testutil.AssertEqual(t, e.EtcdIndex, eidx) - - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - e, err = s.Get("/foo/bar", false, false) - testutil.AssertNil(t, e) - testutil.AssertEqual(t, err.(*etcdErr.Error).ErrorCode, etcdErr.EcodeKeyNotFound) -} - // Ensure that the store can delete a value. func TestStoreDeleteValue(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, err := s.Delete("/foo", false, false) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) @@ -399,11 +309,13 @@ func TestStoreDeleteValue(t *testing.T) { } // Ensure that the store can delete a directory if recursive is specified. -func TestStoreDeleteDiretory(t *testing.T) { - s := newStore() +func TestStoreDeleteDirectory(t *testing.T) { + s := newTestStore(t) + defer s.Close() + // create directory /foo var eidx uint64 = 2 - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) // delete /foo with dir = true and recursive = false // this should succeed, since the directory is empty e, err := s.Delete("/foo", true, false) @@ -416,7 +328,8 @@ func TestStoreDeleteDiretory(t *testing.T) { testutil.AssertEqual(t, e.PrevNode.Dir, true) // create directory /foo and directory /foo/bar - s.Create("/foo/bar", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + _, err = s.Create("/foo/bar", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + testutil.AssertNil(t, err) // delete /foo with dir = true and recursive = false // this should fail, since the directory is not empty _, err = s.Delete("/foo", true, false) @@ -434,9 +347,11 @@ func TestStoreDeleteDiretory(t *testing.T) { // Ensure that the store cannot delete a directory if both of recursive // and dir are not specified. -func TestStoreDeleteDiretoryFailsIfNonRecursiveAndDir(t *testing.T) { - s := newStore() - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) +func TestStoreDeleteDirectoryFailsIfNonRecursiveAndDir(t *testing.T) { + s := newTestStore(t) + defer s.Close() + + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, _err := s.Delete("/foo", false, false) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeNotFile) @@ -445,30 +360,33 @@ func TestStoreDeleteDiretoryFailsIfNonRecursiveAndDir(t *testing.T) { } func TestRootRdOnly(t *testing.T) { - s := newStore("/0") + s := newTestStore(t, "/0") + defer s.Close() for _, tt := range []string{"/", "/0"} { - _, err := s.Set(tt, true, "", TTLOptionSet{ExpireTime: Permanent}) + _, err := s.Set(tt, true, "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNotNil(t, err) _, err = s.Delete(tt, true, true) testutil.AssertNotNil(t, err) - _, err = s.Create(tt, true, "", false, TTLOptionSet{ExpireTime: Permanent}) + _, err = s.Create(tt, true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNotNil(t, err) - _, err = s.Update(tt, "", TTLOptionSet{ExpireTime: Permanent}) + _, err = s.Update(tt, "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNotNil(t, err) - _, err = s.CompareAndSwap(tt, "", 0, "", TTLOptionSet{ExpireTime: Permanent}) + _, err = s.CompareAndSwap(tt, "", 0, "", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNotNil(t, err) } } func TestStoreCompareAndDeletePrevValue(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, err := s.CompareAndDelete("/foo", "bar", 0) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) @@ -484,9 +402,11 @@ func TestStoreCompareAndDeletePrevValue(t *testing.T) { } func TestStoreCompareAndDeletePrevValueFailsIfNotMatch(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, _err := s.CompareAndDelete("/foo", "baz", 0) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeTestFailed) @@ -498,9 +418,11 @@ func TestStoreCompareAndDeletePrevValueFailsIfNotMatch(t *testing.T) { } func TestStoreCompareAndDeletePrevIndex(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, err := s.CompareAndDelete("/foo", "", 1) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) @@ -514,9 +436,11 @@ func TestStoreCompareAndDeletePrevIndex(t *testing.T) { } func TestStoreCompareAndDeletePrevIndexFailsIfNotMatch(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e, _err := s.CompareAndDelete("/foo", "", 100) testutil.AssertNotNil(t, _err) err := _err.(*etcdErr.Error) @@ -529,9 +453,11 @@ func TestStoreCompareAndDeletePrevIndexFailsIfNotMatch(t *testing.T) { } // Ensure that the store cannot delete a directory. -func TestStoreCompareAndDeleteDiretoryFail(t *testing.T) { - s := newStore() - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) +func TestStoreCompareAndDeleteDirectoryFail(t *testing.T) { + s := newTestStore(t) + defer s.Close() + + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) _, _err := s.CompareAndDelete("/foo", "", 0) testutil.AssertNotNil(t, _err) err := _err.(*etcdErr.Error) @@ -540,10 +466,12 @@ func TestStoreCompareAndDeleteDiretoryFail(t *testing.T) { // Ensure that the store can conditionally update a key if it has a previous value. func TestStoreCompareAndSwapPrevValue(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e, err := s.CompareAndSwap("/foo", "bar", 0, "baz", TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e, err := s.CompareAndSwap("/foo", "bar", 0, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "compareAndSwap") @@ -561,10 +489,11 @@ func TestStoreCompareAndSwapPrevValue(t *testing.T) { // Ensure that the store cannot conditionally update a key if it has the wrong previous value. func TestStoreCompareAndSwapPrevValueFailsIfNotMatch(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e, _err := s.CompareAndSwap("/foo", "wrong_value", 0, "baz", TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e, _err := s.CompareAndSwap("/foo", "wrong_value", 0, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeTestFailed) testutil.AssertEqual(t, err.Message, "Compare failed") @@ -576,10 +505,11 @@ func TestStoreCompareAndSwapPrevValueFailsIfNotMatch(t *testing.T) { // Ensure that the store can conditionally update a key if it has a previous index. func TestStoreCompareAndSwapPrevIndex(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e, err := s.CompareAndSwap("/foo", "", 1, "baz", TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e, err := s.CompareAndSwap("/foo", "", 1, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) testutil.AssertNil(t, err) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "compareAndSwap") @@ -598,10 +528,11 @@ func TestStoreCompareAndSwapPrevIndex(t *testing.T) { // Ensure that the store cannot conditionally update a key if it has the wrong previous index. func TestStoreCompareAndSwapPrevIndexFailsIfNotMatch(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e, _err := s.CompareAndSwap("/foo", "", 100, "baz", TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e, _err := s.CompareAndSwap("/foo", "", 100, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) err := _err.(*etcdErr.Error) testutil.AssertEqual(t, err.ErrorCode, etcdErr.EcodeTestFailed) testutil.AssertEqual(t, err.Message, "Compare failed") @@ -613,30 +544,36 @@ func TestStoreCompareAndSwapPrevIndexFailsIfNotMatch(t *testing.T) { // Ensure that the store can watch for key creation. func TestStoreWatchCreate(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 0 w, _ := s.Watch("/foo", false, false, 0) c := w.EventChan() testutil.AssertEqual(t, w.StartIndex(), eidx) - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) eidx = 1 - e := nbselect(c) + e := timeoutSelect(t, c) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") testutil.AssertEqual(t, e.Node.Key, "/foo") - e = nbselect(c) - testutil.AssertNil(t, e) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } } // Ensure that the store can watch for recursive key creation. func TestStoreWatchRecursiveCreate(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 0 - w, _ := s.Watch("/foo", true, false, 0) + w, err := s.Watch("/foo", true, false, 0) + testutil.AssertNil(t, err) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 1 - s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Create("/foo/bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") testutil.AssertEqual(t, e.Node.Key, "/foo/bar") @@ -644,14 +581,15 @@ func TestStoreWatchRecursiveCreate(t *testing.T) { // Ensure that the store can watch for key updates. func TestStoreWatchUpdate(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", false, false, 0) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 - s.Update("/foo", "baz", TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Update("/foo", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "update") testutil.AssertEqual(t, e.Node.Key, "/foo") @@ -659,14 +597,16 @@ func TestStoreWatchUpdate(t *testing.T) { // Ensure that the store can watch for recursive key updates. func TestStoreWatchRecursiveUpdate(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) - w, _ := s.Watch("/foo", true, false, 0) + s.Create("/foo/bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + w, err := s.Watch("/foo", true, false, 0) + testutil.AssertNil(t, err) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 - s.Update("/foo/bar", "baz", TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Update("/foo/bar", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "update") testutil.AssertEqual(t, e.Node.Key, "/foo/bar") @@ -674,14 +614,15 @@ func TestStoreWatchRecursiveUpdate(t *testing.T) { // Ensure that the store can watch for key deletions. func TestStoreWatchDelete(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", false, false, 0) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 s.Delete("/foo", false, false) - e := nbselect(w.EventChan()) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "delete") testutil.AssertEqual(t, e.Node.Key, "/foo") @@ -689,14 +630,16 @@ func TestStoreWatchDelete(t *testing.T) { // Ensure that the store can watch for recursive key deletions. func TestStoreWatchRecursiveDelete(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) - w, _ := s.Watch("/foo", true, false, 0) + s.Create("/foo/bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + w, err := s.Watch("/foo", true, false, 0) + testutil.AssertNil(t, err) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 s.Delete("/foo/bar", false, false) - e := nbselect(w.EventChan()) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "delete") testutil.AssertEqual(t, e.Node.Key, "/foo/bar") @@ -704,14 +647,15 @@ func TestStoreWatchRecursiveDelete(t *testing.T) { // Ensure that the store can watch for CAS updates. func TestStoreWatchCompareAndSwap(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", false, false, 0) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 - s.CompareAndSwap("/foo", "bar", 0, "baz", TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.CompareAndSwap("/foo", "bar", 0, "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "compareAndSwap") testutil.AssertEqual(t, e.Node.Key, "/foo") @@ -719,289 +663,102 @@ func TestStoreWatchCompareAndSwap(t *testing.T) { // Ensure that the store can watch for recursive CAS updates. func TestStoreWatchRecursiveCompareAndSwap(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 - s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", true, false, 0) testutil.AssertEqual(t, w.StartIndex(), eidx) eidx = 2 - s.CompareAndSwap("/foo/bar", "baz", 0, "bat", TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.CompareAndSwap("/foo/bar", "baz", 0, "bat", store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "compareAndSwap") testutil.AssertEqual(t, e.Node.Key, "/foo/bar") } -// Ensure that the store can watch for key expiration. -func TestStoreWatchExpire(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 3 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(400 * time.Millisecond)}) - s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(450 * time.Millisecond)}) - s.Create("/foodir", true, "", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - - w, _ := s.Watch("/", true, false, 0) - testutil.AssertEqual(t, w.StartIndex(), eidx) - c := w.EventChan() - e := nbselect(c) - testutil.AssertNil(t, e) - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - eidx = 4 - e = nbselect(c) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foo") - w, _ = s.Watch("/", true, false, 5) - eidx = 6 - testutil.AssertEqual(t, w.StartIndex(), eidx) - e = nbselect(w.EventChan()) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foofoo") - w, _ = s.Watch("/", true, false, 6) - e = nbselect(w.EventChan()) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foodir") - testutil.AssertEqual(t, e.Node.Dir, true) -} - -// Ensure that the store can watch for key expiration when refreshing. -func TestStoreWatchExpireRefresh(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 2 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(1200 * time.Millisecond), Refresh: true}) - - // Make sure we set watch updates when Refresh is true for newly created keys - w, _ := s.Watch("/", true, false, 0) - testutil.AssertEqual(t, w.StartIndex(), eidx) - c := w.EventChan() - e := nbselect(c) - testutil.AssertNil(t, e) - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - eidx = 3 - e = nbselect(c) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foo") - - s.Update("/foofoo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - w, _ = s.Watch("/", true, false, 4) - fc.Advance(700 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - eidx = 5 // We should skip 4 because a TTL update should occur with no watch notification if set `TTLOptionSet.Refresh` to true - testutil.AssertEqual(t, w.StartIndex(), eidx-1) - e = nbselect(w.EventChan()) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foofoo") -} - -// Ensure that the store can watch for key expiration when refreshing with an empty value. -func TestStoreWatchExpireEmptyRefresh(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - // Should be no-op - fc.Advance(200 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - - s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - w, _ := s.Watch("/", true, false, 2) - fc.Advance(700 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - eidx = 3 // We should skip 2 because a TTL update should occur with no watch notification if set `TTLOptionSet.Refresh` to true - testutil.AssertEqual(t, w.StartIndex(), eidx-1) - e := nbselect(w.EventChan()) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foo") - testutil.AssertEqual(t, *e.PrevNode.Value, "bar") -} - -// Update TTL of a key (set TTLOptionSet.Refresh to false) and send notification -func TestStoreWatchNoRefresh(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - var eidx uint64 = 1 - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - // Should be no-op - fc.Advance(200 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - - // Update key's TTL with setting `TTLOptionSet.Refresh` to false will cause an update event - s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: false}) - w, _ := s.Watch("/", true, false, 2) - fc.Advance(700 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - eidx = 2 - testutil.AssertEqual(t, w.StartIndex(), eidx) - e := nbselect(w.EventChan()) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, e.Action, "update") - testutil.AssertEqual(t, e.Node.Key, "/foo") - testutil.AssertEqual(t, *e.PrevNode.Value, "bar") -} - -// Ensure that the store can update the TTL on a value with refresh. -func TestStoreRefresh(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - s.Create("/bar", true, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - _, err := s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - testutil.AssertNil(t, err) - - _, err = s.Set("/foo", false, "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - testutil.AssertNil(t, err) - - _, err = s.Update("/bar", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - testutil.AssertNil(t, err) - - _, err = s.CompareAndSwap("/foo", "bar", 0, "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) - testutil.AssertNil(t, err) -} - // Ensure that the store can watch in streaming mode. func TestStoreWatchStream(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 w, _ := s.Watch("/foo", false, true, 0) // first modification - s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Create("/foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") testutil.AssertEqual(t, e.Node.Key, "/foo") testutil.AssertEqual(t, *e.Node.Value, "bar") - e = nbselect(w.EventChan()) - testutil.AssertNil(t, e) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } // second modification eidx = 2 - s.Update("/foo", "baz", TTLOptionSet{ExpireTime: Permanent}) - e = nbselect(w.EventChan()) + s.Update("/foo", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) + e = timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "update") testutil.AssertEqual(t, e.Node.Key, "/foo") testutil.AssertEqual(t, *e.Node.Value, "baz") - e = nbselect(w.EventChan()) - testutil.AssertNil(t, e) -} - -// Ensure that the store can recover from a previously saved state. -func TestStoreRecover(t *testing.T) { - s := newStore() - var eidx uint64 = 4 - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/x", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - s.Update("/foo/x", "barbar", TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/y", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) - b, err := s.Save() - testutil.AssertNil(t, err) - - s2 := newStore() - s2.Recovery(b) - - e, err := s.Get("/foo/x", false, false) - testutil.AssertEqual(t, e.Node.CreatedIndex, uint64(2)) - testutil.AssertEqual(t, e.Node.ModifiedIndex, uint64(3)) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, *e.Node.Value, "barbar") - - e, err = s.Get("/foo/y", false, false) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, *e.Node.Value, "baz") -} - -// Ensure that the store can recover from a previously saved state that includes an expiring key. -func TestStoreRecoverWithExpiration(t *testing.T) { - s := newStore() - s.clock = newFakeClock() - - fc := newFakeClock() - - var eidx uint64 = 4 - s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/x", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - s.Create("/foo/y", false, "baz", false, TTLOptionSet{ExpireTime: fc.Now().Add(5 * time.Millisecond)}) - b, err := s.Save() - testutil.AssertNil(t, err) - - time.Sleep(10 * time.Millisecond) - - s2 := newStore() - s2.clock = fc - - s2.Recovery(b) - - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - - e, err := s.Get("/foo/x", false, false) - testutil.AssertNil(t, err) - testutil.AssertEqual(t, e.EtcdIndex, eidx) - testutil.AssertEqual(t, *e.Node.Value, "bar") - - e, err = s.Get("/foo/y", false, false) - testutil.AssertNotNil(t, err) - testutil.AssertNil(t, e) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } } // Ensure that the store can watch for hidden keys as long as it's an exact path match. func TestStoreWatchCreateWithHiddenKey(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 w, _ := s.Watch("/_foo", false, false, 0) - s.Create("/_foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Create("/_foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") testutil.AssertEqual(t, e.Node.Key, "/_foo") - e = nbselect(w.EventChan()) - testutil.AssertNil(t, e) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } } // Ensure that the store doesn't see hidden key creates without an exact path match in recursive mode. func TestStoreWatchRecursiveCreateWithHiddenKey(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() w, _ := s.Watch("/foo", true, false, 0) - s.Create("/foo/_bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/_bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) e := nbselect(w.EventChan()) testutil.AssertNil(t, e) w, _ = s.Watch("/foo", true, false, 0) - s.Create("/foo/_baz", true, "", false, TTLOptionSet{ExpireTime: Permanent}) - e = nbselect(w.EventChan()) - testutil.AssertNil(t, e) - s.Create("/foo/_baz/quux", false, "quux", false, TTLOptionSet{ExpireTime: Permanent}) - e = nbselect(w.EventChan()) - testutil.AssertNil(t, e) + s.Create("/foo/_baz", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } + s.Create("/foo/_baz/quux", false, "quux", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + select { + case e = <-w.EventChan(): + testutil.AssertNil(t, e) + case <-time.After(100 * time.Millisecond): + } } // Ensure that the store doesn't see hidden key updates. func TestStoreWatchUpdateWithHiddenKey(t *testing.T) { - s := newStore() - s.Create("/_foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + s.Create("/_foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/_foo", false, false, 0) - s.Update("/_foo", "baz", TTLOptionSet{ExpireTime: Permanent}) - e := nbselect(w.EventChan()) + s.Update("/_foo", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.Action, "update") testutil.AssertEqual(t, e.Node.Key, "/_foo") e = nbselect(w.EventChan()) @@ -1010,22 +767,24 @@ func TestStoreWatchUpdateWithHiddenKey(t *testing.T) { // Ensure that the store doesn't see hidden key updates without an exact path match in recursive mode. func TestStoreWatchRecursiveUpdateWithHiddenKey(t *testing.T) { - s := newStore() - s.Create("/foo/_bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + s.Create("/foo/_bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", true, false, 0) - s.Update("/foo/_bar", "baz", TTLOptionSet{ExpireTime: Permanent}) + s.Update("/foo/_bar", "baz", store.TTLOptionSet{ExpireTime: store.Permanent}) e := nbselect(w.EventChan()) testutil.AssertNil(t, e) } // Ensure that the store can watch for key deletions. func TestStoreWatchDeleteWithHiddenKey(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 2 - s.Create("/_foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/_foo", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/_foo", false, false, 0) s.Delete("/_foo", false, false) - e := nbselect(w.EventChan()) + e := timeoutSelect(t, w.EventChan()) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "delete") testutil.AssertEqual(t, e.Node.Key, "/_foo") @@ -1035,46 +794,24 @@ func TestStoreWatchDeleteWithHiddenKey(t *testing.T) { // Ensure that the store doesn't see hidden key deletes without an exact path match in recursive mode. func TestStoreWatchRecursiveDeleteWithHiddenKey(t *testing.T) { - s := newStore() - s.Create("/foo/_bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + s := newTestStore(t) + defer s.Close() + s.Create("/foo/_bar", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) w, _ := s.Watch("/foo", true, false, 0) s.Delete("/foo/_bar", false, false) e := nbselect(w.EventChan()) testutil.AssertNil(t, e) } -// Ensure that the store doesn't see expirations of hidden keys. -func TestStoreWatchExpireWithHiddenKey(t *testing.T) { - s := newStore() - fc := newFakeClock() - s.clock = fc - - s.Create("/_foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) - s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(1000 * time.Millisecond)}) - - w, _ := s.Watch("/", true, false, 0) - c := w.EventChan() - e := nbselect(c) - testutil.AssertNil(t, e) - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - e = nbselect(c) - testutil.AssertNil(t, e) - fc.Advance(600 * time.Millisecond) - s.DeleteExpiredKeys(fc.Now()) - e = nbselect(c) - testutil.AssertEqual(t, e.Action, "expire") - testutil.AssertEqual(t, e.Node.Key, "/foofoo") -} - // Ensure that the store does see hidden key creates if watching deeper than a hidden key in recursive mode. func TestStoreWatchRecursiveCreateDeeperThanHiddenKey(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() var eidx uint64 = 1 w, _ := s.Watch("/_foo/bar", true, false, 0) - s.Create("/_foo/bar/baz", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/_foo/bar/baz", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) - e := nbselect(w.EventChan()) + e := timeoutSelect(t, w.EventChan()) testutil.AssertNotNil(t, e) testutil.AssertEqual(t, e.EtcdIndex, eidx) testutil.AssertEqual(t, e.Action, "create") @@ -1089,21 +826,22 @@ func TestStoreWatchRecursiveCreateDeeperThanHiddenKey(t *testing.T) { // This test ensures that after closing the channel, the store can continue // to operate correctly. func TestStoreWatchSlowConsumer(t *testing.T) { - s := newStore() + s := newTestStore(t) + defer s.Close() s.Watch("/foo", true, true, 0) // stream must be true // Fill watch channel with 100 events for i := 1; i <= 100; i++ { - s.Set("/foo", false, string(i), TTLOptionSet{ExpireTime: Permanent}) // ok + s.Set("/foo", false, string(i), store.TTLOptionSet{ExpireTime: store.Permanent}) // ok } - testutil.AssertEqual(t, s.WatcherHub.count, int64(1)) - s.Set("/foo", false, "101", TTLOptionSet{ExpireTime: Permanent}) // ok + // testutil.AssertEqual(t, s.WatcherHub.count, int64(1)) + s.Set("/foo", false, "101", store.TTLOptionSet{ExpireTime: store.Permanent}) // ok // remove watcher - testutil.AssertEqual(t, s.WatcherHub.count, int64(0)) - s.Set("/foo", false, "102", TTLOptionSet{ExpireTime: Permanent}) // must not panic + // testutil.AssertEqual(t, s.WatcherHub.count, int64(0)) + s.Set("/foo", false, "102", store.TTLOptionSet{ExpireTime: store.Permanent}) // must not panic } // Performs a non-blocking select on an event channel. -func nbselect(c <-chan *Event) *Event { +func nbselect(c <-chan *store.Event) *store.Event { select { case e := <-c: return e @@ -1112,11 +850,13 @@ func nbselect(c <-chan *Event) *Event { } } -// newFakeClock creates a new FakeClock that has been advanced to at least minExpireTime -func newFakeClock() clockwork.FakeClock { - fc := clockwork.NewFakeClock() - for minExpireTime.After(fc.Now()) { - fc.Advance((0x1 << 62) * time.Nanosecond) +// Performs a non-blocking select on an event channel. +func timeoutSelect(t *testing.T, c <-chan *store.Event) *store.Event { + select { + case e := <-c: + return e + case <-time.After(time.Second): + t.Errorf("timed out waiting on event") + return nil } - return fc } diff --git a/vendor/github.com/coreos/etcd/store/store_ttl_test.go b/vendor/github.com/coreos/etcd/store/store_ttl_test.go new file mode 100644 index 000000000..62c6a95ee --- /dev/null +++ b/vendor/github.com/coreos/etcd/store/store_ttl_test.go @@ -0,0 +1,360 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package store + +import ( + "testing" + "time" + + etcdErr "github.com/coreos/etcd/error" + "github.com/coreos/etcd/pkg/testutil" + "github.com/jonboulle/clockwork" +) + +// Ensure that any TTL <= minExpireTime becomes Permanent +func TestMinExpireTime(t *testing.T) { + s := newStore() + fc := clockwork.NewFakeClock() + s.clock = fc + // FakeClock starts at 0, so minExpireTime should be far in the future.. but just in case + testutil.AssertTrue(t, minExpireTime.After(fc.Now()), "minExpireTime should be ahead of FakeClock!") + s.Create("/foo", false, "Y", false, TTLOptionSet{ExpireTime: fc.Now().Add(3 * time.Second)}) + fc.Advance(5 * time.Second) + // Ensure it hasn't expired + s.DeleteExpiredKeys(fc.Now()) + var eidx uint64 = 1 + e, err := s.Get("/foo", true, false) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "get") + testutil.AssertEqual(t, e.Node.Key, "/foo") + testutil.AssertEqual(t, e.Node.TTL, int64(0)) +} + +// Ensure that the store can recursively retrieve a directory listing. +// Note that hidden files should not be returned. +func TestStoreGetDirectory(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/bar", false, "X", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/_hidden", false, "*", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/baz", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/baz/bat", false, "Y", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/baz/_hidden", false, "*", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/baz/ttl", false, "Y", false, TTLOptionSet{ExpireTime: fc.Now().Add(time.Second * 3)}) + var eidx uint64 = 7 + e, err := s.Get("/foo", true, false) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "get") + testutil.AssertEqual(t, e.Node.Key, "/foo") + testutil.AssertEqual(t, len(e.Node.Nodes), 2) + var bazNodes NodeExterns + for _, node := range e.Node.Nodes { + switch node.Key { + case "/foo/bar": + testutil.AssertEqual(t, *node.Value, "X") + testutil.AssertEqual(t, node.Dir, false) + case "/foo/baz": + testutil.AssertEqual(t, node.Dir, true) + testutil.AssertEqual(t, len(node.Nodes), 2) + bazNodes = node.Nodes + default: + t.Errorf("key = %s, not matched", node.Key) + } + } + for _, node := range bazNodes { + switch node.Key { + case "/foo/baz/bat": + testutil.AssertEqual(t, *node.Value, "Y") + testutil.AssertEqual(t, node.Dir, false) + case "/foo/baz/ttl": + testutil.AssertEqual(t, *node.Value, "Y") + testutil.AssertEqual(t, node.Dir, false) + testutil.AssertEqual(t, node.TTL, int64(3)) + default: + t.Errorf("key = %s, not matched", node.Key) + } + } +} + +// Ensure that the store can update the TTL on a value. +func TestStoreUpdateValueTTL(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 2 + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + _, err := s.Update("/foo", "baz", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + testutil.AssertNil(t, err) + e, _ := s.Get("/foo", false, false) + testutil.AssertEqual(t, *e.Node.Value, "baz") + testutil.AssertEqual(t, e.EtcdIndex, eidx) + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + e, err = s.Get("/foo", false, false) + testutil.AssertNil(t, e) + testutil.AssertEqual(t, err.(*etcdErr.Error).ErrorCode, etcdErr.EcodeKeyNotFound) +} + +// Ensure that the store can update the TTL on a directory. +func TestStoreUpdateDirTTL(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 3 + s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/bar", false, "baz", false, TTLOptionSet{ExpireTime: Permanent}) + e, err := s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, e.Node.Dir, true) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + e, _ = s.Get("/foo/bar", false, false) + testutil.AssertEqual(t, *e.Node.Value, "baz") + testutil.AssertEqual(t, e.EtcdIndex, eidx) + + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + e, err = s.Get("/foo/bar", false, false) + testutil.AssertNil(t, e) + testutil.AssertEqual(t, err.(*etcdErr.Error).ErrorCode, etcdErr.EcodeKeyNotFound) +} + +// Ensure that the store can watch for key expiration. +func TestStoreWatchExpire(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 3 + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(400 * time.Millisecond)}) + s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(450 * time.Millisecond)}) + s.Create("/foodir", true, "", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + + w, _ := s.Watch("/", true, false, 0) + testutil.AssertEqual(t, w.StartIndex(), eidx) + c := w.EventChan() + e := nbselect(c) + testutil.AssertNil(t, e) + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + eidx = 4 + e = nbselect(c) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foo") + w, _ = s.Watch("/", true, false, 5) + eidx = 6 + testutil.AssertEqual(t, w.StartIndex(), eidx) + e = nbselect(w.EventChan()) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foofoo") + w, _ = s.Watch("/", true, false, 6) + e = nbselect(w.EventChan()) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foodir") + testutil.AssertEqual(t, e.Node.Dir, true) +} + +// Ensure that the store can watch for key expiration when refreshing. +func TestStoreWatchExpireRefresh(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 2 + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(1200 * time.Millisecond), Refresh: true}) + + // Make sure we set watch updates when Refresh is true for newly created keys + w, _ := s.Watch("/", true, false, 0) + testutil.AssertEqual(t, w.StartIndex(), eidx) + c := w.EventChan() + e := nbselect(c) + testutil.AssertNil(t, e) + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + eidx = 3 + e = nbselect(c) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foo") + + s.Update("/foofoo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + w, _ = s.Watch("/", true, false, 4) + fc.Advance(700 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + eidx = 5 // We should skip 4 because a TTL update should occur with no watch notification if set `TTLOptionSet.Refresh` to true + testutil.AssertEqual(t, w.StartIndex(), eidx-1) + e = nbselect(w.EventChan()) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foofoo") +} + +// Ensure that the store can watch for key expiration when refreshing with an empty value. +func TestStoreWatchExpireEmptyRefresh(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 1 + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + // Should be no-op + fc.Advance(200 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + + s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + w, _ := s.Watch("/", true, false, 2) + fc.Advance(700 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + eidx = 3 // We should skip 2 because a TTL update should occur with no watch notification if set `TTLOptionSet.Refresh` to true + testutil.AssertEqual(t, w.StartIndex(), eidx-1) + e := nbselect(w.EventChan()) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foo") + testutil.AssertEqual(t, *e.PrevNode.Value, "bar") +} + +// Update TTL of a key (set TTLOptionSet.Refresh to false) and send notification +func TestStoreWatchNoRefresh(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + var eidx uint64 = 1 + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + // Should be no-op + fc.Advance(200 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + + // Update key's TTL with setting `TTLOptionSet.Refresh` to false will cause an update event + s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: false}) + w, _ := s.Watch("/", true, false, 2) + fc.Advance(700 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + eidx = 2 + testutil.AssertEqual(t, w.StartIndex(), eidx) + e := nbselect(w.EventChan()) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, e.Action, "update") + testutil.AssertEqual(t, e.Node.Key, "/foo") + testutil.AssertEqual(t, *e.PrevNode.Value, "bar") +} + +// Ensure that the store can update the TTL on a value with refresh. +func TestStoreRefresh(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + s.Create("/foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + s.Create("/bar", true, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + _, err := s.Update("/foo", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + testutil.AssertNil(t, err) + + _, err = s.Set("/foo", false, "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + testutil.AssertNil(t, err) + + _, err = s.Update("/bar", "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + testutil.AssertNil(t, err) + + _, err = s.CompareAndSwap("/foo", "bar", 0, "", TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond), Refresh: true}) + testutil.AssertNil(t, err) +} + +// Ensure that the store can recover from a previously saved state that includes an expiring key. +func TestStoreRecoverWithExpiration(t *testing.T) { + s := newStore() + s.clock = newFakeClock() + + fc := newFakeClock() + + var eidx uint64 = 4 + s.Create("/foo", true, "", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/x", false, "bar", false, TTLOptionSet{ExpireTime: Permanent}) + s.Create("/foo/y", false, "baz", false, TTLOptionSet{ExpireTime: fc.Now().Add(5 * time.Millisecond)}) + b, err := s.Save() + testutil.AssertNil(t, err) + + time.Sleep(10 * time.Millisecond) + + s2 := newStore() + s2.clock = fc + + s2.Recovery(b) + + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + + e, err := s.Get("/foo/x", false, false) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertEqual(t, *e.Node.Value, "bar") + + e, err = s.Get("/foo/y", false, false) + testutil.AssertNotNil(t, err) + testutil.AssertNil(t, e) +} + +// Ensure that the store doesn't see expirations of hidden keys. +func TestStoreWatchExpireWithHiddenKey(t *testing.T) { + s := newStore() + fc := newFakeClock() + s.clock = fc + + s.Create("/_foo", false, "bar", false, TTLOptionSet{ExpireTime: fc.Now().Add(500 * time.Millisecond)}) + s.Create("/foofoo", false, "barbarbar", false, TTLOptionSet{ExpireTime: fc.Now().Add(1000 * time.Millisecond)}) + + w, _ := s.Watch("/", true, false, 0) + c := w.EventChan() + e := nbselect(c) + testutil.AssertNil(t, e) + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + e = nbselect(c) + testutil.AssertNil(t, e) + fc.Advance(600 * time.Millisecond) + s.DeleteExpiredKeys(fc.Now()) + e = nbselect(c) + testutil.AssertEqual(t, e.Action, "expire") + testutil.AssertEqual(t, e.Node.Key, "/foofoo") +} + +// newFakeClock creates a new FakeClock that has been advanced to at least minExpireTime +func newFakeClock() clockwork.FakeClock { + fc := clockwork.NewFakeClock() + for minExpireTime.After(fc.Now()) { + fc.Advance((0x1 << 62) * time.Nanosecond) + } + return fc +} + +// Performs a non-blocking select on an event channel. +func nbselect(c <-chan *Event) *Event { + select { + case e := <-c: + return e + default: + return nil + } +} diff --git a/vendor/github.com/coreos/etcd/store/store_v2_test.go b/vendor/github.com/coreos/etcd/store/store_v2_test.go new file mode 100644 index 000000000..295698177 --- /dev/null +++ b/vendor/github.com/coreos/etcd/store/store_v2_test.go @@ -0,0 +1,62 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !v2v3 + +package store_test + +import ( + "testing" + + "github.com/coreos/etcd/pkg/testutil" + "github.com/coreos/etcd/store" +) + +type v2TestStore struct { + store.Store +} + +func (s *v2TestStore) Close() {} + +func newTestStore(t *testing.T, ns ...string) StoreCloser { + return &v2TestStore{store.New(ns...)} +} + +// Ensure that the store can recover from a previously saved state. +func TestStoreRecover(t *testing.T) { + s := newTestStore(t) + defer s.Close() + var eidx uint64 = 4 + s.Create("/foo", true, "", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/x", false, "bar", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Update("/foo/x", "barbar", store.TTLOptionSet{ExpireTime: store.Permanent}) + s.Create("/foo/y", false, "baz", false, store.TTLOptionSet{ExpireTime: store.Permanent}) + b, err := s.Save() + testutil.AssertNil(t, err) + + s2 := newTestStore(t) + s2.Recovery(b) + + e, err := s.Get("/foo/x", false, false) + testutil.AssertEqual(t, e.Node.CreatedIndex, uint64(2)) + testutil.AssertEqual(t, e.Node.ModifiedIndex, uint64(3)) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, *e.Node.Value, "barbar") + + e, err = s.Get("/foo/y", false, false) + testutil.AssertEqual(t, e.EtcdIndex, eidx) + testutil.AssertNil(t, err) + testutil.AssertEqual(t, *e.Node.Value, "baz") +} diff --git a/vendor/github.com/coreos/etcd/store/store_v2v3_test.go b/vendor/github.com/coreos/etcd/store/store_v2v3_test.go new file mode 100644 index 000000000..2778b7c95 --- /dev/null +++ b/vendor/github.com/coreos/etcd/store/store_v2v3_test.go @@ -0,0 +1,42 @@ +// Copyright 2017 The etcd Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build v2v3 + +package store_test + +import ( + "testing" + + "github.com/coreos/etcd/etcdserver/api/v2v3" + "github.com/coreos/etcd/integration" + "github.com/coreos/etcd/store" +) + +type v2v3TestStore struct { + store.Store + clus *integration.ClusterV3 + t *testing.T +} + +func (s *v2v3TestStore) Close() { s.clus.Terminate(s.t) } + +func newTestStore(t *testing.T, ns ...string) StoreCloser { + clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1}) + return &v2v3TestStore{ + v2v3.NewStore(clus.Client(0), "/v2/"), + clus, + t, + } +} diff --git a/vendor/github.com/coreos/etcd/test b/vendor/github.com/coreos/etcd/test index e0cffe0f4..6e60ced3c 100755 --- a/vendor/github.com/coreos/etcd/test +++ b/vendor/github.com/coreos/etcd/test @@ -87,10 +87,15 @@ function unit_pass { function integration_pass { echo "Running integration tests..." go test -timeout 15m -v -cpu 1,2,4 $@ ${REPO_PATH}/integration + integration_extra $@ +} + +function integration_extra { go test -timeout 1m -v ${RACE} -cpu 1,2,4 $@ ${REPO_PATH}/client/integration - go test -timeout 10m -v ${RACE} -cpu 1,2,4 $@ ${REPO_PATH}/clientv3/integration + go test -timeout 15m -v ${RACE} -cpu 1,2,4 $@ ${REPO_PATH}/clientv3/integration go test -timeout 1m -v -cpu 1,2,4 $@ ${REPO_PATH}/contrib/raftexample go test -timeout 1m -v ${RACE} -cpu 1,2,4 -run=Example $@ ${TEST} + go test -timeout 5m -v ${RACE} -tags v2v3 $@ ${REPO_PATH}/store } function functional_pass { @@ -162,6 +167,9 @@ function cov_pass { go test $GOCOVFLAGS -run=Test -coverprofile "$COVERDIR/${tf}.coverprofile" ${REPO_PATH}/$t || failed="$failed $t" done + # v2v3 tests + go test -tags v2v3 $GOCOVFLAGS -coverprofile "$COVERDIR/store-v2v3.coverprofile" ${REPO_PATH}/clientv3/integration || failed="$failed store-v2v3" + # proxy tests go test -tags cluster_proxy $GOCOVFLAGS -coverprofile "$COVERDIR/proxy_integration.coverprofile" ${REPO_PATH}/integration || failed="$failed proxy-integration" go test -tags cluster_proxy $GOCOVFLAGS -coverprofile "$COVERDIR/proxy_clientv3.coverprofile" ${REPO_PATH}/clientv3/integration || failed="$failed proxy-clientv3/integration" @@ -211,10 +219,7 @@ function integration_e2e_pass { intpid="$!" wait $e2epid wait $intpid - go test -timeout 1m -v ${RACE} -cpu 1,2,4 $@ ${REPO_PATH}/client/integration - go test -timeout 20m -v ${RACE} -cpu 1,2,4 $@ ${REPO_PATH}/clientv3/integration - go test -timeout 1m -v -cpu 1,2,4 $@ ${REPO_PATH}/contrib/raftexample - go test -timeout 1m -v ${RACE} -cpu 1,2,4 -run=Example $@ ${TEST} + integration_extra $@ } function grpcproxy_pass { diff --git a/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml index 1bd2340c1..19946dc91 100644 --- a/vendor/github.com/davecgh/go-spew/.travis.yml +++ b/vendor/github.com/davecgh/go-spew/.travis.yml @@ -3,6 +3,7 @@ go: - 1.6.x - 1.7.x - 1.8.x + - 1.9.x sudo: false install: - go get -v github.com/alecthomas/gometalinter @@ -18,7 +19,7 @@ script: --enable=unconvert --deadline=4m ./spew | tee /dev/stderr)" - go test -v -race -tags safe ./spew - - go test -v -race -tags testcgo ./spew -covermode=count -coverprofile=profile.cov + - go test -v -race -tags testcgo ./spew -covermode=atomic -coverprofile=profile.cov after_success: - go get -v github.com/mattn/goveralls - goveralls -coverprofile=profile.cov -service=travis-ci diff --git a/vendor/github.com/docker/docker-credential-helpers/.gitignore b/vendor/github.com/docker/docker-credential-helpers/.gitignore deleted file mode 100644 index c0f37012d..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin -release diff --git a/vendor/github.com/docker/docker-credential-helpers/.travis.yml b/vendor/github.com/docker/docker-credential-helpers/.travis.yml deleted file mode 100644 index bf1ac60e6..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/.travis.yml +++ /dev/null @@ -1,49 +0,0 @@ ---- - # See appveyor.yml for windows build. - sudo: required - language: go - dist: trusty - os: - - linux - - osx - notifications: - email: false - go: - - 1.8 - install: make deps - addons: - apt: - packages: - - libsecret-1-dev - - pass - before_script: - - "export DISPLAY=:99.0" - - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sh ci/before_script_linux.sh; fi - - make validate - script: make test - - before_deploy: - - sh ci/before_deploy.sh - - deploy: - provider: releases - api_key: - secure: "cGs5cao/MeVQVnum+Pr/Tpv+w83NsqGVS3wxvi3LYEf2ON4Kkmtd+Alwi0YFkGPJmSY0jZOct8NVK/M70qSnIU4l+AAq9+3KSMv23u4xrmy2sQog3AF+Ve3Rac+iYwZHOWwGs9I67CSuVv0vjJNVsDsTVefc25lHJImjRvXIS4p9xYzRPeUDCoqAo/QMVE+vFiMyxydsvt8fhd0gZCjPYWEpyHe9tjZ1tr1HsHZKFAjVb6AmF45d8rvadPoVUuLaOtr35wDC3XRKEvCZUefQpwLkrNj7j2L1rVGlY1xTE2APpLtvfd7R1Mx6kSfS1Gm3Pwcv3mugadXIhecL0lsdnU+BANjX3VUiv4ryzTPbsge966mv9ZQYwAzgCQTWRtMNJqsAnPZTeAkiOntd+HMQbPpxljOxv1sjDPY+EIZesyB3yQRJI8vMxqFcAjxeRyLcBqEnRFC2nd/Ln0KZ7ZFu16FcpNqRojdBayyypuXKqAiBNwtp4ti/65x8eHfBJuNjJtNZkRsJEYam4CYMRLxds9plKQfkaZ8045PKpyXO8fMpUhrfqSVID4IrYvD+io6XoXtdR4Lk6isZ2EgrjdrqgdG70S5lwKihL4iAi2F2ZCWhngFhkeNVOZunEWE6qZMk5wKODajR9sixGDApGPZQVojHwCNRGILZaHZ39JCIj3s=" - # upload file artifacts using a glob expression. - # It requires both options `file_glob` and `file`: - # https://github.com/travis-ci/dpl/blob/master/lib/dpl/provider/releases.rb#L47-L53 - file_glob: true - file: docker-credential-*-${TRAVIS_TAG}-amd64.tar.gz - # don't delete the artifacts from previous phases - skip_cleanup: true - # deploy when a new tag is pushed - on: - tags: true - - branches: - only: - # Pushes and PR to the master branch - - master - # IMPORTANT Ruby regex to match tags. Required, or travis won't trigger deploys when a new tag - # is pushed. This regex matches semantic versions like v1.2.3-rc4+2016.02.22 - - /^v\d+\.\d+\.\d+.*$/ diff --git a/vendor/github.com/docker/docker-credential-helpers/CHANGELOG.md b/vendor/github.com/docker/docker-credential-helpers/CHANGELOG.md deleted file mode 100644 index d9d1d1d66..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/CHANGELOG.md +++ /dev/null @@ -1,50 +0,0 @@ -# Changelog - -This changelog tracks the releases of docker-credential-helpers. -This project includes different binaries per platform. -The platform released is identified after the tag name. - -## v0.5.2 (Mac OS X, Windows, Linux) - -- Add a `version` command to output the version -- Fix storing URLs without scheme, and use `https://` by default - -## v0.5.1 (Go client, Mac OS X, Windows, Linux) - -- Redirect credential helpers' standard error to the caller's -- Prevent invalid credentials and credentials queries - -## v0.5.0 (Mac OS X) - -- Add a label for Docker credentials and filter credentials lookup to filter keychain lookups - -## v0.4.2 (Mac OS X, Windows) - -- Fix osxkeychain list -- macOS binary is now signed on release -- Generate a `.exe` instead - -## v0.4.1 (Mac OS X) - -- Fixes to support older version of OSX (10.10, 10.11) - -## v0.4.0 (Go client, Mac OS X, Windows, Linux) - -- Full implementation for OSX ready -- Fix some windows issues -- Implement client.List, change list API -- mac: delete credentials before adding them to avoid already exist error (fixes #37) - -## v0.3.0 (Go client) - -- Add Go client library to talk with the native programs. - -## v0.2.0 (Mac OS X, Windows, Linux) - -- Initial release of docker-credential-secretservice for Linux. -- Use new secrets payload introduced in https://github.com/docker/docker/pull/20970. - -## v0.1.0 (Mac OS X, Windows) - -- Initial release of docker-credential-osxkeychain for Mac OS X. -- Initial release of docker-credential-wincred for Microsoft Windows. diff --git a/vendor/github.com/docker/docker-credential-helpers/LICENSE b/vendor/github.com/docker/docker-credential-helpers/LICENSE deleted file mode 100644 index 1ea555e2a..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2016 David Calavera - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/docker/docker-credential-helpers/MAINTAINERS b/vendor/github.com/docker/docker-credential-helpers/MAINTAINERS deleted file mode 100644 index 7136d1c3c..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/MAINTAINERS +++ /dev/null @@ -1,166 +0,0 @@ -# docker-credential-helpers maintainers file -# -# This file describes who runs the docker/docker-credential-helpers project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "aaronlehmann", - "calavera", - "coolljt0725", - "cpuguy83", - "crosbymichael", - "dnephin", - "dongluochen", - "duglin", - "estesp", - "icecrime", - "jhowardmsft", - "lk4d4", - "mavenugo", - "mhbauer", - "n4ss", - "runcom", - "stevvooe", - "thajeztah", - "tianon", - "tibor", - "tonistiigi", - "unclejack", - "vdemeester", - "vieux" - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.aaronlehmann] - Name = "Aaron Lehmann" - Email = "aaron.lehmann@docker.com" - GitHub = "aaronlehmann" - - [people.calavera] - Name = "David Calavera" - Email = "david.calavera@gmail.com" - GitHub = "calavera" - - [people.coolljt0725] - Name = "Lei Jitang" - Email = "leijitang@huawei.com" - GitHub = "coolljt0725" - - [people.cpuguy83] - Name = "Brian Goff" - Email = "cpuguy83@gmail.com" - Github = "cpuguy83" - - [people.crosbymichael] - Name = "Michael Crosby" - Email = "crosbymichael@gmail.com" - GitHub = "crosbymichael" - - [people.dnephin] - Name = "Daniel Nephin" - Email = "dnephin@gmail.com" - GitHub = "dnephin" - - [people.dongluochen] - Name = "Dongluo Chen" - Email = "dongluo.chen@docker.com" - GitHub = "dongluochen" - - [people.duglin] - Name = "Doug Davis" - Email = "dug@us.ibm.com" - GitHub = "duglin" - - [people.estesp] - Name = "Phil Estes" - Email = "estesp@linux.vnet.ibm.com" - GitHub = "estesp" - - [people.icecrime] - Name = "Arnaud Porterie" - Email = "arnaud@docker.com" - GitHub = "icecrime" - - [people.jhowardmsft] - Name = "John Howard" - Email = "jhoward@microsoft.com" - GitHub = "jhowardmsft" - - [people.lk4d4] - Name = "Alexander Morozov" - Email = "lk4d4@docker.com" - GitHub = "lk4d4" - - [people.mavenugo] - Name = "Madhu Venugopal" - Email = "madhu@docker.com" - GitHub = "mavenugo" - - [people.mhbauer] - Name = "Morgan Bauer" - Email = "mbauer@us.ibm.com" - GitHub = "mhbauer" - - [people.n4ss] - Name = "Nassim Eddequiouaq" - Email = "eddequiouaq.nassim@gmail.com" - GitHub = "n4ss" - - [people.runcom] - Name = "Antonio Murdaca" - Email = "runcom@redhat.com" - GitHub = "runcom" - - [people.stevvooe] - Name = "Stephen Day" - Email = "stephen.day@docker.com" - GitHub = "stevvooe" - - [people.thajeztah] - Name = "Sebastiaan van Stijn" - Email = "github@gone.nl" - GitHub = "thaJeztah" - - [people.tianon] - Name = "Tianon Gravi" - Email = "admwiggin@gmail.com" - GitHub = "tianon" - - [people.tibor] - Name = "Tibor Vass" - Email = "tibor@docker.com" - GitHub = "tiborvass" - - [people.tonistiigi] - Name = "Tõnis Tiigi" - Email = "tonis@docker.com" - GitHub = "tonistiigi" - - [people.unclejack] - Name = "Cristian Staretu" - Email = "cristian.staretu@gmail.com" - GitHub = "unclejack" - - [people.vdemeester] - Name = "Vincent Demeester" - Email = "vincent@sbr.pm" - GitHub = "vdemeester" - - [people.vieux] - Name = "Victor Vieux" - Email = "vieux@docker.com" - GitHub = "vieux" diff --git a/vendor/github.com/docker/docker-credential-helpers/Makefile b/vendor/github.com/docker/docker-credential-helpers/Makefile deleted file mode 100644 index b4715db14..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/Makefile +++ /dev/null @@ -1,82 +0,0 @@ -.PHONY: all deps osxkeychain secretservice test validate wincred pass deb - -TRAVIS_OS_NAME ?= linux -VERSION := $(shell grep 'const Version' credentials/version.go | awk -F'"' '{ print $$2 }') - -all: test - -deps: - go get github.com/golang/lint/golint - -clean: - rm -rf bin - rm -rf release - -osxkeychain: - mkdir bin - go build -ldflags -s -o bin/docker-credential-osxkeychain osxkeychain/cmd/main_darwin.go - -osxcodesign: osxkeychain - $(eval SIGNINGHASH = $(shell security find-identity -v -p codesigning | grep "Developer ID Application: Docker Inc" | cut -d ' ' -f 4)) - xcrun -log codesign -s $(SIGNINGHASH) --force --verbose bin/docker-credential-osxkeychain - xcrun codesign --verify --deep --strict --verbose=2 --display bin/docker-credential-osxkeychain - -osxrelease: clean vet_osx lint fmt test osxcodesign - mkdir -p release - @echo "\nPackaging version ${VERSION}\n" - cd bin && tar cvfz ../release/docker-credential-osxkeychain-v$(VERSION)-amd64.tar.gz docker-credential-osxkeychain - -secretservice: - mkdir bin - go build -o bin/docker-credential-secretservice secretservice/cmd/main_linux.go - -pass: - mkdir -p bin - go build -o bin/docker-credential-pass pass/cmd/main_linux.go - -wincred: - mkdir bin - go build -o bin/docker-credential-wincred.exe wincred/cmd/main_windows.go - -winrelease: clean vet_win lint fmt test wincred - mkdir -p release - @echo "\nPackaging version ${VERSION}\n" - cd bin && zip ../release/docker-credential-wincred-v$(VERSION)-amd64.zip docker-credential-wincred.exe - -test: - # tests all packages except vendor - go test -v `go list ./... | grep -v /vendor/` - -vet: vet_$(TRAVIS_OS_NAME) - go vet ./credentials - -vet_win: - go vet ./wincred - -vet_osx: - go vet ./osxkeychain - -vet_linux: - go vet ./secretservice - -lint: - for p in `go list ./... | grep -v /vendor/`; do \ - golint $$p ; \ - done - -fmt: - gofmt -s -l `ls **/*.go | grep -v vendor` - -validate: vet lint fmt - - -BUILDIMG:=docker-credential-secretservice-$(VERSION) -deb: - mkdir -p release - docker build -f deb/Dockerfile \ - --build-arg VERSION=$(VERSION) \ - --build-arg DISTRO=xenial \ - --tag $(BUILDIMG) \ - . - docker run --rm --net=none $(BUILDIMG) tar cf - /release | tar xf - - docker rmi $(BUILDIMG) diff --git a/vendor/github.com/docker/docker-credential-helpers/README.md b/vendor/github.com/docker/docker-credential-helpers/README.md deleted file mode 100644 index e795f7c5e..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/README.md +++ /dev/null @@ -1,76 +0,0 @@ -## Introduction - -docker-credential-helpers is a suite of programs to use native stores to keep Docker credentials safe. - -## Installation - -Go to the [Releases](https://github.com/docker/docker-credential-helpers/releases) page and download the binary that works better for you. Put that binary in your `$PATH`, so Docker can find it. - -### Building from scratch - -The programs in this repository are written with the Go programming language. These instructions assume that you have previous knowledge about the language and you have it installed in your machine. - -1 - Download the source and put it in your `$GOPATH` with `go get`. - -``` -$ go get github.com/docker/docker-credential-helpers -``` - -2 - Use `make` to build the program you want. That will leave any executable in the `bin` directory inside the repository. - -``` -$ cd $GOPATH/docker/docker-credentials-helpers -$ make osxkeychain -``` - -3 - Put that binary in your `$PATH`, so Docker can find it. - -## Usage - -### With the Docker Engine - -Set the `credsStore` option in your `.docker/config.json` file with the suffix of the program you want to use. For instance, set it to `osxkeychain` if you want to use `docker-credential-osxkeychain`. - -```json -{ - "credsStore": "osxkeychain" -} -``` - -### With other command line applications - -The sub-package [client](https://godoc.org/github.com/docker/docker-credential-helpers/client) includes -functions to call external programs from your own command line applications. - -There are three things you need to know if you need to interact with a helper: - -1. The name of the program to execute, for instance `docker-credential-osxkeychain`. -2. The server address to identify the credentials, for instance `https://example.com`. -3. The username and secret to store, when you want to store credentials. - -You can see examples of each function in the [client](https://godoc.org/github.com/docker/docker-credential-helpers/client) documentation. - -### Available programs - -1. osxkeychain: Provides a helper to use the OS X keychain as credentials store. -2. secretservice: Provides a helper to use the D-Bus secret service as credentials store. -3. wincred: Provides a helper to use Windows credentials manager as store. - -## Development - -A credential helper can be any program that can read values from the standard input. We use the first argument in the command line to differentiate the kind of command to execute. There are four valid values: - -- `store`: Adds credentials to the keychain. The payload in the standard input is a JSON document with `ServerURL`, `Username` and `Secret`. -- `get`: Retrieves credentials from the keychain. The payload in the standard input is the raw value for the `ServerURL`. -- `erase`: Removes credentials from the keychain. The payload in the standard input is the raw value for the `ServerURL`. -- `list`: Lists stored credentials. There is no standard input payload. - -This repository also includes libraries to implement new credentials programs in Go. Adding a new helper program is pretty easy. You can see how the OS X keychain helper works in the [osxkeychain](osxkeychain) directory. - -1. Implement the interface `credentials.Helper` in `YOUR_PACKAGE/YOUR_PACKAGE_$GOOS.go` -2. Create a main program in `YOUR_PACKAGE/cmd/main_$GOOS.go`. -3. Add make tasks to build your program and run tests. - -## License - -MIT. See [LICENSE](LICENSE) for more information. diff --git a/vendor/github.com/docker/docker-credential-helpers/appveyor.yml b/vendor/github.com/docker/docker-credential-helpers/appveyor.yml deleted file mode 100644 index 282e1d530..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/appveyor.yml +++ /dev/null @@ -1,24 +0,0 @@ -image: Visual Studio 2015 -environment: - GOPATH: c:\gopath - -clone_folder: c:\gopath\src\github.com\docker\docker-credential-helpers -clone_depth: 10 - -before_build: - - set PATH=%PATH%;C:\MinGW\bin; - - set PATH=%PATH%;C:\go18\bin; - - set GOROOT=C:\go18 - -build_script: - - mingw32-make vet_win wincred - -test_script: - - mingw32-make test - -deploy: off - -artifacts: - - path: bin/docker-credential-wincred.exe - -configuration: Release diff --git a/vendor/github.com/docker/docker-credential-helpers/ci/before_deploy.sh b/vendor/github.com/docker/docker-credential-helpers/ci/before_deploy.sh deleted file mode 100644 index 2b27bfef6..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/ci/before_deploy.sh +++ /dev/null @@ -1,15 +0,0 @@ -set -ex - -mkdir bin -case "$TRAVIS_OS_NAME" in - "osx") - go build -o bin/docker-credential-osxkeychain osxkeychain/cmd/main_darwin.go - cd bin - tar czf ../docker-credential-osxkeychain-${TRAVIS_TAG}-amd64.tar.gz docker-credential-osxkeychain - ;; - "linux") - go build -o bin/docker-credential-secretservice secretservice/cmd/main_linux.go - cd bin - tar czf ../docker-credential-secretservice-${TRAVIS_TAG}-amd64.tar.gz docker-credential-secretservice - ;; -esac diff --git a/vendor/github.com/docker/docker-credential-helpers/ci/before_script_linux.sh b/vendor/github.com/docker/docker-credential-helpers/ci/before_script_linux.sh deleted file mode 100644 index 9fc0ea2d0..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/ci/before_script_linux.sh +++ /dev/null @@ -1,22 +0,0 @@ -set -ex - -sh -e /etc/init.d/xvfb start -sleep 3 # give xvfb some time to start - -# init key for pass -gpg --batch --gen-key <<-EOF -%echo Generating a standard key -Key-Type: DSA -Key-Length: 1024 -Subkey-Type: ELG-E -Subkey-Length: 1024 -Name-Real: Meshuggah Rocks -Name-Email: meshuggah@example.com -Expire-Date: 0 -# Do a commit here, so that we can later print "done" :-) -%commit -%echo done -EOF - -key=$(gpg --no-auto-check-trustdb --list-secret-keys | grep ^sec | cut -d/ -f2 | cut -d" " -f1) -pass init $key diff --git a/vendor/github.com/docker/docker-credential-helpers/client/client.go b/vendor/github.com/docker/docker-credential-helpers/client/client.go deleted file mode 100644 index d1d0434cb..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/client.go +++ /dev/null @@ -1,121 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - - "github.com/docker/docker-credential-helpers/credentials" -) - -// isValidCredsMessage checks if 'msg' contains invalid credentials error message. -// It returns whether the logs are free of invalid credentials errors and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername. -func isValidCredsMessage(msg string) error { - if credentials.IsCredentialsMissingServerURLMessage(msg) { - return credentials.NewErrCredentialsMissingServerURL() - } - - if credentials.IsCredentialsMissingUsernameMessage(msg) { - return credentials.NewErrCredentialsMissingUsername() - } - - return nil -} - -// Store uses an external program to save credentials. -func Store(program ProgramFunc, creds *credentials.Credentials) error { - cmd := program("store") - - buffer := new(bytes.Buffer) - if err := json.NewEncoder(buffer).Encode(creds); err != nil { - return err - } - cmd.Input(buffer) - - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) - } - - return nil -} - -// Get executes an external program to get the credentials from a native store. -func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { - cmd := program("get") - cmd.Input(strings.NewReader(serverURL)) - - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if credentials.IsErrCredentialsNotFoundMessage(t) { - return nil, credentials.NewErrCredentialsNotFound() - } - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) - } - - resp := &credentials.Credentials{ - ServerURL: serverURL, - } - - if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil { - return nil, err - } - - return resp, nil -} - -// Erase executes a program to remove the server credentials from the native store. -func Erase(program ProgramFunc, serverURL string) error { - cmd := program("erase") - cmd.Input(strings.NewReader(serverURL)) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t) - } - - return nil -} - -// List executes a program to list server credentials in the native store. -func List(program ProgramFunc) (map[string]string, error) { - cmd := program("list") - cmd.Input(strings.NewReader("unused")) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t) - } - - var resp map[string]string - if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/client/client_test.go b/vendor/github.com/docker/docker-credential-helpers/client/client_test.go deleted file mode 100644 index 649c1ae49..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/client_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "strings" - "testing" - - "github.com/docker/docker-credential-helpers/credentials" -) - -const ( - validServerAddress = "https://index.docker.io/v1" - validUsername = "linus" - validServerAddress2 = "https://example.com:5002" - invalidServerAddress = "https://foobar.example.com" - missingCredsAddress = "https://missing.docker.io/v1" -) - -var errProgramExited = fmt.Errorf("exited 1") - -// mockProgram simulates interactions between the docker client and a remote -// credentials helper. -// Unit tests inject this mocked command into the remote to control execution. -type mockProgram struct { - arg string - input io.Reader -} - -// Output returns responses from the remote credentials helper. -// It mocks those responses based in the input in the mock. -func (m *mockProgram) Output() ([]byte, error) { - in, err := ioutil.ReadAll(m.input) - if err != nil { - return nil, err - } - inS := string(in) - - switch m.arg { - case "erase": - switch inS { - case validServerAddress: - return nil, nil - default: - return []byte("program failed"), errProgramExited - } - case "get": - switch inS { - case validServerAddress: - return []byte(`{"Username": "foo", "Secret": "bar"}`), nil - case validServerAddress2: - return []byte(`{"Username": "", "Secret": "abcd1234"}`), nil - case missingCredsAddress: - return []byte(credentials.NewErrCredentialsNotFound().Error()), errProgramExited - case invalidServerAddress: - return []byte("program failed"), errProgramExited - case "": - return []byte(credentials.NewErrCredentialsMissingServerURL().Error()), errProgramExited - } - case "store": - var c credentials.Credentials - err := json.NewDecoder(strings.NewReader(inS)).Decode(&c) - if err != nil { - return []byte("error storing credentials"), errProgramExited - } - switch c.ServerURL { - case validServerAddress: - return nil, nil - case validServerAddress2: - return nil, nil - default: - return []byte("error storing credentials"), errProgramExited - } - case "list": - return []byte(fmt.Sprintf(`{"%s": "%s"}`, validServerAddress, validUsername)), nil - - } - - return []byte(fmt.Sprintf("unknown argument %q with %q", m.arg, inS)), errProgramExited -} - -// Input sets the input to send to a remote credentials helper. -func (m *mockProgram) Input(in io.Reader) { - m.input = in -} - -func mockProgramFn(args ...string) Program { - return &mockProgram{ - arg: args[0], - } -} - -func ExampleStore() { - p := NewShellProgramFunc("docker-credential-secretservice") - - c := &credentials.Credentials{ - ServerURL: "https://example.com", - Username: "calavera", - Secret: "my super secret token", - } - - if err := Store(p, c); err != nil { - fmt.Println(err) - } -} - -func TestStore(t *testing.T) { - valid := []credentials.Credentials{ - {validServerAddress, "foo", "bar"}, - {validServerAddress2, "", "abcd1234"}, - } - - for _, v := range valid { - if err := Store(mockProgramFn, &v); err != nil { - t.Fatal(err) - } - } - - invalid := []credentials.Credentials{ - {invalidServerAddress, "foo", "bar"}, - } - - for _, v := range invalid { - if err := Store(mockProgramFn, &v); err == nil { - t.Fatalf("Expected error for server %s, got nil", v.ServerURL) - } - } -} - -func ExampleGet() { - p := NewShellProgramFunc("docker-credential-secretservice") - - creds, err := Get(p, "https://example.com") - if err != nil { - fmt.Println(err) - } - - fmt.Printf("Got credentials for user `%s` in `%s`\n", creds.Username, creds.ServerURL) -} - -func TestGet(t *testing.T) { - valid := []credentials.Credentials{ - {validServerAddress, "foo", "bar"}, - {validServerAddress2, "", "abcd1234"}, - } - - for _, v := range valid { - c, err := Get(mockProgramFn, v.ServerURL) - if err != nil { - t.Fatal(err) - } - - if c.Username != v.Username { - t.Fatalf("expected username `%s`, got %s", v.Username, c.Username) - } - if c.Secret != v.Secret { - t.Fatalf("expected secret `%s`, got %s", v.Secret, c.Secret) - } - } - - missingServerURLErr := credentials.NewErrCredentialsMissingServerURL() - - invalid := []struct { - serverURL string - err string - }{ - {missingCredsAddress, credentials.NewErrCredentialsNotFound().Error()}, - {invalidServerAddress, "error getting credentials - err: exited 1, out: `program failed`"}, - {"", fmt.Sprintf("error getting credentials - err: %s, out: `%s`", - missingServerURLErr.Error(), missingServerURLErr.Error())}, - } - - for _, v := range invalid { - _, err := Get(mockProgramFn, v.serverURL) - if err == nil { - t.Fatalf("Expected error for server %s, got nil", v.serverURL) - } - if err.Error() != v.err { - t.Fatalf("Expected error `%s`, got `%v`", v.err, err) - } - } -} - -func ExampleErase() { - p := NewShellProgramFunc("docker-credential-secretservice") - - if err := Erase(p, "https://example.com"); err != nil { - fmt.Println(err) - } -} - -func TestErase(t *testing.T) { - if err := Erase(mockProgramFn, validServerAddress); err != nil { - t.Fatal(err) - } - - if err := Erase(mockProgramFn, invalidServerAddress); err == nil { - t.Fatalf("Expected error for server %s, got nil", invalidServerAddress) - } -} - -func TestList(t *testing.T) { - auths, err := List(mockProgramFn) - if err != nil { - t.Fatal(err) - } - - if username, exists := auths[validServerAddress]; !exists || username != validUsername { - t.Fatalf("auths[%s] returned %s, %t; expected %s, %t", validServerAddress, username, exists, validUsername, true) - } -} diff --git a/vendor/github.com/docker/docker-credential-helpers/client/command.go b/vendor/github.com/docker/docker-credential-helpers/client/command.go deleted file mode 100644 index 8da334306..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/command.go +++ /dev/null @@ -1,56 +0,0 @@ -package client - -import ( - "fmt" - "io" - "os" - "os/exec" -) - -// Program is an interface to execute external programs. -type Program interface { - Output() ([]byte, error) - Input(in io.Reader) -} - -// ProgramFunc is a type of function that initializes programs based on arguments. -type ProgramFunc func(args ...string) Program - -// NewShellProgramFunc creates programs that are executed in a Shell. -func NewShellProgramFunc(name string) ProgramFunc { - return NewShellProgramFuncWithEnv(name, nil) -} - -// NewShellProgramFuncWithEnv creates programs that are executed in a Shell with environment variables -func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc { - return func(args ...string) Program { - return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)} - } -} - -func createProgramCmdRedirectErr(commandName string, args []string, env *map[string]string) *exec.Cmd { - programCmd := exec.Command(commandName, args...) - programCmd.Env = os.Environ() - if env != nil { - for k, v := range *env { - programCmd.Env = append(programCmd.Env, fmt.Sprintf("%s=%s", k, v)) - } - } - programCmd.Stderr = os.Stderr - return programCmd -} - -// Shell invokes shell commands to talk with a remote credentials helper. -type Shell struct { - cmd *exec.Cmd -} - -// Output returns responses from the remote credentials helper. -func (s *Shell) Output() ([]byte, error) { - return s.cmd.Output() -} - -// Input sets the input to send to a remote credentials helper. -func (s *Shell) Input(in io.Reader) { - s.cmd.Stdin = in -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go deleted file mode 100644 index da8b594e7..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go +++ /dev/null @@ -1,186 +0,0 @@ -package credentials - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "strings" -) - -// Credentials holds the information shared between docker and the credentials store. -type Credentials struct { - ServerURL string - Username string - Secret string -} - -// isValid checks the integrity of Credentials object such that no credentials lack -// a server URL or a username. -// It returns whether the credentials are valid and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername -func (c *Credentials) isValid() (bool, error) { - if len(c.ServerURL) == 0 { - return false, NewErrCredentialsMissingServerURL() - } - - if len(c.Username) == 0 { - return false, NewErrCredentialsMissingUsername() - } - - return true, nil -} - -// CredsLabel holds the way Docker credentials should be labeled as such in credentials stores that allow labelling. -// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain, -// Windows credentials manager and Linux libsecret. Default value is "Docker Credentials" -var CredsLabel = "Docker Credentials" - -// SetCredsLabel is a simple setter for CredsLabel -func SetCredsLabel(label string) { - CredsLabel = label -} - -// Serve initializes the credentials helper and parses the action argument. -// This function is designed to be called from a command line interface. -// It uses os.Args[1] as the key for the action. -// It uses os.Stdin as input and os.Stdout as output. -// This function terminates the program with os.Exit(1) if there is an error. -func Serve(helper Helper) { - var err error - if len(os.Args) != 2 { - err = fmt.Errorf("Usage: %s ", os.Args[0]) - } - - if err == nil { - err = HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout) - } - - if err != nil { - fmt.Fprintf(os.Stdout, "%v\n", err) - os.Exit(1) - } -} - -// HandleCommand uses a helper and a key to run a credential action. -func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { - switch key { - case "store": - return Store(helper, in) - case "get": - return Get(helper, in, out) - case "erase": - return Erase(helper, in) - case "list": - return List(helper, out) - case "version": - return PrintVersion(out) - } - return fmt.Errorf("Unknown credential action `%s`", key) -} - -// Store uses a helper and an input reader to save credentials. -// The reader must contain the JSON serialization of a Credentials struct. -func Store(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - var creds Credentials - if err := json.NewDecoder(buffer).Decode(&creds); err != nil { - return err - } - - if ok, err := creds.isValid(); !ok { - return err - } - - return helper.Add(&creds) -} - -// Get retrieves the credentials for a given server url. -// The reader must contain the server URL to search. -// The writer is used to write the JSON serialization of the credentials. -func Get(helper Helper, reader io.Reader, writer io.Writer) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - username, secret, err := helper.Get(serverURL) - if err != nil { - return err - } - - resp := Credentials{ - ServerURL: serverURL, - Username: username, - Secret: secret, - } - - buffer.Reset() - if err := json.NewEncoder(buffer).Encode(resp); err != nil { - return err - } - - fmt.Fprint(writer, buffer.String()) - return nil -} - -// Erase removes credentials from the store. -// The reader must contain the server URL to remove. -func Erase(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - return helper.Delete(serverURL) -} - -//List returns all the serverURLs of keys in -//the OS store as a list of strings -func List(helper Helper, writer io.Writer) error { - accts, err := helper.List() - if err != nil { - return err - } - return json.NewEncoder(writer).Encode(accts) -} - -//PrintVersion outputs the current version. -func PrintVersion(writer io.Writer) error { - fmt.Fprintln(writer, Version) - return nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials_test.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials_test.go deleted file mode 100644 index 9c0f1d7e0..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package credentials - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - "testing" -) - -type memoryStore struct { - creds map[string]*Credentials -} - -func newMemoryStore() *memoryStore { - return &memoryStore{ - creds: make(map[string]*Credentials), - } -} - -func (m *memoryStore) Add(creds *Credentials) error { - m.creds[creds.ServerURL] = creds - return nil -} - -func (m *memoryStore) Delete(serverURL string) error { - delete(m.creds, serverURL) - return nil -} - -func (m *memoryStore) Get(serverURL string) (string, string, error) { - c, ok := m.creds[serverURL] - if !ok { - return "", "", fmt.Errorf("creds not found for %s", serverURL) - } - return c.Username, c.Secret, nil -} - -func (m *memoryStore) List() (map[string]string, error) { - //Simply a placeholder to let memoryStore be a valid implementation of Helper interface - return nil, nil -} - -func TestStore(t *testing.T) { - serverURL := "https://index.docker.io/v1/" - creds := &Credentials{ - ServerURL: serverURL, - Username: "foo", - Secret: "bar", - } - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - if err := Store(h, in); err != nil { - t.Fatal(err) - } - - c, ok := h.creds[serverURL] - if !ok { - t.Fatalf("creds not found for %s\n", serverURL) - } - - if c.Username != "foo" { - t.Fatalf("expected username foo, got %s\n", c.Username) - } - - if c.Secret != "bar" { - t.Fatalf("expected username bar, got %s\n", c.Secret) - } -} - -func TestStoreMissingServerURL(t *testing.T) { - creds := &Credentials{ - ServerURL: "", - Username: "foo", - Secret: "bar", - } - - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - - if err := Store(h, in); IsCredentialsMissingServerURL(err) == false { - t.Fatal(err) - } -} - -func TestStoreMissingUsername(t *testing.T) { - creds := &Credentials{ - ServerURL: "https://index.docker.io/v1/", - Username: "", - Secret: "bar", - } - - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - - if err := Store(h, in); IsCredentialsMissingUsername(err) == false { - t.Fatal(err) - } -} - -func TestGet(t *testing.T) { - serverURL := "https://index.docker.io/v1/" - creds := &Credentials{ - ServerURL: serverURL, - Username: "foo", - Secret: "bar", - } - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - if err := Store(h, in); err != nil { - t.Fatal(err) - } - - buf := strings.NewReader(serverURL) - w := new(bytes.Buffer) - if err := Get(h, buf, w); err != nil { - t.Fatal(err) - } - - if w.Len() == 0 { - t.Fatalf("expected output in the writer, got %d", w.Len()) - } - - var c Credentials - if err := json.NewDecoder(w).Decode(&c); err != nil { - t.Fatal(err) - } - - if c.Username != "foo" { - t.Fatalf("expected username foo, got %s\n", c.Username) - } - - if c.Secret != "bar" { - t.Fatalf("expected username bar, got %s\n", c.Secret) - } -} - -func TestGetMissingServerURL(t *testing.T) { - serverURL := "https://index.docker.io/v1/" - creds := &Credentials{ - ServerURL: serverURL, - Username: "foo", - Secret: "bar", - } - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - if err := Store(h, in); err != nil { - t.Fatal(err) - } - - buf := strings.NewReader("") - w := new(bytes.Buffer) - - if err := Get(h, buf, w); IsCredentialsMissingServerURL(err) == false { - t.Fatal(err) - } -} - -func TestErase(t *testing.T) { - serverURL := "https://index.docker.io/v1/" - creds := &Credentials{ - ServerURL: serverURL, - Username: "foo", - Secret: "bar", - } - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - if err := Store(h, in); err != nil { - t.Fatal(err) - } - - buf := strings.NewReader(serverURL) - if err := Erase(h, buf); err != nil { - t.Fatal(err) - } - - w := new(bytes.Buffer) - if err := Get(h, buf, w); err == nil { - t.Fatal("expected error getting missing creds, got empty") - } -} - -func TestEraseMissingServerURL(t *testing.T) { - serverURL := "https://index.docker.io/v1/" - creds := &Credentials{ - ServerURL: serverURL, - Username: "foo", - Secret: "bar", - } - b, err := json.Marshal(creds) - if err != nil { - t.Fatal(err) - } - in := bytes.NewReader(b) - - h := newMemoryStore() - if err := Store(h, in); err != nil { - t.Fatal(err) - } - - buf := strings.NewReader("") - if err := Erase(h, buf); IsCredentialsMissingServerURL(err) == false { - t.Fatal(err) - } -} - -func TestList(t *testing.T) { - //This tests that there is proper input an output into the byte stream - //Individual stores are very OS specific and have been tested in osxkeychain and secretservice respectively - out := new(bytes.Buffer) - h := newMemoryStore() - if err := List(h, out); err != nil { - t.Fatal(err) - } - //testing that there is an output - if out.Len() == 0 { - t.Fatalf("expected output in the writer, got %d", 0) - } -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go deleted file mode 100644 index fe6a5aef4..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -const ( - // ErrCredentialsNotFound standardizes the not found error, so every helper returns - // the same message and docker can handle it properly. - errCredentialsNotFoundMessage = "credentials not found in native keychain" - - // ErrCredentialsMissingServerURL and ErrCredentialsMissingUsername standardize - // invalid credentials or credentials management operations - errCredentialsMissingServerURLMessage = "no credentials server URL" - errCredentialsMissingUsernameMessage = "no credentials username" -) - -// errCredentialsNotFound represents an error -// raised when credentials are not in the store. -type errCredentialsNotFound struct{} - -// Error returns the standard error message -// for when the credentials are not in the store. -func (errCredentialsNotFound) Error() string { - return errCredentialsNotFoundMessage -} - -// NewErrCredentialsNotFound creates a new error -// for when the credentials are not in the store. -func NewErrCredentialsNotFound() error { - return errCredentialsNotFound{} -} - -// IsErrCredentialsNotFound returns true if the error -// was caused by not having a set of credentials in a store. -func IsErrCredentialsNotFound(err error) bool { - _, ok := err.(errCredentialsNotFound) - return ok -} - -// IsErrCredentialsNotFoundMessage returns true if the error -// was caused by not having a set of credentials in a store. -// -// This function helps to check messages returned by an -// external program via its standard output. -func IsErrCredentialsNotFoundMessage(err string) bool { - return err == errCredentialsNotFoundMessage -} - -// errCredentialsMissingServerURL represents an error raised -// when the credentials object has no server URL or when no -// server URL is provided to a credentials operation requiring -// one. -type errCredentialsMissingServerURL struct{} - -func (errCredentialsMissingServerURL) Error() string { - return errCredentialsMissingServerURLMessage -} - -// errCredentialsMissingUsername represents an error raised -// when the credentials object has no username or when no -// username is provided to a credentials operation requiring -// one. -type errCredentialsMissingUsername struct{} - -func (errCredentialsMissingUsername) Error() string { - return errCredentialsMissingUsernameMessage -} - -// NewErrCredentialsMissingServerURL creates a new error for -// errCredentialsMissingServerURL. -func NewErrCredentialsMissingServerURL() error { - return errCredentialsMissingServerURL{} -} - -// NewErrCredentialsMissingUsername creates a new error for -// errCredentialsMissingUsername. -func NewErrCredentialsMissingUsername() error { - return errCredentialsMissingUsername{} -} - -// IsCredentialsMissingServerURL returns true if the error -// was an errCredentialsMissingServerURL. -func IsCredentialsMissingServerURL(err error) bool { - _, ok := err.(errCredentialsMissingServerURL) - return ok -} - -// IsCredentialsMissingServerURLMessage checks for an -// errCredentialsMissingServerURL in the error message. -func IsCredentialsMissingServerURLMessage(err string) bool { - return err == errCredentialsMissingServerURLMessage -} - -// IsCredentialsMissingUsername returns true if the error -// was an errCredentialsMissingUsername. -func IsCredentialsMissingUsername(err error) bool { - _, ok := err.(errCredentialsMissingUsername) - return ok -} - -// IsCredentialsMissingUsernameMessage checks for an -// errCredentialsMissingUsername in the error message. -func IsCredentialsMissingUsernameMessage(err string) bool { - return err == errCredentialsMissingUsernameMessage -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go b/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go deleted file mode 100644 index 135acd254..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go +++ /dev/null @@ -1,14 +0,0 @@ -package credentials - -// Helper is the interface a credentials store helper must implement. -type Helper interface { - // Add appends credentials to the store. - Add(*Credentials) error - // Delete removes credentials from the store. - Delete(serverURL string) error - // Get retrieves credentials from the store. - // It returns username and secret as strings. - Get(serverURL string) (string, string, error) - // List returns the stored serverURLs and their associated usernames. - List() (map[string]string, error) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go b/vendor/github.com/docker/docker-credential-helpers/credentials/version.go deleted file mode 100644 index a4834dd41..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package credentials - -// Version holds a string describing the current version -const Version = "0.5.2" diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/Dockerfile b/vendor/github.com/docker/docker-credential-helpers/deb/Dockerfile deleted file mode 100644 index 1e97b9624..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM ubuntu:xenial - -ARG VERSION -ARG DISTRO - -RUN apt-get update && apt-get install -yy debhelper dh-make golang-go libsecret-1-dev -RUN mkdir -p /build - -WORKDIR /build -ENV GOPATH /build - -COPY Makefile . -COPY credentials credentials -COPY secretservice secretservice -COPY pass pass -COPY deb/debian ./debian -COPY deb/build-deb . - -RUN /build/build-deb ${VERSION} ${DISTRO} diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/build-deb b/vendor/github.com/docker/docker-credential-helpers/deb/build-deb deleted file mode 100755 index dbb9172d0..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/build-deb +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -set -x -set -e - -version=$1 -distro=$2 - -maintainer=$(awk -F ': ' '$1 == "Maintainer" { print $2; exit }' debian/control) - -cat > "debian/changelog" <<-EOF -docker-credential-helpers ($version) $DISTRO; urgency=low - - * New upstream version - - -- $maintainer $(date --rfc-2822) -EOF - -mkdir -p src/github.com/docker/docker-credential-helpers -ln -s /build/credentials /build/src/github.com/docker/docker-credential-helpers/credentials -ln -s /build/secretservice /build/src/github.com/docker/docker-credential-helpers/secretservice -ln -s /build/pass /build/src/github.com/docker/docker-credential-helpers/pass - -dpkg-buildpackage -us -uc - -mkdir /release -mv /docker-credential-* /release diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/debian/compat b/vendor/github.com/docker/docker-credential-helpers/deb/debian/compat deleted file mode 100644 index ec635144f..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/debian/compat +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/debian/control b/vendor/github.com/docker/docker-credential-helpers/deb/debian/control deleted file mode 100644 index 33f2041ab..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/debian/control +++ /dev/null @@ -1,25 +0,0 @@ -Source: docker-credential-helpers -Section: admin -Priority: optional -Maintainer: Docker -Homepage: https://dockerproject.org -Standards-Version: 3.9.6 -Vcs-Browser: https://github.com/docker/docker-credential-helpers -Vcs-Git: git://github.com/docker/docker-credential-helpers.git -Build-Depends: debhelper - , dh-make - , libsecret-1-dev - -Package: docker-credential-secretservice -Architecture: any -Depends: libsecret-1-0 - , ${misc:Depends} -Description: docker-credential-secretservice is a credential helper backend - which uses libsecret to keep Docker credentials safe. - -Package: docker-credential-pass -Architecture: any -Depends: pass - , ${misc:Depends} -Description: docker-credential-secretservice is a credential helper backend - which uses the pass utility to keep Docker credentials safe. diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-pass.install b/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-pass.install deleted file mode 100644 index fb17479b4..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-pass.install +++ /dev/null @@ -1 +0,0 @@ -debian/tmp/usr/bin/docker-credential-pass diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-secretservice.install b/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-secretservice.install deleted file mode 100644 index 4a17630ba..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/debian/docker-credential-secretservice.install +++ /dev/null @@ -1 +0,0 @@ -debian/tmp/usr/bin/docker-credential-secretservice diff --git a/vendor/github.com/docker/docker-credential-helpers/deb/debian/rules b/vendor/github.com/docker/docker-credential-helpers/deb/debian/rules deleted file mode 100755 index e3421e975..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/deb/debian/rules +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/make -f - -DESTDIR := $(CURDIR)/debian/tmp - -override_dh_auto_build: - make secretservice pass - -override_dh_auto_install: - install -D bin/docker-credential-secretservice $(DESTDIR)/usr/bin/docker-credential-secretservice - install -D bin/docker-credential-pass $(DESTDIR)/usr/bin/docker-credential-pass - -%: - dh $@ - -override_dh_auto_test: - # no tests - diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/cmd/main_darwin.go b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/cmd/main_darwin.go deleted file mode 100644 index e3ab9ab76..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/cmd/main_darwin.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/docker/docker-credential-helpers/credentials" - "github.com/docker/docker-credential-helpers/osxkeychain" -) - -func main() { - credentials.Serve(osxkeychain.Osxkeychain{}) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c deleted file mode 100644 index f84d61ee5..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.c +++ /dev/null @@ -1,228 +0,0 @@ -#include "osxkeychain_darwin.h" -#include -#include -#include -#include - -char *get_error(OSStatus status) { - char *buf = malloc(128); - CFStringRef str = SecCopyErrorMessageString(status, NULL); - int success = CFStringGetCString(str, buf, 128, kCFStringEncodingUTF8); - if (!success) { - strncpy(buf, "Unknown error", 128); - } - return buf; -} - -char *keychain_add(struct Server *server, char *label, char *username, char *secret) { - SecKeychainItemRef item; - - OSStatus status = SecKeychainAddInternetPassword( - NULL, - strlen(server->host), server->host, - 0, NULL, - strlen(username), username, - strlen(server->path), server->path, - server->port, - server->proto, - kSecAuthenticationTypeDefault, - strlen(secret), secret, - &item - ); - - if (status) { - return get_error(status); - } - - SecKeychainAttribute attribute; - SecKeychainAttributeList attrs; - attribute.tag = kSecLabelItemAttr; - attribute.data = label; - attribute.length = strlen(label); - attrs.count = 1; - attrs.attr = &attribute; - - status = SecKeychainItemModifyContent(item, &attrs, 0, NULL); - - if (status) { - return get_error(status); - } - - return NULL; -} - -char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret) { - char *tmp; - SecKeychainItemRef item; - - OSStatus status = SecKeychainFindInternetPassword( - NULL, - strlen(server->host), server->host, - 0, NULL, - 0, NULL, - strlen(server->path), server->path, - server->port, - server->proto, - kSecAuthenticationTypeDefault, - secret_l, (void **)&tmp, - &item); - - if (status) { - return get_error(status); - } - - *secret = strdup(tmp); - SecKeychainItemFreeContent(NULL, tmp); - - SecKeychainAttributeList list; - SecKeychainAttribute attr; - - list.count = 1; - list.attr = &attr; - attr.tag = kSecAccountItemAttr; - - status = SecKeychainItemCopyContent(item, NULL, &list, NULL, NULL); - if (status) { - return get_error(status); - } - - *username = strdup(attr.data); - *username_l = attr.length; - SecKeychainItemFreeContent(&list, NULL); - - return NULL; -} - -char *keychain_delete(struct Server *server) { - SecKeychainItemRef item; - - OSStatus status = SecKeychainFindInternetPassword( - NULL, - strlen(server->host), server->host, - 0, NULL, - 0, NULL, - strlen(server->path), server->path, - server->port, - server->proto, - kSecAuthenticationTypeDefault, - 0, NULL, - &item); - - if (status) { - return get_error(status); - } - - status = SecKeychainItemDelete(item); - if (status) { - return get_error(status); - } - return NULL; -} - -char * CFStringToCharArr(CFStringRef aString) { - if (aString == NULL) { - return NULL; - } - CFIndex length = CFStringGetLength(aString); - CFIndex maxSize = - CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; - char *buffer = (char *)malloc(maxSize); - if (CFStringGetCString(aString, buffer, maxSize, - kCFStringEncodingUTF8)) { - return buffer; - } - return NULL; -} - -char *keychain_list(char *credsLabel, char *** paths, char *** accts, unsigned int *list_l) { - CFStringRef credsLabelCF = CFStringCreateWithCString(NULL, credsLabel, kCFStringEncodingUTF8); - CFMutableDictionaryRef query = CFDictionaryCreateMutable (NULL, 1, NULL, NULL); - CFDictionaryAddValue(query, kSecClass, kSecClassInternetPassword); - CFDictionaryAddValue(query, kSecReturnAttributes, kCFBooleanTrue); - CFDictionaryAddValue(query, kSecMatchLimit, kSecMatchLimitAll); - CFDictionaryAddValue(query, kSecAttrLabel, credsLabelCF); - //Use this query dictionary - CFTypeRef result= NULL; - OSStatus status = SecItemCopyMatching( - query, - &result); - - CFRelease(credsLabelCF); - - //Ran a search and store the results in result - if (status) { - return get_error(status); - } - CFIndex numKeys = CFArrayGetCount(result); - *paths = (char **) malloc((int)sizeof(char *)*numKeys); - *accts = (char **) malloc((int)sizeof(char *)*numKeys); - //result is of type CFArray - for(CFIndex i=0; i -*/ -import "C" -import ( - "errors" - "net/url" - "strconv" - "strings" - "unsafe" - - "github.com/docker/docker-credential-helpers/credentials" -) - -// errCredentialsNotFound is the specific error message returned by OS X -// when the credentials are not in the keychain. -const errCredentialsNotFound = "The specified item could not be found in the keychain." - -// Osxkeychain handles secrets using the OS X Keychain as store. -type Osxkeychain struct{} - -// Add adds new credentials to the keychain. -func (h Osxkeychain) Add(creds *credentials.Credentials) error { - h.Delete(creds.ServerURL) - - s, err := splitServer(creds.ServerURL) - if err != nil { - return err - } - defer freeServer(s) - - label := C.CString(credentials.CredsLabel) - defer C.free(unsafe.Pointer(label)) - username := C.CString(creds.Username) - defer C.free(unsafe.Pointer(username)) - secret := C.CString(creds.Secret) - defer C.free(unsafe.Pointer(secret)) - - errMsg := C.keychain_add(s, label, username, secret) - if errMsg != nil { - defer C.free(unsafe.Pointer(errMsg)) - return errors.New(C.GoString(errMsg)) - } - - return nil -} - -// Delete removes credentials from the keychain. -func (h Osxkeychain) Delete(serverURL string) error { - s, err := splitServer(serverURL) - if err != nil { - return err - } - defer freeServer(s) - - errMsg := C.keychain_delete(s) - if errMsg != nil { - defer C.free(unsafe.Pointer(errMsg)) - return errors.New(C.GoString(errMsg)) - } - - return nil -} - -// Get returns the username and secret to use for a given registry server URL. -func (h Osxkeychain) Get(serverURL string) (string, string, error) { - s, err := splitServer(serverURL) - if err != nil { - return "", "", err - } - defer freeServer(s) - - var usernameLen C.uint - var username *C.char - var secretLen C.uint - var secret *C.char - defer C.free(unsafe.Pointer(username)) - defer C.free(unsafe.Pointer(secret)) - - errMsg := C.keychain_get(s, &usernameLen, &username, &secretLen, &secret) - if errMsg != nil { - defer C.free(unsafe.Pointer(errMsg)) - goMsg := C.GoString(errMsg) - if goMsg == errCredentialsNotFound { - return "", "", credentials.NewErrCredentialsNotFound() - } - - return "", "", errors.New(goMsg) - } - - user := C.GoStringN(username, C.int(usernameLen)) - pass := C.GoStringN(secret, C.int(secretLen)) - return user, pass, nil -} - -// List returns the stored URLs and corresponding usernames. -func (h Osxkeychain) List() (map[string]string, error) { - credsLabelC := C.CString(credentials.CredsLabel) - defer C.free(unsafe.Pointer(credsLabelC)) - - var pathsC **C.char - defer C.free(unsafe.Pointer(pathsC)) - var acctsC **C.char - defer C.free(unsafe.Pointer(acctsC)) - var listLenC C.uint - errMsg := C.keychain_list(credsLabelC, &pathsC, &acctsC, &listLenC) - if errMsg != nil { - defer C.free(unsafe.Pointer(errMsg)) - goMsg := C.GoString(errMsg) - return nil, errors.New(goMsg) - } - - defer C.freeListData(&pathsC, listLenC) - defer C.freeListData(&acctsC, listLenC) - - var listLen int - listLen = int(listLenC) - pathTmp := (*[1 << 30]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen] - acctTmp := (*[1 << 30]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen] - //taking the array of c strings into go while ignoring all the stuff irrelevant to credentials-helper - resp := make(map[string]string) - for i := 0; i < listLen; i++ { - if C.GoString(pathTmp[i]) == "0" { - continue - } - resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i]) - } - return resp, nil -} - -func splitServer(serverURL string) (*C.struct_Server, error) { - u, err := parseURL(serverURL) - if err != nil { - return nil, err - } - - proto := C.kSecProtocolTypeHTTPS - if u.Scheme == "http" { - proto = C.kSecProtocolTypeHTTP - } - var port int - p := getPort(u) - if p != "" { - port, err = strconv.Atoi(p) - if err != nil { - return nil, err - } - } - - return &C.struct_Server{ - proto: C.SecProtocolType(proto), - host: C.CString(getHostname(u)), - port: C.uint(port), - path: C.CString(u.Path), - }, nil -} - -func freeServer(s *C.struct_Server) { - C.free(unsafe.Pointer(s.host)) - C.free(unsafe.Pointer(s.path)) -} - -// parseURL parses and validates a given serverURL to an url.URL, and -// returns an error if validation failed. Querystring parameters are -// omitted in the resulting URL, because they are not used in the helper. -// -// If serverURL does not have a valid scheme, `//` is used as scheme -// before parsing. This prevents the hostname being used as path, -// and the credentials being stored without host. -func parseURL(serverURL string) (*url.URL, error) { - // Check if serverURL has a scheme, otherwise add `//` as scheme. - if !strings.Contains(serverURL, "://") && !strings.HasPrefix(serverURL, "//") { - serverURL = "//" + serverURL - } - - u, err := url.Parse(serverURL) - if err != nil { - return nil, err - } - - if u.Scheme != "" && u.Scheme != "https" && u.Scheme != "http" { - return nil, errors.New("unsupported scheme: " + u.Scheme) - } - if getHostname(u) == "" { - return nil, errors.New("no hostname in URL") - } - - u.RawQuery = "" - return u, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h deleted file mode 100644 index c54e7d728..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin.h +++ /dev/null @@ -1,14 +0,0 @@ -#include - -struct Server { - SecProtocolType proto; - char *host; - char *path; - unsigned int port; -}; - -char *keychain_add(struct Server *server, char *label, char *username, char *secret); -char *keychain_get(struct Server *server, unsigned int *username_l, char **username, unsigned int *secret_l, char **secret); -char *keychain_delete(struct Server *server); -char *keychain_list(char *credsLabel, char *** data, char *** accts, unsigned int *list_l); -void freeListData(char *** data, unsigned int length); \ No newline at end of file diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin_test.go b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin_test.go deleted file mode 100644 index b74927ccb..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/osxkeychain_darwin_test.go +++ /dev/null @@ -1,253 +0,0 @@ -package osxkeychain - -import ( - "errors" - "fmt" - "github.com/docker/docker-credential-helpers/credentials" - "testing" -) - -func TestOSXKeychainHelper(t *testing.T) { - creds := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v1", - Username: "foobar", - Secret: "foobarbaz", - } - creds1 := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v2", - Username: "foobarbaz", - Secret: "foobar", - } - helper := Osxkeychain{} - if err := helper.Add(creds); err != nil { - t.Fatal(err) - } - - username, secret, err := helper.Get(creds.ServerURL) - if err != nil { - t.Fatal(err) - } - - if username != "foobar" { - t.Fatalf("expected %s, got %s\n", "foobar", username) - } - - if secret != "foobarbaz" { - t.Fatalf("expected %s, got %s\n", "foobarbaz", secret) - } - - auths, err := helper.List() - if err != nil || len(auths) == 0 { - t.Fatal(err) - } - - helper.Add(creds1) - defer helper.Delete(creds1.ServerURL) - newauths, err := helper.List() - if len(newauths)-len(auths) != 1 { - if err == nil { - t.Fatalf("Error: len(newauths): %d, len(auths): %d", len(newauths), len(auths)) - } - t.Fatalf("Error: len(newauths): %d, len(auths): %d\n Error= %v", len(newauths), len(auths), err) - } - - if err := helper.Delete(creds.ServerURL); err != nil { - t.Fatal(err) - } -} - -// TestOSXKeychainHelperParseURL verifies that a // "scheme" is added to URLs, -// and that invalid URLs produce an error. -func TestOSXKeychainHelperParseURL(t *testing.T) { - tests := []struct { - url string - expectedURL string - err error - }{ - {url: "foobar.docker.io", expectedURL: "//foobar.docker.io"}, - {url: "foobar.docker.io:2376", expectedURL: "//foobar.docker.io:2376"}, - {url: "//foobar.docker.io:2376", expectedURL: "//foobar.docker.io:2376"}, - {url: "http://foobar.docker.io:2376", expectedURL: "http://foobar.docker.io:2376"}, - {url: "https://foobar.docker.io:2376", expectedURL: "https://foobar.docker.io:2376"}, - {url: "https://foobar.docker.io:2376/some/path", expectedURL: "https://foobar.docker.io:2376/some/path"}, - {url: "https://foobar.docker.io:2376/some/other/path?foo=bar", expectedURL: "https://foobar.docker.io:2376/some/other/path"}, - {url: "/foobar.docker.io", err: errors.New("no hostname in URL")}, - {url: "ftp://foobar.docker.io:2376", err: errors.New("unsupported scheme: ftp")}, - } - - for _, te := range tests { - u, err := parseURL(te.url) - - if te.err == nil && err != nil { - t.Errorf("Error: failed to parse URL %q: %s", te.url, err) - continue - } - if te.err != nil && err == nil { - t.Errorf("Error: expected error %q, got none when parsing URL %q", te.err, te.url) - continue - } - if te.err != nil && err.Error() != te.err.Error() { - t.Errorf("Error: expected error %q, got %q when parsing URL %q", te.err, err, te.url) - continue - } - if u != nil && u.String() != te.expectedURL { - t.Errorf("Error: expected URL: %q, but got %q for URL: %q", te.expectedURL, u.String(), te.url) - } - } -} - -// TestOSXKeychainHelperRetrieveAliases verifies that secrets can be accessed -// through variations on the URL -func TestOSXKeychainHelperRetrieveAliases(t *testing.T) { - tests := []struct { - storeURL string - readURL string - }{ - // stored with port, retrieved without - {"https://foobar.docker.io:2376", "https://foobar.docker.io"}, - - // stored as https, retrieved without scheme - {"https://foobar.docker.io:2376", "foobar.docker.io"}, - - // stored with path, retrieved without - {"https://foobar.docker.io:1234/one/two", "https://foobar.docker.io:1234"}, - } - - helper := Osxkeychain{} - defer func() { - for _, te := range tests { - helper.Delete(te.storeURL) - } - }() - - // Clean store before testing. - for _, te := range tests { - helper.Delete(te.storeURL) - } - - for _, te := range tests { - c := &credentials.Credentials{ServerURL: te.storeURL, Username: "hello", Secret: "world"} - if err := helper.Add(c); err != nil { - t.Errorf("Error: failed to store secret for URL %q: %s", te.storeURL, err) - continue - } - if _, _, err := helper.Get(te.readURL); err != nil { - t.Errorf("Error: failed to read secret for URL %q using %q", te.storeURL, te.readURL) - } - helper.Delete(te.storeURL) - } -} - -// TestOSXKeychainHelperRetrieveStrict verifies that only matching secrets are -// returned. -func TestOSXKeychainHelperRetrieveStrict(t *testing.T) { - tests := []struct { - storeURL string - readURL string - }{ - // stored as https, retrieved using http - {"https://foobar.docker.io:2376", "http://foobar.docker.io:2376"}, - - // stored as http, retrieved using https - {"http://foobar.docker.io:2376", "https://foobar.docker.io:2376"}, - - // same: stored as http, retrieved without a scheme specified (hence, using the default https://) - {"http://foobar.docker.io", "foobar.docker.io:5678"}, - - // non-matching ports - {"https://foobar.docker.io:1234", "https://foobar.docker.io:5678"}, - - // non-matching ports TODO is this desired behavior? The other way round does work - //{"https://foobar.docker.io", "https://foobar.docker.io:5678"}, - - // non-matching paths - {"https://foobar.docker.io:1234/one/two", "https://foobar.docker.io:1234/five/six"}, - } - - helper := Osxkeychain{} - defer func() { - for _, te := range tests { - helper.Delete(te.storeURL) - } - }() - - // Clean store before testing. - for _, te := range tests { - helper.Delete(te.storeURL) - } - - for _, te := range tests { - c := &credentials.Credentials{ServerURL: te.storeURL, Username: "hello", Secret: "world"} - if err := helper.Add(c); err != nil { - t.Errorf("Error: failed to store secret for URL %q: %s", te.storeURL, err) - continue - } - if _, _, err := helper.Get(te.readURL); err == nil { - t.Errorf("Error: managed to read secret for URL %q using %q, but should not be able to", te.storeURL, te.readURL) - } - helper.Delete(te.storeURL) - } -} - -// TestOSXKeychainHelperStoreRetrieve verifies that secrets stored in the -// the keychain can be read back using the URL that was used to store them. -func TestOSXKeychainHelperStoreRetrieve(t *testing.T) { - tests := []struct { - url string - }{ - {url: "foobar.docker.io"}, - {url: "foobar.docker.io:2376"}, - {url: "//foobar.docker.io:2376"}, - {url: "https://foobar.docker.io:2376"}, - {url: "http://foobar.docker.io:2376"}, - {url: "https://foobar.docker.io:2376/some/path"}, - {url: "https://foobar.docker.io:2376/some/other/path"}, - {url: "https://foobar.docker.io:2376/some/other/path?foo=bar"}, - } - - helper := Osxkeychain{} - defer func() { - for _, te := range tests { - helper.Delete(te.url) - } - }() - - // Clean store before testing. - for _, te := range tests { - helper.Delete(te.url) - } - - // Note that we don't delete between individual tests here, to verify that - // subsequent stores/overwrites don't affect storing / retrieving secrets. - for i, te := range tests { - c := &credentials.Credentials{ - ServerURL: te.url, - Username: fmt.Sprintf("user-%d", i), - Secret: fmt.Sprintf("secret-%d", i), - } - - if err := helper.Add(c); err != nil { - t.Errorf("Error: failed to store secret for URL: %s: %s", te.url, err) - continue - } - user, secret, err := helper.Get(te.url) - if err != nil { - t.Errorf("Error: failed to read secret for URL %q: %s", te.url, err) - continue - } - if user != c.Username { - t.Errorf("Error: expected username %s, got username %s for URL: %s", c.Username, user, te.url) - } - if secret != c.Secret { - t.Errorf("Error: expected secret %s, got secret %s for URL: %s", c.Secret, secret, te.url) - } - } -} - -func TestMissingCredentials(t *testing.T) { - helper := Osxkeychain{} - _, _, err := helper.Get("https://adsfasdf.wrewerwer.com/asdfsdddd") - if !credentials.IsErrCredentialsNotFound(err) { - t.Fatalf("expected ErrCredentialsNotFound, got %v", err) - } -} diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_go18.go b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_go18.go deleted file mode 100644 index 0b7297d2f..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_go18.go +++ /dev/null @@ -1,13 +0,0 @@ -//+build go1.8 - -package osxkeychain - -import "net/url" - -func getHostname(u *url.URL) string { - return u.Hostname() -} - -func getPort(u *url.URL) string { - return u.Port() -} diff --git a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_non_go18.go b/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_non_go18.go deleted file mode 100644 index bdf9b7b00..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/osxkeychain/url_non_go18.go +++ /dev/null @@ -1,41 +0,0 @@ -//+build !go1.8 - -package osxkeychain - -import ( - "net/url" - "strings" -) - -func getHostname(u *url.URL) string { - return stripPort(u.Host) -} - -func getPort(u *url.URL) string { - return portOnly(u.Host) -} - -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} - -func portOnly(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return "" - } - if i := strings.Index(hostport, "]:"); i != -1 { - return hostport[i+len("]:"):] - } - if strings.Contains(hostport, "]") { - return "" - } - return hostport[colon+len(":"):] -} diff --git a/vendor/github.com/docker/docker-credential-helpers/pass/cmd/main_linux.go b/vendor/github.com/docker/docker-credential-helpers/pass/cmd/main_linux.go deleted file mode 100644 index 4fe7c1edb..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/pass/cmd/main_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/docker/docker-credential-helpers/credentials" - "github.com/docker/docker-credential-helpers/pass" -) - -func main() { - credentials.Serve(pass.Pass{}) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux.go b/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux.go deleted file mode 100644 index 940323658..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux.go +++ /dev/null @@ -1,221 +0,0 @@ -// A `pass` based credential helper. Passwords are stored as arguments to pass -// of the form: "$PASS_FOLDER/base64-url(serverURL)/username". We base64-url -// encode the serverURL, because under the hood pass uses files and folders, so -// /s will get translated into additional folders. -package pass - -import ( - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path" - "strings" - - "github.com/docker/docker-credential-helpers/credentials" -) - -const PASS_FOLDER = "docker-credential-helpers" - -var ( - PassInitialized bool -) - -func init() { - PassInitialized = exec.Command("pass").Run() == nil -} - -func runPass(stdinContent string, args ...string) (string, error) { - cmd := exec.Command("pass", args...) - - stdin, err := cmd.StdinPipe() - if err != nil { - return "", err - } - defer stdin.Close() - - stderr, err := cmd.StderrPipe() - if err != nil { - return "", err - } - defer stderr.Close() - - stdout, err := cmd.StdoutPipe() - if err != nil { - return "", err - } - defer stdout.Close() - - err = cmd.Start() - if err != nil { - return "", err - } - - _, err = stdin.Write([]byte(stdinContent)) - if err != nil { - return "", err - } - stdin.Close() - - errContent, err := ioutil.ReadAll(stderr) - if err != nil { - return "", fmt.Errorf("error reading stderr: %s", err) - } - - result, err := ioutil.ReadAll(stdout) - if err != nil { - return "", fmt.Errorf("Error reading stdout: %s", err) - } - - cmdErr := cmd.Wait() - if cmdErr != nil { - return "", fmt.Errorf("%s: %s", cmdErr, errContent) - } - - return string(result), nil -} - -// Pass handles secrets using Linux secret-service as a store. -type Pass struct{} - -// Add adds new credentials to the keychain. -func (h Pass) Add(creds *credentials.Credentials) error { - if !PassInitialized { - return errors.New("pass store is uninitialized") - } - - if creds == nil { - return errors.New("missing credentials") - } - - encoded := base64.URLEncoding.EncodeToString([]byte(creds.ServerURL)) - - _, err := runPass(creds.Secret, "insert", "-f", "-m", path.Join(PASS_FOLDER, encoded, creds.Username)) - return err -} - -// Delete removes credentials from the store. -func (h Pass) Delete(serverURL string) error { - if !PassInitialized { - return errors.New("pass store is uninitialized") - } - - if serverURL == "" { - return errors.New("missing server url") - } - - encoded := base64.URLEncoding.EncodeToString([]byte(serverURL)) - _, err := runPass("", "rm", "-rf", path.Join(PASS_FOLDER, encoded)) - return err -} - -func getPassDir() string { - passDir := os.ExpandEnv("$HOME/.password-store") - for _, e := range os.Environ() { - parts := strings.SplitN(e, "=", 2) - if len(parts) < 2 { - continue - } - - if parts[0] != "PASSWORD_STORE_DIR" { - continue - } - - passDir = parts[1] - break - } - - return passDir -} - -// listPassDir lists all the contents of a directory in the password store. -// Pass uses fancy unicode to emit stuff to stdout, so rather than try -// and parse this, let's just look at the directory structure instead. -func listPassDir(args ...string) ([]os.FileInfo, error) { - passDir := getPassDir() - p := path.Join(append([]string{passDir, PASS_FOLDER}, args...)...) - contents, err := ioutil.ReadDir(p) - if err != nil { - if os.IsNotExist(err) { - return []os.FileInfo{}, nil - } - - return nil, err - } - - return contents, nil -} - -// Get returns the username and secret to use for a given registry server URL. -func (h Pass) Get(serverURL string) (string, string, error) { - if !PassInitialized { - return "", "", errors.New("pass store is uninitialized") - } - - if serverURL == "" { - return "", "", errors.New("missing server url") - } - - encoded := base64.URLEncoding.EncodeToString([]byte(serverURL)) - - if _, err := os.Stat(path.Join(getPassDir(), PASS_FOLDER, encoded)); err != nil { - if os.IsNotExist(err) { - return "", "", nil; - } - - return "", "", err - } - - usernames, err := listPassDir(encoded) - if err != nil { - return "", "", err - } - - if len(usernames) < 1 { - return "", "", fmt.Errorf("no usernames for %s", serverURL) - } - - actual := strings.TrimSuffix(usernames[0].Name(), ".gpg") - secret, err := runPass("", "show", path.Join(PASS_FOLDER, encoded, actual)) - return actual, secret, err -} - -// List returns the stored URLs and corresponding usernames for a given credentials label -func (h Pass) List() (map[string]string, error) { - if !PassInitialized { - return nil, errors.New("pass store is uninitialized") - } - - servers, err := listPassDir() - if err != nil { - return nil, err - } - - resp := map[string]string{} - - for _, server := range servers { - if !server.IsDir() { - continue - } - - serverURL, err := base64.URLEncoding.DecodeString(server.Name()) - if err != nil { - return nil, err - } - - usernames, err := listPassDir(server.Name()) - if err != nil { - return nil, err - } - - if len(usernames) < 1 { - return nil, fmt.Errorf("no usernames for %s", serverURL) - } - - resp[string(serverURL)] = strings.TrimSuffix(usernames[0].Name(), ".gpg") - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux_test.go b/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux_test.go deleted file mode 100644 index d342b6115..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/pass/pass_linux_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package pass - -import ( - "strings" - "testing" - - "github.com/docker/docker-credential-helpers/credentials" -) - -func TestPassHelper(t *testing.T) { - helper := Pass{} - - creds := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v1", - Username: "nothing", - Secret: "isthebestmeshuggahalbum", - } - - helper.Add(creds) - - creds.ServerURL = "https://foobar.docker.io:9999/v2" - helper.Add(creds) - - credsList, err := helper.List() - if err != nil { - t.Fatal(err) - } - - for server, username := range credsList { - if !(strings.Contains(server, "2376") || - strings.Contains(server, "9999")) { - t.Fatalf("invalid url: %s", creds.ServerURL) - } - - if username != "nothing" { - t.Fatalf("invalid username: %v", username) - } - - u, s, err := helper.Get(server) - if err != nil { - t.Fatal(err) - } - - if u != username { - t.Fatalf("invalid username %s", u) - } - - if s != "isthebestmeshuggahalbum" { - t.Fatalf("invalid secret: %s", s) - } - - err = helper.Delete(server) - if err != nil { - t.Fatal(err) - } - - username, _, err = helper.Get(server) - if err != nil { - t.Fatal(err) - } - - if username != "" { - t.Fatalf("%s shouldn't exist any more", username) - } - } - - credsList, err = helper.List() - if err != nil { - t.Fatal(err) - } - - if len(credsList) != 0 { - t.Fatal("didn't delete all creds?") - } -} diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/cmd/main_linux.go b/vendor/github.com/docker/docker-credential-helpers/secretservice/cmd/main_linux.go deleted file mode 100644 index 6965ca75a..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/secretservice/cmd/main_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/docker/docker-credential-helpers/credentials" - "github.com/docker/docker-credential-helpers/secretservice" -) - -func main() { - credentials.Serve(secretservice.Secretservice{}) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c deleted file mode 100644 index 35dea92da..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.c +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include -#include "secretservice_linux.h" - -const SecretSchema *docker_get_schema(void) -{ - static const SecretSchema docker_schema = { - "io.docker.Credentials", SECRET_SCHEMA_NONE, - { - { "label", SECRET_SCHEMA_ATTRIBUTE_STRING }, - { "server", SECRET_SCHEMA_ATTRIBUTE_STRING }, - { "username", SECRET_SCHEMA_ATTRIBUTE_STRING }, - { "docker_cli", SECRET_SCHEMA_ATTRIBUTE_STRING }, - { "NULL", 0 }, - } - }; - return &docker_schema; -} - -GError *add(char *label, char *server, char *username, char *secret) { - GError *err = NULL; - - secret_password_store_sync (DOCKER_SCHEMA, SECRET_COLLECTION_DEFAULT, - server, secret, NULL, &err, - "label", label, - "server", server, - "username", username, - "docker_cli", "1", - NULL); - return err; -} - -GError *delete(char *server) { - GError *err = NULL; - - secret_password_clear_sync(DOCKER_SCHEMA, NULL, &err, - "server", server, - "docker_cli", "1", - NULL); - if (err != NULL) - return err; - return NULL; -} - -char *get_attribute(const char *attribute, SecretItem *item) { - GHashTable *attributes; - GHashTableIter iter; - gchar *value, *key; - - attributes = secret_item_get_attributes(item); - g_hash_table_iter_init(&iter, attributes); - while (g_hash_table_iter_next(&iter, (void **)&key, (void **)&value)) { - if (strncmp(key, attribute, strlen(key)) == 0) - return (char *)value; - } - g_hash_table_unref(attributes); - return NULL; -} - -GError *get(char *server, char **username, char **secret) { - GError *err = NULL; - GHashTable *attributes; - SecretService *service; - GList *items, *l; - SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK; - SecretValue *secretValue; - gsize length; - gchar *value; - - attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); - g_hash_table_insert(attributes, g_strdup("server"), g_strdup(server)); - g_hash_table_insert(attributes, g_strdup("docker_cli"), g_strdup("1")); - - service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err); - if (err == NULL) { - items = secret_service_search_sync(service, DOCKER_SCHEMA, attributes, flags, NULL, &err); - if (err == NULL) { - for (l = items; l != NULL; l = g_list_next(l)) { - value = secret_item_get_schema_name(l->data); - if (strncmp(value, "io.docker.Credentials", strlen(value)) != 0) { - g_free(value); - continue; - } - g_free(value); - secretValue = secret_item_get_secret(l->data); - if (secret != NULL) { - *secret = strdup(secret_value_get(secretValue, &length)); - secret_value_unref(secretValue); - } - *username = get_attribute("username", l->data); - } - g_list_free_full(items, g_object_unref); - } - g_object_unref(service); - } - g_hash_table_unref(attributes); - if (err != NULL) { - return err; - } - return NULL; -} - -GError *list(char *ref_label, char *** paths, char *** accts, unsigned int *list_l) { - GList *items; - GError *err = NULL; - SecretService *service; - SecretSearchFlags flags = SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK; - GHashTable *attributes = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); - - // List credentials with the right label only - g_hash_table_insert(attributes, g_strdup("label"), g_strdup(ref_label)); - - service = secret_service_get_sync(SECRET_SERVICE_NONE, NULL, &err); - if (err != NULL) { - return err; - } - - items = secret_service_search_sync(service, NULL, attributes, flags, NULL, &err); - int numKeys = g_list_length(items); - if (err != NULL) { - return err; - } - - char **tmp_paths = (char **) calloc(1,(int)sizeof(char *)*numKeys); - char **tmp_accts = (char **) calloc(1,(int)sizeof(char *)*numKeys); - - // items now contains our keys from the gnome keyring - // we will now put it in our two lists to return it to go - GList *current; - int listNumber = 0; - for(current = items; current!=NULL; current = current->next) { - char *pathTmp = secret_item_get_label(current->data); - // you cannot have a key without a label in the gnome keyring - char *acctTmp = get_attribute("username",current->data); - if (acctTmp==NULL) { - acctTmp = "account not defined"; - } - - tmp_paths[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(pathTmp)+1)); - tmp_accts[listNumber] = (char *) calloc(1, sizeof(char)*(strlen(acctTmp)+1)); - - memcpy(tmp_paths[listNumber], pathTmp, sizeof(char)*(strlen(pathTmp)+1)); - memcpy(tmp_accts[listNumber], acctTmp, sizeof(char)*(strlen(acctTmp)+1)); - - listNumber = listNumber + 1; - } - - *paths = (char **) realloc(tmp_paths, (int)sizeof(char *)*listNumber); - *accts = (char **) realloc(tmp_accts, (int)sizeof(char *)*listNumber); - - *list_l = listNumber; - - return NULL; -} - -void freeListData(char *** data, unsigned int length) { - int i; - for(i=0; i -*/ -import "C" -import ( - "errors" - "unsafe" - - "github.com/docker/docker-credential-helpers/credentials" -) - -// Secretservice handles secrets using Linux secret-service as a store. -type Secretservice struct{} - -// Add adds new credentials to the keychain. -func (h Secretservice) Add(creds *credentials.Credentials) error { - if creds == nil { - return errors.New("missing credentials") - } - credsLabel := C.CString(credentials.CredsLabel) - defer C.free(unsafe.Pointer(credsLabel)) - server := C.CString(creds.ServerURL) - defer C.free(unsafe.Pointer(server)) - username := C.CString(creds.Username) - defer C.free(unsafe.Pointer(username)) - secret := C.CString(creds.Secret) - defer C.free(unsafe.Pointer(secret)) - - if err := C.add(credsLabel, server, username, secret); err != nil { - defer C.g_error_free(err) - errMsg := (*C.char)(unsafe.Pointer(err.message)) - return errors.New(C.GoString(errMsg)) - } - return nil -} - -// Delete removes credentials from the store. -func (h Secretservice) Delete(serverURL string) error { - if serverURL == "" { - return errors.New("missing server url") - } - server := C.CString(serverURL) - defer C.free(unsafe.Pointer(server)) - - if err := C.delete(server); err != nil { - defer C.g_error_free(err) - errMsg := (*C.char)(unsafe.Pointer(err.message)) - return errors.New(C.GoString(errMsg)) - } - return nil -} - -// Get returns the username and secret to use for a given registry server URL. -func (h Secretservice) Get(serverURL string) (string, string, error) { - if serverURL == "" { - return "", "", errors.New("missing server url") - } - var username *C.char - defer C.free(unsafe.Pointer(username)) - var secret *C.char - defer C.free(unsafe.Pointer(secret)) - server := C.CString(serverURL) - defer C.free(unsafe.Pointer(server)) - - err := C.get(server, &username, &secret) - if err != nil { - defer C.g_error_free(err) - errMsg := (*C.char)(unsafe.Pointer(err.message)) - return "", "", errors.New(C.GoString(errMsg)) - } - user := C.GoString(username) - pass := C.GoString(secret) - if pass == "" { - return "", "", credentials.NewErrCredentialsNotFound() - } - return user, pass, nil -} - -// List returns the stored URLs and corresponding usernames for a given credentials label -func (h Secretservice) List() (map[string]string, error) { - credsLabelC := C.CString(credentials.CredsLabel) - defer C.free(unsafe.Pointer(credsLabelC)) - - var pathsC **C.char - defer C.free(unsafe.Pointer(pathsC)) - var acctsC **C.char - defer C.free(unsafe.Pointer(acctsC)) - var listLenC C.uint - err := C.list(credsLabelC, &pathsC, &acctsC, &listLenC) - if err != nil { - defer C.free(unsafe.Pointer(err)) - return nil, errors.New("Error from list function in secretservice_linux.c likely due to error in secretservice library") - } - defer C.freeListData(&pathsC, listLenC) - defer C.freeListData(&acctsC, listLenC) - - resp := make(map[string]string) - - listLen := int(listLenC) - if listLen == 0 { - return resp, nil - } - // The maximum capacity of the following two slices is limited to (2^29)-1 to remain compatible - // with 32-bit platforms. The size of a `*C.char` (a pointer) is 4 Byte on a 32-bit system - // and (2^29)*4 == math.MaxInt32 + 1. -- See issue golang/go#13656 - pathTmp := (*[(1 << 29) - 1]*C.char)(unsafe.Pointer(pathsC))[:listLen:listLen] - acctTmp := (*[(1 << 29) - 1]*C.char)(unsafe.Pointer(acctsC))[:listLen:listLen] - for i := 0; i < listLen; i++ { - resp[C.GoString(pathTmp[i])] = C.GoString(acctTmp[i]) - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h deleted file mode 100644 index a28179db3..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux.h +++ /dev/null @@ -1,13 +0,0 @@ -#define SECRET_WITH_UNSTABLE 1 -#define SECRET_API_SUBJECT_TO_CHANGE 1 -#include - -const SecretSchema *docker_get_schema(void) G_GNUC_CONST; - -#define DOCKER_SCHEMA docker_get_schema() - -GError *add(char *label, char *server, char *username, char *secret); -GError *delete(char *server); -GError *get(char *server, char **username, char **secret); -GError *list(char *label, char *** paths, char *** accts, unsigned int *list_l); -void freeListData(char *** data, unsigned int length); diff --git a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux_test.go b/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux_test.go deleted file mode 100644 index 8c7839daf..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/secretservice/secretservice_linux_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package secretservice - -import ( - "strings" - "testing" - - "github.com/docker/docker-credential-helpers/credentials" -) - -func TestSecretServiceHelper(t *testing.T) { - t.Skip("test requires gnome-keyring but travis CI doesn't have it") - - creds := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v1", - Username: "foobar", - Secret: "foobarbaz", - } - - helper := Secretservice{} - - // Check how many docker credentials we have when starting the test - old_auths, err := helper.List() - if err != nil { - t.Fatal(err) - } - - // If any docker credentials with the tests values we are providing, we - // remove them as they probably come from a previous failed test - for k, v := range old_auths { - if strings.Compare(k, creds.ServerURL) == 0 && strings.Compare(v, creds.Username) == 0 { - - if err := helper.Delete(creds.ServerURL); err != nil { - t.Fatal(err) - } - } - } - - // Check again how many docker credentials we have when starting the test - old_auths, err = helper.List() - if err != nil { - t.Fatal(err) - } - - // Add new credentials - if err := helper.Add(creds); err != nil { - t.Fatal(err) - } - - // Verify that it is inside the secret service store - username, secret, err := helper.Get(creds.ServerURL) - if err != nil { - t.Fatal(err) - } - - if username != "foobar" { - t.Fatalf("expected %s, got %s\n", "foobar", username) - } - - if secret != "foobarbaz" { - t.Fatalf("expected %s, got %s\n", "foobarbaz", secret) - } - - // We should have one more credential than before adding - new_auths, err := helper.List() - if err != nil || (len(new_auths)-len(old_auths) != 1) { - t.Fatal(err) - } - old_auths = new_auths - - // Deleting the credentials associated to current server url should succeed - if err := helper.Delete(creds.ServerURL); err != nil { - t.Fatal(err) - } - - // We should have one less credential than before deleting - new_auths, err = helper.List() - if err != nil || (len(old_auths)-len(new_auths) != 1) { - t.Fatal(err) - } -} - -func TestMissingCredentials(t *testing.T) { - t.Skip("test requires gnome-keyring but travis CI doesn't have it") - - helper := Secretservice{} - _, _, err := helper.Get("https://adsfasdf.wrewerwer.com/asdfsdddd") - if !credentials.IsErrCredentialsNotFound(err) { - t.Fatalf("expected ErrCredentialsNotFound, got %v", err) - } -} diff --git a/vendor/github.com/docker/docker-credential-helpers/wincred/cmd/main_windows.go b/vendor/github.com/docker/docker-credential-helpers/wincred/cmd/main_windows.go deleted file mode 100644 index c0b797fb3..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/wincred/cmd/main_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "github.com/docker/docker-credential-helpers/credentials" - "github.com/docker/docker-credential-helpers/wincred" -) - -func main() { - credentials.Serve(wincred.Wincred{}) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows.go b/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows.go deleted file mode 100644 index dcfa123a3..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows.go +++ /dev/null @@ -1,74 +0,0 @@ -package wincred - -import ( - "bytes" - "strings" - - winc "github.com/danieljoos/wincred" - "github.com/docker/docker-credential-helpers/credentials" -) - -// Wincred handles secrets using the Windows credential service. -type Wincred struct{} - -// Add adds new credentials to the windows credentials manager. -func (h Wincred) Add(creds *credentials.Credentials) error { - g := winc.NewGenericCredential(creds.ServerURL) - g.UserName = creds.Username - g.CredentialBlob = []byte(creds.Secret) - g.Persist = winc.PersistLocalMachine - g.Attributes = []winc.CredentialAttribute{{"label", []byte(credentials.CredsLabel)}} - - return g.Write() -} - -// Delete removes credentials from the windows credentials manager. -func (h Wincred) Delete(serverURL string) error { - g, err := winc.GetGenericCredential(serverURL) - if g == nil { - return nil - } - if err != nil { - return err - } - return g.Delete() -} - -// Get retrieves credentials from the windows credentials manager. -func (h Wincred) Get(serverURL string) (string, string, error) { - g, _ := winc.GetGenericCredential(serverURL) - if g == nil { - return "", "", credentials.NewErrCredentialsNotFound() - } - for _, attr := range g.Attributes { - if strings.Compare(attr.Keyword, "label") == 0 && - bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { - - return g.UserName, string(g.CredentialBlob), nil - } - } - return "", "", credentials.NewErrCredentialsNotFound() -} - -// List returns the stored URLs and corresponding usernames for a given credentials label. -func (h Wincred) List() (map[string]string, error) { - creds, err := winc.List() - if err != nil { - return nil, err - } - - resp := make(map[string]string) - for i := range creds { - attrs := creds[i].Attributes - for _, attr := range attrs { - if strings.Compare(attr.Keyword, "label") == 0 && - bytes.Compare(attr.Value, []byte(credentials.CredsLabel)) == 0 { - - resp[creds[i].TargetName] = creds[i].UserName - } - } - - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows_test.go b/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows_test.go deleted file mode 100644 index 4421fb1ed..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/wincred/wincred_windows_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package wincred - -import ( - "strings" - "testing" - - "github.com/docker/docker-credential-helpers/credentials" -) - -func TestWinCredHelper(t *testing.T) { - creds := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v1", - Username: "foobar", - Secret: "foobarbaz", - } - creds1 := &credentials.Credentials{ - ServerURL: "https://foobar.docker.io:2376/v2", - Username: "foobarbaz", - Secret: "foobar", - } - - helper := Wincred{} - - // check for and remove remaining credentials from previous fail tests - oldauths, err := helper.List() - if err != nil { - t.Fatal(err) - } - - for k, v := range oldauths { - if strings.Compare(k, creds.ServerURL) == 0 && strings.Compare(v, creds.Username) == 0 { - if err := helper.Delete(creds.ServerURL); err != nil { - t.Fatal(err) - } - } else if strings.Compare(k, creds1.ServerURL) == 0 && strings.Compare(v, creds1.Username) == 0 { - if err := helper.Delete(creds1.ServerURL); err != nil { - t.Fatal(err) - } - } - } - - // recount for credentials - oldauths, err = helper.List() - if err != nil { - t.Fatal(err) - } - - if err := helper.Add(creds); err != nil { - t.Fatal(err) - } - - username, secret, err := helper.Get(creds.ServerURL) - if err != nil { - t.Fatal(err) - } - - if username != "foobar" { - t.Fatalf("expected %s, got %s\n", "foobar", username) - } - - if secret != "foobarbaz" { - t.Fatalf("expected %s, got %s\n", "foobarbaz", secret) - } - - auths, err := helper.List() - if err != nil || len(auths)-len(oldauths) != 1 { - t.Fatal(err) - } - - helper.Add(creds1) - defer helper.Delete(creds1.ServerURL) - newauths, err := helper.List() - if err != nil { - t.Fatal(err) - } - - if len(newauths)-len(auths) != 1 { - if err == nil { - t.Fatalf("Error: len(newauths): %d, len(auths): %d", len(newauths), len(auths)) - } - t.Fatalf("Error: len(newauths): %d, len(auths): %d\n Error= %v", len(newauths), len(auths), err) - } - - if err := helper.Delete(creds.ServerURL); err != nil { - t.Fatal(err) - } -} - -func TestMissingCredentials(t *testing.T) { - helper := Wincred{} - _, _, err := helper.Get("https://adsfasdf.wrewerwer.com/asdfsdddd") - if !credentials.IsErrCredentialsNotFound(err) { - t.Fatalf("expected ErrCredentialsNotFound, got %v", err) - } -} diff --git a/vendor/github.com/docker/libnetwork/agent.go b/vendor/github.com/docker/libnetwork/agent.go index 1328f0bad..b0d66476e 100644 --- a/vendor/github.com/docker/libnetwork/agent.go +++ b/vendor/github.com/docker/libnetwork/agent.go @@ -892,13 +892,13 @@ func (c *controller) handleEpTableEvent(ev events.Event) { if svcID != "" { // This is a remote task part of a service if err := c.addServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err) + logrus.Errorf("failed adding service binding for %s epRec:%v err:%v", eid, epRec, err) return } } else { // This is a remote container simply attached to an attachable network if err := c.addContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err) + logrus.Errorf("failed adding container name resolution for %s epRec:%v err:%v", eid, epRec, err) } } } else { @@ -906,13 +906,13 @@ func (c *controller) handleEpTableEvent(ev events.Event) { if svcID != "" { // This is a remote task part of a service if err := c.rmServiceBinding(svcName, svcID, nid, eid, containerName, vip, ingressPorts, serviceAliases, taskAliases, ip, "handleEpTableEvent", true); err != nil { - logrus.Errorf("failed removing service binding for %s epRec:%v err:%s", eid, epRec, err) + logrus.Errorf("failed removing service binding for %s epRec:%v err:%v", eid, epRec, err) return } } else { // This is a remote container simply attached to an attachable network if err := c.delContainerNameResolution(nid, eid, containerName, taskAliases, ip, "handleEpTableEvent"); err != nil { - logrus.Errorf("failed adding service binding for %s epRec:%v err:%s", eid, epRec, err) + logrus.Errorf("failed removing container name resolution for %s epRec:%v err:%v", eid, epRec, err) } } } diff --git a/vendor/github.com/docker/libnetwork/circle.yml b/vendor/github.com/docker/libnetwork/circle.yml index e1d6aeeda..9ff2fc7bc 100644 --- a/vendor/github.com/docker/libnetwork/circle.yml +++ b/vendor/github.com/docker/libnetwork/circle.yml @@ -12,3 +12,5 @@ dependencies: test: override: - make circle-ci + post: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/docker/libnetwork/common/setmatrix_test.go b/vendor/github.com/docker/libnetwork/common/setmatrix_test.go index d87ffc7df..875bbfbf7 100644 --- a/vendor/github.com/docker/libnetwork/common/setmatrix_test.go +++ b/vendor/github.com/docker/libnetwork/common/setmatrix_test.go @@ -3,6 +3,7 @@ package common import ( "context" "strconv" + "strings" "testing" "time" @@ -66,6 +67,23 @@ func TestSetSerialInsertDelete(t *testing.T) { if !b || i != 4 { t.Fatalf("error in cardinality count %t %d", b, i) } + keys := s.Keys() + if len(keys) != 1 { + t.Fatalf("error in keys %v", keys) + } + str, b := s.String("a") + if !b || + !strings.Contains(str, "1") || + !strings.Contains(str, "2") || + !strings.Contains(str, "3") || + !strings.Contains(str, "4") { + t.Fatalf("error in string %t %s", b, str) + } + + _, b = s.Get("a") + if !b { + t.Fatalf("error in get %t", b) + } b, i = s.Remove("a", "1") if !b || i != 3 { @@ -96,6 +114,27 @@ func TestSetSerialInsertDelete(t *testing.T) { if b || i != 0 { t.Fatalf("error in cardinality count %t %d", b, i) } + + str, b = s.String("a") + if b || str != "" { + t.Fatalf("error in string %t %s", b, str) + } + + keys = s.Keys() + if len(keys) > 0 { + t.Fatalf("error in keys %v", keys) + } + + // Negative tests + _, b = s.Get("not exists") + if b { + t.Fatalf("error should not happen %t", b) + } + + b1, b := s.Contains("not exists", "a") + if b1 || b { + t.Fatalf("error should not happen %t %t", b1, b) + } } func insertDeleteRotuine(ctx context.Context, endCh chan int, s SetMatrix, key, value string) { diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go index cded48af6..83bee5ad9 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/joinleave_windows.go @@ -39,6 +39,11 @@ func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, if err := jinfo.AddTableEntry(ovPeerTable, eid, buf); err != nil { logrus.Errorf("overlay: Failed adding table entry to joininfo: %v", err) } + + if ep.disablegateway { + jinfo.DisableGatewayService() + } + return nil } diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go index 47af64cb9..b7bda4a6b 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_endpoint_windows.go @@ -6,7 +6,11 @@ import ( "net" "github.com/Microsoft/hcsshim" + "github.com/docker/docker/pkg/system" "github.com/docker/libnetwork/driverapi" + "github.com/docker/libnetwork/drivers/windows" + "github.com/docker/libnetwork/netlabel" + "github.com/docker/libnetwork/types" "github.com/sirupsen/logrus" ) @@ -15,12 +19,14 @@ type endpointTable map[string]*endpoint const overlayEndpointPrefix = "overlay/endpoint" type endpoint struct { - id string - nid string - profileId string - remote bool - mac net.HardwareAddr - addr *net.IPNet + id string + nid string + profileID string + remote bool + mac net.HardwareAddr + addr *net.IPNet + disablegateway bool + portMapping []types.PortBinding // Operation port bindings } func validateID(nid, eid string) error { @@ -71,7 +77,7 @@ func (n *network) removeEndpointWithAddress(addr *net.IPNet) { if networkEndpoint != nil { logrus.Debugf("Removing stale endpoint from HNS") - _, err := hcsshim.HNSEndpointRequest("DELETE", networkEndpoint.profileId, "") + _, err := hcsshim.HNSEndpointRequest("DELETE", networkEndpoint.profileID, "") if err != nil { logrus.Debugf("Failed to delete stale overlay endpoint (%s) from hns", networkEndpoint.id[0:7]) @@ -96,7 +102,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, logrus.Debugf("Deleting stale endpoint %s", eid) n.deleteEndpoint(eid) - _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "") + _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileID, "") if err != nil { return err } @@ -113,17 +119,19 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, return fmt.Errorf("create endpoint was not passed interface IP address") } - if s := n.getSubnetforIP(ep.addr); s == nil { - return fmt.Errorf("no matching subnet for IP %q in network %q\n", ep.addr, nid) + s := n.getSubnetforIP(ep.addr) + if s == nil { + return fmt.Errorf("no matching subnet for IP %q in network %q", ep.addr, nid) } // Todo: Add port bindings and qos policies here hnsEndpoint := &hcsshim.HNSEndpoint{ Name: eid, - VirtualNetwork: n.hnsId, + VirtualNetwork: n.hnsID, IPAddress: ep.addr.IP, EnableInternalDNS: true, + GatewayAddress: s.gwIP.String(), } if ep.mac != nil { @@ -141,6 +149,31 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, hnsEndpoint.Policies = append(hnsEndpoint.Policies, paPolicy) + if system.GetOSVersion().Build > 16236 { + natPolicy, err := json.Marshal(hcsshim.PaPolicy{ + Type: "OutBoundNAT", + }) + + if err != nil { + return err + } + + hnsEndpoint.Policies = append(hnsEndpoint.Policies, natPolicy) + + epConnectivity, err := windows.ParseEndpointConnectivity(epOptions) + if err != nil { + return err + } + + pbPolicy, err := windows.ConvertPortBindings(epConnectivity.PortBindings) + if err != nil { + return err + } + hnsEndpoint.Policies = append(hnsEndpoint.Policies, pbPolicy...) + + ep.disablegateway = true + } + configurationb, err := json.Marshal(hnsEndpoint) if err != nil { return err @@ -151,7 +184,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, return err } - ep.profileId = hnsresponse.Id + ep.profileID = hnsresponse.Id if ep.mac == nil { ep.mac, err = net.ParseMAC(hnsresponse.MacAddress) @@ -164,6 +197,12 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, } } + ep.portMapping, err = windows.ParsePortBindingPolicies(hnsresponse.Policies) + if err != nil { + hcsshim.HNSEndpointRequest("DELETE", hnsresponse.Id, "") + return err + } + n.addEndpoint(ep) return nil @@ -186,7 +225,7 @@ func (d *driver) DeleteEndpoint(nid, eid string) error { n.deleteEndpoint(eid) - _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "") + _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileID, "") if err != nil { return err } @@ -210,7 +249,17 @@ func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, erro } data := make(map[string]interface{}, 1) - data["hnsid"] = ep.profileId + data["hnsid"] = ep.profileID data["AllowUnqualifiedDNSQuery"] = true + + if ep.portMapping != nil { + // Return a copy of the operational data + pmc := make([]types.PortBinding, 0, len(ep.portMapping)) + for _, pm := range ep.portMapping { + pmc = append(pmc, pm.GetCopy()) + } + data[netlabel.PortMap] = pmc + } + return data, nil } diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go index 70c4f02ed..9cc46f8cf 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/ov_network_windows.go @@ -37,7 +37,7 @@ type subnetJSON struct { type network struct { id string name string - hnsId string + hnsID string providerAddress string interfaceName string endpoints endpointTable @@ -108,7 +108,7 @@ func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo d case "com.docker.network.windowsshim.interface": interfaceName = value case "com.docker.network.windowsshim.hnsid": - n.hnsId = value + n.hnsID = value case netlabel.OverlayVxlanIDList: vniStrings := strings.Split(value, ",") for _, vniStr := range vniStrings { @@ -181,7 +181,7 @@ func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo d if err != nil { d.deleteNetwork(id) } else { - genData["com.docker.network.windowsshim.hnsid"] = n.hnsId + genData["com.docker.network.windowsshim.hnsid"] = n.hnsID } return err @@ -197,7 +197,7 @@ func (d *driver) DeleteNetwork(nid string) error { return types.ForbiddenErrorf("could not find network with id %s", nid) } - _, err := hcsshim.HNSNetworkRequest("DELETE", n.hnsId, "") + _, err := hcsshim.HNSNetworkRequest("DELETE", n.hnsID, "") if err != nil { return types.ForbiddenErrorf(err.Error()) } @@ -242,7 +242,7 @@ func (d *driver) network(nid string) *network { // } // for _, endpoint := range hnsresponse { -// if endpoint.VirtualNetwork != n.hnsId { +// if endpoint.VirtualNetwork != n.hnsID { // continue // } @@ -260,7 +260,7 @@ func (d *driver) network(nid string) *network { func (n *network) convertToOverlayEndpoint(v *hcsshim.HNSEndpoint) *endpoint { ep := &endpoint{ id: v.Name, - profileId: v.Id, + profileID: v.Id, nid: n.id, remote: v.IsRemoteEndpoint, } @@ -311,6 +311,7 @@ func (d *driver) createHnsNetwork(n *network) error { Type: d.Type(), Subnets: subnets, NetworkAdapterName: n.interfaceName, + AutomaticDNS: true, } configurationb, err := json.Marshal(network) @@ -326,7 +327,7 @@ func (d *driver) createHnsNetwork(n *network) error { return err } - n.hnsId = hnsresponse.Id + n.hnsID = hnsresponse.Id n.providerAddress = hnsresponse.ManagementIP return nil diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go index d415bebcb..65ad62ae0 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/overlay_windows.go @@ -104,7 +104,7 @@ func (d *driver) restoreHNSNetworks() error { func (d *driver) convertToOverlayNetwork(v *hcsshim.HNSNetwork) *network { n := &network{ id: v.Name, - hnsId: v.Id, + hnsID: v.Id, driver: d, endpoints: endpointTable{}, subnets: []*subnet{}, diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go index 0abc23243..159bfd6ed 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/overlay/peerdb_windows.go @@ -33,7 +33,7 @@ func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, hnsEndpoint := &hcsshim.HNSEndpoint{ Name: eid, - VirtualNetwork: n.hnsId, + VirtualNetwork: n.hnsID, MacAddress: peerMac.String(), IPAddress: peerIP, IsRemoteEndpoint: true, @@ -78,7 +78,7 @@ func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask, nid: nid, addr: addr, mac: peerMac, - profileId: hnsresponse.Id, + profileID: hnsresponse.Id, remote: true, } @@ -108,7 +108,7 @@ func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMas } if updateDb { - _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileId, "") + _, err := hcsshim.HNSEndpointRequest("DELETE", ep.profileID, "") if err != nil { return err } diff --git a/vendor/github.com/docker/libnetwork/drivers/windows/windows.go b/vendor/github.com/docker/libnetwork/drivers/windows/windows.go index 45f835ee0..0b15b2aa4 100644 --- a/vendor/github.com/docker/libnetwork/drivers/windows/windows.go +++ b/vendor/github.com/docker/libnetwork/drivers/windows/windows.go @@ -55,7 +55,8 @@ type endpointOption struct { DisableICC bool } -type endpointConnectivity struct { +// EndpointConnectivity stores the port bindings and exposed ports that the user has specified in epOptions. +type EndpointConnectivity struct { PortBindings []types.PortBinding ExposedPorts []types.TransportPort } @@ -67,7 +68,7 @@ type hnsEndpoint struct { Type string macAddress net.HardwareAddr epOption *endpointOption // User specified parameters - epConnectivity *endpointConnectivity // User specified parameters + epConnectivity *EndpointConnectivity // User specified parameters portMapping []types.PortBinding // Operation port bindings addr *net.IPNet gateway net.IP @@ -95,7 +96,7 @@ const ( errNotFound = "HNS failed with error : The object identifier does not represent a valid object. " ) -// IsBuiltinWindowsDriver vaidates if network-type is a builtin local-scoped driver +// IsBuiltinLocalDriver validates if network-type is a builtin local-scoped driver func IsBuiltinLocalDriver(networkType string) bool { if "l2bridge" == networkType || "l2tunnel" == networkType || "nat" == networkType || "ics" == networkType || "transparent" == networkType { return true @@ -396,7 +397,8 @@ func convertQosPolicies(qosPolicies []types.QosPolicy) ([]json.RawMessage, error return qps, nil } -func convertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) { +// ConvertPortBindings converts PortBindings to JSON for HNS request +func ConvertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, error) { var pbs []json.RawMessage // Enumerate through the port bindings specified by the user and convert @@ -431,7 +433,8 @@ func convertPortBindings(portBindings []types.PortBinding) ([]json.RawMessage, e return pbs, nil } -func parsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) { +// ParsePortBindingPolicies parses HNS endpoint response message to PortBindings +func ParsePortBindingPolicies(policies []json.RawMessage) ([]types.PortBinding, error) { var bindings []types.PortBinding hcsPolicy := &hcsshim.NatPolicy{} @@ -505,12 +508,13 @@ func parseEndpointOptions(epOptions map[string]interface{}) (*endpointOption, er return ec, nil } -func parseEndpointConnectivity(epOptions map[string]interface{}) (*endpointConnectivity, error) { +// ParseEndpointConnectivity parses options passed to CreateEndpoint, specifically port bindings, and store in a endpointConnectivity object. +func ParseEndpointConnectivity(epOptions map[string]interface{}) (*EndpointConnectivity, error) { if epOptions == nil { return nil, nil } - ec := &endpointConnectivity{} + ec := &EndpointConnectivity{} if opt, ok := epOptions[netlabel.PortMap]; ok { if bs, ok := opt.([]types.PortBinding); ok { @@ -550,7 +554,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, if err != nil { return err } - epConnectivity, err := parseEndpointConnectivity(epOptions) + epConnectivity, err := ParseEndpointConnectivity(epOptions) if err != nil { return err } @@ -561,7 +565,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1) } - endpointStruct.Policies, err = convertPortBindings(epConnectivity.PortBindings) + endpointStruct.Policies, err = ConvertPortBindings(epConnectivity.PortBindings) if err != nil { return err } @@ -615,7 +619,7 @@ func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, endpoint.profileID = hnsresponse.Id endpoint.epConnectivity = epConnectivity endpoint.epOption = epOption - endpoint.portMapping, err = parsePortBindingPolicies(hnsresponse.Policies) + endpoint.portMapping, err = ParsePortBindingPolicies(hnsresponse.Policies) if err != nil { hcsshim.HNSEndpointRequest("DELETE", hnsresponse.Id, "") diff --git a/vendor/github.com/docker/libnetwork/ipvs/ipvs.go b/vendor/github.com/docker/libnetwork/ipvs/ipvs.go index a285e102e..ebcdd808c 100644 --- a/vendor/github.com/docker/libnetwork/ipvs/ipvs.go +++ b/vendor/github.com/docker/libnetwork/ipvs/ipvs.go @@ -116,6 +116,13 @@ func (i *Handle) DelService(s *Service) error { return i.doCmd(s, nil, ipvsCmdDelService) } +// Flush deletes all existing services in the passed +// handle. +func (i *Handle) Flush() error { + _, err := i.doCmdWithoutAttr(ipvsCmdFlush) + return err +} + // NewDestination creates a new real server in the passed ipvs // service which should already be existing in the passed handle. func (i *Handle) NewDestination(s *Service, d *Destination) error { diff --git a/vendor/github.com/docker/libnetwork/ipvs/ipvs_test.go b/vendor/github.com/docker/libnetwork/ipvs/ipvs_test.go index 50b5c532e..30ffe9717 100644 --- a/vendor/github.com/docker/libnetwork/ipvs/ipvs_test.go +++ b/vendor/github.com/docker/libnetwork/ipvs/ipvs_test.go @@ -178,6 +178,41 @@ func TestService(t *testing.T) { } } + svcs := []Service{ + { + AddressFamily: nl.FAMILY_V4, + SchedName: RoundRobin, + Protocol: syscall.IPPROTO_TCP, + Port: 80, + Address: net.ParseIP("10.20.30.40"), + Netmask: 0xFFFFFFFF, + }, + { + AddressFamily: nl.FAMILY_V4, + SchedName: LeastConnection, + Protocol: syscall.IPPROTO_UDP, + Port: 8080, + Address: net.ParseIP("10.20.30.41"), + Netmask: 0xFFFFFFFF, + }, + } + // Create services for testing flush + for _, svc := range svcs { + if !i.IsServicePresent(&svc) { + err = i.NewService(&svc) + assert.NoError(t, err) + checkService(t, i, &svc, true) + } else { + t.Errorf("svc: %v exists", svc) + } + } + err = i.Flush() + assert.NoError(t, err) + got, err := i.GetServices() + assert.NoError(t, err) + if len(got) != 0 { + t.Errorf("Unexpected services after flush") + } } func createDummyInterface(t *testing.T) { diff --git a/vendor/github.com/docker/libnetwork/ipvs/netlink.go b/vendor/github.com/docker/libnetwork/ipvs/netlink.go index b8d33dcdc..2089283d1 100644 --- a/vendor/github.com/docker/libnetwork/ipvs/netlink.go +++ b/vendor/github.com/docker/libnetwork/ipvs/netlink.go @@ -402,6 +402,13 @@ func (i *Handle) doGetServicesCmd(svc *Service) ([]*Service, error) { return res, nil } +// doCmdWithoutAttr a simple wrapper of netlink socket execute command +func (i *Handle) doCmdWithoutAttr(cmd uint8) ([][]byte, error) { + req := newIPVSRequest(cmd) + req.Seq = atomic.AddUint32(&i.seq, 1) + return execute(i.sock, req, 0) +} + func assembleDestination(attrs []syscall.NetlinkRouteAttr) (*Destination, error) { var d Destination diff --git a/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go b/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go new file mode 100644 index 000000000..97d7fbb49 --- /dev/null +++ b/vendor/github.com/docker/libnetwork/portallocator/portallocator_freebsd.go @@ -0,0 +1,42 @@ +package portallocator + +import ( + "bytes" + "fmt" + "os/exec" +) + +func getDynamicPortRange() (start int, end int, err error) { + portRangeKernelSysctl := []string{"net.inet.ip.portrange.hifirst", "net.ip.portrange.hilast"} + portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", DefaultPortRangeStart, DefaultPortRangeEnd) + portRangeLowCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[0]) + var portRangeLowOut bytes.Buffer + portRangeLowCmd.Stdout = &portRangeLowOut + cmdErr := portRangeLowCmd.Run() + if cmdErr != nil { + return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hifirst failed - %s: %v", portRangeFallback, err) + } + n, err := fmt.Sscanf(portRangeLowOut.String(), "%d", &start) + if n != 1 || err != nil { + if err == nil { + err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) + } + return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range start from %s - %s: %v", portRangeLowOut.String(), portRangeFallback, err) + } + + portRangeHighCmd := exec.Command("/sbin/sysctl", portRangeKernelSysctl[1]) + var portRangeHighOut bytes.Buffer + portRangeHighCmd.Stdout = &portRangeHighOut + cmdErr = portRangeHighCmd.Run() + if cmdErr != nil { + return 0, 0, fmt.Errorf("port allocator - sysctl net.inet.ip.portrange.hilast failed - %s: %v", portRangeFallback, err) + } + n, err = fmt.Sscanf(portRangeHighOut.String(), "%d", &end) + if n != 1 || err != nil { + if err == nil { + err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) + } + return 0, 0, fmt.Errorf("port allocator - failed to parse system ephemeral port range end from %s - %s: %v", portRangeHighOut.String(), portRangeFallback, err) + } + return start, end, nil +} diff --git a/vendor/github.com/fsouza/go-dockerclient/.travis.yml b/vendor/github.com/fsouza/go-dockerclient/.travis.yml index b780602ae..e768e88ba 100644 --- a/vendor/github.com/fsouza/go-dockerclient/.travis.yml +++ b/vendor/github.com/fsouza/go-dockerclient/.travis.yml @@ -1,9 +1,8 @@ language: go sudo: required go: - - 1.7.x - 1.8.x - - 1.9rc2 + - 1.9 - tip os: - linux diff --git a/vendor/github.com/fsouza/go-dockerclient/appveyor.yml b/vendor/github.com/fsouza/go-dockerclient/appveyor.yml index 4a332b10c..3d8e319cd 100644 --- a/vendor/github.com/fsouza/go-dockerclient/appveyor.yml +++ b/vendor/github.com/fsouza/go-dockerclient/appveyor.yml @@ -5,9 +5,8 @@ clone_folder: c:\gopath\src\github.com\fsouza\go-dockerclient environment: GOPATH: c:\gopath matrix: - - GOVERSION: 1.7.5 - GOVERSION: 1.8.3 - - GOVERSION: 1.9rc2 + - GOVERSION: 1.9 install: - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - rmdir c:\go /s /q diff --git a/vendor/github.com/fsouza/go-dockerclient/container.go b/vendor/github.com/fsouza/go-dockerclient/container.go index 9c121095d..652deee8f 100644 --- a/vendor/github.com/fsouza/go-dockerclient/container.go +++ b/vendor/github.com/fsouza/go-dockerclient/container.go @@ -778,6 +778,7 @@ type HostConfig struct { IOMaximumBandwidth int64 `json:"IOMaximumBandwidth,omitempty" yaml:"IOMaximumBandwidth,omitempty"` IOMaximumIOps int64 `json:"IOMaximumIOps,omitempty" yaml:"IOMaximumIOps,omitempty"` Mounts []HostMount `json:"Mounts,omitempty" yaml:"Mounts,omitempty" toml:"Mounts,omitempty"` + Init bool `json:",omitempty" yaml:",omitempty"` } // NetworkingConfig represents the container's networking configuration for each of its interfaces diff --git a/vendor/github.com/fsouza/go-dockerclient/network.go b/vendor/github.com/fsouza/go-dockerclient/network.go index 295efd565..b79b67cd5 100644 --- a/vendor/github.com/fsouza/go-dockerclient/network.go +++ b/vendor/github.com/fsouza/go-dockerclient/network.go @@ -125,8 +125,9 @@ type CreateNetworkOptions struct { // // See https://goo.gl/T8kRVH for more details. type IPAMOptions struct { - Driver string `json:"Driver" yaml:"Driver" toml:"Driver"` - Config []IPAMConfig `json:"Config" yaml:"Config" toml:"Config"` + Driver string `json:"Driver" yaml:"Driver" toml:"Driver"` + Config []IPAMConfig `json:"Config" yaml:"Config" toml:"Config"` + Options map[string]string `json:"Options" yaml:"Options" toml:"Options"` } // IPAMConfig represents IPAM configurations diff --git a/vendor/github.com/gin-gonic/gin/.travis.yml b/vendor/github.com/gin-gonic/gin/.travis.yml index 821ce8dfd..72daa3f35 100644 --- a/vendor/github.com/gin-gonic/gin/.travis.yml +++ b/vendor/github.com/gin-gonic/gin/.travis.yml @@ -4,6 +4,7 @@ go: - 1.6.x - 1.7.x - 1.8.x + - 1.9 - master git: diff --git a/vendor/github.com/gin-gonic/gin/README.md b/vendor/github.com/gin-gonic/gin/README.md index b14c2a2a0..07357be4e 100644 --- a/vendor/github.com/gin-gonic/gin/README.md +++ b/vendor/github.com/gin-gonic/gin/README.md @@ -40,7 +40,7 @@ $ go run example.go ## Benchmarks -Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) +Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) [See all benchmarks](/BENCHMARKS.md) @@ -74,10 +74,10 @@ BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 21848 BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 609 -(1): Total Repetitions achieved in constant time, higher means more confident result -(2): Single Repetition Duration (ns/op), lower is better -(3): Heap Memory (B/op), lower is better -(4): Average Allocations per Repetition (allocs/op), lower is better +(1): Total Repetitions achieved in constant time, higher means more confident result +(2): Single Repetition Duration (ns/op), lower is better +(3): Heap Memory (B/op), lower is better +(4): Average Allocations per Repetition (allocs/op), lower is better ## Gin v1. stable @@ -281,10 +281,10 @@ func main() { // single file file, _ := c.FormFile("file") log.Println(file.Filename) - + // Upload the file to specific dst. - // c.SaveUploadedFile(file, dst) - + // c.SaveUploadedFile(file, dst) + c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.Run(":8080") @@ -313,9 +313,9 @@ func main() { for _, file := range files { log.Println(file.Filename) - + // Upload the file to specific dst. - // c.SaveUploadedFile(file, dst) + // c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) @@ -369,6 +369,7 @@ r := gin.New() instead of ```go +// Default With the Logger and Recovery middleware already attached r := gin.Default() ``` @@ -380,7 +381,11 @@ func main() { r := gin.New() // Global middleware + // Logger middleware will write the logs to gin.DefaultWriter even you set with GIN_MODE=release. + // By default gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) + + // Recovery middleware recovers from any panics and writes a 500 if there was one. r.Use(gin.Recovery()) // Per route middleware, you can add as many as you desire. @@ -408,6 +413,28 @@ func main() { } ``` +### How to write log file +```go +func main() { + // Disable Console Color, you don't need console color when writing the logs to file. + gin.DisableConsoleColor() + + // Logging to a file. + f, _ := os.Create("gin.log") + gin.DefaultWriter = io.MultiWriter(f) + + // Use the following code if you need to write the logs to file and console at the same time. + // gin.DefaultWriter = io.MultiWriter(f, os.Stdout) + + router := gin.Default() + router.GET("/ping", func(c *gin.Context) { + c.String(200, "pong") + }) + + r.Run(":8080") +} +``` + ### Model binding and validation To bind a request body into a type, use model binding. We currently support binding of JSON, XML and standard form values (foo=bar&boo=baz). @@ -460,6 +487,67 @@ func main() { } ``` +### Custom Validators + +It is also possible to register custom validators. See the [example code](examples/custom-validation/server.go). + +[embedmd]:# (examples/custom-validation/server.go go) +```go +package main + +import ( + "net/http" + "reflect" + "time" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + validator "gopkg.in/go-playground/validator.v8" +) + +type Booking struct { + CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` + CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` +} + +func bookableDate( + v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, + field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, +) bool { + if date, ok := field.Interface().(time.Time); ok { + today := time.Now() + if today.Year() > date.Year() || today.YearDay() > date.YearDay() { + return false + } + } + return true +} + +func main() { + route := gin.Default() + binding.Validator.RegisterValidation("bookabledate", bookableDate) + route.GET("/bookable", getBookable) + route.Run(":8085") +} + +func getBookable(c *gin.Context) { + var b Booking + if err := c.ShouldBindWith(&b, binding.Query); err == nil { + c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) + } else { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } +} +``` + +```console +$ curl "localhost:8085/bookable?check_in=2017-08-16&check_out=2017-08-17" +{"message":"Booking dates are valid!"} + +$ curl "localhost:8085/bookable?check_in=2017-08-15&check_out=2017-08-16" +{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"} +``` + ### Only Bind Query String `BindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017). @@ -505,10 +593,12 @@ package main import "log" import "github.com/gin-gonic/gin" +import "time" type Person struct { - Name string `form:"name"` - Address string `form:"address"` + Name string `form:"name"` + Address string `form:"address"` + Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` } func main() { @@ -525,12 +615,18 @@ func startPage(c *gin.Context) { if c.Bind(&person) == nil { log.Println(person.Name) log.Println(person.Address) + log.Println(person.Birthday) } c.String(200, "Success") } ``` +Test it with: +```sh +$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15" +``` + ### Bind HTML checkboxes See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092) @@ -676,7 +772,7 @@ func main() { // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } -``` +``` ### Serving static files @@ -787,7 +883,7 @@ You may use custom delims r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates")) -``` +``` #### Custom Template Funcs diff --git a/vendor/github.com/gin-gonic/gin/auth.go b/vendor/github.com/gin-gonic/gin/auth.go index e7c46bf67..85d96fd38 100644 --- a/vendor/github.com/gin-gonic/gin/auth.go +++ b/vendor/github.com/gin-gonic/gin/auth.go @@ -47,7 +47,7 @@ func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc { pairs := processAccounts(accounts) return func(c *Context) { // Search user in the slice of allowed credentials - user, found := pairs.searchCredential(c.Request.Header.Get("Authorization")) + user, found := pairs.searchCredential(c.requestHeader("Authorization")) if !found { // Credentials doesn't match, we return 401 and abort handlers chain. c.Header("WWW-Authenticate", realm) diff --git a/vendor/github.com/gin-gonic/gin/binding/binding.go b/vendor/github.com/gin-gonic/gin/binding/binding.go index 971547c21..a09cc2214 100644 --- a/vendor/github.com/gin-gonic/gin/binding/binding.go +++ b/vendor/github.com/gin-gonic/gin/binding/binding.go @@ -4,7 +4,11 @@ package binding -import "net/http" +import ( + "net/http" + + validator "gopkg.in/go-playground/validator.v8" +) const ( MIMEJSON = "application/json" @@ -31,6 +35,11 @@ type StructValidator interface { // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(interface{}) error + + // RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key + // NOTE: if the key already exists, the previous validation function will be replaced. + // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation + RegisterValidation(string, validator.Func) error } var Validator StructValidator = &defaultValidator{} diff --git a/vendor/github.com/gin-gonic/gin/binding/default_validator.go b/vendor/github.com/gin-gonic/gin/binding/default_validator.go index 19885f164..6336bb6e2 100644 --- a/vendor/github.com/gin-gonic/gin/binding/default_validator.go +++ b/vendor/github.com/gin-gonic/gin/binding/default_validator.go @@ -28,6 +28,11 @@ func (v *defaultValidator) ValidateStruct(obj interface{}) error { return nil } +func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error { + v.lazyinit() + return v.validate.RegisterValidation(key, fn) +} + func (v *defaultValidator) lazyinit() { v.once.Do(func() { config := &validator.Config{TagName: "binding"} diff --git a/vendor/github.com/gin-gonic/gin/binding/form.go b/vendor/github.com/gin-gonic/gin/binding/form.go index 557333e6f..0be59660b 100644 --- a/vendor/github.com/gin-gonic/gin/binding/form.go +++ b/vendor/github.com/gin-gonic/gin/binding/form.go @@ -6,6 +6,8 @@ package binding import "net/http" +const defaultMemory = 32 * 1024 * 1024 + type formBinding struct{} type formPostBinding struct{} type formMultipartBinding struct{} @@ -18,7 +20,7 @@ func (formBinding) Bind(req *http.Request, obj interface{}) error { if err := req.ParseForm(); err != nil { return err } - req.ParseMultipartForm(32 << 10) // 32 MB + req.ParseMultipartForm(defaultMemory) if err := mapForm(obj, req.Form); err != nil { return err } @@ -44,7 +46,7 @@ func (formMultipartBinding) Name() string { } func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error { - if err := req.ParseMultipartForm(32 << 10); err != nil { + if err := req.ParseMultipartForm(defaultMemory); err != nil { return err } if err := mapForm(obj, req.MultipartForm.Value); err != nil { diff --git a/vendor/github.com/gin-gonic/gin/binding/validate_test.go b/vendor/github.com/gin-gonic/gin/binding/validate_test.go index cbcb389de..523e12983 100644 --- a/vendor/github.com/gin-gonic/gin/binding/validate_test.go +++ b/vendor/github.com/gin-gonic/gin/binding/validate_test.go @@ -6,9 +6,12 @@ package binding import ( "bytes" + "reflect" "testing" "time" + validator "gopkg.in/go-playground/validator.v8" + "github.com/stretchr/testify/assert" ) @@ -190,3 +193,42 @@ func TestValidatePrimitives(t *testing.T) { assert.NoError(t, validate(&str)) assert.Equal(t, str, "value") } + +// structCustomValidation is a helper struct we use to check that +// custom validation can be registered on it. +// The `notone` binding directive is for custom validation and registered later. +type structCustomValidation struct { + Integer int `binding:"notone"` +} + +// notOne is a custom validator meant to be used with `validator.v8` library. +// The method signature for `v9` is significantly different and this function +// would need to be changed for tests to pass after upgrade. +// See https://github.com/gin-gonic/gin/pull/1015. +func notOne( + v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, + field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, +) bool { + if val, ok := field.Interface().(int); ok { + return val != 1 + } + return false +} + +func TestRegisterValidation(t *testing.T) { + // This validates that the function `notOne` matches + // the expected function signature by `defaultValidator` + // and by extension the validator library. + err := Validator.RegisterValidation("notone", notOne) + // Check that we can register custom validation without error + assert.Nil(t, err) + + // Create an instance which will fail validation + withOne := structCustomValidation{Integer: 1} + errs := validate(withOne) + + // Check that we got back non-nil errs + assert.NotNil(t, errs) + // Check that the error matches expactation + assert.Error(t, errs, "", "", "notone") +} diff --git a/vendor/github.com/gin-gonic/gin/context.go b/vendor/github.com/gin-gonic/gin/context.go index 497cbfd61..d7b6c61da 100644 --- a/vendor/github.com/gin-gonic/gin/context.go +++ b/vendor/github.com/gin-gonic/gin/context.go @@ -509,7 +509,7 @@ func (c *Context) ClientIP() string { } if c.engine.AppEngine { - if addr := c.Request.Header.Get("X-Appengine-Remote-Addr"); addr != "" { + if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" { return addr } } @@ -537,10 +537,7 @@ func (c *Context) IsWebsocket() bool { } func (c *Context) requestHeader(key string) string { - if values, _ := c.Request.Header[key]; len(values) > 0 { - return values[0] - } - return "" + return c.Request.Header.Get(key) } /************************************/ @@ -586,6 +583,9 @@ func (c *Context) GetRawData() ([]byte, error) { return ioutil.ReadAll(c.Request.Body) } +// SetCookie adds a Set-Cookie header to the ResponseWriter's headers. +// The provided cookie must have a valid Name. Invalid cookies may be +// silently dropped. func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) { if path == "" { path = "/" @@ -601,6 +601,10 @@ func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, }) } +// Cookie returns the named cookie provided in the request or +// ErrNoCookie if not found. And return the named cookie is unescaped. +// If multiple cookies match the given name, only one cookie will +// be returned. func (c *Context) Cookie(name string) (string, error) { cookie, err := c.Request.Cookie(name) if err != nil { diff --git a/vendor/github.com/gin-gonic/gin/examples/custom-validation/server.go b/vendor/github.com/gin-gonic/gin/examples/custom-validation/server.go new file mode 100644 index 000000000..0b67ce10d --- /dev/null +++ b/vendor/github.com/gin-gonic/gin/examples/custom-validation/server.go @@ -0,0 +1,45 @@ +package main + +import ( + "net/http" + "reflect" + "time" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + validator "gopkg.in/go-playground/validator.v8" +) + +type Booking struct { + CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` + CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` +} + +func bookableDate( + v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, + field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, +) bool { + if date, ok := field.Interface().(time.Time); ok { + today := time.Now() + if today.Year() > date.Year() || today.YearDay() > date.YearDay() { + return false + } + } + return true +} + +func main() { + route := gin.Default() + binding.Validator.RegisterValidation("bookabledate", bookableDate) + route.GET("/bookable", getBookable) + route.Run(":8085") +} + +func getBookable(c *gin.Context) { + var b Booking + if err := c.ShouldBindWith(&b, binding.Query); err == nil { + c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) + } else { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + } +} diff --git a/vendor/github.com/gin-gonic/gin/gin.go b/vendor/github.com/gin-gonic/gin/gin.go index 23853a977..ee39c9aab 100644 --- a/vendor/github.com/gin-gonic/gin/gin.go +++ b/vendor/github.com/gin-gonic/gin/gin.go @@ -316,14 +316,11 @@ func (engine *Engine) HandleContext(c *Context) { func (engine *Engine) handleHTTPRequest(context *Context) { httpMethod := context.Request.Method - var path string - var unescape bool + path := context.Request.URL.Path + unescape := false if engine.UseRawPath && len(context.Request.URL.RawPath) > 0 { path = context.Request.URL.RawPath unescape = engine.UnescapePathValues - } else { - path = context.Request.URL.Path - unescape = false } // Find root of the tree for the given HTTP method diff --git a/vendor/github.com/gin-gonic/gin/ginS/gins.go b/vendor/github.com/gin-gonic/gin/ginS/gins.go index d40d1c3a3..ee00b3816 100644 --- a/vendor/github.com/gin-gonic/gin/ginS/gins.go +++ b/vendor/github.com/gin-gonic/gin/ginS/gins.go @@ -9,15 +9,15 @@ import ( "net/http" "sync" - . "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" ) var once sync.Once -var internalEngine *Engine +var internalEngine *gin.Engine -func engine() *Engine { +func engine() *gin.Engine { once.Do(func() { - internalEngine = Default() + internalEngine = gin.Default() }) return internalEngine } @@ -35,65 +35,65 @@ func SetHTMLTemplate(templ *template.Template) { } // NoRoute adds handlers for NoRoute. It return a 404 code by default. -func NoRoute(handlers ...HandlerFunc) { +func NoRoute(handlers ...gin.HandlerFunc) { engine().NoRoute(handlers...) } // NoMethod sets the handlers called when... TODO -func NoMethod(handlers ...HandlerFunc) { +func NoMethod(handlers ...gin.HandlerFunc) { engine().NoMethod(handlers...) } // Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. // For example, all the routes that use a common middlware for authorization could be grouped. -func Group(relativePath string, handlers ...HandlerFunc) *RouterGroup { +func Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup { return engine().Group(relativePath, handlers...) } -func Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { +func Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Handle(httpMethod, relativePath, handlers...) } // POST is a shortcut for router.Handle("POST", path, handle) -func POST(relativePath string, handlers ...HandlerFunc) IRoutes { +func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().POST(relativePath, handlers...) } // GET is a shortcut for router.Handle("GET", path, handle) -func GET(relativePath string, handlers ...HandlerFunc) IRoutes { +func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } // DELETE is a shortcut for router.Handle("DELETE", path, handle) -func DELETE(relativePath string, handlers ...HandlerFunc) IRoutes { +func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) } // PATCH is a shortcut for router.Handle("PATCH", path, handle) -func PATCH(relativePath string, handlers ...HandlerFunc) IRoutes { +func PATCH(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PATCH(relativePath, handlers...) } // PUT is a shortcut for router.Handle("PUT", path, handle) -func PUT(relativePath string, handlers ...HandlerFunc) IRoutes { +func PUT(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().PUT(relativePath, handlers...) } // OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) -func OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes { +func OPTIONS(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().OPTIONS(relativePath, handlers...) } // HEAD is a shortcut for router.Handle("HEAD", path, handle) -func HEAD(relativePath string, handlers ...HandlerFunc) IRoutes { +func HEAD(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().HEAD(relativePath, handlers...) } -func Any(relativePath string, handlers ...HandlerFunc) IRoutes { +func Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().Any(relativePath, handlers...) } -func StaticFile(relativePath, filepath string) IRoutes { +func StaticFile(relativePath, filepath string) gin.IRoutes { return engine().StaticFile(relativePath, filepath) } @@ -103,18 +103,18 @@ func StaticFile(relativePath, filepath string) IRoutes { // To use the operating system's file system implementation, // use : // router.Static("/static", "/var/www") -func Static(relativePath, root string) IRoutes { +func Static(relativePath, root string) gin.IRoutes { return engine().Static(relativePath, root) } -func StaticFS(relativePath string, fs http.FileSystem) IRoutes { +func StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes { return engine().StaticFS(relativePath, fs) } // Use attachs a global middleware to the router. ie. the middlewares attached though Use() will be // included in the handlers chain for every single request. Even 404, 405, static files... // For example, this is the right place for a logger or error management middleware. -func Use(middlewares ...HandlerFunc) IRoutes { +func Use(middlewares ...gin.HandlerFunc) gin.IRoutes { return engine().Use(middlewares...) } diff --git a/vendor/github.com/gin-gonic/gin/logger.go b/vendor/github.com/gin-gonic/gin/logger.go index a6f7f140b..c679c7871 100644 --- a/vendor/github.com/gin-gonic/gin/logger.go +++ b/vendor/github.com/gin-gonic/gin/logger.go @@ -91,10 +91,11 @@ func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { clientIP := c.ClientIP() method := c.Request.Method statusCode := c.Writer.Status() - var statusColor, methodColor string + var statusColor, methodColor, resetColor string if isTerm { statusColor = colorForStatus(statusCode) methodColor = colorForMethod(method) + resetColor = reset } comment := c.Errors.ByType(ErrorTypePrivate).String() @@ -104,10 +105,10 @@ func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc { fmt.Fprintf(out, "[GIN] %v |%s %3d %s| %13v | %15s |%s %-7s %s %s\n%s", end.Format("2006/01/02 - 15:04:05"), - statusColor, statusCode, reset, + statusColor, statusCode, resetColor, latency, clientIP, - methodColor, method, reset, + methodColor, method, resetColor, path, comment, ) diff --git a/vendor/github.com/gin-gonic/gin/recovery.go b/vendor/github.com/gin-gonic/gin/recovery.go index 7aff3d877..89b39fecd 100644 --- a/vendor/github.com/gin-gonic/gin/recovery.go +++ b/vendor/github.com/gin-gonic/gin/recovery.go @@ -26,6 +26,7 @@ func Recovery() HandlerFunc { return RecoveryWithWriter(DefaultErrorWriter) } +// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one. func RecoveryWithWriter(out io.Writer) HandlerFunc { var logger *log.Logger if out != nil { @@ -46,7 +47,7 @@ func RecoveryWithWriter(out io.Writer) HandlerFunc { } } -// stack returns a nicely formated stack frame, skipping skip frames. +// stack returns a nicely formatted stack frame, skipping skip frames. func stack(skip int) []byte { buf := new(bytes.Buffer) // the returned data // As we loop, we open files and read them. These variables record the currently diff --git a/vendor/github.com/go-openapi/runtime/authinfo_test.go b/vendor/github.com/go-openapi/runtime/authinfo_test.go index 6a7d94b1a..0768df3b7 100644 --- a/vendor/github.com/go-openapi/runtime/authinfo_test.go +++ b/vendor/github.com/go-openapi/runtime/authinfo_test.go @@ -23,11 +23,11 @@ import ( func TestAuthInfoWriter(t *testing.T) { hand := ClientAuthInfoWriterFunc(func(r ClientRequest, _ strfmt.Registry) error { - r.SetHeaderParam("authorization", "Bearer the-token-goes-here") - return nil + return r.SetHeaderParam("authorization", "Bearer the-token-goes-here") }) tr := new(trw) - hand.AuthenticateRequest(tr, nil) + err := hand.AuthenticateRequest(tr, nil) + assert.NoError(t, err) assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get("Authorization")) } diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info.go b/vendor/github.com/go-openapi/runtime/client/auth_info.go index 290a3eb62..9e18222b5 100644 --- a/vendor/github.com/go-openapi/runtime/client/auth_info.go +++ b/vendor/github.com/go-openapi/runtime/client/auth_info.go @@ -32,8 +32,7 @@ func init() { func BasicAuth(username, password string) runtime.ClientAuthInfoWriter { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) - r.SetHeaderParam("Authorization", "Basic "+encoded) - return nil + return r.SetHeaderParam("Authorization", "Basic "+encoded) }) } @@ -41,15 +40,13 @@ func BasicAuth(username, password string) runtime.ClientAuthInfoWriter { func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter { if in == "query" { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - r.SetQueryParam(name, value) - return nil + return r.SetQueryParam(name, value) }) } if in == "header" { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - r.SetHeaderParam(name, value) - return nil + return r.SetHeaderParam(name, value) }) } return nil @@ -58,7 +55,6 @@ func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter { // BearerToken provides a header based oauth2 bearer access token auth info writer func BearerToken(token string) runtime.ClientAuthInfoWriter { return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - r.SetHeaderParam("Authorization", "Bearer "+token) - return nil + return r.SetHeaderParam("Authorization", "Bearer "+token) }) } diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info_test.go b/vendor/github.com/go-openapi/runtime/client/auth_info_test.go index 70cf8466f..ef8859443 100644 --- a/vendor/github.com/go-openapi/runtime/client/auth_info_test.go +++ b/vendor/github.com/go-openapi/runtime/client/auth_info_test.go @@ -25,7 +25,8 @@ func TestBasicAuth(t *testing.T) { r, _ := newRequest("GET", "/", nil) writer := BasicAuth("someone", "with a password") - writer.AuthenticateRequest(r, nil) + err := writer.AuthenticateRequest(r, nil) + assert.NoError(t, err) req := new(http.Request) req.Header = make(http.Header) @@ -41,7 +42,8 @@ func TestAPIKeyAuth_Query(t *testing.T) { r, _ := newRequest("GET", "/", nil) writer := APIKeyAuth("api_key", "query", "the-shared-key") - writer.AuthenticateRequest(r, nil) + err := writer.AuthenticateRequest(r, nil) + assert.NoError(t, err) assert.Equal(t, "the-shared-key", r.query.Get("api_key")) } @@ -50,7 +52,8 @@ func TestAPIKeyAuth_Header(t *testing.T) { r, _ := newRequest("GET", "/", nil) writer := APIKeyAuth("x-api-token", "header", "the-shared-key") - writer.AuthenticateRequest(r, nil) + err := writer.AuthenticateRequest(r, nil) + assert.NoError(t, err) assert.Equal(t, "the-shared-key", r.header.Get("x-api-token")) } @@ -59,7 +62,8 @@ func TestBearerTokenAuth(t *testing.T) { r, _ := newRequest("GET", "/", nil) writer := BearerToken("the-shared-token") - writer.AuthenticateRequest(r, nil) + err := writer.AuthenticateRequest(r, nil) + assert.NoError(t, err) assert.Equal(t, "Bearer the-shared-token", r.header.Get("Authorization")) } diff --git a/vendor/github.com/go-openapi/runtime/client/request_test.go b/vendor/github.com/go-openapi/runtime/client/request_test.go index 7f44095e8..0f1d60267 100644 --- a/vendor/github.com/go-openapi/runtime/client/request_test.go +++ b/vendor/github.com/go-openapi/runtime/client/request_test.go @@ -38,20 +38,20 @@ var testProducers = map[string]runtime.Producer{ func TestBuildRequest_SetHeaders(t *testing.T) { r, _ := newRequest("GET", "/flats/{id}/", nil) // single value - r.SetHeaderParam("X-Rate-Limit", "500") + _ = r.SetHeaderParam("X-Rate-Limit", "500") assert.Equal(t, "500", r.header.Get("X-Rate-Limit")) - r.SetHeaderParam("X-Rate-Limit", "400") + _ = r.SetHeaderParam("X-Rate-Limit", "400") assert.Equal(t, "400", r.header.Get("X-Rate-Limit")) // multi value - r.SetHeaderParam("X-Accepts", "json", "xml", "yaml") + _ = r.SetHeaderParam("X-Accepts", "json", "xml", "yaml") assert.EqualValues(t, []string{"json", "xml", "yaml"}, r.header["X-Accepts"]) } func TestBuildRequest_SetPath(t *testing.T) { r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) - r.SetPathParam("id", "1345") + _ = r.SetPathParam("id", "1345") assert.Equal(t, "1345", r.pathParams["id"]) } @@ -59,20 +59,20 @@ func TestBuildRequest_SetQuery(t *testing.T) { r, _ := newRequest("GET", "/flats/{id}/", nil) // single value - r.SetQueryParam("hello", "there") + _ = r.SetQueryParam("hello", "there") assert.Equal(t, "there", r.query.Get("hello")) // multi value - r.SetQueryParam("goodbye", "cruel", "world") + _ = r.SetQueryParam("goodbye", "cruel", "world") assert.Equal(t, []string{"cruel", "world"}, r.query["goodbye"]) } func TestBuildRequest_SetForm(t *testing.T) { // non-multipart r, _ := newRequest("POST", "/flats", nil) - r.SetFormParam("hello", "world") + _ = r.SetFormParam("hello", "world") assert.Equal(t, "world", r.formFields.Get("hello")) - r.SetFormParam("goodbye", "cruel", "world") + _ = r.SetFormParam("goodbye", "cruel", "world") assert.Equal(t, []string{"cruel", "world"}, r.formFields["goodbye"]) } @@ -107,16 +107,16 @@ func TestBuildRequest_SetBody(t *testing.T) { r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - r.SetBodyParam(bd) + _ = r.SetBodyParam(bd) assert.Equal(t, bd, r.payload) } func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) { reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetBodyParam(nil) - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetBodyParam(nil) + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) @@ -133,14 +133,14 @@ func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) { func TestBuildRequest_BuildHTTP_Payload(t *testing.T) { bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetBodyParam(bd) - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetBodyParam(bd) + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { @@ -160,14 +160,14 @@ func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) { Hobby string `xml:"hobby"` }{{xml.Name{}, "Tom", "Organ trail"}, {xml.Name{}, "John", "Bird watching"}} reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetBodyParam(bd) - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetBodyParam(bd) + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime) req, err := r.BuildHTTP(runtime.XMLMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { @@ -183,14 +183,14 @@ func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) { func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) { bd := "Tom: Organ trail; John: Bird watching" reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetBodyParam(bd) - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetBodyParam(bd) + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime) req, err := r.BuildHTTP(runtime.TextMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { @@ -205,14 +205,14 @@ func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) { func TestBuildRequest_BuildHTTP_Form(t *testing.T) { reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetFormParam("something", "some value") - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetFormParam("something", "some value") + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { @@ -227,14 +227,14 @@ func TestBuildRequest_BuildHTTP_Form(t *testing.T) { func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) { reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetFormParam("something", "some value") - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetFormParam("something", "some value") + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { @@ -252,15 +252,15 @@ func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) { func TestBuildRequest_BuildHTTP_Files(t *testing.T) { cont, _ := ioutil.ReadFile("./runtime.go") reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - req.SetFormParam("something", "some value") - req.SetFileParam("file", mustGetFile("./runtime.go")) - req.SetQueryParam("hello", "world") - req.SetPathParam("id", "1234") - req.SetHeaderParam("X-Rate-Limit", "200") + _ = req.SetFormParam("something", "some value") + _ = req.SetFileParam("file", mustGetFile("./runtime.go")) + _ = req.SetQueryParam("hello", "world") + _ = req.SetPathParam("id", "1234") + _ = req.SetHeaderParam("X-Rate-Limit", "200") return nil }) r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) + _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil) if assert.NoError(t, err) && assert.NotNil(t, req) { assert.Equal(t, "200", req.Header.Get("x-rate-limit")) diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index 3fea025c9..6ec9cb6dc 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -214,10 +214,10 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error } var accept []string - for _, mimeType := range operation.ProducesMediaTypes { - accept = append(accept, mimeType) + accept = append(accept, operation.ProducesMediaTypes...) + if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { + return nil, err } - request.SetHeaderParam(runtime.HeaderAccept, accept...) if auth == nil && r.DefaultAuthentication != nil { auth = r.DefaultAuthentication diff --git a/vendor/github.com/go-openapi/runtime/client/runtime_test.go b/vendor/github.com/go-openapi/runtime/client/runtime_test.go index 6572ad78f..1d878f22f 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime_test.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime_test.go @@ -77,7 +77,7 @@ func TestRuntime_Concurrent(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() @@ -153,7 +153,7 @@ func TestRuntime_Canary(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() @@ -204,7 +204,7 @@ func TestRuntime_XMLCanary(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.XMLMime) rw.WriteHeader(http.StatusOK) xmlgen := xml.NewEncoder(rw) - xmlgen.Encode(result) + _ = xmlgen.Encode(result) })) defer server.Close() @@ -245,7 +245,7 @@ func TestRuntime_TextCanary(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Add(runtime.HeaderContentType, runtime.TextMime) rw.WriteHeader(http.StatusOK) - rw.Write([]byte(result)) + _, _ = rw.Write([]byte(result)) })) defer server.Close() @@ -305,7 +305,7 @@ func TestRuntime_CustomTransport(t *testing.T) { resp.Header.Set("content-type", "application/json") buf := bytes.NewBuffer(nil) enc := json.NewEncoder(buf) - enc.Encode(result) + _ = enc.Encode(result) resp.Body = ioutil.NopCloser(buf) return &resp, nil }) @@ -354,7 +354,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode([]task{}) + _ = jsongen.Encode([]task{}) } else { rw.WriteHeader(http.StatusUnauthorized) } @@ -407,7 +407,7 @@ func TestRuntime_AuthCanary(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() @@ -455,13 +455,12 @@ func TestRuntime_PickConsumer(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - req.SetBodyParam(bytes.NewBufferString("hello")) - return nil + return req.SetBodyParam(bytes.NewBufferString("hello")) }) hu, _ := url.Parse(server.URL) @@ -509,7 +508,7 @@ func TestRuntime_ContentTypeCanary(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() @@ -563,7 +562,7 @@ func TestRuntime_ChunkedResponse(t *testing.T) { rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") rw.WriteHeader(http.StatusOK) jsongen := json.NewEncoder(rw) - jsongen.Encode(result) + _ = jsongen.Encode(result) })) defer server.Close() @@ -605,26 +604,26 @@ func TestRuntime_DebugValue(t *testing.T) { original := os.Getenv("DEBUG") // Emtpy DEBUG means Debug is False - os.Setenv("DEBUG", "") + _ = os.Setenv("DEBUG", "") runtime := New("", "/", []string{"https"}) assert.False(t, runtime.Debug) // Non-Empty Debug means Debug is True - os.Setenv("DEBUG", "1") + _ = os.Setenv("DEBUG", "1") runtime = New("", "/", []string{"https"}) assert.True(t, runtime.Debug) - os.Setenv("DEBUG", "true") + _ = os.Setenv("DEBUG", "true") runtime = New("", "/", []string{"https"}) assert.True(t, runtime.Debug) - os.Setenv("DEBUG", "foo") + _ = os.Setenv("DEBUG", "foo") runtime = New("", "/", []string{"https"}) assert.True(t, runtime.Debug) // Make sure DEBUG is initial value once again - os.Setenv("DEBUG", original) + _ = os.Setenv("DEBUG", original) } func TestRuntime_OverrideScheme(t *testing.T) { diff --git a/vendor/github.com/go-openapi/runtime/client_request_test.go b/vendor/github.com/go-openapi/runtime/client_request_test.go index 5fc3a4460..ea93401d3 100644 --- a/vendor/github.com/go-openapi/runtime/client_request_test.go +++ b/vendor/github.com/go-openapi/runtime/client_request_test.go @@ -56,13 +56,13 @@ func (t *trw) SetTimeout(timeout time.Duration) error { func TestRequestWriterFunc(t *testing.T) { hand := ClientRequestWriterFunc(func(r ClientRequest, reg strfmt.Registry) error { - r.SetHeaderParam("blah", "blah blah") - r.SetBodyParam(struct{ Name string }{"Adriana"}) + _ = r.SetHeaderParam("blah", "blah blah") + _ = r.SetBodyParam(struct{ Name string }{"Adriana"}) return nil }) tr := new(trw) - hand.WriteToRequest(tr, nil) + _ = hand.WriteToRequest(tr, nil) assert.Equal(t, "blah blah", tr.Headers.Get("blah")) assert.Equal(t, "Adriana", tr.Body.(struct{ Name string }).Name) } diff --git a/vendor/github.com/go-openapi/runtime/client_response_test.go b/vendor/github.com/go-openapi/runtime/client_response_test.go index d3f5db4d1..7422d349d 100644 --- a/vendor/github.com/go-openapi/runtime/client_response_test.go +++ b/vendor/github.com/go-openapi/runtime/client_response_test.go @@ -52,7 +52,7 @@ func TestResponseReaderFunc(t *testing.T) { actual.Header = r.GetHeader("blah") return actual, nil }) - reader.ReadResponse(response{}, nil) + _, _ = reader.ReadResponse(response{}, nil) assert.Equal(t, "the content", actual.Body) assert.Equal(t, "the message", actual.Message) assert.Equal(t, "the header", actual.Header) diff --git a/vendor/github.com/go-openapi/runtime/interfaces.go b/vendor/github.com/go-openapi/runtime/interfaces.go index 85330aa3f..5f2a472a8 100644 --- a/vendor/github.com/go-openapi/runtime/interfaces.go +++ b/vendor/github.com/go-openapi/runtime/interfaces.go @@ -15,8 +15,10 @@ package runtime import ( - "github.com/go-openapi/strfmt" "io" + "net/http" + + "github.com/go-openapi/strfmt" ) // OperationHandlerFunc an adapter for a function to the OperationHandler interface @@ -77,6 +79,21 @@ type Authenticator interface { Authenticate(interface{}) (bool, interface{}, error) } +// AuthorizerFunc turns a function into an authorizer +type AuthorizerFunc func(*http.Request, interface{}) error + +// Authorize authorizes the processing of the request for the principal +func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error { + return f(r, principal) +} + +// Authorizer represents an authorization strategy +// implementations of Authorizer know how to authorize the principal object +// using the request data and returns error if unauthorized +type Authorizer interface { + Authorize(*http.Request, interface{}) error +} + // Validatable types implementing this interface allow customizing their validation // this will be used instead of the reflective valditation based on the spec document. // the implementations are assumed to have been generated by the swagger tool so they should diff --git a/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go b/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go index e5bf19385..2a066cee1 100644 --- a/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go +++ b/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go @@ -15,7 +15,10 @@ package petstore import ( + goerrors "errors" "io" + "net/http" + "strings" gotest "testing" "github.com/go-openapi/errors" @@ -46,6 +49,8 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) { if username == "admin" && password == "admin" { return "admin", nil + } else if username == "topuser" && password == "topuser" { + return "topuser", nil } return nil, errors.Unauthenticated("basic") })) @@ -55,6 +60,12 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { } return nil, errors.Unauthenticated("token") })) + api.RegisterAuthorizer(runtime.AuthorizerFunc(func(r *http.Request, user interface{}) error { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/pets") && user.(string) != "admin" { + return goerrors.New("unauthorized") + } + return nil + })) api.RegisterOperation("get", "/pets", new(stubOperationHandler)) api.RegisterOperation("post", "/pets", new(stubOperationHandler)) api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler)) @@ -94,6 +105,7 @@ func NewRootAPI(t gotest.TB) (*loads.Document, *untyped.API) { } return nil, errors.Unauthenticated("token") })) + api.RegisterAuthorizer(security.Authorized()) api.RegisterOperation("get", "/pets", new(stubOperationHandler)) api.RegisterOperation("post", "/pets", new(stubOperationHandler)) api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler)) diff --git a/vendor/github.com/go-openapi/runtime/middleware/body_test.go b/vendor/github.com/go-openapi/runtime/middleware/body_test.go index f78783a65..7e8ad0f93 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/body_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/body_test.go @@ -68,12 +68,12 @@ func TestBindRequest_DeleteNoBody(t *testing.T) { ri, rCtx, ok := ctx.RouteInfo(req) if assert.True(t, ok) { req = rCtx - err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { + bverr := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { return nil })) - assert.NoError(t, err) - //assert.Equal(t, io.EOF, err) + assert.NoError(t, bverr) + //assert.Equal(t, io.EOF, bverr) } } diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go index 8b472d9c0..c5c6c6efc 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context.go @@ -75,7 +75,6 @@ type Context struct { analyzer *analysis.Spec api RoutableAPI router Router - formats strfmt.Registry } type routableUntypedAPI struct { @@ -173,6 +172,9 @@ func (r *routableUntypedAPI) ProducersFor(mediaTypes []string) map[string]runtim func (r *routableUntypedAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { return r.api.AuthenticatorsFor(schemes) } +func (r *routableUntypedAPI) Authorizer() runtime.Authorizer { + return r.api.Authorizer() +} func (r *routableUntypedAPI) Formats() strfmt.Registry { return r.api.Formats() } @@ -225,12 +227,9 @@ const ( ctxContentType ctxResponseFormat ctxMatchedRoute - ctxAllowedMethods ctxBoundParams ctxSecurityPrincipal ctxSecurityScopes - - ctxConsumer ) type contentTypeValue struct { @@ -396,6 +395,11 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interfa } continue } + if route.Authorizer != nil { + if err := route.Authorizer.Authorize(request, usr); err != nil { + return nil, nil, errors.New(http.StatusForbidden, err.Error()) + } + } rCtx = stdContext.WithValue(rCtx, ctxSecurityPrincipal, usr) rCtx = stdContext.WithValue(rCtx, ctxSecurityScopes, route.Scopes[scheme]) return usr, request.WithContext(rCtx), nil @@ -542,7 +546,7 @@ func (c *Context) APIHandler(builder Builder) http.Handler { Title: title, } - return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(builder))) + return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b))) } // RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec diff --git a/vendor/github.com/go-openapi/runtime/middleware/context_test.go b/vendor/github.com/go-openapi/runtime/middleware/context_test.go index d02d3c4c3..e236ece89 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context_test.go @@ -39,13 +39,6 @@ func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { return nil, nil } -type testBinder struct { -} - -func (t *testBinder) BindRequest(r *http.Request, m *MatchedRoute) error { - return nil -} - func init() { loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc) } @@ -138,6 +131,32 @@ func TestContextAuthorize(t *testing.T) { assert.Equal(t, request, reqCtx) } +func TestContextAuthorize_WithAuthorizer(t *testing.T) { + spec, api := petstore.NewAPI(t) + ctx := NewContext(spec, api, nil) + ctx.router = DefaultRouter(spec, ctx.api) + + request, _ := runtime.JSONRequest("POST", "/api/pets", nil) + + ri, reqWithCtx, ok := ctx.RouteInfo(request) + assert.True(t, ok) + assert.NotNil(t, reqWithCtx) + + request = reqWithCtx + + request.SetBasicAuth("topuser", "topuser") + p, reqWithCtx, err := ctx.Authorize(request, ri) + assert.Error(t, err) + assert.Nil(t, p) + assert.Nil(t, reqWithCtx) + + request.SetBasicAuth("admin", "admin") + p, reqWithCtx, err = ctx.Authorize(request, ri) + assert.NoError(t, err) + assert.Equal(t, "admin", p) + assert.NotNil(t, reqWithCtx) +} + func TestContextNegotiateContentType(t *testing.T) { spec, api := petstore.NewAPI(t) ctx := NewContext(spec, api, nil) @@ -240,6 +259,7 @@ func TestContextRender(t *testing.T) { ri, request, _ = ctx.RouteInfo(request) ctx.Respond(recorder, request, ri.Produces, ri, nil) assert.Equal(t, 204, recorder.Code) + } func TestContextValidResponseFormat(t *testing.T) { @@ -266,7 +286,7 @@ func TestContextValidResponseFormat(t *testing.T) { assert.Equal(t, ct, cached) // check if the cast works and fetch from cache too - mt, request = ctx.ResponseFormat(request, []string{ct}) + mt, _ = ctx.ResponseFormat(request, []string{ct}) assert.Equal(t, ct, mt) } diff --git a/vendor/github.com/go-openapi/runtime/middleware/header/header.go b/vendor/github.com/go-openapi/runtime/middleware/header/header.go index 4bfde8b86..3e342258b 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/header/header.go +++ b/vendor/github.com/go-openapi/runtime/middleware/header/header.go @@ -46,8 +46,8 @@ func init() { var t octetType isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 - isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 - if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { + isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) + if strings.ContainsRune(" \t\r\n", rune(c)) { t |= isSpace } if isChar && !isCtl && !isSeparator { @@ -167,11 +167,13 @@ func parseValueAndParams(s string) (value string, params map[string]string) { return } +// AcceptSpec ... type AcceptSpec struct { Value string Q float64 } +// ParseAccept2 ... func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) { for _, en := range ParseList(header, key) { v, p := parseValueAndParams(en) diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/vendor/github.com/go-openapi/runtime/middleware/parameter.go index 9eb39c82e..8975b6e1c 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter.go +++ b/vendor/github.com/go-openapi/runtime/middleware/parameter.go @@ -193,28 +193,28 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams } if mt == "multipart/form-data" { - if err := request.ParseMultipartForm(defaultMaxMemory); err != nil { + if err = request.ParseMultipartForm(defaultMaxMemory); err != nil { return errors.NewParseError(p.Name, p.parameter.In, "", err) } } - if err := request.ParseForm(); err != nil { + if err = request.ParseForm(); err != nil { return errors.NewParseError(p.Name, p.parameter.In, "", err) } if p.parameter.Type == "file" { - file, header, err := request.FormFile(p.parameter.Name) - if err != nil { - return errors.NewParseError(p.Name, p.parameter.In, "", err) + file, header, ffErr := request.FormFile(p.parameter.Name) + if ffErr != nil { + return errors.NewParseError(p.Name, p.parameter.In, "", ffErr) } target.Set(reflect.ValueOf(runtime.File{Data: file, Header: header})) return nil } if request.MultipartForm != nil { - data, custom, hasKey, err := p.readValue(runtime.Values(request.MultipartForm.Value), target) - if err != nil { - return err + data, custom, hasKey, rvErr := p.readValue(runtime.Values(request.MultipartForm.Value), target) + if rvErr != nil { + return rvErr } if custom { return nil diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go b/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go index 8cba12145..d0524ab9a 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go @@ -28,9 +28,9 @@ import ( "github.com/stretchr/testify/assert" ) -type email struct { - Address string -} +// type email struct { +// Address string +// } type paramFactory func(string) *spec.Parameter diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go index 23ce367e6..21277948c 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/redoc.go @@ -51,7 +51,7 @@ func Redoc(opts RedocOpts, next http.Handler) http.Handler { tmpl := template.Must(template.New("redoc").Parse(redocTemplate)) buf := bytes.NewBuffer(nil) - tmpl.Execute(buf, opts) + _ = tmpl.Execute(buf, opts) b := buf.Bytes() return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { @@ -59,14 +59,14 @@ func Redoc(opts RedocOpts, next http.Handler) http.Handler { rw.Header().Set("Content-Type", "text/html; charset=utf-8") rw.WriteHeader(http.StatusOK) - rw.Write(b) + _, _ = rw.Write(b) return } if next == nil { rw.Header().Set("Content-Type", "text/plain") rw.WriteHeader(http.StatusNotFound) - rw.Write([]byte(fmt.Sprintf("%q not found", pth))) + _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) return } next.ServeHTTP(rw, r) diff --git a/vendor/github.com/go-openapi/runtime/middleware/request.go b/vendor/github.com/go-openapi/runtime/middleware/request.go index 6171ca71b..ee725f587 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/request.go +++ b/vendor/github.com/go-openapi/runtime/middleware/request.go @@ -54,7 +54,7 @@ func (o *untypedRequestBinder) Bind(request *http.Request, routeParams RoutePara debugLog("binding %d parameters for %s %s", len(o.Parameters), request.Method, request.URL.EscapedPath()) for fieldName, param := range o.Parameters { binder := o.paramBinders[fieldName] - debugLog("binding paramter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath()) + debugLog("binding parameter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath()) var target reflect.Value if !isMap { binder.Name = fieldName diff --git a/vendor/github.com/go-openapi/runtime/middleware/request_test.go b/vendor/github.com/go-openapi/runtime/middleware/request_test.go index 091bad07d..395065b80 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/request_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/request_test.go @@ -67,21 +67,6 @@ type jsonRequestSlice struct { Friend []friend } -type jsonRequestAllTypes struct { - Confirmed bool - Planned strfmt.Date - Delivered strfmt.DateTime - Age int32 - ID int64 - Score float32 - Factor float64 - Friend friend - Name string - Tags []string - Picture []byte - RequestID int64 -} - func parametersForAllTypes(fmt string) map[string]spec.Parameter { if fmt == "" { fmt = "csv" @@ -299,7 +284,7 @@ func TestRequestBindingForValid(t *testing.T) { binder := newUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) lval := []string{"one", "two", "three"} - queryString := "" + var queryString string switch fmt { case "multi": queryString = strings.Join(lval, "&tags=") @@ -428,8 +413,8 @@ func TestBindingFileUpload(t *testing.T) { part, err := writer.CreateFormFile("file", "plain-jane.txt") assert.NoError(t, err) - part.Write([]byte("the file contents")) - writer.WriteField("name", "the-name") + _, _ = part.Write([]byte("the file contents")) + _ = writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) urlStr := "http://localhost:8002/hello" @@ -462,8 +447,8 @@ func TestBindingFileUpload(t *testing.T) { part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") assert.NoError(t, err) - part.Write([]byte("the file contents")) - writer.WriteField("name", "the-name") + _, _ = part.Write([]byte("the file contents")) + _ = writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) @@ -473,7 +458,7 @@ func TestBindingFileUpload(t *testing.T) { req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) - req.MultipartReader() + _, _ = req.MultipartReader() data = fileRequest{} assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) diff --git a/vendor/github.com/go-openapi/runtime/middleware/router.go b/vendor/github.com/go-openapi/runtime/middleware/router.go index 44e7fae38..6ae490508 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/router.go @@ -92,6 +92,7 @@ type RoutableAPI interface { ConsumersFor([]string) map[string]runtime.Consumer ProducersFor([]string) map[string]runtime.Producer AuthenticatorsFor(map[string]spec.SecurityScheme) map[string]runtime.Authenticator + Authorizer() runtime.Authorizer Formats() strfmt.Registry DefaultProduces() string DefaultConsumes() string @@ -112,7 +113,6 @@ type defaultRouteBuilder struct { type defaultRouter struct { spec *loads.Document - api RoutableAPI routers map[string]*denco.Router } @@ -153,6 +153,7 @@ type routeEntry struct { Formats strfmt.Registry Binder *untypedRequestBinder Authenticators map[string]runtime.Authenticator + Authorizer runtime.Authorizer Scopes map[string][]string } @@ -248,6 +249,7 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper Formats: d.api.Formats(), Binder: newUntypedRequestBinder(parameters, d.spec.Spec(), d.api.Formats()), Authenticators: d.api.AuthenticatorsFor(definitions), + Authorizer: d.api.Authorizer(), Scopes: scopes, }) d.records[mn] = append(d.records[mn], record) @@ -258,7 +260,7 @@ func (d *defaultRouteBuilder) Build() *defaultRouter { routers := make(map[string]*denco.Router) for method, records := range d.records { router := denco.New() - router.Build(records) + _ = router.Build(records) routers[method] = router } return &defaultRouter{ diff --git a/vendor/github.com/go-openapi/runtime/middleware/security.go b/vendor/github.com/go-openapi/runtime/middleware/security.go index 1e21a81af..399058310 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/security.go +++ b/vendor/github.com/go-openapi/runtime/middleware/security.go @@ -27,12 +27,12 @@ func newSecureAPI(ctx *Context, next http.Handler) http.Handler { return } - if _, rCtx, err := ctx.Authorize(r, route); err != nil { + _, rCtx, err := ctx.Authorize(r, route) + if err != nil { ctx.Respond(rw, r, route.Produces, route, err) return - } else { - r = rCtx } + r = rCtx next.ServeHTTP(rw, r) }) diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go index 8a09fb75f..72bc5643a 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ b/vendor/github.com/go-openapi/runtime/middleware/spec.go @@ -33,7 +33,7 @@ func Spec(basePath string, b []byte, next http.Handler) http.Handler { if r.URL.Path == pth { rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusOK) - rw.Write(b) + _, _ = rw.Write(b) return } diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go index 3e7b37db8..3b0cd4e28 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go +++ b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go @@ -57,6 +57,7 @@ type API struct { consumers map[string]runtime.Consumer producers map[string]runtime.Producer authenticators map[string]runtime.Authenticator + authorizer runtime.Authorizer operations map[string]map[string]runtime.OperationHandler ServeError func(http.ResponseWriter, *http.Request, error) Models map[string]func() interface{} @@ -105,6 +106,11 @@ func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) { d.authenticators[scheme] = handler } +// RegisterAuthorizer registers an authorizer handler in this api +func (d *API) RegisterAuthorizer(handler runtime.Authorizer) { + d.authorizer = handler +} + // RegisterConsumer registers a consumer for a media type. func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) { if d.consumers == nil { @@ -178,6 +184,11 @@ func (d *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[stri return result } +// AuthorizersFor returns the registered authorizer +func (d *API) Authorizer() runtime.Authorizer { + return d.authorizer +} + // Validate validates this API for any missing items func (d *API) Validate() error { return d.validate() diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go index 580fb6215..551bec71f 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go @@ -16,6 +16,7 @@ package untyped import ( "io" + "net/http" "sort" "testing" @@ -31,6 +32,10 @@ func stubAutenticator() runtime.Authenticator { return runtime.AuthenticatorFunc(func(_ interface{}) (bool, interface{}, error) { return false, nil, nil }) } +func stubAuthorizer() runtime.Authorizer { + return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil }) +} + type stubConsumer struct { } @@ -63,7 +68,9 @@ func TestUntypedAPIRegistrations(t *testing.T) { api.RegisterProducer("application/yada-2", new(stubProducer)) api.RegisterOperation("get", "/{someId}", new(stubOperationHandler)) api.RegisterAuth("basic", stubAutenticator()) + api.RegisterAuthorizer(stubAuthorizer()) + assert.NotNil(t, api.authorizer) assert.NotEmpty(t, api.authenticators) _, ok := api.authenticators["basic"] @@ -79,6 +86,9 @@ func TestUntypedAPIRegistrations(t *testing.T) { _, ok = api.operations["GET"]["/{someId}"] assert.True(t, ok) + authorizer := api.Authorizer() + assert.NotNil(t, authorizer) + h, ok := api.OperationHandlerFor("get", "/{someId}") assert.True(t, ok) assert.NotNil(t, h) diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go b/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go index bc2af1f95..5c226f62e 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go @@ -59,8 +59,8 @@ func TestUntypedFileUpload(t *testing.T) { part, err := writer.CreateFormFile("file", "plain-jane.txt") assert.NoError(t, err) - part.Write([]byte("the file contents")) - writer.WriteField("name", "the-name") + _, _ = part.Write([]byte("the file contents")) + _ = writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) urlStr := "http://localhost:8002/hello" @@ -95,8 +95,8 @@ func TestUntypedFileUpload(t *testing.T) { part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") assert.NoError(t, err) - part.Write([]byte("the file contents")) - writer.WriteField("name", "the-name") + _, _ = part.Write([]byte("the file contents")) + _ = writer.WriteField("name", "the-name") assert.NoError(t, writer.Close()) req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) @@ -106,7 +106,7 @@ func TestUntypedFileUpload(t *testing.T) { req, _ = http.NewRequest("POST", urlStr, body) req.Header.Set("Content-Type", writer.FormDataContentType()) - req.MultipartReader() + _, _ = req.MultipartReader() data = make(map[string]interface{}) assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go index 8d6686f5d..bb8df3cb3 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation.go @@ -24,30 +24,6 @@ import ( "github.com/go-openapi/swag" ) -// NewValidation starts a new validation middleware -func newValidation(ctx *Context, next http.Handler) http.Handler { - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - matched, rCtx, _ := ctx.RouteInfo(r) - if rCtx != nil { - r = rCtx - } - if matched == nil { - ctx.NotFound(rw, r) - return - } - _, r, result := ctx.BindAndValidate(r, matched) - - if result != nil { - ctx.Respond(rw, r, matched.Produces, matched, result) - return - } - - debugLog("no result for %s %s", r.Method, r.URL.EscapedPath()) - next.ServeHTTP(rw, r) - }) -} - type validation struct { context *Context result []error @@ -56,15 +32,6 @@ type validation struct { bound map[string]interface{} } -type untypedBinder map[string]interface{} - -func (ub untypedBinder) BindRequest(r *http.Request, route *MatchedRoute, consumer runtime.Consumer) error { - if err := route.Binder.Bind(r, route.Params, consumer, ub); err != nil { - return err - } - return nil -} - // ContentType validates the content type of a request func validateContentType(allowed []string, actual string) error { debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", ")) diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation_test.go b/vendor/github.com/go-openapi/runtime/middleware/validation_test.go index de9107e1d..10ec57879 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation_test.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation_test.go @@ -26,11 +26,33 @@ import ( "github.com/stretchr/testify/assert" ) +func newTestValidation(ctx *Context, next http.Handler) http.Handler { + + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + matched, rCtx, _ := ctx.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + if matched == nil { + ctx.NotFound(rw, r) + return + } + _, r, result := ctx.BindAndValidate(r, matched) + + if result != nil { + ctx.Respond(rw, r, matched.Produces, matched, result) + return + } + + next.ServeHTTP(rw, r) + }) +} + func TestContentTypeValidation(t *testing.T) { spec, api := petstore.NewAPI(t) context := NewContext(spec, api, nil) context.router = DefaultRouter(spec, context.api) - mw := newValidation(context, http.HandlerFunc(terminator)) + mw := newTestValidation(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/api/pets", nil) @@ -82,7 +104,7 @@ func TestResponseFormatValidation(t *testing.T) { spec, api := petstore.NewAPI(t) context := NewContext(spec, api, nil) context.router = DefaultRouter(spec, context.api) - mw := newValidation(context, http.HandlerFunc(terminator)) + mw := newTestValidation(context, http.HandlerFunc(terminator)) recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`))) diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer.go b/vendor/github.com/go-openapi/runtime/security/authorizer.go new file mode 100644 index 000000000..00c1a4d6a --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/security/authorizer.go @@ -0,0 +1,27 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package security + +import ( + "net/http" + + "github.com/go-openapi/runtime" +) + +// Authorized provides a default implementation of the Authorizer interface where all +// requests are authorized (successful) +func Authorized() runtime.Authorizer { + return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil }) +} diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer_test.go b/vendor/github.com/go-openapi/runtime/security/authorizer_test.go new file mode 100644 index 000000000..7f1f9b053 --- /dev/null +++ b/vendor/github.com/go-openapi/runtime/security/authorizer_test.go @@ -0,0 +1,28 @@ +// Copyright 2015 go-swagger maintainers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package security + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAuthorized(t *testing.T) { + authorizer := Authorized() + + err := authorizer.Authorize(nil, nil) + assert.NoError(t, err) +} diff --git a/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go b/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go index 0e577175a..899dc73d9 100644 --- a/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go +++ b/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go @@ -49,7 +49,7 @@ func TestValidBearerAuth(t *testing.T) { mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - writer.WriteField("access_token", "token123") + _ = writer.WriteField("access_token", "token123") writer.Close() req4, _ := http.NewRequest("POST", "/blah", mpbody) req4.Header.Set("Content-Type", writer.FormDataContentType()) @@ -90,7 +90,7 @@ func TestInvalidBearerAuth(t *testing.T) { mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - writer.WriteField("access_token", "token124") + _ = writer.WriteField("access_token", "token124") writer.Close() req4, _ := http.NewRequest("POST", "/blah", mpbody) req4.Header.Set("Content-Type", writer.FormDataContentType()) @@ -131,7 +131,7 @@ func TestMissingBearerAuth(t *testing.T) { mpbody := bytes.NewBuffer(nil) writer := multipart.NewWriter(mpbody) - writer.WriteField("access_toke", "token123") + _ = writer.WriteField("access_toke", "token123") writer.Close() req4, _ := http.NewRequest("POST", "/blah", mpbody) req4.Header.Set("Content-Type", writer.FormDataContentType()) diff --git a/vendor/github.com/go-openapi/strfmt/time.go b/vendor/github.com/go-openapi/strfmt/time.go index ebf97c7bb..c1e3745b9 100644 --- a/vendor/github.com/go-openapi/strfmt/time.go +++ b/vendor/github.com/go-openapi/strfmt/time.go @@ -55,13 +55,16 @@ func IsDateTime(str string) bool { const ( // RFC3339Millis represents a ISO8601 format to millis instead of to nanos RFC3339Millis = "2006-01-02T15:04:05.000Z07:00" + // RFC3339Micro represents a ISO8601 format to micro instead of to nano + RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00" // DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6 DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$` ) var ( - dateTimeFormats = []string{RFC3339Millis, time.RFC3339, time.RFC3339Nano} + dateTimeFormats = []string{RFC3339Micro, RFC3339Millis, time.RFC3339, time.RFC3339Nano} rxDateTime = regexp.MustCompile(DateTimePattern) + MarshalFormat = RFC3339Millis ) // ParseDateTime parses a string that represents an ISO8601 time or a unix epoch @@ -96,7 +99,7 @@ func NewDateTime() DateTime { } func (t DateTime) String() string { - return time.Time(t).Format(RFC3339Millis) + return time.Time(t).Format(MarshalFormat) } // MarshalText implements the text marshaller interface @@ -145,7 +148,7 @@ func (t DateTime) MarshalJSON() ([]byte, error) { } func (t DateTime) MarshalEasyJSON(w *jwriter.Writer) { - w.String(time.Time(t).Format(RFC3339Millis)) + w.String(time.Time(t).Format(MarshalFormat)) } func (t *DateTime) UnmarshalJSON(data []byte) error { diff --git a/vendor/github.com/go-sql-driver/mysql/AUTHORS b/vendor/github.com/go-sql-driver/mysql/AUTHORS index 5526e3e90..646159940 100644 --- a/vendor/github.com/go-sql-driver/mysql/AUTHORS +++ b/vendor/github.com/go-sql-driver/mysql/AUTHORS @@ -56,6 +56,7 @@ Paul Bonser Peter Schultz Rebecca Chin Runrioter Wung +Shuode Li Soroush Pour Stan Putrya Stanley Gunawan diff --git a/vendor/github.com/go-sql-driver/mysql/README.md b/vendor/github.com/go-sql-driver/mysql/README.md index bfe40e15d..925a69cf1 100644 --- a/vendor/github.com/go-sql-driver/mysql/README.md +++ b/vendor/github.com/go-sql-driver/mysql/README.md @@ -138,9 +138,9 @@ Default: false ``` Type: bool Valid Values: true, false -Default: false +Default: true ``` -`allowNativePasswords=true` allows the usage of the mysql native password method. +`allowNativePasswords=false` disallows the usage of MySQL native password method. ##### `allowOldPasswords` diff --git a/vendor/github.com/go-sql-driver/mysql/connection.go b/vendor/github.com/go-sql-driver/mysql/connection.go index 2630f5211..b07528653 100644 --- a/vendor/github.com/go-sql-driver/mysql/connection.go +++ b/vendor/github.com/go-sql-driver/mysql/connection.go @@ -81,6 +81,16 @@ func (mc *mysqlConn) handleParams() (err error) { return } +func (mc *mysqlConn) markBadConn(err error) error { + if mc == nil { + return err + } + if err != errBadConnNoWrite { + return err + } + return driver.ErrBadConn +} + func (mc *mysqlConn) Begin() (driver.Tx, error) { if mc.closed.IsSet() { errLog.Print(ErrInvalidConn) @@ -90,8 +100,7 @@ func (mc *mysqlConn) Begin() (driver.Tx, error) { if err == nil { return &mysqlTx{mc}, err } - - return nil, err + return nil, mc.markBadConn(err) } func (mc *mysqlConn) Close() (err error) { @@ -142,7 +151,7 @@ func (mc *mysqlConn) Prepare(query string) (driver.Stmt, error) { // Send command err := mc.writeCommandPacketStr(comStmtPrepare, query) if err != nil { - return nil, err + return nil, mc.markBadConn(err) } stmt := &mysqlStmt{ @@ -176,7 +185,7 @@ func (mc *mysqlConn) interpolateParams(query string, args []driver.Value) (strin if buf == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return "", driver.ErrBadConn + return "", ErrInvalidConn } buf = buf[:0] argPos := 0 @@ -314,14 +323,14 @@ func (mc *mysqlConn) Exec(query string, args []driver.Value) (driver.Result, err insertId: int64(mc.insertId), }, err } - return nil, err + return nil, mc.markBadConn(err) } // Internal function to execute commands func (mc *mysqlConn) exec(query string) error { // Send command if err := mc.writeCommandPacketStr(comQuery, query); err != nil { - return err + return mc.markBadConn(err) } // Read Result @@ -390,7 +399,7 @@ func (mc *mysqlConn) query(query string, args []driver.Value) (*textRows, error) return rows, err } } - return nil, err + return nil, mc.markBadConn(err) } // Gets the value of the given MySQL System Variable diff --git a/vendor/github.com/go-sql-driver/mysql/dsn.go b/vendor/github.com/go-sql-driver/mysql/dsn.go index ab2fdfc6a..9cf4bb94a 100644 --- a/vendor/github.com/go-sql-driver/mysql/dsn.go +++ b/vendor/github.com/go-sql-driver/mysql/dsn.go @@ -104,12 +104,12 @@ func (cfg *Config) FormatDSN() string { } } - if cfg.AllowNativePasswords { + if !cfg.AllowNativePasswords { if hasParam { - buf.WriteString("&allowNativePasswords=true") + buf.WriteString("&allowNativePasswords=false") } else { hasParam = true - buf.WriteString("?allowNativePasswords=true") + buf.WriteString("?allowNativePasswords=false") } } @@ -284,8 +284,9 @@ func (cfg *Config) FormatDSN() string { func ParseDSN(dsn string) (cfg *Config, err error) { // New config with some default values cfg = &Config{ - Loc: time.UTC, - Collation: defaultCollation, + Loc: time.UTC, + Collation: defaultCollation, + AllowNativePasswords: true, } // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] diff --git a/vendor/github.com/go-sql-driver/mysql/dsn_test.go b/vendor/github.com/go-sql-driver/mysql/dsn_test.go index d1957f8e8..671af020b 100644 --- a/vendor/github.com/go-sql-driver/mysql/dsn_test.go +++ b/vendor/github.com/go-sql-driver/mysql/dsn_test.go @@ -22,46 +22,49 @@ var testDSNs = []struct { out *Config }{{ "username:password@protocol(address)/dbname?param=value", - &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", - &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC, ColumnsWithAlias: true}, + &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true, ColumnsWithAlias: true}, }, { "username:password@protocol(address)/dbname?param=value&columnsWithAlias=true&multiStatements=true", - &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC, ColumnsWithAlias: true, MultiStatements: true}, + &Config{User: "username", Passwd: "password", Net: "protocol", Addr: "address", DBName: "dbname", Params: map[string]string{"param": "value"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true, ColumnsWithAlias: true, MultiStatements: true}, }, { "user@unix(/path/to/socket)/dbname?charset=utf8", - &Config{User: "user", Net: "unix", Addr: "/path/to/socket", DBName: "dbname", Params: map[string]string{"charset": "utf8"}, Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{User: "user", Net: "unix", Addr: "/path/to/socket", DBName: "dbname", Params: map[string]string{"charset": "utf8"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", - &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", Params: map[string]string{"charset": "utf8"}, Collation: "utf8_general_ci", Loc: time.UTC, TLSConfig: "true"}, + &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", Params: map[string]string{"charset": "utf8"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true, TLSConfig: "true"}, }, { "user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", - &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", Params: map[string]string{"charset": "utf8mb4,utf8"}, Collation: "utf8_general_ci", Loc: time.UTC, TLSConfig: "skip-verify"}, + &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "localhost:5555", DBName: "dbname", Params: map[string]string{"charset": "utf8mb4,utf8"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true, TLSConfig: "skip-verify"}, }, { "user:password@/dbname?loc=UTC&timeout=30s&readTimeout=1s&writeTimeout=1s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci&maxAllowedPacket=16777216", - &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8mb4_unicode_ci", Loc: time.UTC, Timeout: 30 * time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, AllowAllFiles: true, AllowOldPasswords: true, ClientFoundRows: true, MaxAllowedPacket: 16777216}, + &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8mb4_unicode_ci", Loc: time.UTC, AllowNativePasswords: true, Timeout: 30 * time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, AllowAllFiles: true, AllowOldPasswords: true, ClientFoundRows: true, MaxAllowedPacket: 16777216}, +}, { + "user:password@/dbname?allowNativePasswords=false", + &Config{User: "user", Passwd: "password", Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: false}, }, { "user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", - &Config{User: "user", Passwd: "p@ss(word)", Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:80", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.Local}, + &Config{User: "user", Passwd: "p@ss(word)", Net: "tcp", Addr: "[de:ad:be:ef::ca:fe]:80", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.Local, AllowNativePasswords: true}, }, { "/dbname", - &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{Net: "tcp", Addr: "127.0.0.1:3306", DBName: "dbname", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "@/", - &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "/", - &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "", - &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "user:p@/ssword@/", - &Config{User: "user", Passwd: "p@/ssword", Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{User: "user", Passwd: "p@/ssword", Net: "tcp", Addr: "127.0.0.1:3306", Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }, { "unix/?arg=%2Fsome%2Fpath.ext", - &Config{Net: "unix", Addr: "/tmp/mysql.sock", Params: map[string]string{"arg": "/some/path.ext"}, Collation: "utf8_general_ci", Loc: time.UTC}, + &Config{Net: "unix", Addr: "/tmp/mysql.sock", Params: map[string]string{"arg": "/some/path.ext"}, Collation: "utf8_general_ci", Loc: time.UTC, AllowNativePasswords: true}, }} func TestDSNParser(t *testing.T) { @@ -223,8 +226,9 @@ func TestDSNUnsafeCollation(t *testing.T) { func TestParamsAreSorted(t *testing.T) { expected := "/dbname?interpolateParams=true&foobar=baz&quux=loo" dsn := &Config{ - DBName: "dbname", - InterpolateParams: true, + DBName: "dbname", + InterpolateParams: true, + AllowNativePasswords: true, Params: map[string]string{ "quux": "loo", "foobar": "baz", diff --git a/vendor/github.com/go-sql-driver/mysql/errors.go b/vendor/github.com/go-sql-driver/mysql/errors.go index 857854e14..d0d0d2e11 100644 --- a/vendor/github.com/go-sql-driver/mysql/errors.go +++ b/vendor/github.com/go-sql-driver/mysql/errors.go @@ -31,6 +31,12 @@ var ( ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") ErrBusyBuffer = errors.New("busy buffer") + + // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. + // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn + // to trigger a resend. + // See https://github.com/go-sql-driver/mysql/pull/302 + errBadConnNoWrite = errors.New("bad connection") ) var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) diff --git a/vendor/github.com/go-sql-driver/mysql/packets.go b/vendor/github.com/go-sql-driver/mysql/packets.go index 9715067c4..79648d572 100644 --- a/vendor/github.com/go-sql-driver/mysql/packets.go +++ b/vendor/github.com/go-sql-driver/mysql/packets.go @@ -35,7 +35,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { } errLog.Print(err) mc.Close() - return nil, driver.ErrBadConn + return nil, ErrInvalidConn } // packet length [24 bit] @@ -57,7 +57,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { if prevData == nil { errLog.Print(ErrMalformPkt) mc.Close() - return nil, driver.ErrBadConn + return nil, ErrInvalidConn } return prevData, nil @@ -71,7 +71,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) { } errLog.Print(err) mc.Close() - return nil, driver.ErrBadConn + return nil, ErrInvalidConn } // return data if this was the last packet @@ -137,10 +137,14 @@ func (mc *mysqlConn) writePacket(data []byte) error { if cerr := mc.canceled.Value(); cerr != nil { return cerr } + if n == 0 && pktLen == len(data)-4 { + // only for the first loop iteration when nothing was written yet + return errBadConnNoWrite + } mc.cleanup() errLog.Print(err) } - return driver.ErrBadConn + return ErrInvalidConn } } @@ -274,7 +278,7 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // ClientFlags [32 bit] @@ -352,7 +356,9 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error { // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error { // User password - scrambleBuff := scrambleOldPassword(cipher, []byte(mc.cfg.Passwd)) + // https://dev.mysql.com/doc/internals/en/old-password-authentication.html + // Old password authentication only need and will need 8-byte challenge. + scrambleBuff := scrambleOldPassword(cipher[:8], []byte(mc.cfg.Passwd)) // Calculate the packet length and add a tailing 0 pktLen := len(scrambleBuff) + 1 @@ -360,7 +366,7 @@ func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add the scrambled password [null terminated string] @@ -379,7 +385,7 @@ func (mc *mysqlConn) writeClearAuthPacket() error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add the clear password [null terminated string] @@ -392,7 +398,9 @@ func (mc *mysqlConn) writeClearAuthPacket() error { // Native password authentication method // http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse func (mc *mysqlConn) writeNativeAuthPacket(cipher []byte) error { - scrambleBuff := scramblePassword(cipher, []byte(mc.cfg.Passwd)) + // https://dev.mysql.com/doc/internals/en/secure-password-authentication.html + // Native password authentication only need and will need 20-byte challenge. + scrambleBuff := scramblePassword(cipher[0:20], []byte(mc.cfg.Passwd)) // Calculate the packet length and add a tailing 0 pktLen := len(scrambleBuff) @@ -400,7 +408,7 @@ func (mc *mysqlConn) writeNativeAuthPacket(cipher []byte) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add the scramble @@ -421,7 +429,7 @@ func (mc *mysqlConn) writeCommandPacket(command byte) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add command byte @@ -440,7 +448,7 @@ func (mc *mysqlConn) writeCommandPacketStr(command byte, arg string) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add command byte @@ -461,7 +469,7 @@ func (mc *mysqlConn) writeCommandPacketUint32(command byte, arg uint32) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // Add command byte @@ -495,7 +503,7 @@ func (mc *mysqlConn) readResultOK() ([]byte, error) { if len(data) > 1 { pluginEndIndex := bytes.IndexByte(data, 0x00) plugin := string(data[1:pluginEndIndex]) - cipher := data[pluginEndIndex+1 : len(data)-1] + cipher := data[pluginEndIndex+1:] switch plugin { case "mysql_old_password": @@ -927,7 +935,7 @@ func (stmt *mysqlStmt) writeExecutePacket(args []driver.Value) error { if data == nil { // can not take the buffer. Something must be wrong with the connection errLog.Print(ErrBusyBuffer) - return driver.ErrBadConn + return errBadConnNoWrite } // command [1 byte] diff --git a/vendor/github.com/go-sql-driver/mysql/packets_test.go b/vendor/github.com/go-sql-driver/mysql/packets_test.go index 31c892d85..2f8207511 100644 --- a/vendor/github.com/go-sql-driver/mysql/packets_test.go +++ b/vendor/github.com/go-sql-driver/mysql/packets_test.go @@ -9,7 +9,6 @@ package mysql import ( - "database/sql/driver" "errors" "net" "testing" @@ -252,8 +251,8 @@ func TestReadPacketFail(t *testing.T) { conn.data = []byte{0x00, 0x00, 0x00, 0x00} conn.maxReads = 1 _, err := mc.readPacket() - if err != driver.ErrBadConn { - t.Errorf("expected ErrBadConn, got %v", err) + if err != ErrInvalidConn { + t.Errorf("expected ErrInvalidConn, got %v", err) } // reset @@ -264,8 +263,8 @@ func TestReadPacketFail(t *testing.T) { // fail to read header conn.closed = true _, err = mc.readPacket() - if err != driver.ErrBadConn { - t.Errorf("expected ErrBadConn, got %v", err) + if err != ErrInvalidConn { + t.Errorf("expected ErrInvalidConn, got %v", err) } // reset @@ -277,7 +276,7 @@ func TestReadPacketFail(t *testing.T) { // fail to read body conn.maxReads = 1 _, err = mc.readPacket() - if err != driver.ErrBadConn { - t.Errorf("expected ErrBadConn, got %v", err) + if err != ErrInvalidConn { + t.Errorf("expected ErrInvalidConn, got %v", err) } } diff --git a/vendor/github.com/go-sql-driver/mysql/statement.go b/vendor/github.com/go-sql-driver/mysql/statement.go index ae6d33b72..ae223507f 100644 --- a/vendor/github.com/go-sql-driver/mysql/statement.go +++ b/vendor/github.com/go-sql-driver/mysql/statement.go @@ -52,7 +52,7 @@ func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { // Send command err := stmt.writeExecutePacket(args) if err != nil { - return nil, err + return nil, stmt.mc.markBadConn(err) } mc := stmt.mc @@ -100,7 +100,7 @@ func (stmt *mysqlStmt) query(args []driver.Value) (*binaryRows, error) { // Send command err := stmt.writeExecutePacket(args) if err != nil { - return nil, err + return nil, stmt.mc.markBadConn(err) } mc := stmt.mc diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md index 859539732..8dcd71887 100644 --- a/vendor/github.com/gorilla/mux/README.md +++ b/vendor/github.com/gorilla/mux/README.md @@ -274,7 +274,7 @@ This also works for host and query value variables: r := mux.NewRouter() r.Host("{subdomain}.domain.com"). Path("/articles/{category}/{id:[0-9]+}"). - Queries("filter", "{filter}") + Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go index aa195979a..fb69196db 100644 --- a/vendor/github.com/gorilla/mux/mux.go +++ b/vendor/github.com/gorilla/mux/mux.go @@ -13,6 +13,10 @@ import ( "strings" ) +var ( + ErrMethodMismatch = errors.New("method is not allowed") +) + // NewRouter returns a new router instance. func NewRouter() *Router { return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} @@ -39,6 +43,10 @@ func NewRouter() *Router { type Router struct { // Configurable Handler to be used when no route matches. NotFoundHandler http.Handler + + // Configurable Handler to be used when the request method does not match the route. + MethodNotAllowedHandler http.Handler + // Parent route, if this is a subrouter. parent parentRoute // Routes to be matched, in order. @@ -65,6 +73,11 @@ func (r *Router) Match(req *http.Request, match *RouteMatch) bool { } } + if match.MatchErr == ErrMethodMismatch && r.MethodNotAllowedHandler != nil { + match.Handler = r.MethodNotAllowedHandler + return true + } + // Closest match for a router (includes sub-routers) if r.NotFoundHandler != nil { match.Handler = r.NotFoundHandler @@ -105,9 +118,15 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { req = setVars(req, match.Vars) req = setCurrentRoute(req, match.Route) } + + if handler == nil && match.MatchErr == ErrMethodMismatch { + handler = methodNotAllowedHandler() + } + if handler == nil { handler = http.NotFoundHandler() } + if !r.KeepContext { defer contextClear(req) } @@ -344,6 +363,11 @@ type RouteMatch struct { Route *Route Handler http.Handler Vars map[string]string + + // MatchErr is set to appropriate matching error + // It is set to ErrMethodMismatch if there is a mismatch in + // the request method and route method + MatchErr error } type contextKey int @@ -545,3 +569,12 @@ func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]s } return true } + +// methodNotAllowed replies to the request with an HTTP status code 405. +func methodNotAllowed(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusMethodNotAllowed) +} + +// methodNotAllowedHandler returns a simple request handler +// that replies to each request with a status code 405. +func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) } diff --git a/vendor/github.com/gorilla/mux/mux_test.go b/vendor/github.com/gorilla/mux/mux_test.go index f6cfb443d..484fab431 100644 --- a/vendor/github.com/gorilla/mux/mux_test.go +++ b/vendor/github.com/gorilla/mux/mux_test.go @@ -1871,3 +1871,42 @@ func newRequest(method, url string) *http.Request { } return req } + +func TestNoMatchMethodErrorHandler(t *testing.T) { + func1 := func(w http.ResponseWriter, r *http.Request) {} + + r := NewRouter() + r.HandleFunc("/", func1).Methods("GET", "POST") + + req, _ := http.NewRequest("PUT", "http://localhost/", nil) + match := new(RouteMatch) + matched := r.Match(req, match) + + if matched { + t.Error("Should not have matched route for methods") + } + + if match.MatchErr != ErrMethodMismatch { + t.Error("Should get ErrMethodMismatch error") + } + + resp := NewRecorder() + r.ServeHTTP(resp, req) + if resp.Code != 405 { + t.Errorf("Expecting code %v", 405) + } + + // Add matching route + r.HandleFunc("/", func1).Methods("PUT") + + match = new(RouteMatch) + matched = r.Match(req, match) + + if !matched { + t.Error("Should have matched route for methods") + } + + if match.MatchErr != nil { + t.Error("Should not have any matching error. Found:", match.MatchErr) + } +} diff --git a/vendor/github.com/gorilla/mux/old_test.go b/vendor/github.com/gorilla/mux/old_test.go index 9bdc5e5d1..3751e4727 100644 --- a/vendor/github.com/gorilla/mux/old_test.go +++ b/vendor/github.com/gorilla/mux/old_test.go @@ -121,12 +121,7 @@ func TestRouteMatchers(t *testing.T) { var routeMatch RouteMatch matched := router.Match(request, &routeMatch) if matched != shouldMatch { - // Need better messages. :) - if matched { - t.Errorf("Should match.") - } else { - t.Errorf("Should not match.") - } + t.Errorf("Expected: %v\nGot: %v\nRequest: %v %v", shouldMatch, matched, request.Method, url) } if matched { @@ -188,7 +183,6 @@ func TestRouteMatchers(t *testing.T) { match(true) // 2nd route -------------------------------------------------------------- - // Everything match. reset2() match(true) diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go index 6d4a07a20..6863adba5 100644 --- a/vendor/github.com/gorilla/mux/route.go +++ b/vendor/github.com/gorilla/mux/route.go @@ -52,12 +52,27 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool { if r.buildOnly || r.err != nil { return false } + + var matchErr error + // Match everything. for _, m := range r.matchers { if matched := m.Match(req, match); !matched { + if _, ok := m.(methodMatcher); ok { + matchErr = ErrMethodMismatch + continue + } + matchErr = nil return false } } + + if matchErr != nil { + match.MatchErr = matchErr + return false + } + + match.MatchErr = nil // Yay, we have a match. Let's collect some info about it. if match.Route == nil { match.Route = r @@ -68,6 +83,7 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool { if match.Vars == nil { match.Vars = make(map[string]string) } + // Set variables. if r.regexp != nil { r.regexp.setMatch(req, match, r) diff --git a/vendor/github.com/hashicorp/go-memdb/README.md b/vendor/github.com/hashicorp/go-memdb/README.md index 4e051c81a..65e1eaefe 100644 --- a/vendor/github.com/hashicorp/go-memdb/README.md +++ b/vendor/github.com/hashicorp/go-memdb/README.md @@ -3,7 +3,7 @@ Provides the `memdb` package that implements a simple in-memory database built on immutable radix trees. The database provides Atomicity, Consistency and Isolation from ACID. Being that it is in-memory, it does not provide durability. -The database is instantiated with a schema that specifies the tables and indicies +The database is instantiated with a schema that specifies the tables and indices that exist and allows transactions to be executed. The database provides the following: diff --git a/vendor/github.com/hashicorp/go-memdb/filter.go b/vendor/github.com/hashicorp/go-memdb/filter.go new file mode 100644 index 000000000..2e3a9b3f7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-memdb/filter.go @@ -0,0 +1,33 @@ +package memdb + +// FilterFunc is a function that takes the results of an iterator and returns +// whether the result should be filtered out. +type FilterFunc func(interface{}) bool + +// FilterIterator is used to wrap a ResultIterator and apply a filter over it. +type FilterIterator struct { + // filter is the filter function applied over the base iterator. + filter FilterFunc + + // iter is the iterator that is being wrapped. + iter ResultIterator +} + +func NewFilterIterator(wrap ResultIterator, filter FilterFunc) *FilterIterator { + return &FilterIterator{ + filter: filter, + iter: wrap, + } +} + +// WatchCh returns the watch channel of the wrapped iterator. +func (f *FilterIterator) WatchCh() <-chan struct{} { return f.iter.WatchCh() } + +// Next returns the next non-filtered result from the wrapped iterator +func (f *FilterIterator) Next() interface{} { + for { + if value := f.iter.Next(); value == nil || !f.filter(value) { + return value + } + } +} diff --git a/vendor/github.com/hashicorp/go-memdb/filter_test.go b/vendor/github.com/hashicorp/go-memdb/filter_test.go new file mode 100644 index 000000000..19a5e68f2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-memdb/filter_test.go @@ -0,0 +1,122 @@ +package memdb + +import "testing" + +// Test that the iterator meets the required interface +func TestFilterIterator_Interface(t *testing.T) { + var _ ResultIterator = &FilterIterator{} +} + +func TestFilterIterator(t *testing.T) { + db := testDB(t) + txn := db.Txn(true) + + obj1 := &TestObject{ + ID: "a", + Foo: "xyz", + Qux: []string{"xyz1"}, + } + obj2 := &TestObject{ + ID: "medium-length", + Foo: "xyz", + Qux: []string{"xyz1", "xyz2"}, + } + obj3 := &TestObject{ + ID: "super-long-unique-identifier", + Foo: "xyz", + Qux: []string{"xyz1", "xyz2"}, + } + + err := txn.Insert("main", obj1) + if err != nil { + t.Fatalf("err: %v", err) + } + err = txn.Insert("main", obj2) + if err != nil { + t.Fatalf("err: %v", err) + } + err = txn.Insert("main", obj3) + if err != nil { + t.Fatalf("err: %v", err) + } + + filterFactory := func(idLengthLimit int) func(interface{}) bool { + limit := idLengthLimit + return func(raw interface{}) bool { + obj, ok := raw.(*TestObject) + if !ok { + return true + } + + return len(obj.ID) > limit + } + } + + checkResult := func(txn *Txn) { + // Attempt a row scan on the ID + result, err := txn.Get("main", "id") + if err != nil { + t.Fatalf("err: %v", err) + } + + // Wrap the iterator and try various filters + filter := NewFilterIterator(result, filterFactory(6)) + if raw := filter.Next(); raw != obj1 { + t.Fatalf("bad: %#v %#v", raw, obj1) + } + + if raw := filter.Next(); raw != nil { + t.Fatalf("bad: %#v %#v", raw, nil) + } + + result, err = txn.Get("main", "id") + if err != nil { + t.Fatalf("err: %v", err) + } + + filter = NewFilterIterator(result, filterFactory(15)) + if raw := filter.Next(); raw != obj1 { + t.Fatalf("bad: %#v %#v", raw, obj1) + } + + if raw := filter.Next(); raw != obj2 { + t.Fatalf("bad: %#v %#v", raw, obj2) + } + + if raw := filter.Next(); raw != nil { + t.Fatalf("bad: %#v %#v", raw, nil) + } + + result, err = txn.Get("main", "id") + if err != nil { + t.Fatalf("err: %v", err) + } + + filter = NewFilterIterator(result, filterFactory(150)) + if raw := filter.Next(); raw != obj1 { + t.Fatalf("bad: %#v %#v", raw, obj1) + } + + if raw := filter.Next(); raw != obj2 { + t.Fatalf("bad: %#v %#v", raw, obj2) + } + + if raw := filter.Next(); raw != obj3 { + t.Fatalf("bad: %#v %#v", raw, obj3) + } + + if raw := filter.Next(); raw != nil { + t.Fatalf("bad: %#v %#v", raw, nil) + } + } + + // Check the results within the txn + checkResult(txn) + + // Commit and start a new read transaction + txn.Commit() + txn = db.Txn(false) + + // Check the results in a new txn + checkResult(txn) +} diff --git a/vendor/github.com/hashicorp/go-memdb/memdb.go b/vendor/github.com/hashicorp/go-memdb/memdb.go index 994a35232..9e9b98df5 100644 --- a/vendor/github.com/hashicorp/go-memdb/memdb.go +++ b/vendor/github.com/hashicorp/go-memdb/memdb.go @@ -76,7 +76,7 @@ func (db *MemDB) Snapshot() *MemDB { func (db *MemDB) initialize() error { root := db.getRoot() for tName, tableSchema := range db.schema.Tables { - for iName, _ := range tableSchema.Indexes { + for iName := range tableSchema.Indexes { index := iradix.New() path := indexPath(tName, iName) root, _, _ = root.Insert(path, index) diff --git a/vendor/github.com/hashicorp/go-memdb/watch-gen/main.go b/vendor/github.com/hashicorp/go-memdb/watch-gen/main.go index ce6e7c858..ce1def4fd 100644 --- a/vendor/github.com/hashicorp/go-memdb/watch-gen/main.go +++ b/vendor/github.com/hashicorp/go-memdb/watch-gen/main.go @@ -17,11 +17,12 @@ import ( const aFew = 32 // source is the template we use to generate the source file. -const source = `//go:generate sh -c "go run watch-gen/main.go >watch_few.go" -package memdb +const source = `package memdb + +//go:generate sh -c "go run watch-gen/main.go >watch_few.go" import( - "time" + "context" ) // aFew gives how many watchers this function is wired to support. You must @@ -30,14 +31,14 @@ const aFew = {{len .}} // watchFew is used if there are only a few watchers as a performance // optimization. -func watchFew(ch []<-chan struct{}, timeoutCh <-chan time.Time) bool { +func watchFew(ctx context.Context, ch []<-chan struct{}) error { select { {{range $i, $unused := .}} case <-ch[{{printf "%d" $i}}]: - return false + return nil {{end}} - case <-timeoutCh: - return true + case <-ctx.Done(): + return ctx.Err() } } ` diff --git a/vendor/github.com/hashicorp/go-memdb/watch.go b/vendor/github.com/hashicorp/go-memdb/watch.go index 7c4a3ba6e..a6f01213b 100644 --- a/vendor/github.com/hashicorp/go-memdb/watch.go +++ b/vendor/github.com/hashicorp/go-memdb/watch.go @@ -1,6 +1,9 @@ package memdb -import "time" +import ( + "context" + "time" +) // WatchSet is a collection of watch channels. type WatchSet map[<-chan struct{}]struct{} @@ -46,6 +49,29 @@ func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { return false } + // Create a context that gets cancelled when the timeout is triggered + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + go func() { + select { + case <-timeoutCh: + cancel() + case <-ctx.Done(): + } + }() + + return w.WatchCtx(ctx) == context.Canceled +} + +// WatchCtx is used to wait for either the watch set to trigger or for the +// context to be cancelled. Watch with a timeout channel can be mimicked by +// creating a context with a deadline. WatchCtx should be preferred over Watch. +func (w WatchSet) WatchCtx(ctx context.Context) error { + if w == nil { + return nil + } + if n := len(w); n <= aFew { idx := 0 chunk := make([]<-chan struct{}, aFew) @@ -53,23 +79,18 @@ func (w WatchSet) Watch(timeoutCh <-chan time.Time) bool { chunk[idx] = watchCh idx++ } - return watchFew(chunk, timeoutCh) - } else { - return w.watchMany(timeoutCh) + return watchFew(ctx, chunk) } + + return w.watchMany(ctx) } // watchMany is used if there are many watchers. -func (w WatchSet) watchMany(timeoutCh <-chan time.Time) bool { - // Make a fake timeout channel we can feed into watchFew to cancel all - // the blocking goroutines. - doneCh := make(chan time.Time) - defer close(doneCh) - +func (w WatchSet) watchMany(ctx context.Context) error { // Set up a goroutine for each watcher. triggerCh := make(chan struct{}, 1) watcher := func(chunk []<-chan struct{}) { - if timeout := watchFew(chunk, doneCh); !timeout { + if err := watchFew(ctx, chunk); err == nil { select { case triggerCh <- struct{}{}: default: @@ -101,8 +122,8 @@ func (w WatchSet) watchMany(timeoutCh <-chan time.Time) bool { // Wait for a channel to trigger or timeout. select { case <-triggerCh: - return false - case <-timeoutCh: - return true + return nil + case <-ctx.Done(): + return ctx.Err() } } diff --git a/vendor/github.com/hashicorp/go-memdb/watch_few.go b/vendor/github.com/hashicorp/go-memdb/watch_few.go index f2bb19db1..880f098b7 100644 --- a/vendor/github.com/hashicorp/go-memdb/watch_few.go +++ b/vendor/github.com/hashicorp/go-memdb/watch_few.go @@ -1,8 +1,9 @@ -//go:generate sh -c "go run watch-gen/main.go >watch_few.go" package memdb +//go:generate sh -c "go run watch-gen/main.go >watch_few.go" + import( - "time" + "context" ) // aFew gives how many watchers this function is wired to support. You must @@ -11,106 +12,106 @@ const aFew = 32 // watchFew is used if there are only a few watchers as a performance // optimization. -func watchFew(ch []<-chan struct{}, timeoutCh <-chan time.Time) bool { +func watchFew(ctx context.Context, ch []<-chan struct{}) error { select { case <-ch[0]: - return false + return nil case <-ch[1]: - return false + return nil case <-ch[2]: - return false + return nil case <-ch[3]: - return false + return nil case <-ch[4]: - return false + return nil case <-ch[5]: - return false + return nil case <-ch[6]: - return false + return nil case <-ch[7]: - return false + return nil case <-ch[8]: - return false + return nil case <-ch[9]: - return false + return nil case <-ch[10]: - return false + return nil case <-ch[11]: - return false + return nil case <-ch[12]: - return false + return nil case <-ch[13]: - return false + return nil case <-ch[14]: - return false + return nil case <-ch[15]: - return false + return nil case <-ch[16]: - return false + return nil case <-ch[17]: - return false + return nil case <-ch[18]: - return false + return nil case <-ch[19]: - return false + return nil case <-ch[20]: - return false + return nil case <-ch[21]: - return false + return nil case <-ch[22]: - return false + return nil case <-ch[23]: - return false + return nil case <-ch[24]: - return false + return nil case <-ch[25]: - return false + return nil case <-ch[26]: - return false + return nil case <-ch[27]: - return false + return nil case <-ch[28]: - return false + return nil case <-ch[29]: - return false + return nil case <-ch[30]: - return false + return nil case <-ch[31]: - return false + return nil - case <-timeoutCh: - return true + case <-ctx.Done(): + return ctx.Err() } } diff --git a/vendor/github.com/hashicorp/go-memdb/watch_test.go b/vendor/github.com/hashicorp/go-memdb/watch_test.go index 4f0f913fb..c622c62ef 100644 --- a/vendor/github.com/hashicorp/go-memdb/watch_test.go +++ b/vendor/github.com/hashicorp/go-memdb/watch_test.go @@ -1,6 +1,7 @@ package memdb import ( + "context" "fmt" "testing" "time" @@ -8,8 +9,9 @@ import ( // testWatch makes a bunch of watch channels based on the given size and fires // the one at the given fire index to make sure it's detected (or a timeout -// occurs if the fire index isn't hit). -func testWatch(size, fire int) error { +// occurs if the fire index isn't hit). useCtx parameterizes whether the context +// based watch is used or timer based. +func testWatch(size, fire int, useCtx bool) error { shouldTimeout := true ws := NewWatchSet() for i := 0; i < size; i++ { @@ -21,10 +23,22 @@ func testWatch(size, fire int) error { } } - timeoutCh := make(chan time.Time) + var timeoutCh chan time.Time + var ctx context.Context + var cancelFn context.CancelFunc + if useCtx { + ctx, cancelFn = context.WithCancel(context.Background()) + } else { + timeoutCh = make(chan time.Time) + } + doneCh := make(chan bool, 1) go func() { - doneCh <- ws.Watch(timeoutCh) + if useCtx { + doneCh <- ws.WatchCtx(ctx) != nil + } else { + doneCh <- ws.Watch(timeoutCh) + } }() if shouldTimeout { @@ -34,7 +48,11 @@ func testWatch(size, fire int) error { default: } - close(timeoutCh) + if useCtx { + cancelFn() + } else { + close(timeoutCh) + } select { case didTimeout := <-doneCh: if !didTimeout { @@ -52,28 +70,39 @@ func testWatch(size, fire int) error { case <-time.After(10 * time.Second): return fmt.Errorf("should have triggered") } - close(timeoutCh) + if useCtx { + cancelFn() + } else { + close(timeoutCh) + } } return nil } func TestWatch(t *testing.T) { - // Sweep through a bunch of chunks to hit the various cases of dividing - // the work into watchFew calls. - for size := 0; size < 3*aFew; size++ { - // Fire each possible channel slot. - for fire := 0; fire < size; fire++ { - if err := testWatch(size, fire); err != nil { - t.Fatalf("err %d %d: %v", size, fire, err) + testFactory := func(useCtx bool) func(t *testing.T) { + return func(t *testing.T) { + // Sweep through a bunch of chunks to hit the various cases of dividing + // the work into watchFew calls. + for size := 0; size < 3*aFew; size++ { + // Fire each possible channel slot. + for fire := 0; fire < size; fire++ { + if err := testWatch(size, fire, useCtx); err != nil { + t.Fatalf("err %d %d: %v", size, fire, err) + } + } + + // Run a timeout case as well. + fire := -1 + if err := testWatch(size, fire, useCtx); err != nil { + t.Fatalf("err %d %d: %v", size, fire, err) + } } } - - // Run a timeout case as well. - fire := -1 - if err := testWatch(size, fire); err != nil { - t.Fatalf("err %d %d: %v", size, fire, err) - } } + + t.Run("Timer", testFactory(false)) + t.Run("Context", testFactory(true)) } func TestWatch_AddWithLimit(t *testing.T) { diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index b4881806e..098e1bc49 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -197,9 +197,12 @@ func (p *Parser) objectItem() (*ast.ObjectItem, error) { keyStr = append(keyStr, k.Token.Text) } - return nil, fmt.Errorf( - "key '%s' expected start of object ('{') or assignment ('=')", - strings.Join(keyStr, " ")) + return nil, &PosError{ + Pos: p.tok.Pos, + Err: fmt.Errorf( + "key '%s' expected start of object ('{') or assignment ('=')", + strings.Join(keyStr, " ")), + } } // do a look-ahead for line comment @@ -319,7 +322,10 @@ func (p *Parser) objectType() (*ast.ObjectType, error) { // No error, scan and expect the ending to be a brace if tok := p.scan(); tok.Type != token.RBRACE { - return nil, fmt.Errorf("object expected closing RBRACE got: %s", tok.Type) + return nil, &PosError{ + Pos: tok.Pos, + Err: fmt.Errorf("object expected closing RBRACE got: %s", tok.Type), + } } o.List = l diff --git a/vendor/github.com/json-iterator/go/extra/fuzzy_decoder.go b/vendor/github.com/json-iterator/go/extra/fuzzy_decoder.go index df602f342..2dae7af45 100644 --- a/vendor/github.com/json-iterator/go/extra/fuzzy_decoder.go +++ b/vendor/github.com/json-iterator/go/extra/fuzzy_decoder.go @@ -7,6 +7,7 @@ import ( "reflect" "strings" "unsafe" + "io" ) const maxUint = ^uint(0) @@ -206,7 +207,7 @@ func (decoder *fuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.It defer iter.Pool().ReturnIterator(newIter) isFloat := strings.IndexByte(str, '.') != -1 decoder.fun(isFloat, ptr, newIter) - if newIter.Error != nil { + if newIter.Error != nil && newIter.Error != io.EOF { iter.Error = newIter.Error } } @@ -225,7 +226,7 @@ func (decoder *fuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.It newIter := iter.Pool().BorrowIterator([]byte(str)) defer iter.Pool().ReturnIterator(newIter) *((*float32)(ptr)) = newIter.ReadFloat32() - if newIter.Error != nil { + if newIter.Error != nil && newIter.Error != io.EOF { iter.Error = newIter.Error } default: @@ -247,7 +248,7 @@ func (decoder *fuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.It newIter := iter.Pool().BorrowIterator([]byte(str)) defer iter.Pool().ReturnIterator(newIter) *((*float64)(ptr)) = newIter.ReadFloat64() - if newIter.Error != nil { + if newIter.Error != nil && newIter.Error != io.EOF { iter.Error = newIter.Error } default: diff --git a/vendor/github.com/json-iterator/go/extra/fuzzy_decoder_test.go b/vendor/github.com/json-iterator/go/extra/fuzzy_decoder_test.go index c4aad6807..a59bf7c51 100644 --- a/vendor/github.com/json-iterator/go/extra/fuzzy_decoder_test.go +++ b/vendor/github.com/json-iterator/go/extra/fuzzy_decoder_test.go @@ -257,3 +257,24 @@ func Test_empty_array_as_object(t *testing.T) { should.Nil(jsoniter.UnmarshalFromString(`[]`, &val)) should.Equal(struct{}{}, val) } + +func Test_bad_case(t *testing.T) { + var jsonstr = ` +{ + "extra_type": 181760, + "combo_type": 0, + "trigger_time_ms": 1498800398000, + "_create_time": "2017-06-16 11:21:39", + "_msg_type": 41000 +} +` + + type OrderEventRequestParams struct { + ExtraType uint64 `json:"extra_type"` + } + + var a OrderEventRequestParams + err := jsoniter.UnmarshalFromString(jsonstr, &a) + should := require.New(t) + should.Nil(err) +} diff --git a/vendor/github.com/json-iterator/go/feature_config.go b/vendor/github.com/json-iterator/go/feature_config.go index 3c64b6bb3..fc055d504 100644 --- a/vendor/github.com/json-iterator/go/feature_config.go +++ b/vendor/github.com/json-iterator/go/feature_config.go @@ -17,6 +17,7 @@ type Config struct { EscapeHTML bool SortMapKeys bool UseNumber bool + TagKey string } type frozenConfig struct { @@ -95,6 +96,13 @@ func (cfg *frozenConfig) useNumber() { } }}) } +func (cfg *frozenConfig) getTagKey() string { + tagKey := cfg.configBeforeFrozen.TagKey + if tagKey == "" { + return "json" + } + return tagKey +} func (cfg *frozenConfig) registerExtension(extension Extension) { cfg.extensions = append(cfg.extensions, extension) diff --git a/vendor/github.com/json-iterator/go/feature_iter.go b/vendor/github.com/json-iterator/go/feature_iter.go index 82e49da5c..4357d69ba 100644 --- a/vendor/github.com/json-iterator/go/feature_iter.go +++ b/vendor/github.com/json-iterator/go/feature_iter.go @@ -285,14 +285,18 @@ func (iter *Iterator) Read() interface{} { case ArrayValue: arr := []interface{}{} iter.ReadArrayCB(func(iter *Iterator) bool { - arr = append(arr, iter.Read()) + var elem interface{} + iter.ReadVal(&elem) + arr = append(arr, elem) return true }) return arr case ObjectValue: obj := map[string]interface{}{} iter.ReadMapCB(func(Iter *Iterator, field string) bool { - obj[field] = iter.Read() + var elem interface{} + iter.ReadVal(&elem) + obj[field] = elem return true }) return obj diff --git a/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go b/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go index d26763825..cc1933de2 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go +++ b/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go @@ -64,7 +64,7 @@ func (iter *Iterator) trySkipString() bool { } else if c == '\\' { return false } else if c < ' ' { - iter.ReportError("ReadString", + iter.ReportError("trySkipString", fmt.Sprintf(`invalid control character found: %d`, c)) return true // already failed } diff --git a/vendor/github.com/json-iterator/go/feature_iter_string.go b/vendor/github.com/json-iterator/go/feature_iter_string.go index b76460046..59174ea4b 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_string.go +++ b/vendor/github.com/json-iterator/go/feature_iter_string.go @@ -47,7 +47,7 @@ func (iter *Iterator) readStringSlowPath() (ret string) { str = append(str, c) } } - iter.ReportError("ReadString", "unexpected end of input") + iter.ReportError("readStringSlowPath", "unexpected end of input") return } @@ -104,7 +104,7 @@ func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { case 't': str = append(str, '\t') default: - iter.ReportError("ReadString", + iter.ReportError("readEscapedChar", `invalid escape char after \`) return nil } @@ -139,7 +139,7 @@ func (iter *Iterator) ReadStringAsSlice() (ret []byte) { } return copied } - iter.ReportError("ReadString", `expects " or n`) + iter.ReportError("ReadStringAsSlice", `expects " or n`) return } diff --git a/vendor/github.com/json-iterator/go/feature_json_number.go b/vendor/github.com/json-iterator/go/feature_json_number.go index aba538499..0439f6725 100644 --- a/vendor/github.com/json-iterator/go/feature_json_number.go +++ b/vendor/github.com/json-iterator/go/feature_json_number.go @@ -12,4 +12,4 @@ func CastJsonNumber(val interface{}) (string, bool) { return string(typedVal), true } return "", false -} \ No newline at end of file +} diff --git a/vendor/github.com/json-iterator/go/feature_reflect.go b/vendor/github.com/json-iterator/go/feature_reflect.go index 05d91b49c..7c3006ee8 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect.go +++ b/vendor/github.com/json-iterator/go/feature_reflect.go @@ -466,6 +466,19 @@ func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error } 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, + } + encoder = &optionalEncoder{encoder} + return encoder, nil + } if typ.Implements(textMarshalerType) { checkIsEmpty, err := createCheckIsEmpty(typ) if err != nil { diff --git a/vendor/github.com/json-iterator/go/feature_reflect_extension.go b/vendor/github.com/json-iterator/go/feature_reflect_extension.go index 7321566b6..3dd38299d 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_extension.go +++ b/vendor/github.com/json-iterator/go/feature_reflect_extension.go @@ -227,7 +227,7 @@ func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, err bindings := []*Binding{} for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) - tag := field.Tag.Get("json") + tag := field.Tag.Get(cfg.getTagKey()) tagParts := strings.Split(tag, ",") if tag == "-" { continue @@ -373,7 +373,7 @@ 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("json"), ",") + tagParts := strings.Split(binding.Field.Tag.Get(cfg.getTagKey()), ",") for _, tagPart := range tagParts[1:] { if tagPart == "omitempty" { shouldOmitEmpty = true diff --git a/vendor/github.com/json-iterator/go/feature_reflect_native.go b/vendor/github.com/json-iterator/go/feature_reflect_native.go index b37dab3d8..0832101f5 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_native.go +++ b/vendor/github.com/json-iterator/go/feature_reflect_native.go @@ -31,6 +31,10 @@ type intCodec struct { } func (codec *intCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*int)(ptr)) = 0 + return + } *((*int)(ptr)) = iter.ReadInt() } @@ -50,6 +54,10 @@ type uintptrCodec struct { } func (codec *uintptrCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uintptr)(ptr)) = 0 + return + } *((*uintptr)(ptr)) = uintptr(iter.ReadUint64()) } @@ -69,6 +77,10 @@ type int8Codec struct { } func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint8)(ptr)) = 0 + return + } *((*int8)(ptr)) = iter.ReadInt8() } @@ -88,6 +100,10 @@ type int16Codec struct { } func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*int16)(ptr)) = 0 + return + } *((*int16)(ptr)) = iter.ReadInt16() } @@ -107,6 +123,10 @@ type int32Codec struct { } func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*int32)(ptr)) = 0 + return + } *((*int32)(ptr)) = iter.ReadInt32() } @@ -126,6 +146,10 @@ type int64Codec struct { } func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*int64)(ptr)) = 0 + return + } *((*int64)(ptr)) = iter.ReadInt64() } @@ -145,6 +169,10 @@ type uintCodec struct { } func (codec *uintCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint)(ptr)) = 0 + return + } *((*uint)(ptr)) = iter.ReadUint() } @@ -164,6 +192,10 @@ type uint8Codec struct { } func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint8)(ptr)) = 0 + return + } *((*uint8)(ptr)) = iter.ReadUint8() } @@ -183,6 +215,10 @@ type uint16Codec struct { } func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint16)(ptr)) = 0 + return + } *((*uint16)(ptr)) = iter.ReadUint16() } @@ -202,6 +238,10 @@ type uint32Codec struct { } func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint32)(ptr)) = 0 + return + } *((*uint32)(ptr)) = iter.ReadUint32() } @@ -221,6 +261,10 @@ type uint64Codec struct { } func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*uint64)(ptr)) = 0 + return + } *((*uint64)(ptr)) = iter.ReadUint64() } @@ -240,6 +284,10 @@ type float32Codec struct { } func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*float32)(ptr)) = 0 + return + } *((*float32)(ptr)) = iter.ReadFloat32() } @@ -259,6 +307,10 @@ type float64Codec struct { } func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*float64)(ptr)) = 0 + return + } *((*float64)(ptr)) = iter.ReadFloat64() } diff --git a/vendor/github.com/json-iterator/go/feature_reflect_object.go b/vendor/github.com/json-iterator/go/feature_reflect_object.go index 2a4283c1c..59b1235c0 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_object.go +++ b/vendor/github.com/json-iterator/go/feature_reflect_object.go @@ -4,8 +4,8 @@ import ( "fmt" "io" "reflect" - "unsafe" "strings" + "unsafe" ) func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { @@ -29,7 +29,7 @@ func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { if old.toName != toName { continue } - old.ignored, new.ignored = resolveConflictBinding(old.binding, new.binding) + old.ignored, new.ignored = resolveConflictBinding(cfg, old.binding, new.binding) } orderedBindings = append(orderedBindings, new) } @@ -49,9 +49,9 @@ func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { return &structEncoder{structDescriptor.onePtrEmbedded, structDescriptor.onePtrOptimization, finalOrderedFields}, nil } -func resolveConflictBinding(old, new *Binding) (ignoreOld, ignoreNew bool) { - newTagged := new.Field.Tag.Get("json") != "" - oldTagged := old.Field.Tag.Get("json") != "" +func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { + 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) { @@ -91,7 +91,7 @@ func decoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { bindings[fromName] = binding continue } - ignoreOld, ignoreNew := resolveConflictBinding(old, binding) + ignoreOld, ignoreNew := resolveConflictBinding(cfg, old, binding) if ignoreOld { delete(bindings, fromName) } diff --git a/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go index 797b143a2..b3417fd73 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go +++ b/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go @@ -4,8 +4,8 @@ import ( "fmt" "io" "reflect" - "unsafe" "strings" + "unsafe" ) func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder) (ValDecoder, error) { diff --git a/vendor/github.com/json-iterator/go/feature_stream_string.go b/vendor/github.com/json-iterator/go/feature_stream_string.go index 2856836f7..334282f05 100644 --- a/vendor/github.com/json-iterator/go/feature_stream_string.go +++ b/vendor/github.com/json-iterator/go/feature_stream_string.go @@ -289,6 +289,8 @@ func writeStringSlowPathWithHTMLEscaped(stream *Stream, i int, s string, valLen if start < i { stream.WriteRaw(s[start:i]) } + stream.WriteRaw(`\ufffd`) + i++ start = i continue } diff --git a/vendor/github.com/json-iterator/go/jsoniter_customize_test.go b/vendor/github.com/json-iterator/go/jsoniter_customize_test.go index d625f6e33..b4bf5294b 100644 --- a/vendor/github.com/json-iterator/go/jsoniter_customize_test.go +++ b/vendor/github.com/json-iterator/go/jsoniter_customize_test.go @@ -285,3 +285,56 @@ func Test_marshal_json_with_time(t *testing.T) { 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_int_test.go b/vendor/github.com/json-iterator/go/jsoniter_int_test.go index 9d639d70b..79670c77c 100644 --- a/vendor/github.com/json-iterator/go/jsoniter_int_test.go +++ b/vendor/github.com/json-iterator/go/jsoniter_int_test.go @@ -20,7 +20,45 @@ func Test_read_uint64_invalid(t *testing.T) { should.NotNil(iter.Error) } -func Test_read_int8(t *testing.T) { +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) { diff --git a/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go b/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go index 358c19a7b..9f30bf5d8 100644 --- a/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go +++ b/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go @@ -1,6 +1,7 @@ package jsoniter import ( + "bytes" "encoding/json" "github.com/stretchr/testify/require" "io" @@ -98,3 +99,34 @@ func Test_invalid_float(t *testing.T) { }) } } + +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)) +} 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 index 93ab4813f..257bbdb65 100644 --- a/vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go +++ b/vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go @@ -1,8 +1,8 @@ package jsoniter import ( - "testing" "github.com/stretchr/testify/require" + "testing" ) func Test_decode_one_field_struct(t *testing.T) { diff --git a/vendor/github.com/magiconair/properties/.travis.yml b/vendor/github.com/magiconair/properties/.travis.yml index 60436b202..ab9803902 100644 --- a/vendor/github.com/magiconair/properties/.travis.yml +++ b/vendor/github.com/magiconair/properties/.travis.yml @@ -5,4 +5,5 @@ go: - 1.6.x - 1.7.x - 1.8.x + - 1.9.x - tip diff --git a/vendor/github.com/magiconair/properties/CHANGELOG.md b/vendor/github.com/magiconair/properties/CHANGELOG.md index 4905fec99..ebd1bcd32 100644 --- a/vendor/github.com/magiconair/properties/CHANGELOG.md +++ b/vendor/github.com/magiconair/properties/CHANGELOG.md @@ -1,5 +1,10 @@ ## Changelog +### Unreleased + + * [PR #24](https://github.com/magiconair/properties/pull/24): Update keys when DisableExpansion is enabled + Thanks to @mgurov for the fix. + ### [1.7.3](https://github.com/magiconair/properties/tags/v1.7.3) - 10 Jul 2017 * [Issue #17](https://github.com/magiconair/properties/issues/17): Add [SetValue()](http://godoc.org/github.com/magiconair/properties#Properties.SetValue) method to set values generically diff --git a/vendor/github.com/magiconair/properties/properties.go b/vendor/github.com/magiconair/properties/properties.go index 4f3d5a458..85bb18618 100644 --- a/vendor/github.com/magiconair/properties/properties.go +++ b/vendor/github.com/magiconair/properties/properties.go @@ -511,6 +511,9 @@ func (p *Properties) Set(key, value string) (prev string, ok bool, err error) { if p.DisableExpansion { prev, ok = p.Get(key) p.m[key] = value + if !ok { + p.k = append(p.k, key) + } return prev, ok, nil } diff --git a/vendor/github.com/magiconair/properties/properties_test.go b/vendor/github.com/magiconair/properties/properties_test.go index 0eac1f492..7e92618e0 100644 --- a/vendor/github.com/magiconair/properties/properties_test.go +++ b/vendor/github.com/magiconair/properties/properties_test.go @@ -458,6 +458,19 @@ func TestDisableExpansion(t *testing.T) { assert.Equal(t, p.MustGet("keyB"), "${keyA}") } +func TestDisableExpansionStillUpdatesKeys(t *testing.T) { + p := NewProperties() + p.MustSet("p1", "a") + assert.Equal(t, p.Keys(), []string{"p1"}) + assert.Equal(t, p.String(), "p1 = a\n") + + p.DisableExpansion = true + p.MustSet("p2", "b") + + assert.Equal(t, p.Keys(), []string{"p1", "p2"}) + assert.Equal(t, p.String(), "p1 = a\np2 = b\n") +} + func TestMustGet(t *testing.T) { input := "key = value\nkey2 = ghi" p := mustParse(t, input) diff --git a/vendor/github.com/mailru/easyjson/.travis.yml b/vendor/github.com/mailru/easyjson/.travis.yml index 3e5ac1320..884f8bbdf 100644 --- a/vendor/github.com/mailru/easyjson/.travis.yml +++ b/vendor/github.com/mailru/easyjson/.travis.yml @@ -1,8 +1,9 @@ language: go go: - - tip + - tip install: - - go get github.com/ugorji/go/codec - - go get github.com/pquerna/ffjson/fflib/v1 - - go get github.com/golang/lint/golint + - go get github.com/ugorji/go/codec + - go get github.com/pquerna/ffjson/fflib/v1 + - go get github.com/json-iterator/go + - go get github.com/golang/lint/golint diff --git a/vendor/github.com/mailru/easyjson/Makefile b/vendor/github.com/mailru/easyjson/Makefile index 8e720a084..ea591b0c0 100644 --- a/vendor/github.com/mailru/easyjson/Makefile +++ b/vendor/github.com/mailru/easyjson/Makefile @@ -4,7 +4,7 @@ export GOPATH all: test -.root/src/$(PKG): +.root/src/$(PKG): mkdir -p $@ for i in $$PWD/* ; do ln -s $$i $@/`basename $$i` ; done @@ -45,6 +45,7 @@ test: generate root bench-other: generate root @go test -benchmem -bench . $(PKG)/benchmark @go test -benchmem -tags use_ffjson -bench . $(PKG)/benchmark + @go test -benchmem -tags use_jsoniter -bench . $(PKG)/benchmark @go test -benchmem -tags use_codec -bench . $(PKG)/benchmark bench-python: diff --git a/vendor/github.com/mailru/easyjson/README.md b/vendor/github.com/mailru/easyjson/README.md index d19751e0e..9366e3f71 100644 --- a/vendor/github.com/mailru/easyjson/README.md +++ b/vendor/github.com/mailru/easyjson/README.md @@ -56,7 +56,7 @@ Usage of easyjson: ``` Using `-all` will generate marshalers/unmarshalers for all Go structs in the -file. If `-all` is not provided, then only those structs whose preceeding +file. If `-all` is not provided, then only those structs whose preceding comment starts with `easyjson:json` will have marshalers/unmarshalers generated. For example: diff --git a/vendor/github.com/mailru/easyjson/benchmark/default_test.go b/vendor/github.com/mailru/easyjson/benchmark/default_test.go index b647bef23..68b37910d 100644 --- a/vendor/github.com/mailru/easyjson/benchmark/default_test.go +++ b/vendor/github.com/mailru/easyjson/benchmark/default_test.go @@ -1,4 +1,4 @@ -// +build !use_easyjson,!use_ffjson,!use_codec +// +build !use_easyjson,!use_ffjson,!use_codec,!use_jsoniter package benchmark diff --git a/vendor/github.com/mailru/easyjson/benchmark/jsoniter_test.go b/vendor/github.com/mailru/easyjson/benchmark/jsoniter_test.go new file mode 100644 index 000000000..004f891da --- /dev/null +++ b/vendor/github.com/mailru/easyjson/benchmark/jsoniter_test.go @@ -0,0 +1,119 @@ +// +build use_jsoniter + +package benchmark + +import ( + "testing" + + jsoniter "github.com/json-iterator/go" +) + +func BenchmarkJI_Unmarshal_M(b *testing.B) { + b.SetBytes(int64(len(largeStructText))) + for i := 0; i < b.N; i++ { + var s LargeStruct + err := jsoniter.Unmarshal(largeStructText, &s) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkJI_Unmarshal_S(b *testing.B) { + for i := 0; i < b.N; i++ { + var s Entities + err := jsoniter.Unmarshal(smallStructText, &s) + if err != nil { + b.Error(err) + } + } + b.SetBytes(int64(len(smallStructText))) +} + +func BenchmarkJI_Marshal_M(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := jsoniter.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_L(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := jsoniter.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_M_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := jsoniter.Marshal(&largeStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_L_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := jsoniter.Marshal(&xlStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_S(b *testing.B) { + var l int64 + for i := 0; i < b.N; i++ { + data, err := jsoniter.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_S_Parallel(b *testing.B) { + var l int64 + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + data, err := jsoniter.Marshal(&smallStructData) + if err != nil { + b.Error(err) + } + l = int64(len(data)) + } + }) + b.SetBytes(l) +} + +func BenchmarkJI_Marshal_M_ToWriter(b *testing.B) { + enc := jsoniter.NewEncoder(&DummyWriter{}) + for i := 0; i < b.N; i++ { + err := enc.Encode(&largeStructData) + if err != nil { + b.Error(err) + } + } +} diff --git a/vendor/github.com/mailru/easyjson/easyjson/main.go b/vendor/github.com/mailru/easyjson/easyjson/main.go index 1c3949757..1cd30bb36 100644 --- a/vendor/github.com/mailru/easyjson/easyjson/main.go +++ b/vendor/github.com/mailru/easyjson/easyjson/main.go @@ -54,8 +54,13 @@ func generate(fname string) (err error) { outName = *specifiedName } + var trimmedBuildTags string + if *buildTags != "" { + trimmedBuildTags = strings.TrimSpace(*buildTags) + } + g := bootstrap.Generator{ - BuildTags: *buildTags, + BuildTags: trimmedBuildTags, PkgPath: p.PkgPath, PkgName: p.PkgName, Types: p.StructNames, diff --git a/vendor/github.com/mailru/easyjson/gen/generator.go b/vendor/github.com/mailru/easyjson/gen/generator.go index f4312f64e..eb0d70ba2 100644 --- a/vendor/github.com/mailru/easyjson/gen/generator.go +++ b/vendor/github.com/mailru/easyjson/gen/generator.go @@ -224,6 +224,10 @@ func fixAliasName(alias string) string { "_", -1, ) + + if alias[0] == 'v' { // to void conflicting with var names, say v1 + alias = "_" + alias + } return alias } @@ -380,7 +384,7 @@ func (DefaultFieldNamer) GetJSONFieldName(t reflect.Type, f reflect.StructField) } // LowerCamelCaseFieldNamer -type LowerCamelCaseFieldNamer struct {} +type LowerCamelCaseFieldNamer struct{} func isLower(b byte) bool { return b <= 122 && b >= 97 @@ -407,7 +411,7 @@ func lowerFirst(s string) string { If the following char is upper OR numeric, LOWER it If is the end of string, LEAVE it Else lowercase - */ + */ foundLower := false for i := range s { diff --git a/vendor/github.com/mailru/easyjson/parser/parser_windows.go b/vendor/github.com/mailru/easyjson/parser/parser_windows.go index 64974aa97..a0b261195 100644 --- a/vendor/github.com/mailru/easyjson/parser/parser_windows.go +++ b/vendor/github.com/mailru/easyjson/parser/parser_windows.go @@ -4,15 +4,18 @@ import ( "fmt" "os" "path" + "path/filepath" "strings" ) func normalizePath(path string) string { - return strings.Replace(path, "\\", "/", -1) + // use lower case, as Windows file systems will almost always be case insensitive + return strings.ToLower(strings.Replace(path, "\\", "/", -1)) } func getPkgPath(fname string, isDir bool) (string, error) { - if !path.IsAbs(fname) { + // path.IsAbs doesn't work properly on Windows; use filepath.IsAbs instead + if !filepath.IsAbs(fname) { pwd, err := os.Getwd() if err != nil { return "", err diff --git a/vendor/github.com/mattn/go-sqlite3/README.md b/vendor/github.com/mattn/go-sqlite3/README.md index 01d28a204..ad00f10da 100644 --- a/vendor/github.com/mattn/go-sqlite3/README.md +++ b/vendor/github.com/mattn/go-sqlite3/README.md @@ -65,7 +65,7 @@ FAQ * Want to get time.Time with current locale - Use `loc=auto` in SQLite3 filename schema like `file:foo.db?loc=auto`. + Use `_loc=auto` in SQLite3 filename schema like `file:foo.db?_loc=auto`. * Can I use this in multiple routines concurrently? diff --git a/vendor/github.com/mattn/go-sqlite3/callback.go b/vendor/github.com/mattn/go-sqlite3/callback.go index 6a55964a1..29ece3d11 100644 --- a/vendor/github.com/mattn/go-sqlite3/callback.go +++ b/vendor/github.com/mattn/go-sqlite3/callback.go @@ -53,6 +53,12 @@ func doneTrampoline(ctx *C.sqlite3_context) { ai.Done(ctx) } +//export compareTrampoline +func compareTrampoline(handlePtr uintptr, la C.int, a *C.char, lb C.int, b *C.char) C.int { + cmp := lookupHandle(handlePtr).(func(string, string) int) + return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb))) +} + //export commitHookTrampoline func commitHookTrampoline(handle uintptr) int { callback := lookupHandle(handle).(func() int) diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3.go b/vendor/github.com/mattn/go-sqlite3/sqlite3.go index d0327b86e..1ff58c3cd 100644 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3.go +++ b/vendor/github.com/mattn/go-sqlite3/sqlite3.go @@ -100,6 +100,8 @@ int _sqlite3_create_function( } void callbackTrampoline(sqlite3_context*, int, sqlite3_value**); + +int compareTrampoline(void*, int, char*, int, char*); int commitHookTrampoline(void*); void rollbackHookTrampoline(void*); void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64); @@ -182,6 +184,7 @@ type SQLiteTx struct { // SQLiteStmt implement sql.Stmt. type SQLiteStmt struct { + mu sync.Mutex c *SQLiteConn s *C.sqlite3_stmt t string @@ -325,6 +328,29 @@ func (tx *SQLiteTx) Rollback() error { return err } +// RegisterCollation makes a Go function available as a collation. +// +// cmp receives two UTF-8 strings, a and b. The result should be 0 if +// a==b, -1 if a < b, and +1 if a > b. +// +// cmp must always return the same result given the same +// inputs. Additionally, it must have the following properties for all +// strings A, B and C: if A==B then B==A; if A==B and B==C then A==C; +// if AA; if A= 'A' && r <= 'Z': + return 'A' + (r-'A'+13)%26 + case r >= 'a' && r <= 'z': + return 'a' + (r-'a'+13)%26 + } + return r +} + +func TestCollationRegistration(t *testing.T) { + collateRot13 := func(a, b string) int { + ra, rb := strings.Map(rot13, a), strings.Map(rot13, b) + return strings.Compare(ra, rb) + } + collateRot13Reverse := func(a, b string) int { + return collateRot13(b, a) + } + + sql.Register("sqlite3_CollationRegistration", &SQLiteDriver{ + ConnectHook: func(conn *SQLiteConn) error { + if err := conn.RegisterCollation("rot13", collateRot13); err != nil { + return err + } + if err := conn.RegisterCollation("rot13reverse", collateRot13Reverse); err != nil { + return err + } + return nil + }, + }) + + db, err := sql.Open("sqlite3_CollationRegistration", ":memory:") + if err != nil { + t.Fatal("Failed to open database:", err) + } + defer db.Close() + + populate := []string{ + `CREATE TABLE test (s TEXT)`, + `INSERT INTO test VALUES ("aaaa")`, + `INSERT INTO test VALUES ("ffff")`, + `INSERT INTO test VALUES ("qqqq")`, + `INSERT INTO test VALUES ("tttt")`, + `INSERT INTO test VALUES ("zzzz")`, + } + for _, stmt := range populate { + if _, err := db.Exec(stmt); err != nil { + t.Fatal("Failed to populate test DB:", err) + } + } + + ops := []struct { + query string + want []string + }{ + { + "SELECT * FROM test ORDER BY s COLLATE rot13 ASC", + []string{ + "qqqq", + "tttt", + "zzzz", + "aaaa", + "ffff", + }, + }, + { + "SELECT * FROM test ORDER BY s COLLATE rot13 DESC", + []string{ + "ffff", + "aaaa", + "zzzz", + "tttt", + "qqqq", + }, + }, + { + "SELECT * FROM test ORDER BY s COLLATE rot13reverse ASC", + []string{ + "ffff", + "aaaa", + "zzzz", + "tttt", + "qqqq", + }, + }, + { + "SELECT * FROM test ORDER BY s COLLATE rot13reverse DESC", + []string{ + "qqqq", + "tttt", + "zzzz", + "aaaa", + "ffff", + }, + }, + } + + for _, op := range ops { + rows, err := db.Query(op.query) + if err != nil { + t.Fatalf("Query %q failed: %s", op.query, err) + } + got := []string{} + defer rows.Close() + for rows.Next() { + var s string + if err = rows.Scan(&s); err != nil { + t.Fatalf("Reading row for %q: %s", op.query, err) + } + got = append(got, s) + } + if err = rows.Err(); err != nil { + t.Fatalf("Reading rows for %q: %s", op.query, err) + } + + if !reflect.DeepEqual(got, op.want) { + t.Fatalf("Unexpected output from %q\ngot:\n%s\n\nwant:\n%s", op.query, strings.Join(got, "\n"), strings.Join(op.want, "\n")) + } + } +} + func TestDeclTypes(t *testing.T) { d := SQLiteDriver{} @@ -1343,6 +1465,61 @@ func TestUpdateAndTransactionHooks(t *testing.T) { } } +func TestNilAndEmptyBytes(t *testing.T) { + db, err := sql.Open("sqlite3", ":memory:") + if err != nil { + t.Fatal(err) + } + defer db.Close() + actualNil := []byte("use this to use an actual nil not a reference to nil") + emptyBytes := []byte{} + for tsti, tst := range []struct { + name string + columnType string + insertBytes []byte + expectedBytes []byte + }{ + {"actual nil blob", "blob", actualNil, nil}, + {"referenced nil blob", "blob", nil, nil}, + {"empty blob", "blob", emptyBytes, emptyBytes}, + {"actual nil text", "text", actualNil, nil}, + {"referenced nil text", "text", nil, nil}, + {"empty text", "text", emptyBytes, emptyBytes}, + } { + if _, err = db.Exec(fmt.Sprintf("create table tbl%d (txt %s)", tsti, tst.columnType)); err != nil { + t.Fatal(tst.name, err) + } + if bytes.Equal(tst.insertBytes, actualNil) { + if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), nil); err != nil { + t.Fatal(tst.name, err) + } + } else { + if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), &tst.insertBytes); err != nil { + t.Fatal(tst.name, err) + } + } + rows, err := db.Query(fmt.Sprintf("select txt from tbl%d", tsti)) + if err != nil { + t.Fatal(tst.name, err) + } + if !rows.Next() { + t.Fatal(tst.name, "no rows") + } + var scanBytes []byte + if err = rows.Scan(&scanBytes); err != nil { + t.Fatal(tst.name, err) + } + if err = rows.Err(); err != nil { + t.Fatal(tst.name, err) + } + if tst.expectedBytes == nil && scanBytes != nil { + t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes) + } else if !bytes.Equal(scanBytes, tst.expectedBytes) { + t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes) + } + } +} + var customFunctionOnce sync.Once func BenchmarkCustomFunctions(b *testing.B) { diff --git a/vendor/github.com/opencontainers/image-spec/MAINTAINERS b/vendor/github.com/opencontainers/image-spec/MAINTAINERS index f5bd5a6ed..9c9d60b8a 100644 --- a/vendor/github.com/opencontainers/image-spec/MAINTAINERS +++ b/vendor/github.com/opencontainers/image-spec/MAINTAINERS @@ -5,3 +5,4 @@ John Starks (@jstarks) Jonathan Boulle (@jonboulle) Stephen Day (@stevvooe) Vincent Batts (@vbatts) +Aleksa Sarai (@cyphar) \ No newline at end of file diff --git a/vendor/github.com/opencontainers/image-spec/implementations.md b/vendor/github.com/opencontainers/image-spec/implementations.md index cedeb7335..be26efdcc 100644 --- a/vendor/github.com/opencontainers/image-spec/implementations.md +++ b/vendor/github.com/opencontainers/image-spec/implementations.md @@ -8,9 +8,9 @@ Projects or Companies currently adopting the OCI Image Specification * [cloudfoundry/grootfs](https://github.com/cloudfoundry/grootfs) ([source](https://github.com/cloudfoundry/grootfs/blob/c3da26e1e463b51be1add289032f3dca6698b335/fetcher/remote/docker_src.go)) * [Mesos plans](https://issues.apache.org/jira/browse/MESOS-5011) ([design doc](https://docs.google.com/document/d/1Pus7D-inIBoLSIPyu3rl_apxvUhtp3rp0_b0Ttr2Xww/edit#heading=h.hrvk2wboog4p)) * [Docker](https://github.com/docker) - - [docker/containerd](https://github.com/docker/containerd) - [docker/docker (`docker save/load` WIP)](https://github.com/docker/docker/pull/26369) - [docker/distribution (registry PR)](https://github.com/docker/distribution/pull/2076) +* [containerd/containerd](https://github.com/containerd/containerd) * [Containers](https://github.com/containers/) - [containers/build](https://github.com/containers/build) - [containers/image](https://github.com/containers/image) diff --git a/vendor/github.com/openzipkin/zipkin-go-opentracing/collector-http.go b/vendor/github.com/openzipkin/zipkin-go-opentracing/collector-http.go index ea507ac18..6fb7b8c7a 100644 --- a/vendor/github.com/openzipkin/zipkin-go-opentracing/collector-http.go +++ b/vendor/github.com/openzipkin/zipkin-go-opentracing/collector-http.go @@ -214,10 +214,16 @@ func (c *HTTPCollector) send() error { if c.reqCallback != nil { c.reqCallback(req) } - if _, err = c.client.Do(req); err != nil { + resp, err := c.client.Do(req) + if err != nil { c.logger.Log("err", err.Error()) return err } + resp.Body.Close() + // non 2xx code + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + c.logger.Log("err", "HTTP POST span failed", "code", resp.Status) + } // Remove sent spans from the batch c.batchMutex.Lock() diff --git a/vendor/github.com/pelletier/go-toml/.travis.yml b/vendor/github.com/pelletier/go-toml/.travis.yml index 1f8b41ffe..496691166 100644 --- a/vendor/github.com/pelletier/go-toml/.travis.yml +++ b/vendor/github.com/pelletier/go-toml/.travis.yml @@ -1,9 +1,9 @@ sudo: false language: go go: - - 1.6.4 - 1.7.6 - 1.8.3 + - 1.9 - tip matrix: allow_failures: diff --git a/vendor/github.com/pelletier/go-toml/doc_test.go b/vendor/github.com/pelletier/go-toml/doc_test.go index 9dd773899..a48c04b01 100644 --- a/vendor/github.com/pelletier/go-toml/doc_test.go +++ b/vendor/github.com/pelletier/go-toml/doc_test.go @@ -1,13 +1,16 @@ // code examples for godoc -package toml +package toml_test import ( "fmt" + "log" + + toml "github.com/pelletier/go-toml" ) func Example_tree() { - config, err := LoadFile("config.toml") + config, err := toml.LoadFile("config.toml") if err != nil { fmt.Println("Error ", err.Error()) @@ -17,7 +20,7 @@ func Example_tree() { password := config.Get("postgres.password").(string) // or using an intermediate object - configTree := config.Get("postgres").(*Tree) + configTree := config.Get("postgres").(*toml.Tree) user = configTree.Get("user").(string) password = configTree.Get("password").(string) fmt.Println("User is", user, " and password is", password) @@ -48,6 +51,50 @@ func Example_unmarshal() { `) person := Person{} - Unmarshal(document, &person) + toml.Unmarshal(document, &person) fmt.Println(person.Name, "is", person.Age, "and works at", person.Employer.Name) + // Output: + // John is 30 and works at Company Inc. +} + +func ExampleMarshal() { + type Postgres struct { + User string `toml:"user"` + Password string `toml:"password"` + } + type Config struct { + Postgres Postgres `toml:"postgres"` + } + + config := Config{Postgres{User: "pelletier", Password: "mypassword"}} + b, err := toml.Marshal(config) + if err != nil { + log.Fatal(err) + } + fmt.Println(string(b)) + // Output: + // [postgres] + // password = "mypassword" + // user = "pelletier" +} + +func ExampleUnmarshal() { + type Postgres struct { + User string + Password string + } + type Config struct { + Postgres Postgres + } + + doc := []byte(` + [postgres] + user = "pelletier" + password = "mypassword"`) + + config := Config{} + toml.Unmarshal(doc, &config) + fmt.Println("user=", config.Postgres.User) + // Output: + // user= pelletier } diff --git a/vendor/github.com/pelletier/go-toml/marshal_test.go b/vendor/github.com/pelletier/go-toml/marshal_test.go index a3fa128d2..dbfc7c1d1 100644 --- a/vendor/github.com/pelletier/go-toml/marshal_test.go +++ b/vendor/github.com/pelletier/go-toml/marshal_test.go @@ -177,25 +177,6 @@ func TestDocUnmarshal(t *testing.T) { } } -func ExampleUnmarshal() { - type Postgres struct { - User string - Password string - } - type Config struct { - Postgres Postgres - } - - doc := []byte(` - [postgres] - user = "pelletier" - password = "mypassword"`) - - config := Config{} - Unmarshal(doc, &config) - fmt.Println("user=", config.Postgres.User) -} - func TestDocPartialUnmarshal(t *testing.T) { result := testDocSubs{} diff --git a/vendor/github.com/pelletier/go-toml/query/parser.go b/vendor/github.com/pelletier/go-toml/query/parser.go index e4f91b97e..5f69b70d4 100644 --- a/vendor/github.com/pelletier/go-toml/query/parser.go +++ b/vendor/github.com/pelletier/go-toml/query/parser.go @@ -253,7 +253,7 @@ func (p *queryParser) parseFilterExpr() queryParserStateFn { } tok = p.getToken() if tok.typ != tokenKey && tok.typ != tokenString { - return p.parseError(tok, "expected key or string for filter funciton name") + return p.parseError(tok, "expected key or string for filter function name") } name := tok.val tok = p.getToken() diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go new file mode 100644 index 000000000..08b3b7e01 --- /dev/null +++ b/vendor/github.com/spf13/afero/match.go @@ -0,0 +1,110 @@ +// 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 ( + "path/filepath" + "sort" + "strings" +) + +// Glob returns the names of all files matching pattern or nil +// if there is no matching file. The syntax of patterns is the same +// as in Match. The pattern may describe hierarchical names such as +// /usr/*/bin/ed (assuming the Separator is '/'). +// +// Glob ignores file system errors such as I/O errors reading directories. +// The only possible returned error is ErrBadPattern, when pattern +// is malformed. +// +// This was adapted from (http://golang.org/pkg/path/filepath) and uses several +// 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 { + return nil, nil + } + return []string{pattern}, nil + } + + dir, file := filepath.Split(pattern) + switch dir { + case "": + dir = "." + case string(filepath.Separator): + // nothing + default: + dir = dir[0 : len(dir)-1] // chop off trailing separator + } + + if !hasMeta(dir) { + return glob(fs, dir, file, nil) + } + + var m []string + m, err = Glob(fs, dir) + if err != nil { + return + } + for _, d := range m { + matches, err = glob(fs, d, file, matches) + if err != nil { + return + } + } + return +} + +// glob searches for files matching pattern in the directory dir +// and appends them to matches. If the directory cannot be +// opened, it returns the existing matches. New matches are +// added in lexicographical order. +func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) { + m = matches + fi, err := fs.Stat(dir) + if err != nil { + return + } + if !fi.IsDir() { + return + } + d, err := fs.Open(dir) + if err != nil { + return + } + defer d.Close() + + names, _ := d.Readdirnames(-1) + sort.Strings(names) + + for _, n := range names { + matched, err := filepath.Match(pattern, n) + if err != nil { + return m, err + } + if matched { + m = append(m, filepath.Join(dir, n)) + } + } + return +} + +// hasMeta reports whether path contains any of the magic characters +// recognized by Match. +func hasMeta(path string) bool { + // TODO(niemeyer): Should other magic characters be added here? + return strings.IndexAny(path, "*?[") >= 0 +} diff --git a/vendor/github.com/spf13/afero/match_test.go b/vendor/github.com/spf13/afero/match_test.go new file mode 100644 index 000000000..21e1faecd --- /dev/null +++ b/vendor/github.com/spf13/afero/match_test.go @@ -0,0 +1,183 @@ +// 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/memmap.go b/vendor/github.com/spf13/afero/memmap.go index 767ac1d5f..14cd438fb 100644 --- a/vendor/github.com/spf13/afero/memmap.go +++ b/vendor/github.com/spf13/afero/memmap.go @@ -66,7 +66,10 @@ func (m *MemMapFs) unRegisterWithParent(fileName string) error { if parent == nil { log.Panic("parent of ", f.Name(), " is nil") } + + parent.Lock() mem.RemoveFromMemDir(parent, f) + parent.Unlock() return nil } @@ -99,8 +102,10 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData) { } } + parent.Lock() mem.InitializeDir(parent) mem.AddToMemDir(parent, f) + parent.Unlock() } func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error { diff --git a/vendor/github.com/spf13/afero/memmap_test.go b/vendor/github.com/spf13/afero/memmap_test.go index ca5abbca6..d28e91220 100644 --- a/vendor/github.com/spf13/afero/memmap_test.go +++ b/vendor/github.com/spf13/afero/memmap_test.go @@ -1,6 +1,7 @@ package afero import ( + "fmt" "os" "path/filepath" "runtime" @@ -343,3 +344,43 @@ func TestRacingDeleteAndClose(t *testing.T) { }() 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) + } + } + } +} diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad.go b/vendor/github.com/spf13/jwalterweatherman/notepad.go index edeff3a86..ae5aaf711 100644 --- a/vendor/github.com/spf13/jwalterweatherman/notepad.go +++ b/vendor/github.com/spf13/jwalterweatherman/notepad.go @@ -148,7 +148,7 @@ func (n *Notepad) GetStdoutThreshold() Threshold { } // SetPrefix changes the prefix used by the notepad. Prefixes are displayed between -// brackets at the begining of the line. An empty prefix won't be displayed at all. +// brackets at the beginning of the line. An empty prefix won't be displayed at all. func (n *Notepad) SetPrefix(prefix string) { if len(prefix) != 0 { n.prefix = "[" + prefix + "] " diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 6f1fc3007..7b84e2cde 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -556,6 +556,10 @@ func UnquoteUsage(flag *Flag) (name string, usage string) { name = "int" case "uint64": name = "uint" + case "stringSlice": + name = "strings" + case "intSlice": + name = "ints" } return diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go index c3def0fd4..29fec8671 100644 --- a/vendor/github.com/spf13/pflag/flag_test.go +++ b/vendor/github.com/spf13/pflag/flag_test.go @@ -978,12 +978,12 @@ const defaultOutput = ` --A for bootstrapping, allo --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 + --Ints ints 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 + --StringSlice strings 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) diff --git a/vendor/github.com/ugorji/go/codec/codec_test.go b/vendor/github.com/ugorji/go/codec/codec_test.go index 5157e8b55..b05d19463 100644 --- a/vendor/github.com/ugorji/go/codec/codec_test.go +++ b/vendor/github.com/ugorji/go/codec/codec_test.go @@ -1470,6 +1470,21 @@ func TestJsonLargeInteger(t *testing.T) { } } +func TestJsonDecodeNonStringScalarInStringContext(t *testing.T) { + var b = `{"s.true": "true", "b.true": true, "s.false": "false", "b.false": false, "s.10": "10", "i.10": 10, "i.-10": -10}` + var golden = map[string]string{"s.true": "true", "b.true": "true", "s.false": "false", "b.false": "false", "s.10": "10", "i.10": "10", "i.-10": "-10"} + + var m map[string]string + d := NewDecoderBytes([]byte(b), testJsonH) + d.MustDecode(&m) + if err := deepEqual(golden, m); err == nil { + logT(t, "++++ match: decoded: %#v", m) + } else { + logT(t, "---- mismatch: %v ==> golden: %#v, decoded: %#v", err, golden, m) + failT(t) + } +} + // TODO: // Add Tests for: // - decoding empty list/map in stream into a nil slice/map diff --git a/vendor/github.com/ugorji/go/codec/json.go b/vendor/github.com/ugorji/go/codec/json.go index 463cae3db..df67d68ce 100644 --- a/vendor/github.com/ugorji/go/codec/json.go +++ b/vendor/github.com/ugorji/go/codec/json.go @@ -702,7 +702,9 @@ LOOP: switch state { case 0: state = 2 - // do not add sign to the slice ... + if storeBytes { + d.bs = append(d.bs, b) + } b, eof = r.readn1eof() continue case 6: // typ = jsonNumFloat @@ -715,7 +717,9 @@ LOOP: case 0: state = 2 n.neg = true - // do not add sign to the slice ... + if storeBytes { + d.bs = append(d.bs, b) + } b, eof = r.readn1eof() continue case 6: // typ = jsonNumFloat @@ -981,16 +985,28 @@ func (d *jsonDecDriver) appendStringAsBytes() { d.tok = b } - // handle null as a string - if d.tok == 'n' { - d.readStrIdx(10, 13) // ull - d.bs = d.bs[:0] + if d.tok != '"' { + // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok) + // handle non-string scalar: null, true, false or a number + switch d.tok { + case 'n': + d.readStrIdx(10, 13) // ull + d.bs = d.bs[:0] + case 'f': + d.readStrIdx(5, 9) // alse + d.bs = d.bs[:5] + copy(d.bs, "false") + case 't': + d.readStrIdx(1, 4) // rue + d.bs = d.bs[:4] + copy(d.bs, "true") + default: + // try to parse a valid number + d.decNum(true) + } return } - if d.tok != '"' { - d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok) - } d.tok = 0 v := d.bs[:0] @@ -1159,6 +1175,7 @@ func (d *jsonDecDriver) DecodeNaked() { type JsonHandle struct { textEncodingType BasicHandle + // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way. // If not configured, raw bytes are encoded to/from base64 text. RawBytesExt InterfaceExt diff --git a/vendor/github.com/ugorji/go/codec/prebuild.sh b/vendor/github.com/ugorji/go/codec/prebuild.sh index 422c1a734..04c61e48f 100755 --- a/vendor/github.com/ugorji/go/codec/prebuild.sh +++ b/vendor/github.com/ugorji/go/codec/prebuild.sh @@ -155,8 +155,8 @@ _codegenerators() { # remove (M|Unm)arshalJSON implementations, so they don't conflict with encoding/json bench \ if [[ $zexternal == "1" ]] then - sed -i 's+ MarshalJSON(+ _MarshalJSON(+g' values_ffjson${zsfx} && \ - sed -i 's+ UnmarshalJSON(+ _UnmarshalJSON(+g' values_ffjson${zsfx} + sed -i '' -e 's+ MarshalJSON(+ _MarshalJSON(+g' values_ffjson${zsfx} && \ + sed -i '' -e 's+ UnmarshalJSON(+ _UnmarshalJSON(+g' values_ffjson${zsfx} fi && \ echo "generators done!" && \ true diff --git a/vendor/github.com/ugorji/go/codec/test.py b/vendor/github.com/ugorji/go/codec/test.py index f983d9d9e..800376f68 100755 --- a/vendor/github.com/ugorji/go/codec/test.py +++ b/vendor/github.com/ugorji/go/codec/test.py @@ -84,7 +84,7 @@ def doRpcServer(port, stopTimeSec): def EchoStruct(self, msg): return ("%s" % msg) - addr = msgpackrpc.Address('localhost', port) + addr = msgpackrpc.Address('127.0.0.1', port) server = msgpackrpc.Server(EchoHandler()) server.listen(addr) # run thread to stop it after stopTimeSec seconds if > 0 @@ -96,14 +96,14 @@ def doRpcServer(port, stopTimeSec): server.start() def doRpcClientToPythonSvc(port): - address = msgpackrpc.Address('localhost', port) + address = msgpackrpc.Address('127.0.0.1', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("Echo123", "A1", "B2", "C3") print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doRpcClientToGoSvc(port): # print ">>>> port: ", port, " <<<<<" - address = msgpackrpc.Address('localhost', port) + address = msgpackrpc.Address('127.0.0.1', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"]) print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) diff --git a/vendor/golang.org/x/crypto/sha3/sha3.go b/vendor/golang.org/x/crypto/sha3/sha3.go index c86167c0b..b12a35c87 100644 --- a/vendor/golang.org/x/crypto/sha3/sha3.go +++ b/vendor/golang.org/x/crypto/sha3/sha3.go @@ -42,9 +42,8 @@ type state struct { storage [maxRate]byte // Specific to SHA-3 and SHAKE. - fixedOutput bool // whether this is a fixed-output-length instance - outputLen int // the default output size in bytes - state spongeDirection // whether the sponge is absorbing or squeezing + outputLen int // the default output size in bytes + state spongeDirection // whether the sponge is absorbing or squeezing } // BlockSize returns the rate of sponge underlying this hash function. diff --git a/vendor/golang.org/x/sys/unix/creds_test.go b/vendor/golang.org/x/sys/unix/creds_test.go index eaae7c367..7ae330532 100644 --- a/vendor/golang.org/x/sys/unix/creds_test.go +++ b/vendor/golang.org/x/sys/unix/creds_test.go @@ -21,101 +21,116 @@ import ( // sockets. The SO_PASSCRED socket option is enabled on the sending // socket for this to work. func TestSCMCredentials(t *testing.T) { - 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]) - - err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) - if err != nil { - t.Fatalf("SetsockoptInt: %v", err) + socketTypeTests := []struct { + socketType int + dataLen int + }{ + { + unix.SOCK_STREAM, + 1, + }, { + unix.SOCK_DGRAM, + 0, + }, } - 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() + 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]) - 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() + 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) + } + } - var ucred unix.Ucred - if os.Getuid() != 0 { ucred.Pid = int32(os.Getpid()) - ucred.Uid = 0 - ucred.Gid = 0 + ucred.Uid = uint32(os.Getuid()) + ucred.Gid = uint32(os.Getgid()) oob := unix.UnixCredentials(&ucred) - _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if op, ok := err.(*net.OpError); ok { - err = op.Err + + // 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 sys, ok := err.(*os.SyscallError); ok { - err = sys.Err + if n != 0 { + t.Fatalf("WriteMsgUnix n = %d, want 0", n) } - if err != syscall.EPERM { - t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) + if oobn != len(oob) { + t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) } - } - ucred.Pid = int32(os.Getpid()) - ucred.Uid = uint32(os.Getuid()) - ucred.Gid = uint32(os.Getgid()) - oob := unix.UnixCredentials(&ucred) + 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") + } - // this is 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 != 1 { - t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n) - } - 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) + 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.go b/vendor/golang.org/x/sys/unix/dev_darwin.go new file mode 100644 index 000000000..7d101d527 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/dev_darwin.go @@ -0,0 +1,24 @@ +// 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. + +// Functions to access/create device major and minor numbers matching the +// encoding used in Darwin's sys/types.h header. + +package unix + +// Major returns the major component of a Darwin device number. +func Major(dev uint64) uint32 { + return uint32((dev >> 24) & 0xff) +} + +// Minor returns the minor component of a Darwin device number. +func Minor(dev uint64) uint32 { + return uint32(dev & 0xffffff) +} + +// Mkdev returns a Darwin device number generated from the given major and minor +// components. +func Mkdev(major, minor uint32) uint64 { + return uint64((major << 24) | minor) +} diff --git a/vendor/golang.org/x/sys/unix/dev_darwin_test.go b/vendor/golang.org/x/sys/unix/dev_darwin_test.go new file mode 100644 index 000000000..48d044860 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/dev_darwin_test.go @@ -0,0 +1,49 @@ +// 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_netbsd.go b/vendor/golang.org/x/sys/unix/dev_netbsd.go new file mode 100644 index 000000000..08db58ee3 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/dev_netbsd.go @@ -0,0 +1,29 @@ +// 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. + +// Functions to access/create device major and minor numbers matching the +// encoding used in NetBSD's sys/types.h header. + +package unix + +// Major returns the major component of a NetBSD device number. +func Major(dev uint64) uint32 { + return uint32((dev & 0x000fff00) >> 8) +} + +// Minor returns the minor component of a NetBSD device number. +func Minor(dev uint64) uint32 { + minor := uint32((dev & 0x000000ff) >> 0) + minor |= uint32((dev & 0xfff00000) >> 12) + return minor +} + +// Mkdev returns a NetBSD device number generated from the given major and minor +// components. +func Mkdev(major, minor uint32) uint64 { + dev := uint64((major << 8) & 0x000fff00) + dev |= uint64((minor << 12) & 0xfff00000) + dev |= uint64((minor << 0) & 0x000000ff) + return 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 new file mode 100644 index 000000000..c39a80a48 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/dev_netbsd_test.go @@ -0,0 +1,50 @@ +// 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/linux/types.go b/vendor/golang.org/x/sys/unix/linux/types.go index e5769db57..27d9a991a 100644 --- a/vendor/golang.org/x/sys/unix/linux/types.go +++ b/vendor/golang.org/x/sys/unix/linux/types.go @@ -62,6 +62,8 @@ package unix #include #include #include +#include +#include // On mips64, the glibc stat and kernel stat do not agree #if (defined(__mips__) && _MIPS_SIM == _MIPS_SIM_ABI64) @@ -550,3 +552,56 @@ const _SC_PAGESIZE = C._SC_PAGESIZE type Termios C.termios_t type Winsize C.struct_winsize + +// Taskstats + +type Taskstats C.struct_taskstats + +const ( + TASKSTATS_CMD_UNSPEC = C.TASKSTATS_CMD_UNSPEC + TASKSTATS_CMD_GET = C.TASKSTATS_CMD_GET + TASKSTATS_CMD_NEW = C.TASKSTATS_CMD_NEW + TASKSTATS_TYPE_UNSPEC = C.TASKSTATS_TYPE_UNSPEC + TASKSTATS_TYPE_PID = C.TASKSTATS_TYPE_PID + TASKSTATS_TYPE_TGID = C.TASKSTATS_TYPE_TGID + TASKSTATS_TYPE_STATS = C.TASKSTATS_TYPE_STATS + TASKSTATS_TYPE_AGGR_PID = C.TASKSTATS_TYPE_AGGR_PID + TASKSTATS_TYPE_AGGR_TGID = C.TASKSTATS_TYPE_AGGR_TGID + TASKSTATS_TYPE_NULL = C.TASKSTATS_TYPE_NULL + TASKSTATS_CMD_ATTR_UNSPEC = C.TASKSTATS_CMD_ATTR_UNSPEC + TASKSTATS_CMD_ATTR_PID = C.TASKSTATS_CMD_ATTR_PID + TASKSTATS_CMD_ATTR_TGID = C.TASKSTATS_CMD_ATTR_TGID + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = C.TASKSTATS_CMD_ATTR_REGISTER_CPUMASK + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = C.TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK +) + +// Generic netlink + +type Genlmsghdr C.struct_genlmsghdr + +const ( + CTRL_CMD_UNSPEC = C.CTRL_CMD_UNSPEC + CTRL_CMD_NEWFAMILY = C.CTRL_CMD_NEWFAMILY + CTRL_CMD_DELFAMILY = C.CTRL_CMD_DELFAMILY + CTRL_CMD_GETFAMILY = C.CTRL_CMD_GETFAMILY + CTRL_CMD_NEWOPS = C.CTRL_CMD_NEWOPS + CTRL_CMD_DELOPS = C.CTRL_CMD_DELOPS + CTRL_CMD_GETOPS = C.CTRL_CMD_GETOPS + CTRL_CMD_NEWMCAST_GRP = C.CTRL_CMD_NEWMCAST_GRP + CTRL_CMD_DELMCAST_GRP = C.CTRL_CMD_DELMCAST_GRP + CTRL_CMD_GETMCAST_GRP = C.CTRL_CMD_GETMCAST_GRP + CTRL_ATTR_UNSPEC = C.CTRL_ATTR_UNSPEC + CTRL_ATTR_FAMILY_ID = C.CTRL_ATTR_FAMILY_ID + CTRL_ATTR_FAMILY_NAME = C.CTRL_ATTR_FAMILY_NAME + CTRL_ATTR_VERSION = C.CTRL_ATTR_VERSION + CTRL_ATTR_HDRSIZE = C.CTRL_ATTR_HDRSIZE + CTRL_ATTR_MAXATTR = C.CTRL_ATTR_MAXATTR + CTRL_ATTR_OPS = C.CTRL_ATTR_OPS + CTRL_ATTR_MCAST_GROUPS = C.CTRL_ATTR_MCAST_GROUPS + CTRL_ATTR_OP_UNSPEC = C.CTRL_ATTR_OP_UNSPEC + CTRL_ATTR_OP_ID = C.CTRL_ATTR_OP_ID + CTRL_ATTR_OP_FLAGS = C.CTRL_ATTR_OP_FLAGS + CTRL_ATTR_MCAST_GRP_UNSPEC = C.CTRL_ATTR_MCAST_GRP_UNSPEC + CTRL_ATTR_MCAST_GRP_NAME = C.CTRL_ATTR_MCAST_GRP_NAME + CTRL_ATTR_MCAST_GRP_ID = C.CTRL_ATTR_MCAST_GRP_ID +) diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 08dd77518..2c434f7ae 100755 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -181,6 +181,8 @@ struct ltchars { #include #include #include +#include +#include #include #include @@ -413,6 +415,8 @@ ccflags="$@" $2 ~ /^SECCOMP_MODE_/ || $2 ~ /^SPLICE_/ || $2 ~ /^(VM|VMADDR)_/ || + $2 ~ /^(TASKSTATS|TS)_/ || + $2 ~ /^GENL_/ || $2 ~ /^XATTR_(CREATE|REPLACE)/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ || diff --git a/vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl b/vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl index d31f2c48f..85988b140 100755 --- a/vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl +++ b/vendor/golang.org/x/sys/unix/mksysnum_netbsd.pl @@ -47,7 +47,7 @@ while(<>){ $name = "$7_$11" if $11 ne ''; $name =~ y/a-z/A-Z/; - if($compat eq '' || $compat eq '30' || $compat eq '50') { + if($compat eq '' || $compat eq '13' || $compat eq '30' || $compat eq '50') { print " $name = $num; // $proto\n"; } } diff --git a/vendor/golang.org/x/sys/unix/mmap_unix_test.go b/vendor/golang.org/x/sys/unix/mmap_unix_test.go index 18ccec05f..8de55feaf 100644 --- a/vendor/golang.org/x/sys/unix/mmap_unix_test.go +++ b/vendor/golang.org/x/sys/unix/mmap_unix_test.go @@ -17,6 +17,18 @@ func TestMmap(t *testing.T) { if err != nil { t.Fatalf("Mmap: %v", err) } + if err := unix.Mprotect(b, 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/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index 71f0037d9..c2846b32d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -610,9 +610,6 @@ func Futimes(fd int, tv []Timeval) error { // TODO: wrap // Acct(name nil-string) (err error) // Gethostuuid(uuid *byte, timeout *Timespec) (err error) -// Madvise(addr *byte, len int, behav int) (err error) -// Mprotect(addr *byte, len int, prot int) (err error) -// Msync(addr *byte, len int, flags int) (err error) // Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error) var mapper = &mmapper{ @@ -628,3 +625,11 @@ func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, e func Munmap(b []byte) (err error) { return mapper.Munmap(b) } + +//sys Madvise(b []byte, behav int) (err error) +//sys Mlock(b []byte) (err error) +//sys Mlockall(flags int) (err error) +//sys Mprotect(b []byte, prot int) (err error) +//sys Msync(b []byte, flags int) (err error) +//sys Munlock(b []byte) (err error) +//sys Munlockall() (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index c9be499aa..ad74a11fb 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -292,12 +292,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Msync(b []byte, flags int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) @@ -374,9 +368,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Add_profil // Kdebug_trace // Sigreturn -// Mmap -// Mlock -// Munlock // Atsocket // Kqueue_from_portset_np // Kqueue_portset @@ -469,8 +460,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Lio_listio // __pthread_cond_wait // Iopolicysys -// Mlockall -// Munlockall // __pthread_kill // __pthread_sigmask // __sigwait diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go index bfaaed292..3a483373d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go +++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go @@ -174,11 +174,6 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) @@ -253,9 +248,6 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { // Add_profil // Kdebug_trace // Sigreturn -// Mmap -// Mlock -// Munlock // Atsocket // Kqueue_from_portset_np // Kqueue_portset @@ -348,8 +340,6 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { // Lio_listio // __pthread_cond_wait // Iopolicysys -// Mlockall -// Munlockall // __pthread_kill // __pthread_sigmask // __sigwait @@ -402,7 +392,6 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { // Sendmsg_nocancel // Recvfrom_nocancel // Accept_nocancel -// Msync_nocancel // Fcntl_nocancel // Select_nocancel // Fsync_nocancel diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index e9847c429..d26e52eae 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -461,11 +461,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(fdat int, path string, mode int, perm uint32) (fd int, err error) @@ -546,9 +541,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Add_profil // Kdebug_trace // Sigreturn -// Mmap -// Mlock -// Munlock // Atsocket // Kqueue_from_portset_np // Kqueue_portset @@ -641,8 +633,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Lio_listio // __pthread_cond_wait // Iopolicysys -// Mlockall -// Munlockall // __pthread_kill // __pthread_sigmask // __sigwait @@ -695,7 +685,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Sendmsg_nocancel // Recvfrom_nocancel // Accept_nocancel -// Msync_nocancel // Fcntl_nocancel // Select_nocancel // Fsync_nocancel diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index bb9022571..1b7d59d89 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -931,8 +931,13 @@ 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 len(p) == 0 { + if sockType != SOCK_DGRAM && len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } @@ -978,8 +983,13 @@ 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 len(p) == 0 { + if sockType != SOCK_DGRAM && len(p) == 0 { iov.Base = &dummy iov.SetLen(1) } @@ -1314,9 +1324,9 @@ func Munmap(b []byte) (err error) { //sys Madvise(b []byte, advice int) (err error) //sys Mprotect(b []byte, prot int) (err error) //sys Mlock(b []byte) (err error) -//sys Munlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Msync(b []byte, flags int) (err error) +//sys Munlock(b []byte) (err error) //sys Munlockall() (err error) // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd, @@ -1384,7 +1394,6 @@ func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { // ModifyLdt // Mount // MovePages -// Mprotect // MqGetsetattr // MqNotify // MqOpen diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 75e604ed9..e12966845 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -170,11 +170,6 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go index b32f0eaf3..408e63081 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -149,11 +149,6 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { //sys Mkdir(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) -//sys Mlock(b []byte) (err error) -//sys Mlockall(flags int) (err error) -//sys Mprotect(b []byte, prot int) (err error) -//sys Munlock(b []byte) (err error) -//sys Munlockall() (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Pathconf(path string, name int) (val int, err error) 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 a6b3b5f14..33ced1ae4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1626,6 +1639,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 @@ -1765,6 +1784,7 @@ const ( TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf 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 4ffc8d29c..a6618fc11 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1627,6 +1640,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 @@ -1766,6 +1785,7 @@ const ( TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf 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 f4b178ef1..1adff0b28 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1631,6 +1644,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 @@ -1770,6 +1789,7 @@ const ( TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf 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 495f13b61..c0ecd47c2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -508,6 +508,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1616,6 +1629,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 @@ -1755,6 +1774,7 @@ const ( TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf 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 59651e415..900f568af 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1629,6 +1642,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d @@ -1769,6 +1788,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 TUNGETFEATURES = 0x400454cf 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 a09bf9b18..4148f2773 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1629,6 +1642,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d @@ -1769,6 +1788,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf 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 72a0083c4..2310beebd 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1629,6 +1642,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d @@ -1769,6 +1788,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf 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 84c0e3cc1..44191b0c2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1629,6 +1642,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d @@ -1769,6 +1788,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x8000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 TUNGETFEATURES = 0x400454cf 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 8e4606e06..6772a59be 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x4000 @@ -1684,6 +1697,12 @@ const ( TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 @@ -1827,6 +1846,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x400000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf 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 16ed19311..ad29c3d3d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x4000 @@ -1684,6 +1697,12 @@ const ( TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 @@ -1827,6 +1846,7 @@ const ( TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 TOSTOP = 0x400000 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf 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 bd385f809..3b5707548 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -507,6 +507,19 @@ const ( F_ULOCK = 0x0 F_UNLCK = 0x2 F_WRLCK = 0x1 + GENL_ADMIN_PERM = 0x1 + GENL_CMD_CAP_DO = 0x2 + GENL_CMD_CAP_DUMP = 0x4 + GENL_CMD_CAP_HASPOL = 0x8 + GENL_HDRLEN = 0x4 + GENL_ID_CTRL = 0x10 + GENL_ID_PMCRAID = 0x12 + GENL_ID_VFS_DQUOT = 0x11 + GENL_MAX_ID = 0x3ff + GENL_MIN_ID = 0x10 + GENL_NAMSIZ = 0x10 + GENL_START_ALLOC = 0x13 + GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HUPCL = 0x400 @@ -1688,6 +1701,12 @@ const ( TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 + TASKSTATS_CMD_ATTR_MAX = 0x4 + TASKSTATS_CMD_MAX = 0x2 + TASKSTATS_GENL_NAME = "TASKSTATS" + TASKSTATS_GENL_VERSION = 0x1 + TASKSTATS_TYPE_MAX = 0x6 + TASKSTATS_VERSION = 0x8 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 @@ -1827,6 +1846,7 @@ const ( TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 TOSTOP = 0x100 + TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf 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 ac85ca645..206c75f09 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go @@ -1006,6 +1006,9 @@ const ( MSG_TRUNC = 0x10 MSG_USERFLAGS = 0xffffff MSG_WAITALL = 0x40 + MS_ASYNC = 0x1 + MS_INVALIDATE = 0x2 + MS_SYNC = 0x4 NAME_MAX = 0x1ff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 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 92708acc3..10491e9ed 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { @@ -905,90 +1005,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Msync(b []byte, flags int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) 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 44fc14f8a..5f1f6bfef 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { @@ -905,90 +1005,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Msync(b []byte, flags int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) 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 6e5bd7532..7a4097459 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { @@ -905,74 +1005,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) 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 7005b8dd4..07c6ebc9f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { @@ -905,74 +1005,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) 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 632263090..7fa205cd0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) @@ -829,74 +929,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 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 7c302d30a..1a0bb4cb0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) @@ -1139,74 +1239,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 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 7550811c2..ac1e8e013 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) @@ -1139,74 +1239,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 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 6ce6cc18c..2b4e6acf0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (r int, w int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) r = int(r0) @@ -1139,74 +1239,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 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 138e5a443..db99fd0c9 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) @@ -777,74 +877,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 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 83ca58e1f..7b6c2c87e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) @@ -777,74 +877,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 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 ef30db134..0f4cc3b52 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) @@ -777,74 +877,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 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 3426ad714..7baea87c7 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { @@ -785,74 +885,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { 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 086c994cc..0d69ce6b5 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { @@ -785,74 +885,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { 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 ca2ed7d0e..41572c26e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -266,6 +266,106 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Madvise(b []byte, behav int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mlockall(flags int) (err error) { + _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlock(b []byte) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Munlockall() (err error) { + _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pipe(p *[2]_C_int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if e1 != 0 { @@ -785,74 +885,6 @@ func Mknod(path string, mode uint32, dev int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, 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 Mprotect(b []byte, prot int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlock(b []byte) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go index f60d8f988..8afda9c45 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go @@ -134,6 +134,7 @@ const ( SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } + SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go index 48a91d464..aea8dbec4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go @@ -134,6 +134,7 @@ const ( SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } + SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go index 612ba662c..c6158a7ef 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go @@ -134,6 +134,7 @@ const ( SYS_MINHERIT = 273 // { int|sys||minherit(void *addr, size_t len, int inherit); } SYS_LCHMOD = 274 // { int|sys||lchmod(const char *path, mode_t mode); } SYS_LCHOWN = 275 // { int|sys||lchown(const char *path, uid_t uid, gid_t gid); } + SYS_MSYNC = 277 // { int|sys|13|msync(void *addr, size_t len, int flags); } SYS___POSIX_CHOWN = 283 // { int|sys||__posix_chown(const char *path, uid_t uid, gid_t gid); } SYS___POSIX_FCHOWN = 284 // { int|sys||__posix_fchown(int fd, uid_t uid, gid_t gid); } SYS___POSIX_LCHOWN = 285 // { int|sys||__posix_lchown(const char *path, uid_t uid, gid_t gid); } 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 0dcebb50b..7b36896ea 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -692,3 +692,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 d70e54348..e54fa9847 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -710,3 +710,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 497f56319..bff6ce258 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -681,3 +681,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]uint8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 f0bdaede6..a3d0cc4a1 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -689,3 +689,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 850a68cb2..8fa6603fb 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -686,3 +686,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 92aac5d93..3e5fc6252 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -691,3 +691,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 623f58127..f9bd1ab0c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -691,3 +691,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 56598a1bf..74c542132 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -686,3 +686,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 acc7c819d..2b0b18e94 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -699,3 +699,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]uint8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 b348885c8..b2b59992d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -699,3 +699,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + Pad_cgo_0 [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + Pad_cgo_1 [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]uint8 + Ac_sched uint8 + Ac_pad [3]uint8 + Pad_cgo_2 [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + Pad_cgo_3 [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) 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 a706e2f8c..5e0aa6636 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -716,3 +716,104 @@ type Winsize struct { Xpixel uint16 Ypixel uint16 } + +type Taskstats struct { + Version uint16 + _ [2]byte + Ac_exitcode uint32 + Ac_flag uint8 + Ac_nice uint8 + _ [6]byte + Cpu_count uint64 + Cpu_delay_total uint64 + Blkio_count uint64 + Blkio_delay_total uint64 + Swapin_count uint64 + Swapin_delay_total uint64 + Cpu_run_real_total uint64 + Cpu_run_virtual_total uint64 + Ac_comm [32]int8 + Ac_sched uint8 + Ac_pad [3]uint8 + _ [4]byte + Ac_uid uint32 + Ac_gid uint32 + Ac_pid uint32 + Ac_ppid uint32 + Ac_btime uint32 + _ [4]byte + Ac_etime uint64 + Ac_utime uint64 + Ac_stime uint64 + Ac_minflt uint64 + Ac_majflt uint64 + Coremem uint64 + Virtmem uint64 + Hiwater_rss uint64 + Hiwater_vm uint64 + Read_char uint64 + Write_char uint64 + Read_syscalls uint64 + Write_syscalls uint64 + Read_bytes uint64 + Write_bytes uint64 + Cancelled_write_bytes uint64 + Nvcsw uint64 + Nivcsw uint64 + Ac_utimescaled uint64 + Ac_stimescaled uint64 + Cpu_scaled_run_real_total uint64 + Freepages_count uint64 + Freepages_delay_total uint64 +} + +const ( + TASKSTATS_CMD_UNSPEC = 0x0 + TASKSTATS_CMD_GET = 0x1 + TASKSTATS_CMD_NEW = 0x2 + TASKSTATS_TYPE_UNSPEC = 0x0 + TASKSTATS_TYPE_PID = 0x1 + TASKSTATS_TYPE_TGID = 0x2 + TASKSTATS_TYPE_STATS = 0x3 + TASKSTATS_TYPE_AGGR_PID = 0x4 + TASKSTATS_TYPE_AGGR_TGID = 0x5 + TASKSTATS_TYPE_NULL = 0x6 + TASKSTATS_CMD_ATTR_UNSPEC = 0x0 + TASKSTATS_CMD_ATTR_PID = 0x1 + TASKSTATS_CMD_ATTR_TGID = 0x2 + TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3 + TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 +) + +type Genlmsghdr struct { + Cmd uint8 + Version uint8 + Reserved uint16 +} + +const ( + CTRL_CMD_UNSPEC = 0x0 + CTRL_CMD_NEWFAMILY = 0x1 + CTRL_CMD_DELFAMILY = 0x2 + CTRL_CMD_GETFAMILY = 0x3 + CTRL_CMD_NEWOPS = 0x4 + CTRL_CMD_DELOPS = 0x5 + CTRL_CMD_GETOPS = 0x6 + CTRL_CMD_NEWMCAST_GRP = 0x7 + CTRL_CMD_DELMCAST_GRP = 0x8 + CTRL_CMD_GETMCAST_GRP = 0x9 + CTRL_ATTR_UNSPEC = 0x0 + CTRL_ATTR_FAMILY_ID = 0x1 + CTRL_ATTR_FAMILY_NAME = 0x2 + CTRL_ATTR_VERSION = 0x3 + CTRL_ATTR_HDRSIZE = 0x4 + CTRL_ATTR_MAXATTR = 0x5 + CTRL_ATTR_OPS = 0x6 + CTRL_ATTR_MCAST_GROUPS = 0x7 + CTRL_ATTR_OP_UNSPEC = 0x0 + CTRL_ATTR_OP_ID = 0x1 + CTRL_ATTR_OP_FLAGS = 0x2 + CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0 + CTRL_ATTR_MCAST_GRP_NAME = 0x1 + CTRL_ATTR_MCAST_GRP_ID = 0x2 +) diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 53e7b4723..c7ff24b55 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -188,8 +188,12 @@ func NewCallbackCDecl(fn interface{}) uintptr //sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW //sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW //sys GetCurrentThreadId() (id uint32) -//sys CreateEvent(eventAttrs *syscall.SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW +//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW +//sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) = kernel32.CreateEventExW +//sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW //sys SetEvent(event Handle) (err error) = kernel32.SetEvent +//sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent +//sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent // syscall interface implementation for other packages diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 9343dd828..2f893d2ef 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -173,7 +173,11 @@ var ( procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW") procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId") procCreateEventW = modkernel32.NewProc("CreateEventW") + procCreateEventExW = modkernel32.NewProc("CreateEventExW") + procOpenEventW = modkernel32.NewProc("OpenEventW") procSetEvent = modkernel32.NewProc("SetEvent") + procResetEvent = modkernel32.NewProc("ResetEvent") + procPulseEvent = modkernel32.NewProc("PulseEvent") procWSAStartup = modws2_32.NewProc("WSAStartup") procWSACleanup = modws2_32.NewProc("WSACleanup") procWSAIoctl = modws2_32.NewProc("WSAIoctl") @@ -1644,7 +1648,7 @@ func SetConsoleMode(console Handle, mode uint32) (err error) { } func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) { - r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(&info)), 0) + r1, _, e1 := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(console), uintptr(unsafe.Pointer(info)), 0) if r1 == 0 { if e1 != 0 { err = errnoErr(e1) @@ -1758,7 +1762,7 @@ func GetCurrentThreadId() (id uint32) { return } -func CreateEvent(eventAttrs *syscall.SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) { +func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) { r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0) handle = Handle(r0) if handle == 0 { @@ -1771,6 +1775,38 @@ func CreateEvent(eventAttrs *syscall.SecurityAttributes, manualReset uint32, ini return } +func CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall6(procCreateEventExW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(desiredAccess), 0, 0) + handle = Handle(r0) + if handle == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) { + var _p0 uint32 + if inheritHandle { + _p0 = 1 + } else { + _p0 = 0 + } + r0, _, e1 := syscall.Syscall(procOpenEventW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(name))) + handle = Handle(r0) + if handle == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + func SetEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procSetEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { @@ -1783,6 +1819,30 @@ func SetEvent(event Handle) (err error) { return } +func ResetEvent(event Handle) (err error) { + r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func PulseEvent(event Handle) (err error) { + r1, _, e1 := syscall.Syscall(procPulseEvent.Addr(), 1, uintptr(event), 0, 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 {