From b436a1e8887c50e73ca3edfc73873324ba141f12 Mon Sep 17 00:00:00 2001
From: unclejack
Date: Tue, 12 Apr 2016 22:00:38 +0300
Subject: [PATCH] Godeps: bump libovsdb,netlink; update to new godep
Signed-off-by: Cristian Staretu
---
Godeps/Godeps.json | 75 +-
.../toml/cmd/toml-test-decoder/COPYING | 14 -
.../toml/cmd/toml-test-decoder/README.md | 14 -
.../toml/cmd/toml-test-decoder/main.go | 90 --
.../toml/cmd/toml-test-encoder/COPYING | 14 -
.../toml/cmd/toml-test-encoder/README.md | 14 -
.../toml/cmd/toml-test-encoder/main.go | 131 ---
.../BurntSushi/toml/cmd/tomlv/COPYING | 14 -
.../BurntSushi/toml/cmd/tomlv/README.md | 22 -
.../BurntSushi/toml/cmd/tomlv/main.go | 61 -
.../github.com/Sirupsen/logrus/entry_test.go | 77 --
.../Sirupsen/logrus/examples/basic/basic.go | 50 -
.../Sirupsen/logrus/examples/hook/hook.go | 30 -
.../Sirupsen/logrus/formatter_bench_test.go | 98 --
.../logrus/formatters/logstash/logstash.go | 61 -
.../formatters/logstash/logstash_test.go | 52 -
.../github.com/Sirupsen/logrus/hook_test.go | 122 --
.../logrus/hooks/syslog/syslog_test.go | 26 -
.../Sirupsen/logrus/json_formatter_test.go | 120 --
.../github.com/Sirupsen/logrus/logrus_test.go | 301 -----
.../Sirupsen/logrus/text_formatter_test.go | 61 -
.../cenkalti/backoff/adv_example_test.go | 117 --
.../cenkalti/backoff/backoff_test.go | 27 -
.../cenkalti/backoff/example_test.go | 51 -
.../cenkalti/backoff/exponential_test.go | 108 --
.../github.com/cenkalti/backoff/retry_test.go | 34 -
.../cenkalti/backoff/ticker_test.go | 45 -
.../github.com/cenkalti/hub/example_test.go | 28 -
.../src/github.com/cenkalti/hub/hub_test.go | 37 -
.../cenkalti/rpc2/jsonrpc/jsonrpc_test.go | 109 --
.../src/github.com/cenkalti/rpc2/rpc2_test.go | 88 --
.../cli/autocomplete/bash_autocomplete | 15 -
.../cli/autocomplete/zsh_autocomplete | 5 -
.../src/github.com/contiv/go-etcd/LICENSE | 202 ++++
.../contiv/go-etcd/etcd/add_child_test.go | 73 --
.../contiv/go-etcd/etcd/client_test.go | 96 --
.../go-etcd/etcd/compare_and_delete_test.go | 46 -
.../go-etcd/etcd/compare_and_swap_test.go | 57 -
.../contiv/go-etcd/etcd/debug_test.go | 28 -
.../contiv/go-etcd/etcd/delete_test.go | 81 --
.../contiv/go-etcd/etcd/get_test.go | 131 ---
.../contiv/go-etcd/etcd/requests_test.go | 22 -
.../contiv/go-etcd/etcd/set_curl_chan_test.go | 42 -
.../go-etcd/etcd/set_update_create_test.go | 241 ----
.../contiv/go-etcd/etcd/watch_test.go | 119 --
.../contiv/libovsdb/Godeps/Godeps.json | 18 -
.../github.com/contiv/libovsdb/Godeps/Readme | 5 -
.../contiv/libovsdb/example/play_with_ovs.go | 165 ---
.../contiv/libovsdb/notation_test.go | 175 ---
.../contiv/libovsdb/ovs_integration_test.go | 501 --------
.../github.com/contiv/libovsdb/rpc_test.go | 129 ---
.../contiv/objdb/Godeps/Godeps.json | 56 -
.../src/github.com/contiv/objdb/Godeps/Readme | 5 -
.../contiv/ofnet/Godeps/Godeps.json | 130 ---
.../src/github.com/contiv/ofnet/Godeps/Readme | 5 -
.../github.com/contiv/ofnet/libpkt/libpkt.go | 386 -------
.../contiv/ofnet/ovsSwitch/ovsSwitch.go | 369 ------
.../contiv/ofnet/ovsSwitch/utils.go | 74 --
.../contiv/vagrantssh/Godeps/Godeps.json | 22 -
.../contiv/vagrantssh/Godeps/Readme | 5 -
.../src/github.com/coreos/etcd/LICENSE | 202 ++++
.../src/github.com/coreos/etcd/NOTICE | 5 +
.../etcdhttp/httptypes/errors_test.go | 47 -
.../etcdhttp/httptypes/member_test.go | 135 ---
.../coreos/etcd/pkg/types/id_test.go | 95 --
.../coreos/etcd/pkg/types/set_test.go | 186 ---
.../coreos/etcd/pkg/types/slice_test.go | 30 -
.../coreos/etcd/pkg/types/urls_test.go | 169 ---
.../src/github.com/coreos/go-etcd/LICENSE | 202 ++++
.../coreos/go-etcd/etcd/add_child_test.go | 73 --
.../coreos/go-etcd/etcd/client_test.go | 108 --
.../go-etcd/etcd/compare_and_delete_test.go | 46 -
.../go-etcd/etcd/compare_and_swap_test.go | 57 -
.../coreos/go-etcd/etcd/debug_test.go | 28 -
.../coreos/go-etcd/etcd/delete_test.go | 81 --
.../coreos/go-etcd/etcd/get_test.go | 131 ---
.../coreos/go-etcd/etcd/member_test.go | 71 --
.../coreos/go-etcd/etcd/requests_test.go | 22 -
.../coreos/go-etcd/etcd/set_curl_chan_test.go | 42 -
.../go-etcd/etcd/set_update_create_test.go | 241 ----
.../coreos/go-etcd/etcd/watch_test.go | 119 --
.../docker/docker/pkg/plugins/client_test.go | 107 --
.../docker/pkg/plugins/discovery_test.go | 169 ---
.../pkg/plugins/pluginrpc-gen/fixtures/foo.go | 35 -
.../docker/pkg/plugins/pluginrpc-gen/main.go | 91 --
.../pkg/plugins/pluginrpc-gen/parser.go | 162 ---
.../pkg/plugins/pluginrpc-gen/parser_test.go | 168 ---
.../pkg/plugins/pluginrpc-gen/template.go | 97 --
.../protobuf/proto/proto3_proto/proto3.pb.go | 122 --
.../protobuf/proto/proto3_proto/proto3.proto | 68 --
.../gorilla/context/context_test.go | 161 ---
.../src/github.com/gorilla/mux/bench_test.go | 21 -
.../src/github.com/gorilla/mux/mux_test.go | 1003 -----------------
.../src/github.com/gorilla/mux/old_test.go | 714 ------------
.../src/github.com/hashicorp/consul/LICENSE | 354 ++++++
.../hashicorp/consul/api/acl_test.go | 152 ---
.../hashicorp/consul/api/agent_test.go | 524 ---------
.../hashicorp/consul/api/api_test.go | 242 ----
.../hashicorp/consul/api/catalog_test.go | 279 -----
.../hashicorp/consul/api/event_test.go | 49 -
.../hashicorp/consul/api/health_test.go | 125 --
.../hashicorp/consul/api/kv_test.go | 439 --------
.../hashicorp/consul/api/lock_test.go | 363 ------
.../hashicorp/consul/api/semaphore_test.go | 313 -----
.../hashicorp/consul/api/session_test.go | 205 ----
.../hashicorp/consul/api/status_test.go | 37 -
.../jainvipin/bitset/bitset_test.go | 792 -------------
.../samalba/dockerclient/examples/events.go | 39 -
.../dockerclient/examples/stats/stats.go | 43 -
.../samalba/dockerclient/mockclient/mock.go | 232 ----
.../samalba/dockerclient/nopclient/nop.go | 195 ----
.../github.com/stretchr/testify/LICENCE.txt | 9 +
.../testify/assert/assertions_test.go | 986 ----------------
.../testify/assert/forward_assertions_test.go | 611 ----------
.../testify/assert/http_assertions_test.go | 86 --
.../vishvananda/netlink/.travis.yml | 7 +-
.../github.com/vishvananda/netlink/Makefile | 2 +-
.../github.com/vishvananda/netlink/addr.go | 4 +-
.../vishvananda/netlink/addr_linux.go | 144 ++-
.../vishvananda/netlink/addr_test.go | 45 -
.../vishvananda/netlink/bpf_linux.go | 60 +
.../github.com/vishvananda/netlink/class.go | 111 ++
.../vishvananda/netlink/class_linux.go | 186 +++
.../github.com/vishvananda/netlink/filter.go | 190 ++++
.../vishvananda/netlink/filter_linux.go | 424 +++++++
.../github.com/vishvananda/netlink/link.go | 369 +++++-
.../vishvananda/netlink/link_linux.go | 478 +++++++-
.../vishvananda/netlink/link_test.go | 643 -----------
.../vishvananda/netlink/link_tuntap_linux.go | 14 +
.../vishvananda/netlink/neigh_linux.go | 5 +-
.../vishvananda/netlink/neigh_test.go | 104 --
.../github.com/vishvananda/netlink/netlink.go | 9 +-
.../vishvananda/netlink/netlink_test.go | 34 -
.../vishvananda/netlink/nl/addr_linux_test.go | 39 -
.../vishvananda/netlink/nl/link_linux.go | 292 +++++
.../vishvananda/netlink/nl/nl_linux.go | 14 +-
.../vishvananda/netlink/nl/nl_linux_test.go | 60 -
.../netlink/nl/route_linux_test.go | 43 -
.../vishvananda/netlink/nl/syscall.go | 37 +
.../vishvananda/netlink/nl/tc_linux.go | 686 +++++++++++
.../vishvananda/netlink/nl/xfrm_linux_test.go | 161 ---
.../netlink/nl/xfrm_policy_linux_test.go | 109 --
.../netlink/nl/xfrm_state_linux_test.go | 207 ----
.../vishvananda/netlink/protinfo_test.go | 98 --
.../github.com/vishvananda/netlink/qdisc.go | 295 +++++
.../vishvananda/netlink/qdisc_linux.go | 415 +++++++
.../github.com/vishvananda/netlink/route.go | 67 +-
.../vishvananda/netlink/route_linux.go | 218 +++-
.../vishvananda/netlink/route_test.go | 84 --
.../github.com/vishvananda/netlink/rule.go | 43 +
.../vishvananda/netlink/rule_linux.go | 198 ++++
.../vishvananda/netlink/xfrm_policy_test.go | 49 -
.../vishvananda/netlink/xfrm_state.go | 2 +-
.../vishvananda/netlink/xfrm_state_linux.go | 3 -
.../vishvananda/netlink/xfrm_state_test.go | 50 -
.../golang.org/x/crypto/ssh/agent/client.go | 563 ---------
.../golang.org/x/crypto/ssh/agent/forward.go | 103 --
.../golang.org/x/crypto/ssh/agent/keyring.go | 183 ---
.../golang.org/x/crypto/ssh/agent/server.go | 209 ----
.../x/crypto/ssh/terminal/terminal.go | 892 ---------------
.../golang.org/x/crypto/ssh/terminal/util.go | 128 ---
.../x/crypto/ssh/terminal/util_bsd.go | 12 -
.../x/crypto/ssh/terminal/util_linux.go | 11 -
.../x/crypto/ssh/terminal/util_windows.go | 174 ---
.../src/golang.org/x/crypto/ssh/test/doc.go | 7 -
.../golang.org/x/net/http2/h2demo/.gitignore | 5 -
.../golang.org/x/net/http2/h2demo/Makefile | 8 -
.../src/golang.org/x/net/http2/h2demo/README | 16 -
.../golang.org/x/net/http2/h2demo/h2demo.go | 436 -------
.../golang.org/x/net/http2/h2demo/launch.go | 302 -----
.../golang.org/x/net/http2/h2demo/rootCA.key | 27 -
.../golang.org/x/net/http2/h2demo/rootCA.pem | 26 -
.../golang.org/x/net/http2/h2demo/rootCA.srl | 1 -
.../golang.org/x/net/http2/h2demo/server.crt | 20 -
.../golang.org/x/net/http2/h2demo/server.key | 27 -
.../src/golang.org/x/net/http2/h2i/README.md | 97 --
.../src/golang.org/x/net/http2/h2i/h2i.go | 499 --------
.../src/golang.org/x/sys/unix/mkerrors.sh | 2 +-
.../src/golang.org/x/sys/unix/mksyscall.pl | 4 +-
.../x/sys/unix/mksyscall_solaris.pl | 4 +-
.../grpc/Documentation/grpc-auth-support.md | 41 -
.../grpc/benchmark/benchmark.go | 147 ---
.../grpc/benchmark/client/main.go | 161 ---
.../grpc/benchmark/grpc_testing/test.pb.go | 641 -----------
.../grpc/benchmark/grpc_testing/test.proto | 148 ---
.../grpc/benchmark/server/main.go | 35 -
.../grpc/benchmark/stats/counter.go | 135 ---
.../grpc/benchmark/stats/histogram.go | 255 -----
.../grpc/benchmark/stats/stats.go | 116 --
.../grpc/benchmark/stats/timeseries.go | 154 ---
.../grpc/benchmark/stats/tracker.go | 159 ---
.../grpc/benchmark/stats/util.go | 191 ----
.../grpc/credentials/oauth/oauth.go | 177 ---
.../google.golang.org/grpc/examples/README.md | 57 -
.../grpc/examples/gotutorial.md | 431 -------
.../helloworld/greeter_client/main.go | 69 --
.../helloworld/greeter_server/main.go | 65 --
.../helloworld/helloworld/helloworld.pb.go | 109 --
.../helloworld/helloworld/helloworld.proto | 51 -
.../grpc/examples/route_guide/README.md | 35 -
.../examples/route_guide/client/client.go | 202 ----
.../route_guide/routeguide/route_guide.pb.go | 426 -------
.../route_guide/routeguide/route_guide.proto | 121 --
.../examples/route_guide/server/server.go | 239 ----
.../grpc/grpclog/glogger/glogger.go | 72 --
.../health/grpc_health_v1alpha/health.pb.go | 133 ---
.../health/grpc_health_v1alpha/health.proto | 20 -
.../google.golang.org/grpc/health/health.go | 49 -
.../grpc/interop/client/client.go | 584 ----------
.../grpc/interop/grpc_testing/test.pb.go | 702 ------------
.../grpc/interop/grpc_testing/test.proto | 140 ---
.../grpc/interop/server/server.go | 209 ----
.../grpc/naming/etcd/etcd.go | 157 ---
.../google.golang.org/grpc/naming/naming.go | 75 --
.../grpc/test/codec_perf/perf.pb.go | 42 -
.../grpc/test/codec_perf/perf.proto | 11 -
.../grpc/test/grpc_testing/test.pb.go | 702 ------------
.../grpc/test/grpc_testing/test.proto | 140 ---
.../_workspace/src/gopkg.in/check.v1/LICENSE | 8 +-
.../src/gopkg.in/check.v1/README.md | 2 +-
.../src/gopkg.in/check.v1/benchmark.go | 6 +-
221 files changed, 5208 insertions(+), 28141 deletions(-)
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/main.go
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/README.md
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/main.go
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/COPYING
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/README.md
delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/main.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go
delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/adv_example_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/backoff_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/example_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/exponential_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/retry_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/backoff/ticker_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/hub/example_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/hub/hub_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/rpc2/jsonrpc/jsonrpc_test.go
delete mode 100644 Godeps/_workspace/src/github.com/cenkalti/rpc2/rpc2_test.go
delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete
delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
create mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/LICENSE
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/add_child_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/client_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_delete_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_swap_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/debug_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/delete_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/get_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/requests_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_curl_chan_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_update_create_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/watch_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Godeps.json
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Readme
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/example/play_with_ovs.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/notation_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/ovs_integration_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/libovsdb/rpc_test.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Godeps.json
delete mode 100644 Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Readme
delete mode 100644 Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Godeps.json
delete mode 100644 Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Readme
delete mode 100644 Godeps/_workspace/src/github.com/contiv/ofnet/libpkt/libpkt.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/ovsSwitch.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/utils.go
delete mode 100644 Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Godeps.json
delete mode 100644 Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Readme
create mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/LICENSE
create mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/NOTICE
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/errors_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/member_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/id_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/set_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/slice_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/urls_test.go
create mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/LICENSE
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go
delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/client_test.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/discovery_test.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/fixtures/foo.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/main.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser_test.go
delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/template.go
delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
delete mode 100644 Godeps/_workspace/src/github.com/gorilla/context/context_test.go
delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go
delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
create mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/LICENSE
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go
delete mode 100644 Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go
delete mode 100644 Godeps/_workspace/src/github.com/jainvipin/bitset/bitset_test.go
delete mode 100644 Godeps/_workspace/src/github.com/samalba/dockerclient/examples/events.go
delete mode 100644 Godeps/_workspace/src/github.com/samalba/dockerclient/examples/stats/stats.go
delete mode 100644 Godeps/_workspace/src/github.com/samalba/dockerclient/mockclient/mock.go
delete mode 100644 Godeps/_workspace/src/github.com/samalba/dockerclient/nopclient/nop.go
create mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/LICENCE.txt
delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/addr_test.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/bpf_linux.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/class.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/class_linux.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/filter.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/filter_linux.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/link_test.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/link_tuntap_linux.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/netlink_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/addr_linux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/route_linux_test.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/syscall.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/tc_linux.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_linux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_policy_linux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_state_linux_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo_test.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc_linux.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/route_test.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/rule.go
create mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/rule_linux.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy_test.go
delete mode 100644 Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_test.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/forward.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/keyring.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_bsd.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_linux.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_windows.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/crypto/ssh/test/doc.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/.gitignore
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/Makefile
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/README
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/h2demo.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/launch.go
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.key
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.pem
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.srl
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.crt
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.key
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2i/README.md
delete mode 100644 Godeps/_workspace/src/golang.org/x/net/http2/h2i/h2i.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/Documentation/grpc-auth-support.md
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/benchmark.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/client/main.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/server/main.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/counter.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/histogram.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/stats.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/timeseries.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/tracker.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/util.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/credentials/oauth/oauth.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/README.md
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/gotutorial.md
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_client/main.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_server/main.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/README.md
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/client/client.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/server/server.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/grpclog/glogger/glogger.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/health/health.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/interop/client/client.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/interop/server/server.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/naming/etcd/etcd.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/naming/naming.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.proto
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.pb.go
delete mode 100644 Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.proto
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
index fc545a57e..531b21c61 100644
--- a/Godeps/Godeps.json
+++ b/Godeps/Godeps.json
@@ -12,7 +12,12 @@
},
{
"ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.8.3-92-gf7f79f7",
+ "Comment": "v0.8.7-55-gf7f79f7",
+ "Rev": "f7f79f729e0fbe2fcc061db48a9ba0263f588252"
+ },
+ {
+ "ImportPath": "github.com/Sirupsen/logrus/hooks/syslog",
+ "Comment": "v0.8.7-55-gf7f79f7",
"Rev": "f7f79f729e0fbe2fcc061db48a9ba0263f588252"
},
{
@@ -32,6 +37,10 @@
"ImportPath": "github.com/cenkalti/rpc2",
"Rev": "44d0d95e4f529a0fe230c90d2126bd597c61148c"
},
+ {
+ "ImportPath": "github.com/cenkalti/rpc2/jsonrpc",
+ "Rev": "44d0d95e4f529a0fe230c90d2126bd597c61148c"
+ },
{
"ImportPath": "github.com/codegangsta/cli",
"Comment": "1.2.0-155-g96f1fed",
@@ -41,6 +50,10 @@
"ImportPath": "github.com/contiv/contivmodel",
"Rev": "12422da891c2ad18c1e3fb57ec541929d25fcff0"
},
+ {
+ "ImportPath": "github.com/contiv/contivmodel/client",
+ "Rev": "12422da891c2ad18c1e3fb57ec541929d25fcff0"
+ },
{
"ImportPath": "github.com/contiv/go-etcd/etcd",
"Comment": "v0.4.6-6-g4734e7a",
@@ -48,17 +61,37 @@
},
{
"ImportPath": "github.com/contiv/libovsdb",
- "Comment": "v0.1-3-g45476f1",
- "Rev": "45476f107954c5e22cf114211e684a5dd9a69595"
+ "Comment": "v0.1-7-gbbc744d",
+ "Rev": "bbc744d8ddc88c6a997e600b19736055c24d87d5"
},
{
"ImportPath": "github.com/contiv/objdb",
"Rev": "26ca13052130613588a9b1a3a1691b7b59f41103"
},
+ {
+ "ImportPath": "github.com/contiv/objdb/modeldb",
+ "Rev": "26ca13052130613588a9b1a3a1691b7b59f41103"
+ },
{
"ImportPath": "github.com/contiv/ofnet",
"Rev": "2b27831b6d282c193bd1420980ff0c3a73244436"
},
+ {
+ "ImportPath": "github.com/contiv/ofnet/ofctrl",
+ "Rev": "2b27831b6d282c193bd1420980ff0c3a73244436"
+ },
+ {
+ "ImportPath": "github.com/contiv/ofnet/ovsdbDriver",
+ "Rev": "2b27831b6d282c193bd1420980ff0c3a73244436"
+ },
+ {
+ "ImportPath": "github.com/contiv/ofnet/pqueue",
+ "Rev": "2b27831b6d282c193bd1420980ff0c3a73244436"
+ },
+ {
+ "ImportPath": "github.com/contiv/ofnet/rpcHub",
+ "Rev": "2b27831b6d282c193bd1420980ff0c3a73244436"
+ },
{
"ImportPath": "github.com/contiv/systemtests-utils",
"Rev": "912796a0a1310b462f441bbe7f4140da781d0548"
@@ -104,7 +137,7 @@
},
{
"ImportPath": "github.com/docker/go-units",
- "Comment": "v0.1.0-23-g5d2041e",
+ "Comment": "v0.3.0",
"Rev": "5d2041e26a699eaca682e2ea41c8f891e1060444"
},
{
@@ -221,7 +254,11 @@
},
{
"ImportPath": "github.com/vishvananda/netlink",
- "Rev": "4b5dce31de6d42af5bb9811c6d265472199e0fec"
+ "Rev": "a632d6dc2806fa19d2f7693017d3fb79d3d8fa03"
+ },
+ {
+ "ImportPath": "github.com/vishvananda/netlink/nl",
+ "Rev": "a632d6dc2806fa19d2f7693017d3fb79d3d8fa03"
},
{
"ImportPath": "golang.org/x/crypto/ssh",
@@ -231,10 +268,18 @@
"ImportPath": "golang.org/x/net/context",
"Rev": "195180cfebf7362bd243a52477697895128c8777"
},
+ {
+ "ImportPath": "golang.org/x/net/context/ctxhttp",
+ "Rev": "195180cfebf7362bd243a52477697895128c8777"
+ },
{
"ImportPath": "golang.org/x/net/http2",
"Rev": "195180cfebf7362bd243a52477697895128c8777"
},
+ {
+ "ImportPath": "golang.org/x/net/http2/hpack",
+ "Rev": "195180cfebf7362bd243a52477697895128c8777"
+ },
{
"ImportPath": "golang.org/x/net/internal/timeseries",
"Rev": "195180cfebf7362bd243a52477697895128c8777"
@@ -251,6 +296,26 @@
"ImportPath": "google.golang.org/grpc",
"Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
},
+ {
+ "ImportPath": "google.golang.org/grpc/codes",
+ "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
+ },
+ {
+ "ImportPath": "google.golang.org/grpc/credentials",
+ "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
+ },
+ {
+ "ImportPath": "google.golang.org/grpc/grpclog",
+ "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
+ },
+ {
+ "ImportPath": "google.golang.org/grpc/metadata",
+ "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
+ },
+ {
+ "ImportPath": "google.golang.org/grpc/transport",
+ "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
+ },
{
"ImportPath": "gopkg.in/check.v1",
"Rev": "11d3bc7aa68e238947792f30573146a3231fc0f1"
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING
deleted file mode 100644
index 5a8e33254..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING
+++ /dev/null
@@ -1,14 +0,0 @@
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- Version 2, December 2004
-
- Copyright (C) 2004 Sam Hocevar
-
- Everyone is permitted to copy and distribute verbatim or modified
- copies of this license document, and changing it is allowed as long
- as the name is changed.
-
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. You just DO WHAT THE FUCK YOU WANT TO.
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md
deleted file mode 100644
index 24421eb70..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Implements the TOML test suite interface
-
-This is an implementation of the interface expected by
-[toml-test](https://github.com/BurntSushi/toml-test) for my
-[toml parser written in Go](https://github.com/BurntSushi/toml).
-In particular, it maps TOML data on `stdin` to a JSON format on `stdout`.
-
-
-Compatible with TOML version
-[v0.2.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md)
-
-Compatible with `toml-test` version
-[v0.2.0](https://github.com/BurntSushi/toml-test/tree/v0.2.0)
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/main.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/main.go
deleted file mode 100644
index 14e755700..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-decoder/main.go
+++ /dev/null
@@ -1,90 +0,0 @@
-// Command toml-test-decoder satisfies the toml-test interface for testing
-// TOML decoders. Namely, it accepts TOML on stdin and outputs JSON on stdout.
-package main
-
-import (
- "encoding/json"
- "flag"
- "fmt"
- "log"
- "os"
- "path"
- "time"
-
- "github.com/BurntSushi/toml"
-)
-
-func init() {
- log.SetFlags(0)
-
- flag.Usage = usage
- flag.Parse()
-}
-
-func usage() {
- log.Printf("Usage: %s < toml-file\n", path.Base(os.Args[0]))
- flag.PrintDefaults()
-
- os.Exit(1)
-}
-
-func main() {
- if flag.NArg() != 0 {
- flag.Usage()
- }
-
- var tmp interface{}
- if _, err := toml.DecodeReader(os.Stdin, &tmp); err != nil {
- log.Fatalf("Error decoding TOML: %s", err)
- }
-
- typedTmp := translate(tmp)
- if err := json.NewEncoder(os.Stdout).Encode(typedTmp); err != nil {
- log.Fatalf("Error encoding JSON: %s", err)
- }
-}
-
-func translate(tomlData interface{}) interface{} {
- switch orig := tomlData.(type) {
- case map[string]interface{}:
- typed := make(map[string]interface{}, len(orig))
- for k, v := range orig {
- typed[k] = translate(v)
- }
- return typed
- case []map[string]interface{}:
- typed := make([]map[string]interface{}, len(orig))
- for i, v := range orig {
- typed[i] = translate(v).(map[string]interface{})
- }
- return typed
- case []interface{}:
- typed := make([]interface{}, len(orig))
- for i, v := range orig {
- typed[i] = translate(v)
- }
-
- // We don't really need to tag arrays, but let's be future proof.
- // (If TOML ever supports tuples, we'll need this.)
- return tag("array", typed)
- case time.Time:
- return tag("datetime", orig.Format("2006-01-02T15:04:05Z"))
- case bool:
- return tag("bool", fmt.Sprintf("%v", orig))
- case int64:
- return tag("integer", fmt.Sprintf("%d", orig))
- case float64:
- return tag("float", fmt.Sprintf("%v", orig))
- case string:
- return tag("string", orig)
- }
-
- panic(fmt.Sprintf("Unknown type: %T", tomlData))
-}
-
-func tag(typeName string, data interface{}) map[string]interface{} {
- return map[string]interface{}{
- "type": typeName,
- "value": data,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING
deleted file mode 100644
index 5a8e33254..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING
+++ /dev/null
@@ -1,14 +0,0 @@
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- Version 2, December 2004
-
- Copyright (C) 2004 Sam Hocevar
-
- Everyone is permitted to copy and distribute verbatim or modified
- copies of this license document, and changing it is allowed as long
- as the name is changed.
-
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. You just DO WHAT THE FUCK YOU WANT TO.
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/README.md b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/README.md
deleted file mode 100644
index 45a603f29..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Implements the TOML test suite interface for TOML encoders
-
-This is an implementation of the interface expected by
-[toml-test](https://github.com/BurntSushi/toml-test) for the
-[TOML encoder](https://github.com/BurntSushi/toml).
-In particular, it maps JSON data on `stdin` to a TOML format on `stdout`.
-
-
-Compatible with TOML version
-[v0.2.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md)
-
-Compatible with `toml-test` version
-[v0.2.0](https://github.com/BurntSushi/toml-test/tree/v0.2.0)
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/main.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/main.go
deleted file mode 100644
index 092cc6844..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/toml-test-encoder/main.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Command toml-test-encoder satisfies the toml-test interface for testing
-// TOML encoders. Namely, it accepts JSON on stdin and outputs TOML on stdout.
-package main
-
-import (
- "encoding/json"
- "flag"
- "log"
- "os"
- "path"
- "strconv"
- "time"
-
- "github.com/BurntSushi/toml"
-)
-
-func init() {
- log.SetFlags(0)
-
- flag.Usage = usage
- flag.Parse()
-}
-
-func usage() {
- log.Printf("Usage: %s < json-file\n", path.Base(os.Args[0]))
- flag.PrintDefaults()
-
- os.Exit(1)
-}
-
-func main() {
- if flag.NArg() != 0 {
- flag.Usage()
- }
-
- var tmp interface{}
- if err := json.NewDecoder(os.Stdin).Decode(&tmp); err != nil {
- log.Fatalf("Error decoding JSON: %s", err)
- }
-
- tomlData := translate(tmp)
- if err := toml.NewEncoder(os.Stdout).Encode(tomlData); err != nil {
- log.Fatalf("Error encoding TOML: %s", err)
- }
-}
-
-func translate(typedJson interface{}) interface{} {
- switch v := typedJson.(type) {
- case map[string]interface{}:
- if len(v) == 2 && in("type", v) && in("value", v) {
- return untag(v)
- }
- m := make(map[string]interface{}, len(v))
- for k, v2 := range v {
- m[k] = translate(v2)
- }
- return m
- case []interface{}:
- tabArray := make([]map[string]interface{}, len(v))
- for i := range v {
- if m, ok := translate(v[i]).(map[string]interface{}); ok {
- tabArray[i] = m
- } else {
- log.Fatalf("JSON arrays may only contain objects. This " +
- "corresponds to only tables being allowed in " +
- "TOML table arrays.")
- }
- }
- return tabArray
- }
- log.Fatalf("Unrecognized JSON format '%T'.", typedJson)
- panic("unreachable")
-}
-
-func untag(typed map[string]interface{}) interface{} {
- t := typed["type"].(string)
- v := typed["value"]
- switch t {
- case "string":
- return v.(string)
- case "integer":
- v := v.(string)
- n, err := strconv.Atoi(v)
- if err != nil {
- log.Fatalf("Could not parse '%s' as integer: %s", v, err)
- }
- return n
- case "float":
- v := v.(string)
- f, err := strconv.ParseFloat(v, 64)
- if err != nil {
- log.Fatalf("Could not parse '%s' as float64: %s", v, err)
- }
- return f
- case "datetime":
- v := v.(string)
- t, err := time.Parse("2006-01-02T15:04:05Z", v)
- if err != nil {
- log.Fatalf("Could not parse '%s' as a datetime: %s", v, err)
- }
- return t
- case "bool":
- v := v.(string)
- switch v {
- case "true":
- return true
- case "false":
- return false
- }
- log.Fatalf("Could not parse '%s' as a boolean.", v)
- case "array":
- v := v.([]interface{})
- array := make([]interface{}, len(v))
- for i := range v {
- if m, ok := v[i].(map[string]interface{}); ok {
- array[i] = untag(m)
- } else {
- log.Fatalf("Arrays may only contain other arrays or "+
- "primitive values, but found a '%T'.", m)
- }
- }
- return array
- }
- log.Fatalf("Unrecognized tag type '%s'.", t)
- panic("unreachable")
-}
-
-func in(key string, m map[string]interface{}) bool {
- _, ok := m[key]
- return ok
-}
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/COPYING b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/COPYING
deleted file mode 100644
index 5a8e33254..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/COPYING
+++ /dev/null
@@ -1,14 +0,0 @@
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- Version 2, December 2004
-
- Copyright (C) 2004 Sam Hocevar
-
- Everyone is permitted to copy and distribute verbatim or modified
- copies of this license document, and changing it is allowed as long
- as the name is changed.
-
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. You just DO WHAT THE FUCK YOU WANT TO.
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/README.md b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/README.md
deleted file mode 100644
index 5df0dc32b..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/README.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# TOML Validator
-
-If Go is installed, it's simple to try it out:
-
-```bash
-go get github.com/BurntSushi/toml/cmd/tomlv
-tomlv some-toml-file.toml
-```
-
-You can see the types of every key in a TOML file with:
-
-```bash
-tomlv -types some-toml-file.toml
-```
-
-At the moment, only one error message is reported at a time. Error messages
-include line numbers. No output means that the files given are valid TOML, or
-there is a bug in `tomlv`.
-
-Compatible with TOML version
-[v0.1.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.1.0.md)
-
diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/main.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/main.go
deleted file mode 100644
index c7d689a7e..000000000
--- a/Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/main.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Command tomlv validates TOML documents and prints each key's type.
-package main
-
-import (
- "flag"
- "fmt"
- "log"
- "os"
- "path"
- "strings"
- "text/tabwriter"
-
- "github.com/BurntSushi/toml"
-)
-
-var (
- flagTypes = false
-)
-
-func init() {
- log.SetFlags(0)
-
- flag.BoolVar(&flagTypes, "types", flagTypes,
- "When set, the types of every defined key will be shown.")
-
- flag.Usage = usage
- flag.Parse()
-}
-
-func usage() {
- log.Printf("Usage: %s toml-file [ toml-file ... ]\n",
- path.Base(os.Args[0]))
- flag.PrintDefaults()
-
- os.Exit(1)
-}
-
-func main() {
- if flag.NArg() < 1 {
- flag.Usage()
- }
- for _, f := range flag.Args() {
- var tmp interface{}
- md, err := toml.DecodeFile(f, &tmp)
- if err != nil {
- log.Fatalf("Error in '%s': %s", f, err)
- }
- if flagTypes {
- printTypes(md)
- }
- }
-}
-
-func printTypes(md toml.MetaData) {
- tabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
- for _, key := range md.Keys() {
- fmt.Fprintf(tabw, "%s%s\t%s\n",
- strings.Repeat(" ", len(key)-1), key, md.Type(key...))
- }
- tabw.Flush()
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go
deleted file mode 100644
index 99c3b41d5..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-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/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go
deleted file mode 100644
index a1623ec00..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.JSONFormatter)
- log.Formatter = new(logrus.TextFormatter) // default
- log.Level = logrus.DebugLevel
-}
-
-func main() {
- defer func() {
- err := recover()
- if err != nil {
- log.WithFields(logrus.Fields{
- "omg": true,
- "err": err,
- "number": 100,
- }).Fatal("The ice breaks!")
- }
- }()
-
- 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!")
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go
deleted file mode 100644
index 3187f6d3e..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
- "gopkg.in/gemnasium/logrus-airbrake-hook.v2"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.TextFormatter) // default
- log.Hooks.Add(airbrake.NewHook(123, "xyz", "development"))
-}
-
-func main() {
- 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,
- }).Fatal("The ice breaks!")
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go
deleted file mode 100644
index c6d290c77..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-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) {
- entry := &Entry{
- Time: time.Time{},
- Level: InfoLevel,
- Message: "message",
- Data: fields,
- }
- 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/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
deleted file mode 100644
index aad646abf..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logstash
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/Sirupsen/logrus"
-)
-
-// Formatter generates json in logstash format.
-// Logstash site: http://logstash.net/
-type LogstashFormatter struct {
- Type string // if not empty use for logstash type field.
-
- // TimestampFormat sets the format used for timestamps.
- TimestampFormat string
-}
-
-func (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) {
- fields := make(logrus.Fields)
- for k, v := range entry.Data {
- fields[k] = v
- }
-
- fields["@version"] = 1
-
- if f.TimestampFormat == "" {
- f.TimestampFormat = logrus.DefaultTimestampFormat
- }
-
- fields["@timestamp"] = entry.Time.Format(f.TimestampFormat)
-
- // set message field
- v, ok := entry.Data["message"]
- if ok {
- fields["fields.message"] = v
- }
- fields["message"] = entry.Message
-
- // set level field
- v, ok = entry.Data["level"]
- if ok {
- fields["fields.level"] = v
- }
- fields["level"] = entry.Level.String()
-
- // set type field
- if f.Type != "" {
- v, ok = entry.Data["type"]
- if ok {
- fields["fields.type"] = v
- }
- fields["type"] = f.Type
- }
-
- serialized, err := json.Marshal(fields)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go
deleted file mode 100644
index d8814a0ea..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package logstash
-
-import (
- "bytes"
- "encoding/json"
- "github.com/Sirupsen/logrus"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestLogstashFormatter(t *testing.T) {
- assert := assert.New(t)
-
- lf := LogstashFormatter{Type: "abc"}
-
- fields := logrus.Fields{
- "message": "def",
- "level": "ijk",
- "type": "lmn",
- "one": 1,
- "pi": 3.14,
- "bool": true,
- }
-
- entry := logrus.WithFields(fields)
- entry.Message = "msg"
- entry.Level = logrus.InfoLevel
-
- b, _ := lf.Format(entry)
-
- var data map[string]interface{}
- dec := json.NewDecoder(bytes.NewReader(b))
- dec.UseNumber()
- dec.Decode(&data)
-
- // base fields
- assert.Equal(json.Number("1"), data["@version"])
- assert.NotEmpty(data["@timestamp"])
- assert.Equal("abc", data["type"])
- assert.Equal("msg", data["message"])
- assert.Equal("info", data["level"])
-
- // substituted fields
- assert.Equal("def", data["fields.message"])
- assert.Equal("ijk", data["fields.level"])
- assert.Equal("lmn", data["fields.type"])
-
- // formats
- assert.Equal(json.Number("1"), data["one"])
- assert.Equal(json.Number("3.14"), data["pi"])
- assert.Equal(true, data["bool"])
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go
deleted file mode 100644
index 13f34cb6f..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package logrus
-
-import (
- "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)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go
deleted file mode 100644
index 42762dc10..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package logrus_syslog
-
-import (
- "github.com/Sirupsen/logrus"
- "log/syslog"
- "testing"
-)
-
-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/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go
deleted file mode 100644
index 1d7087325..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "errors"
-
- "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")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go
deleted file mode 100644
index efaacea23..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go
+++ /dev/null
@@ -1,301 +0,0 @@
-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("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("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("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("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()
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go
deleted file mode 100644
index e25a44f67..000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "errors"
- "testing"
- "time"
-)
-
-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, "abcd")
- checkQuoting(false, "v1.0")
- checkQuoting(false, "1234567890")
- checkQuoting(true, "/foobar")
- checkQuoting(true, "x y")
- checkQuoting(true, "x,y")
- checkQuoting(false, errors.New("invalid"))
- checkQuoting(true, errors.New("invalid argument"))
-}
-
-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 : timeEnd-1]
- if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' {
- timeStr = timeStr[1 : len(timeStr)-1]
- }
- 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("")
-}
-
-// TODO add tests for sorting etc., this requires a parser for the text
-// formatter output.
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/adv_example_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/adv_example_test.go
deleted file mode 100644
index 3fe6783b8..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/adv_example_test.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package backoff
-
-import (
- "io/ioutil"
- "log"
- "net/http"
- "time"
-)
-
-// This is an example that demonstrates how this package could be used
-// to perform various advanced operations.
-//
-// It executes an HTTP GET request with exponential backoff,
-// while errors are logged and failed responses are closed, as required by net/http package.
-//
-// Note we define a condition function which is used inside the operation to
-// determine whether the operation succeeded or failed.
-func Example() error {
- res, err := GetWithRetry(
- "http://localhost:9999",
- ErrorIfStatusCodeIsNot(http.StatusOK),
- NewExponentialBackOff())
-
- if err != nil {
- // Close response body of last (failed) attempt.
- // The Last attempt isn't handled by the notify-on-error function,
- // which closes the body of all the previous attempts.
- if e := res.Body.Close(); e != nil {
- log.Printf("error closing last attempt's response body: %s", e)
- }
- log.Printf("too many failed request attempts: %s", err)
- return err
- }
- defer res.Body.Close() // The response's Body must be closed.
-
- // Read body
- _, _ = ioutil.ReadAll(res.Body)
-
- // Do more stuff
- return nil
-}
-
-// GetWithRetry is a helper function that performs an HTTP GET request
-// to the given URL, and retries with the given backoff using the given condition function.
-//
-// It also uses a notify-on-error function which logs
-// and closes the response body of the failed request.
-func GetWithRetry(url string, condition Condition, bck BackOff) (*http.Response, error) {
- var res *http.Response
- err := RetryNotify(
- func() error {
- var err error
- res, err = http.Get(url)
- if err != nil {
- return err
- }
- return condition(res)
- },
- bck,
- LogAndClose())
-
- return res, err
-}
-
-// Condition is a retry condition function.
-// It receives a response, and returns an error
-// if the response failed the condition.
-type Condition func(*http.Response) error
-
-// ErrorIfStatusCodeIsNot returns a retry condition function.
-// The condition returns an error
-// if the given response's status code is not the given HTTP status code.
-func ErrorIfStatusCodeIsNot(status int) Condition {
- return func(res *http.Response) error {
- if res.StatusCode != status {
- return NewError(res)
- }
- return nil
- }
-}
-
-// Error is returned on ErrorIfX() condition functions throughout this package.
-type Error struct {
- Response *http.Response
-}
-
-func NewError(res *http.Response) *Error {
- // Sanity check
- if res == nil {
- panic("response object is nil")
- }
- return &Error{Response: res}
-}
-func (err *Error) Error() string { return "request failed" }
-
-// LogAndClose is a notify-on-error function.
-// It logs the error and closes the response body.
-func LogAndClose() Notify {
- return func(err error, wait time.Duration) {
- switch e := err.(type) {
- case *Error:
- defer e.Response.Body.Close()
-
- b, err := ioutil.ReadAll(e.Response.Body)
- var body string
- if err != nil {
- body = "can't read body"
- } else {
- body = string(b)
- }
-
- log.Printf("%s: %s", e.Response.Status, body)
- default:
- log.Println(err)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/backoff_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/backoff_test.go
deleted file mode 100644
index 91f27c4f1..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/backoff_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package backoff
-
-import (
- "testing"
- "time"
-)
-
-func TestNextBackOffMillis(t *testing.T) {
- subtestNextBackOff(t, 0, new(ZeroBackOff))
- subtestNextBackOff(t, Stop, new(StopBackOff))
-}
-
-func subtestNextBackOff(t *testing.T, expectedValue time.Duration, backOffPolicy BackOff) {
- for i := 0; i < 10; i++ {
- next := backOffPolicy.NextBackOff()
- if next != expectedValue {
- t.Errorf("got: %d expected: %d", next, expectedValue)
- }
- }
-}
-
-func TestConstantBackOff(t *testing.T) {
- backoff := NewConstantBackOff(time.Second)
- if backoff.NextBackOff() != time.Second {
- t.Error("invalid interval")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/example_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/example_test.go
deleted file mode 100644
index 0d1852e45..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/example_test.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package backoff
-
-import "log"
-
-func ExampleRetry() error {
- operation := func() error {
- // An operation that might fail.
- return nil // or return errors.New("some error")
- }
-
- err := Retry(operation, NewExponentialBackOff())
- if err != nil {
- // Handle error.
- return err
- }
-
- // Operation is successful.
- return nil
-}
-
-func ExampleTicker() error {
- operation := func() error {
- // An operation that might fail
- return nil // or return errors.New("some error")
- }
-
- b := NewExponentialBackOff()
- ticker := NewTicker(b)
-
- var err error
-
- // Ticks will continue to arrive when the previous operation is still running,
- // so operations that take a while to fail could run in quick succession.
- for _ = range ticker.C {
- if err = operation(); err != nil {
- log.Println(err, "will retry...")
- continue
- }
-
- ticker.Stop()
- break
- }
-
- if err != nil {
- // Operation has failed.
- return err
- }
-
- // Operation is successful.
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/exponential_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/exponential_test.go
deleted file mode 100644
index 11b95e4f6..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/exponential_test.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package backoff
-
-import (
- "math"
- "testing"
- "time"
-)
-
-func TestBackOff(t *testing.T) {
- var (
- testInitialInterval = 500 * time.Millisecond
- testRandomizationFactor = 0.1
- testMultiplier = 2.0
- testMaxInterval = 5 * time.Second
- testMaxElapsedTime = 15 * time.Minute
- )
-
- exp := NewExponentialBackOff()
- exp.InitialInterval = testInitialInterval
- exp.RandomizationFactor = testRandomizationFactor
- exp.Multiplier = testMultiplier
- exp.MaxInterval = testMaxInterval
- exp.MaxElapsedTime = testMaxElapsedTime
- exp.Reset()
-
- var expectedResults = []time.Duration{500, 1000, 2000, 4000, 5000, 5000, 5000, 5000, 5000, 5000}
- for i, d := range expectedResults {
- expectedResults[i] = d * time.Millisecond
- }
-
- for _, expected := range expectedResults {
- assertEquals(t, expected, exp.currentInterval)
- // Assert that the next backoff falls in the expected range.
- var minInterval = expected - time.Duration(testRandomizationFactor*float64(expected))
- var maxInterval = expected + time.Duration(testRandomizationFactor*float64(expected))
- var actualInterval = exp.NextBackOff()
- if !(minInterval <= actualInterval && actualInterval <= maxInterval) {
- t.Error("error")
- }
- }
-}
-
-func TestGetRandomizedInterval(t *testing.T) {
- // 33% chance of being 1.
- assertEquals(t, 1, getRandomValueFromInterval(0.5, 0, 2))
- assertEquals(t, 1, getRandomValueFromInterval(0.5, 0.33, 2))
- // 33% chance of being 2.
- assertEquals(t, 2, getRandomValueFromInterval(0.5, 0.34, 2))
- assertEquals(t, 2, getRandomValueFromInterval(0.5, 0.66, 2))
- // 33% chance of being 3.
- assertEquals(t, 3, getRandomValueFromInterval(0.5, 0.67, 2))
- assertEquals(t, 3, getRandomValueFromInterval(0.5, 0.99, 2))
-}
-
-type TestClock struct {
- i time.Duration
- start time.Time
-}
-
-func (c *TestClock) Now() time.Time {
- t := c.start.Add(c.i)
- c.i += time.Second
- return t
-}
-
-func TestGetElapsedTime(t *testing.T) {
- var exp = NewExponentialBackOff()
- exp.Clock = &TestClock{}
- exp.Reset()
-
- var elapsedTime = exp.GetElapsedTime()
- if elapsedTime != time.Second {
- t.Errorf("elapsedTime=%d", elapsedTime)
- }
-}
-
-func TestMaxElapsedTime(t *testing.T) {
- var exp = NewExponentialBackOff()
- exp.Clock = &TestClock{start: time.Time{}.Add(10000 * time.Second)}
- // Change the currentElapsedTime to be 0 ensuring that the elapsed time will be greater
- // than the max elapsed time.
- exp.startTime = time.Time{}
- assertEquals(t, Stop, exp.NextBackOff())
-}
-
-func TestBackOffOverflow(t *testing.T) {
- var (
- testInitialInterval time.Duration = math.MaxInt64 / 2
- testMaxInterval time.Duration = math.MaxInt64
- testMultiplier = 2.1
- )
-
- exp := NewExponentialBackOff()
- exp.InitialInterval = testInitialInterval
- exp.Multiplier = testMultiplier
- exp.MaxInterval = testMaxInterval
- exp.Reset()
-
- exp.NextBackOff()
- // Assert that when an overflow is possible the current varerval time.Duration is set to the max varerval time.Duration .
- assertEquals(t, testMaxInterval, exp.currentInterval)
-}
-
-func assertEquals(t *testing.T, expected, value time.Duration) {
- if expected != value {
- t.Errorf("got: %d, expected: %d", value, expected)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/retry_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/retry_test.go
deleted file mode 100644
index c0d25ab76..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/retry_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package backoff
-
-import (
- "errors"
- "log"
- "testing"
-)
-
-func TestRetry(t *testing.T) {
- const successOn = 3
- var i = 0
-
- // This function is successfull on "successOn" calls.
- f := func() error {
- i++
- log.Printf("function is called %d. time\n", i)
-
- if i == successOn {
- log.Println("OK")
- return nil
- }
-
- log.Println("error")
- return errors.New("error")
- }
-
- err := Retry(f, NewExponentialBackOff())
- if err != nil {
- t.Errorf("unexpected error: %s", err.Error())
- }
- if i != successOn {
- t.Errorf("invalid number of retries: %d", i)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/backoff/ticker_test.go b/Godeps/_workspace/src/github.com/cenkalti/backoff/ticker_test.go
deleted file mode 100644
index 7c392df46..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/backoff/ticker_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package backoff
-
-import (
- "errors"
- "log"
- "testing"
-)
-
-func TestTicker(t *testing.T) {
- const successOn = 3
- var i = 0
-
- // This function is successfull on "successOn" calls.
- f := func() error {
- i++
- log.Printf("function is called %d. time\n", i)
-
- if i == successOn {
- log.Println("OK")
- return nil
- }
-
- log.Println("error")
- return errors.New("error")
- }
-
- b := NewExponentialBackOff()
- ticker := NewTicker(b)
-
- var err error
- for _ = range ticker.C {
- if err = f(); err != nil {
- t.Log(err)
- continue
- }
-
- break
- }
- if err != nil {
- t.Errorf("unexpected error: %s", err.Error())
- }
- if i != successOn {
- t.Errorf("invalid number of retries: %d", i)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/hub/example_test.go b/Godeps/_workspace/src/github.com/cenkalti/hub/example_test.go
deleted file mode 100644
index 1923e679a..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/hub/example_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package hub
-
-import "fmt"
-
-// Different event kinds
-const (
- happenedA = iota
- happenedB
- happenedC
-)
-
-// Our custom event type
-type EventA struct {
- arg1, arg2 int
-}
-
-// Implement hub.Event interface
-func (e EventA) Kind() int { return happenedA }
-
-func Example() {
- Subscribe(happenedA, func(e Event) {
- a := e.(EventA) // Cast to concrete type
- fmt.Println(a.arg1 + a.arg2)
- })
-
- Publish(EventA{2, 3})
- // Output: 5
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/hub/hub_test.go b/Godeps/_workspace/src/github.com/cenkalti/hub/hub_test.go
deleted file mode 100644
index b2f718252..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/hub/hub_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package hub
-
-import "testing"
-
-const testKind = 1
-const testValue = "foo"
-
-type testEvent string
-
-func (e testEvent) Kind() int {
- return testKind
-}
-
-func TestPubSub(t *testing.T) {
- var h Hub
- var s string
-
- h.Subscribe(testKind, func(e Event) { s = string(e.(testEvent)) })
- h.Publish(testEvent(testValue))
-
- if s != testValue {
- t.Errorf("invalid value: %s", s)
- }
-}
-
-func TestCancel(t *testing.T) {
- var h Hub
- var called bool
-
- cancel := h.Subscribe(testKind, func(e Event) { called = true })
- cancel()
- h.Publish(testEvent(testValue))
-
- if called {
- t.Error("unexpected call")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/rpc2/jsonrpc/jsonrpc_test.go b/Godeps/_workspace/src/github.com/cenkalti/rpc2/jsonrpc/jsonrpc_test.go
deleted file mode 100644
index ed49b6a91..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/rpc2/jsonrpc/jsonrpc_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package jsonrpc
-
-import (
- "github.com/cenkalti/rpc2"
- "net"
- "testing"
- "time"
-)
-
-const (
- network = "tcp4"
- addr = "127.0.0.1:5000"
-)
-
-func TestJSONRPC(t *testing.T) {
- type Args struct{ A, B int }
- type Reply int
-
- lis, err := net.Listen(network, addr)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := rpc2.NewServer()
- srv.Handle("add", func(client *rpc2.Client, args *Args, reply *Reply) error {
- *reply = Reply(args.A + args.B)
-
- var rep Reply
- err := client.Call("mult", Args{2, 3}, &rep)
- if err != nil {
- t.Fatal(err)
- }
-
- if rep != 6 {
- t.Fatalf("not expected: %d", rep)
- }
-
- return nil
- })
- srv.Handle("addPos", func(client *rpc2.Client, args []interface{}, result *float64) error {
- *result = args[0].(float64) + args[1].(float64)
- return nil
- })
- number := make(chan int, 1)
- srv.Handle("set", func(client *rpc2.Client, i int, _ *struct{}) error {
- number <- i
- return nil
- })
-
- go func() {
- conn, err := lis.Accept()
- if err != nil {
- t.Fatal(err)
- }
- srv.ServeCodec(NewJSONCodec(conn))
- }()
-
- conn, err := net.Dial(network, addr)
- if err != nil {
- t.Fatal(err)
- }
-
- clt := rpc2.NewClientWithCodec(NewJSONCodec(conn))
- clt.Handle("mult", func(client *rpc2.Client, args *Args, reply *Reply) error {
- *reply = Reply(args.A * args.B)
- return nil
- })
- go clt.Run()
-
- // Test Call.
- var rep Reply
- err = clt.Call("add", Args{1, 2}, &rep)
- if err != nil {
- t.Fatal(err)
- }
- if rep != 3 {
- t.Fatalf("not expected: %d", rep)
- }
-
- // Test notification.
- err = clt.Notify("set", 6)
- if err != nil {
- t.Fatal(err)
- }
- select {
- case i := <-number:
- if i != 6 {
- t.Fatalf("unexpected number: %d", i)
- }
- case <-time.After(time.Second):
- t.Fatal("did not get notification")
- }
-
- // Test undefined method.
- err = clt.Call("foo", 1, &rep)
- if err.Error() != "rpc2: can't find method foo" {
- t.Fatal(err)
- }
-
- // Test Positional arguments.
- var result float64
- err = clt.Call("addPos", []interface{}{1, 2}, &result)
- if err != nil {
- t.Fatal(err)
- }
- if result != 3 {
- t.Fatalf("not expected: %d", result)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/cenkalti/rpc2/rpc2_test.go b/Godeps/_workspace/src/github.com/cenkalti/rpc2/rpc2_test.go
deleted file mode 100644
index b2b7c0a46..000000000
--- a/Godeps/_workspace/src/github.com/cenkalti/rpc2/rpc2_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package rpc2
-
-import (
- "net"
- "testing"
- "time"
-)
-
-const (
- network = "tcp4"
- addr = "127.0.0.1:5000"
-)
-
-func TestTCPGOB(t *testing.T) {
- type Args struct{ A, B int }
- type Reply int
-
- lis, err := net.Listen(network, addr)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := NewServer()
- srv.Handle("add", func(client *Client, args *Args, reply *Reply) error {
- *reply = Reply(args.A + args.B)
-
- var rep Reply
- err := client.Call("mult", Args{2, 3}, &rep)
- if err != nil {
- t.Fatal(err)
- }
-
- if rep != 6 {
- t.Fatalf("not expected: %d", rep)
- }
-
- return nil
- })
- number := make(chan int, 1)
- srv.Handle("set", func(client *Client, i int, _ *struct{}) error {
- number <- i
- return nil
- })
- go srv.Accept(lis)
-
- conn, err := net.Dial(network, addr)
- if err != nil {
- t.Fatal(err)
- }
-
- clt := NewClient(conn)
- clt.Handle("mult", func(client *Client, args *Args, reply *Reply) error {
- *reply = Reply(args.A * args.B)
- return nil
- })
- go clt.Run()
- defer clt.Close()
-
- // Test Call.
- var rep Reply
- err = clt.Call("add", Args{1, 2}, &rep)
- if err != nil {
- t.Fatal(err)
- }
- if rep != 3 {
- t.Fatalf("not expected: %d", rep)
- }
-
- // Test notification.
- err = clt.Notify("set", 6)
- if err != nil {
- t.Fatal(err)
- }
- select {
- case i := <-number:
- if i != 6 {
- t.Fatalf("unexpected number: %d", i)
- }
- case <-time.After(time.Second):
- t.Fatal("did not get notification")
- }
-
- // Test undefined method.
- err = clt.Call("foo", 1, &rep)
- if err.Error() != "rpc2: can't find method foo" {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete b/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete
deleted file mode 100644
index d9231f4cf..000000000
--- a/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/bash_autocomplete
+++ /dev/null
@@ -1,15 +0,0 @@
-#! /bin/bash
-
-: ${PROG:=$(basename ${BASH_SOURCE})}
-
-_cli_bash_autocomplete() {
- local cur prev opts base
- COMPREPLY=()
- cur="${COMP_WORDS[COMP_CWORD]}"
- prev="${COMP_WORDS[COMP_CWORD-1]}"
- opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
- COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
- return 0
- }
-
- complete -F _cli_bash_autocomplete $PROG
\ No newline at end of file
diff --git a/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete b/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
deleted file mode 100644
index 5430a18f9..000000000
--- a/Godeps/_workspace/src/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
+++ /dev/null
@@ -1,5 +0,0 @@
-autoload -U compinit && compinit
-autoload -U bashcompinit && bashcompinit
-
-script_dir=$(dirname $0)
-source ${script_dir}/bash_autocomplete
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/LICENSE b/Godeps/_workspace/src/github.com/contiv/go-etcd/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/contiv/go-etcd/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/add_child_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/add_child_test.go
deleted file mode 100644
index 26223ff1c..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/add_child_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package etcd
-
-import "testing"
-
-func TestAddChild(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- c.Delete("nonexistentDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
-
- _, err := c.AddChild("fooDir", "v0", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = c.AddChild("fooDir", "v1", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := c.Get("fooDir", true, false)
- // The child with v0 should proceed the child with v1 because it's added
- // earlier, so it should have a lower key.
- if !(len(resp.Node.Nodes) == 2 && (resp.Node.Nodes[0].Value == "v0" && resp.Node.Nodes[1].Value == "v1")) {
- t.Fatalf("AddChild 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+
- " The response was: %#v", resp)
- }
-
- // Creating a child under a nonexistent directory should succeed.
- // The directory should be created.
- resp, err = c.AddChild("nonexistentDir", "foo", 5)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestAddChildDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- c.Delete("nonexistentDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
-
- _, err := c.AddChildDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = c.AddChildDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := c.Get("fooDir", true, false)
- // The child with v0 should proceed the child with v1 because it's added
- // earlier, so it should have a lower key.
- if !(len(resp.Node.Nodes) == 2 && (len(resp.Node.Nodes[0].Nodes) == 0 && len(resp.Node.Nodes[1].Nodes) == 0)) {
- t.Fatalf("AddChildDir 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+
- " The response was: %#v", resp)
- }
-
- // Creating a child under a nonexistent directory should succeed.
- // The directory should be created.
- resp, err = c.AddChildDir("nonexistentDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/client_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/client_test.go
deleted file mode 100644
index 66d79d733..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/client_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package etcd
-
-import (
- "encoding/json"
- "fmt"
- "net"
- "net/url"
- "os"
- "testing"
-)
-
-// To pass this test, we need to create a cluster of 3 machines
-// The server should be listening on localhost:4001, 4002, 4003
-func TestSync(t *testing.T) {
- fmt.Println("Make sure there are three nodes at 0.0.0.0:4001-4003")
-
- // Explicit trailing slash to ensure this doesn't reproduce:
- // https://github.com/coreos/go-etcd/issues/82
- c := NewClient([]string{"http://127.0.0.1:4001/"})
-
- success := c.SyncCluster()
- if !success {
- t.Fatal("cannot sync machines")
- }
-
- for _, m := range c.GetCluster() {
- u, err := url.Parse(m)
- if err != nil {
- t.Fatal(err)
- }
- if u.Scheme != "http" {
- t.Fatal("scheme must be http")
- }
-
- host, _, err := net.SplitHostPort(u.Host)
- if err != nil {
- t.Fatal(err)
- }
- if host != "localhost" {
- t.Fatal("Host must be localhost")
- }
- }
-
- badMachines := []string{"abc", "edef"}
-
- success = c.SetCluster(badMachines)
-
- if success {
- t.Fatal("should not sync on bad machines")
- }
-
- goodMachines := []string{"127.0.0.1:4002"}
-
- success = c.SetCluster(goodMachines)
-
- if !success {
- t.Fatal("cannot sync machines")
- } else {
- fmt.Println(c.cluster.Machines)
- }
-
-}
-
-func TestPersistence(t *testing.T) {
- c := NewClient(nil)
- c.SyncCluster()
-
- fo, err := os.Create("config.json")
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- if err := fo.Close(); err != nil {
- panic(err)
- }
- }()
-
- c.SetPersistence(fo)
- err = c.saveConfig()
- if err != nil {
- t.Fatal(err)
- }
-
- c2, err := NewClientFromFile("config.json")
- if err != nil {
- t.Fatal(err)
- }
-
- // Verify that the two clients have the same config
- b1, _ := json.Marshal(c)
- b2, _ := json.Marshal(c2)
-
- if string(b1) != string(b2) {
- t.Fatalf("The two configs should be equal!")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_delete_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_delete_test.go
deleted file mode 100644
index 223e50f29..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_delete_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestCompareAndDelete(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- // This should succeed an correct prevValue
- resp, err := c.CompareAndDelete("foo", "bar", 0)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndDelete 1 prevNode failed: %#v", resp)
- }
-
- resp, _ = c.Set("foo", "bar", 5)
- // This should fail because it gives an incorrect prevValue
- _, err = c.CompareAndDelete("foo", "xxx", 0)
- if err == nil {
- t.Fatalf("CompareAndDelete 2 should have failed. The response is: %#v", resp)
- }
-
- // This should succeed because it gives an correct prevIndex
- resp, err = c.CompareAndDelete("foo", "", resp.Node.ModifiedIndex)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp)
- }
-
- c.Set("foo", "bar", 5)
- // This should fail because it gives an incorrect prevIndex
- resp, err = c.CompareAndDelete("foo", "", 29817514)
- if err == nil {
- t.Fatalf("CompareAndDelete 4 should have failed. The response is: %#v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_swap_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_swap_test.go
deleted file mode 100644
index 14a1b00f5..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/compare_and_swap_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestCompareAndSwap(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- // This should succeed
- resp, err := c.CompareAndSwap("foo", "bar2", 5, "bar", 0)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("CompareAndSwap 1 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 1 prevNode failed: %#v", resp)
- }
-
- // This should fail because it gives an incorrect prevValue
- resp, err = c.CompareAndSwap("foo", "bar3", 5, "xxx", 0)
- if err == nil {
- t.Fatalf("CompareAndSwap 2 should have failed. The response is: %#v", resp)
- }
-
- resp, err = c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed
- resp, err = c.CompareAndSwap("foo", "bar2", 5, "", resp.Node.ModifiedIndex)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp)
- }
-
- // This should fail because it gives an incorrect prevIndex
- resp, err = c.CompareAndSwap("foo", "bar3", 5, "", 29817514)
- if err == nil {
- t.Fatalf("CompareAndSwap 4 should have failed. The response is: %#v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/debug_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/debug_test.go
deleted file mode 100644
index 97f6d1110..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/debug_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-type Foo struct{}
-type Bar struct {
- one string
- two int
-}
-
-// Tests that logs don't panic with arbitrary interfaces
-func TestDebug(t *testing.T) {
- f := &Foo{}
- b := &Bar{"asfd", 3}
- for _, test := range []interface{}{
- 1234,
- "asdf",
- f,
- b,
- } {
- logger.Debug(test)
- logger.Debugf("something, %s", test)
- logger.Warning(test)
- logger.Warningf("something, %s", test)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/delete_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/delete_test.go
deleted file mode 100644
index 590497155..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/delete_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestDelete(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
- resp, err := c.Delete("foo", false)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("Delete failed with %s", resp.Node.Value)
- }
-
- if !(resp.PrevNode.Value == "bar") {
- t.Fatalf("Delete PrevNode failed with %s", resp.Node.Value)
- }
-
- resp, err = c.Delete("foo", false)
- if err == nil {
- t.Fatalf("Delete should have failed because the key foo did not exist. "+
- "The response was: %v", resp)
- }
-}
-
-func TestDeleteAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("fooDir", true)
- }()
-
- c.SetDir("foo", 5)
- // test delete an empty dir
- resp, err := c.DeleteDir("foo")
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("DeleteAll 1 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") {
- t.Fatalf("DeleteAll 1 PrevNode failed: %#v", resp)
- }
-
- c.CreateDir("fooDir", 5)
- c.Set("fooDir/foo", "bar", 5)
- _, err = c.DeleteDir("fooDir")
- if err == nil {
- t.Fatal("should not able to delete a non-empty dir with deletedir")
- }
-
- resp, err = c.Delete("fooDir", true)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("DeleteAll 2 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") {
- t.Fatalf("DeleteAll 2 PrevNode failed: %#v", resp)
- }
-
- resp, err = c.Delete("foo", true)
- if err == nil {
- t.Fatalf("DeleteAll should have failed because the key foo did not exist. "+
- "The response was: %v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/get_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/get_test.go
deleted file mode 100644
index 279c4e26f..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/get_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package etcd
-
-import (
- "reflect"
- "testing"
-)
-
-// cleanNode scrubs Expiration, ModifiedIndex and CreatedIndex of a node.
-func cleanNode(n *Node) {
- n.Expiration = nil
- n.ModifiedIndex = 0
- n.CreatedIndex = 0
-}
-
-// cleanResult scrubs a result object two levels deep of Expiration,
-// ModifiedIndex and CreatedIndex.
-func cleanResult(result *Response) {
- // TODO(philips): make this recursive.
- cleanNode(result.Node)
- for i, _ := range result.Node.Nodes {
- cleanNode(result.Node.Nodes[i])
- for j, _ := range result.Node.Nodes[i].Nodes {
- cleanNode(result.Node.Nodes[i].Nodes[j])
- }
- }
-}
-
-func TestGet(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- result, err := c.Get("foo", false, false)
-
- if err != nil {
- t.Fatal(err)
- }
-
- if result.Node.Key != "/foo" || result.Node.Value != "bar" {
- t.Fatalf("Get failed with %s %s %v", result.Node.Key, result.Node.Value, result.Node.TTL)
- }
-
- result, err = c.Get("goo", false, false)
- if err == nil {
- t.Fatalf("should not be able to get non-exist key")
- }
-}
-
-func TestGetAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
- c.Set("fooDir/k0", "v0", 5)
- c.Set("fooDir/k1", "v1", 5)
-
- // Return kv-pairs in sorted order
- result, err := c.Get("fooDir", true, false)
-
- if err != nil {
- t.Fatal(err)
- }
-
- expected := Nodes{
- &Node{
- Key: "/fooDir/k0",
- Value: "v0",
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k1",
- Value: "v1",
- TTL: 5,
- },
- }
-
- cleanResult(result)
-
- if !reflect.DeepEqual(result.Node.Nodes, expected) {
- t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected)
- }
-
- // Test the `recursive` option
- c.CreateDir("fooDir/childDir", 5)
- c.Set("fooDir/childDir/k2", "v2", 5)
-
- // Return kv-pairs in sorted order
- result, err = c.Get("fooDir", true, true)
-
- cleanResult(result)
-
- if err != nil {
- t.Fatal(err)
- }
-
- expected = Nodes{
- &Node{
- Key: "/fooDir/childDir",
- Dir: true,
- Nodes: Nodes{
- &Node{
- Key: "/fooDir/childDir/k2",
- Value: "v2",
- TTL: 5,
- },
- },
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k0",
- Value: "v0",
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k1",
- Value: "v1",
- TTL: 5,
- },
- }
-
- cleanResult(result)
-
- if !reflect.DeepEqual(result.Node.Nodes, expected) {
- t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/requests_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/requests_test.go
deleted file mode 100644
index 7a2bd190a..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/requests_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package etcd
-
-import "testing"
-
-func TestKeyToPath(t *testing.T) {
- tests := []struct {
- key string
- wpath string
- }{
- {"", "keys/"},
- {"foo", "keys/foo"},
- {"foo/bar", "keys/foo/bar"},
- {"%z", "keys/%25z"},
- {"/", "keys/"},
- }
- for i, tt := range tests {
- path := keyToPath(tt.key)
- if path != tt.wpath {
- t.Errorf("#%d: path = %s, want %s", i, path, tt.wpath)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_curl_chan_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_curl_chan_test.go
deleted file mode 100644
index 87c86b830..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_curl_chan_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package etcd
-
-import (
- "fmt"
- "testing"
-)
-
-func TestSetCurlChan(t *testing.T) {
- c := NewClient(nil)
- c.OpenCURL()
-
- defer func() {
- c.Delete("foo", true)
- }()
-
- _, err := c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- expected := fmt.Sprintf("curl -X PUT %s/v2/keys/foo -d value=bar -d ttl=5",
- c.cluster.pick())
- actual := c.RecvCURL()
- if expected != actual {
- t.Fatalf(`Command "%s" is not equal to expected value "%s"`,
- actual, expected)
- }
-
- c.SetConsistency(STRONG_CONSISTENCY)
- _, err = c.Get("foo", false, false)
- if err != nil {
- t.Fatal(err)
- }
-
- expected = fmt.Sprintf("curl -X GET %s/v2/keys/foo?quorum=true&recursive=false&sorted=false",
- c.cluster.pick())
- actual = c.RecvCURL()
- if expected != actual {
- t.Fatalf(`Command "%s" is not equal to expected value "%s"`,
- actual, expected)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_update_create_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_update_create_test.go
deleted file mode 100644
index ced0f06e7..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/set_update_create_test.go
+++ /dev/null
@@ -1,241 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestSet(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- resp, err := c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
- if resp.Node.Key != "/foo" || resp.Node.Value != "bar" || resp.Node.TTL != 5 {
- t.Fatalf("Set 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("Set 1 PrevNode failed: %#v", resp)
- }
-
- resp, err = c.Set("foo", "bar2", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/foo" && resp.Node.Value == "bar2" && resp.Node.TTL == 5) {
- t.Fatalf("Set 2 failed: %#v", resp)
- }
- if resp.PrevNode.Key != "/foo" || resp.PrevNode.Value != "bar" || resp.Node.TTL != 5 {
- t.Fatalf("Set 2 PrevNode failed: %#v", resp)
- }
-}
-
-func TestUpdate(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("nonexistent", true)
- }()
-
- resp, err := c.Set("foo", "bar", 5)
-
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed.
- resp, err = c.Update("foo", "wakawaka", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "update" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("Update 1 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.Node.TTL == 5) {
- t.Fatalf("Update 1 prevValue failed: %#v", resp)
- }
-
- // This should fail because the key does not exist.
- resp, err = c.Update("nonexistent", "whatever", 5)
- if err == nil {
- t.Fatalf("The key %v did not exist, so the update should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreate(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("newKey", true)
- }()
-
- newKey := "/newKey"
- newValue := "/newValue"
-
- // This should succeed
- resp, err := c.Create(newKey, newValue, 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Key == newKey &&
- resp.Node.Value == newValue && resp.Node.TTL == 5) {
- t.Fatalf("Create 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("Create 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail, because the key is already there
- resp, err = c.Create(newKey, newValue, 5)
- if err == nil {
- t.Fatalf("The key %v did exist, so the creation should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreateInOrder(t *testing.T) {
- c := NewClient(nil)
- dir := "/queue"
- defer func() {
- c.DeleteDir(dir)
- }()
-
- var firstKey, secondKey string
-
- resp, err := c.CreateInOrder(dir, "1", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Value == "1" && resp.Node.TTL == 5) {
- t.Fatalf("Create 1 failed: %#v", resp)
- }
-
- firstKey = resp.Node.Key
-
- resp, err = c.CreateInOrder(dir, "2", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Value == "2" && resp.Node.TTL == 5) {
- t.Fatalf("Create 2 failed: %#v", resp)
- }
-
- secondKey = resp.Node.Key
-
- if firstKey >= secondKey {
- t.Fatalf("Expected first key to be greater than second key, but %s is not greater than %s",
- firstKey, secondKey)
- }
-}
-
-func TestSetDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("fooDir", true)
- }()
-
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/fooDir" && resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("SetDir 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("SetDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail because /fooDir already points to a directory
- resp, err = c.CreateDir("/fooDir", 5)
- if err == nil {
- t.Fatalf("fooDir already points to a directory, so SetDir should have failed."+
- "The response was: %#v", resp)
- }
-
- _, err = c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed
- // It should replace the key
- resp, err = c.SetDir("foo", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/foo" && resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("SetDir 2 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.PrevNode.TTL == 5) {
- t.Fatalf("SetDir 2 failed: %#v", resp)
- }
-}
-
-func TestUpdateDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed.
- resp, err = c.UpdateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "update" && resp.Node.Key == "/fooDir" &&
- resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("UpdateDir 1 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/fooDir" && resp.PrevNode.Dir == true && resp.PrevNode.TTL == 5) {
- t.Fatalf("UpdateDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail because the key does not exist.
- resp, err = c.UpdateDir("nonexistentDir", 5)
- if err == nil {
- t.Fatalf("The key %v did not exist, so the update should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreateDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- // This should succeed
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Key == "/fooDir" &&
- resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("CreateDir 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("CreateDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail, because the key is already there
- resp, err = c.CreateDir("fooDir", 5)
- if err == nil {
- t.Fatalf("The key %v did exist, so the creation should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/watch_test.go b/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/watch_test.go
deleted file mode 100644
index 43e1dfeb8..000000000
--- a/Godeps/_workspace/src/github.com/contiv/go-etcd/etcd/watch_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package etcd
-
-import (
- "fmt"
- "runtime"
- "testing"
- "time"
-)
-
-func TestWatch(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("watch_foo", true)
- }()
-
- go setHelper("watch_foo", "bar", c)
-
- resp, err := c.Watch("watch_foo", 0, false, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") {
- t.Fatalf("Watch 1 failed: %#v", resp)
- }
-
- go setHelper("watch_foo", "bar", c)
-
- resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, false, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") {
- t.Fatalf("Watch 2 failed: %#v", resp)
- }
-
- routineNum := runtime.NumGoroutine()
-
- ch := make(chan *Response, 10)
- stop := make(chan bool, 1)
-
- go setLoop("watch_foo", "bar", c)
-
- go receiver(ch, stop)
-
- _, err = c.Watch("watch_foo", 0, false, ch, stop)
- if err != ErrWatchStoppedByUser {
- t.Fatalf("Watch returned a non-user stop error")
- }
-
- if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum {
- t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum)
- }
-}
-
-func TestWatchAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("watch_foo", true)
- }()
-
- go setHelper("watch_foo/foo", "bar", c)
-
- resp, err := c.Watch("watch_foo", 0, true, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") {
- t.Fatalf("WatchAll 1 failed: %#v", resp)
- }
-
- go setHelper("watch_foo/foo", "bar", c)
-
- resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, true, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") {
- t.Fatalf("WatchAll 2 failed: %#v", resp)
- }
-
- ch := make(chan *Response, 10)
- stop := make(chan bool, 1)
-
- routineNum := runtime.NumGoroutine()
-
- go setLoop("watch_foo/foo", "bar", c)
-
- go receiver(ch, stop)
-
- _, err = c.Watch("watch_foo", 0, true, ch, stop)
- if err != ErrWatchStoppedByUser {
- t.Fatalf("Watch returned a non-user stop error")
- }
-
- if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum {
- t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum)
- }
-}
-
-func setHelper(key, value string, c *Client) {
- time.Sleep(time.Second)
- c.Set(key, value, 100)
-}
-
-func setLoop(key, value string, c *Client) {
- time.Sleep(time.Second)
- for i := 0; i < 10; i++ {
- newValue := fmt.Sprintf("%s_%v", value, i)
- c.Set(key, newValue, 100)
- time.Sleep(time.Second / 10)
- }
-}
-
-func receiver(c chan *Response, stop chan bool) {
- for i := 0; i < 10; i++ {
- <-c
- }
- stop <- true
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Godeps.json b/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Godeps.json
deleted file mode 100644
index d8081f6d8..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Godeps.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "ImportPath": "github.com/socketplane/libovsdb",
- "GoVersion": "go1.3.3",
- "Packages": [
- "./..."
- ],
- "Deps": [
- {
- "ImportPath": "github.com/cenkalti/hub",
- "Comment": "v1.0.0-12-g7be60e1",
- "Rev": "7be60e186e66cd86db2d50ef2ca3778e281c87b4"
- },
- {
- "ImportPath": "github.com/cenkalti/rpc2",
- "Rev": "44d0d95e4f529a0fe230c90d2126bd597c61148c"
- }
- ]
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Readme b/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Readme
deleted file mode 100644
index 4cdaa53d5..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/example/play_with_ovs.go b/Godeps/_workspace/src/github.com/contiv/libovsdb/example/play_with_ovs.go
deleted file mode 100644
index 9c2bf142a..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/example/play_with_ovs.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
- "reflect"
-
- "github.com/socketplane/libovsdb"
-)
-
-// Silly game that detects creation of Bridge named "stop" and exits
-// Just a demonstration of how an app can use libovsdb library to configure and manage OVS
-
-var quit chan bool
-var update chan *libovsdb.TableUpdates
-var cache map[string]map[string]libovsdb.Row
-
-func play(ovs *libovsdb.OvsdbClient) {
- go processInput(ovs)
- for {
- select {
- case currUpdate := <-update:
- for table, tableUpdate := range currUpdate.Updates {
- if table == "Bridge" {
- for uuid, row := range tableUpdate.Rows {
- newRow := row.New
- if _, ok := newRow.Fields["name"]; ok {
- name := newRow.Fields["name"].(string)
- if name == "stop" {
- fmt.Println("Bridge stop detected : ", uuid)
- quit <- true
- }
- }
- }
- }
- }
- }
- }
-
-}
-
-func createBridge(ovs *libovsdb.OvsdbClient, bridgeName string) {
- namedUuid := "gopher"
- // bridge row to insert
- bridge := make(map[string]interface{})
- bridge["name"] = bridgeName
-
- // simple insert operation
- insertOp := libovsdb.Operation{
- Op: "insert",
- Table: "Bridge",
- Row: bridge,
- UUIDName: namedUuid,
- }
-
- // Inserting a Bridge row in Bridge table requires mutating the open_vswitch table.
- mutateUuid := []libovsdb.UUID{libovsdb.UUID{namedUuid}}
- mutateSet, _ := libovsdb.NewOvsSet(mutateUuid)
- mutation := libovsdb.NewMutation("bridges", "insert", mutateSet)
- condition := libovsdb.NewCondition("_uuid", "==", libovsdb.UUID{getRootUuid()})
-
- // simple mutate operation
- mutateOp := libovsdb.Operation{
- Op: "mutate",
- Table: "Open_vSwitch",
- Mutations: []interface{}{mutation},
- Where: []interface{}{condition},
- }
-
- operations := []libovsdb.Operation{insertOp, mutateOp}
- reply, _ := ovs.Transact("Open_vSwitch", operations...)
-
- if len(reply) < len(operations) {
- fmt.Println("Number of Replies should be atleast equal to number of Operations")
- }
- ok := true
- for i, o := range reply {
- if o.Error != "" && i < len(operations) {
- fmt.Println("Transaction Failed due to an error :", o.Error, " details:", o.Details, " in ", operations[i])
- ok = false
- } else if o.Error != "" {
- fmt.Println("Transaction Failed due to an error :", o.Error)
- ok = false
- }
- }
- if ok {
- fmt.Println("Bridge Addition Successful : ", reply[0].UUID.GoUuid)
- }
-}
-
-func processInput(ovs *libovsdb.OvsdbClient) {
- for {
- fmt.Printf("\n Enter a Bridge Name : ")
- var bridgeName string
- fmt.Scanf("%s", &bridgeName)
- createBridge(ovs, bridgeName)
- }
-}
-
-func getRootUuid() string {
- for uuid, _ := range cache["Open_vSwitch"] {
- return uuid
- }
- return ""
-}
-
-func populateCache(updates libovsdb.TableUpdates) {
- for table, tableUpdate := range updates.Updates {
- if _, ok := cache[table]; !ok {
- cache[table] = make(map[string]libovsdb.Row)
-
- }
- for uuid, row := range tableUpdate.Rows {
- empty := libovsdb.Row{}
- if !reflect.DeepEqual(row.New, empty) {
- cache[table][uuid] = row.New
- } else {
- delete(cache[table], uuid)
- }
- }
- }
-}
-
-func main() {
- quit = make(chan bool)
- update = make(chan *libovsdb.TableUpdates)
- cache = make(map[string]map[string]libovsdb.Row)
-
- // By default libovsdb connects to 127.0.0.0:6400.
- ovs, err := libovsdb.Connect("", 0)
-
- // If you prefer to connect to OVS in a specific location :
- // ovs, err := libovsdb.Connect("192.168.56.101", 6640)
-
- // If you prefer to connect over a Unix socket:
- // ovs, err := libovsdb.ConnectUnix("")
-
- if err != nil {
- fmt.Println("Unable to Connect ", err)
- os.Exit(1)
- }
- var notifier Notifier
- ovs.Register(notifier)
-
- initial, _ := ovs.MonitorAll("Open_vSwitch", "")
- populateCache(*initial)
-
- fmt.Println(`Silly game of stopping this app when a Bridge with name "stop" is monitored !`)
- go play(ovs)
- <-quit
-}
-
-type Notifier struct {
-}
-
-func (n Notifier) Update(context interface{}, tableUpdates libovsdb.TableUpdates) {
- populateCache(tableUpdates)
- update <- &tableUpdates
-}
-func (n Notifier) Locked([]interface{}) {
-}
-func (n Notifier) Stolen([]interface{}) {
-}
-func (n Notifier) Echo([]interface{}) {
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/notation_test.go b/Godeps/_workspace/src/github.com/contiv/libovsdb/notation_test.go
deleted file mode 100644
index 7907008ea..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/notation_test.go
+++ /dev/null
@@ -1,175 +0,0 @@
-package libovsdb
-
-import (
- "encoding/json"
- "log"
- "testing"
-)
-
-func TestOpRowSerialization(t *testing.T) {
- operation := Operation{
- Op: "insert",
- Table: "Bridge",
- }
-
- operation.Row = make(map[string]interface{})
- operation.Row["name"] = "docker-ovs"
-
- str, err := json.Marshal(operation)
-
- if err != nil {
- log.Fatal("serialization error:", err)
- }
-
- expected := `{"op":"insert","table":"Bridge","row":{"name":"docker-ovs"}}`
-
- if string(str) != expected {
- t.Error("Expected: ", expected, "Got", string(str))
- }
-}
-
-func TestOpRowsSerialization(t *testing.T) {
- operation := Operation{
- Op: "insert",
- Table: "Interface",
- }
-
- iface1 := make(map[string]interface{})
- iface1["name"] = "test-iface1"
- iface1["mac"] = "0000ffaaaa"
- iface1["ofport"] = 1
-
- iface2 := make(map[string]interface{})
- iface2["name"] = "test-iface2"
- iface2["mac"] = "0000ffaabb"
- iface2["ofport"] = 2
-
- operation.Rows = []map[string]interface{}{iface1, iface2}
-
- str, err := json.Marshal(operation)
-
- if err != nil {
- log.Fatal("serialization error:", err)
- }
-
- expected := `{"op":"insert","table":"Interface","rows":[{"mac":"0000ffaaaa","name":"test-iface1","ofport":1},{"mac":"0000ffaabb","name":"test-iface2","ofport":2}]}`
-
- if string(str) != expected {
- t.Error("Expected: ", expected, "Got", string(str))
- }
-}
-
-func TestValidateOvsSet(t *testing.T) {
- goSlice := []int{1, 2, 3, 4}
- oSet, err := NewOvsSet(goSlice)
- if err != nil {
- t.Error("Error creating OvsSet ", err)
- }
- data, err := json.Marshal(oSet)
- if err != nil {
- t.Error("Error Marshalling OvsSet", err)
- }
- expected := `["set",[1,2,3,4]]`
- if string(data) != expected {
- t.Error("Expected: ", expected, "Got", string(data))
- }
- // Negative condition test
- integer := 5
- oSet, err = NewOvsSet(integer)
- if err == nil {
- t.Error("OvsSet must fail for anything other than Slices")
- t.Error("Expected: ", expected, "Got", string(data))
- }
-}
-
-func TestValidateOvsMap(t *testing.T) {
- myMap := make(map[int]string)
- myMap[1] = "hello"
- myMap[2] = "world"
- oMap, err := NewOvsMap(myMap)
- if err != nil {
- t.Error("Error creating OvsMap ", err)
- }
- data, err := json.Marshal(oMap)
- if err != nil {
- t.Error("Error Marshalling OvsMap", err)
- }
- expected1 := `["map",[[1,"hello"],[2,"world"]]]`
- expected2 := `["map",[[2,"world"],[1,"hello"]]]`
- if string(data) != expected1 && string(data) != expected2 {
- t.Error("Expected: ", expected1, "Got", string(data))
- }
- // Negative condition test
- integer := 5
- oMap, err = NewOvsMap(integer)
- if err == nil {
- t.Error("OvsMap must fail for anything other than Maps")
- }
-}
-
-func TestValidateUuid(t *testing.T) {
- uuid1 := UUID{"this is a bad uuid"} // Bad
- uuid2 := UUID{"alsoabaduuid"} // Bad
- uuid3 := UUID{"550e8400-e29b-41d4-a716-446655440000"} // Good
- uuid4 := UUID{"thishoul-dnot-pass-vali-dationchecks"} // Bad
-
- err := uuid1.validateUUID()
-
- if err == nil {
- t.Error(uuid1, " is not a valid UUID")
- }
-
- err = uuid2.validateUUID()
-
- if err == nil {
- t.Error(uuid2, " is not a valid UUID")
- }
-
- err = uuid3.validateUUID()
-
- if err != nil {
- t.Error(uuid3, " is a valid UUID")
- }
-
- err = uuid4.validateUUID()
-
- if err == nil {
- t.Error(uuid4, " is not a valid UUID")
- }
-}
-
-func TestNewUUID(t *testing.T) {
- uuid := UUID{"550e8400-e29b-41d4-a716-446655440000"}
- uuidStr, _ := json.Marshal(uuid)
- expected := `["uuid","550e8400-e29b-41d4-a716-446655440000"]`
- if string(uuidStr) != expected {
- t.Error("uuid is not correctly formatted")
- }
-}
-
-func TestNewNamedUUID(t *testing.T) {
- uuid := UUID{"test-uuid"}
- uuidStr, _ := json.Marshal(uuid)
- expected := `["named-uuid","test-uuid"]`
- if string(uuidStr) != expected {
- t.Error("uuid is not correctly formatted")
- }
-}
-
-func TestNewCondition(t *testing.T) {
- cond := NewCondition("uuid", "==", "550e8400-e29b-41d4-a716-446655440000")
- condStr, _ := json.Marshal(cond)
- expected := `["uuid","==","550e8400-e29b-41d4-a716-446655440000"]`
- if string(condStr) != expected {
- t.Error("condition is not correctly formatted")
- }
-}
-
-func TestNewMutation(t *testing.T) {
- mutation := NewMutation("column", "+=", 1)
- mutationStr, _ := json.Marshal(mutation)
- expected := `["column","+=",1]`
- if string(mutationStr) != expected {
- t.Error("mutation is not correctly formatted")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/ovs_integration_test.go b/Godeps/_workspace/src/github.com/contiv/libovsdb/ovs_integration_test.go
deleted file mode 100644
index 54b3cad79..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/ovs_integration_test.go
+++ /dev/null
@@ -1,501 +0,0 @@
-package libovsdb
-
-import (
- "bytes"
- "fmt"
- "log"
- "net"
- "os"
- "testing"
- "time"
-)
-
-func TestConnectUnix(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
-
- f, err := os.Open(DEFAULT_SOCK)
- if err != nil {
- t.Skip("Missing OVSDB unix socket")
- }
- f.Close()
-
- timeoutChan := make(chan bool)
- connected := make(chan bool)
- go func() {
- time.Sleep(10 * time.Second)
- timeoutChan <- true
- }()
-
- go func() {
- ovs, err := ConnectUnix("")
- if err != nil {
- connected <- false
- } else {
- connected <- true
- ovs.Disconnect()
- }
- }()
-
- select {
- case <-timeoutChan:
- t.Error("Connection Timed Out")
- case b := <-connected:
- if !b {
- t.Error("Couldnt connect to OVSDB Server")
- }
- }
-}
-
-func TestConnect(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
-
- c, err := net.Dial("tcp", os.Getenv("DOCKER_IP")+":6640")
- if err != nil {
- t.Skip("No OVSDB connection over TCP")
- }
- c.Close()
-
- timeoutChan := make(chan bool)
- connected := make(chan bool)
- go func() {
- time.Sleep(10 * time.Second)
- timeoutChan <- true
- }()
-
- go func() {
- // Use Convenience params. Ignore failure even if any
- _, err := Connect("", 0)
- if err != nil {
- log.Println("Couldnt establish OVSDB connection with Default params. No big deal")
- }
- }()
-
- go func() {
- ovs, err := Connect(os.Getenv("DOCKER_IP"), int(6640))
- if err != nil {
- connected <- false
- } else {
- connected <- true
- ovs.Disconnect()
- }
- }()
-
- select {
- case <-timeoutChan:
- t.Error("Connection Timed Out")
- case b := <-connected:
- if !b {
- t.Error("Couldnt connect to OVSDB Server")
- }
- }
-}
-
-func getOvsClient() (*OvsdbClient, error) {
- ovs, err := Connect(os.Getenv("DOCKER_IP"), int(6640))
- if err != nil {
- ovs, err = ConnectUnix("")
- if err != nil {
- panic(err)
- }
- }
-
- return ovs, err
-}
-
-func TestListDbs(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- reply, err := ovs.ListDbs()
-
- if err != nil {
- log.Fatal("ListDbs error:", err)
- }
-
- if reply[0] != "Open_vSwitch" {
- t.Error("Expected: 'Open_vSwitch', Got:", reply)
- }
- var b bytes.Buffer
- ovs.Schema[reply[0]].Print(&b)
- ovs.Disconnect()
-}
-
-func TestGetSchemas(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- if err != nil {
- panic(err)
- }
-
- var dbName string = "Open_vSwitch"
- reply, err := ovs.GetSchema(dbName)
-
- if err != nil {
- log.Fatal("GetSchemas error:", err)
- t.Error("Error Processing GetSchema for ", dbName, err)
- }
-
- if reply.Name != dbName {
- t.Error("Schema Name mismatch. Expected: ", dbName, "Got: ", reply.Name)
- }
- ovs.Disconnect()
-}
-
-var bridgeName string = "gopher-br7"
-var bridgeUuid string
-
-func TestInsertTransact(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- if err != nil {
- log.Fatal("Failed to Connect. error:", err)
- panic(err)
- }
-
- // NamedUuid is used to add multiple related Operations in a single Transact operation
- namedUuid := "gopher"
-
- externalIds := make(map[string]string)
- externalIds["go"] = "awesome"
- externalIds["docker"] = "made-for-each-other"
- oMap, err := NewOvsMap(externalIds)
- // bridge row to insert
- bridge := make(map[string]interface{})
- bridge["name"] = bridgeName
- bridge["external_ids"] = oMap
-
- // simple insert operation
- insertOp := Operation{
- Op: "insert",
- Table: "Bridge",
- Row: bridge,
- UUIDName: namedUuid,
- }
-
- // Inserting a Bridge row in Bridge table requires mutating the open_vswitch table.
- mutateUuid := []UUID{UUID{namedUuid}}
- mutateSet, _ := NewOvsSet(mutateUuid)
- mutation := NewMutation("bridges", "insert", mutateSet)
- // hacked Condition till we get Monitor / Select working
- condition := NewCondition("_uuid", "!=", UUID{"2f77b348-9768-4866-b761-89d5177ecdab"})
-
- // simple mutate operation
- mutateOp := Operation{
- Op: "mutate",
- Table: "Open_vSwitch",
- Mutations: []interface{}{mutation},
- Where: []interface{}{condition},
- }
-
- operations := []Operation{insertOp, mutateOp}
- reply, err := ovs.Transact("Open_vSwitch", operations...)
-
- if len(reply) < len(operations) {
- t.Error("Number of Replies should be atleast equal to number of Operations")
- }
- ok := true
- for i, o := range reply {
- if o.Error != "" && i < len(operations) {
- t.Error("Transaction Failed due to an error :", o.Error, " details:", o.Details, " in ", operations[i])
- ok = false
- } else if o.Error != "" {
- t.Error("Transaction Failed due to an error :", o.Error)
- ok = false
- }
- }
- if ok {
- fmt.Println("Bridge Addition Successful : ", reply[0].UUID.GoUuid)
- bridgeUuid = reply[0].UUID.GoUuid
- }
- ovs.Disconnect()
-}
-
-func TestDeleteTransact(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- if bridgeUuid == "" {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- if err != nil {
- log.Fatal("Failed to Connect. error:", err)
- panic(err)
- }
-
- // simple delete operation
- condition := NewCondition("name", "==", bridgeName)
- deleteOp := Operation{
- Op: "delete",
- Table: "Bridge",
- Where: []interface{}{condition},
- }
-
- // Deleting a Bridge row in Bridge table requires mutating the open_vswitch table.
- mutateUuid := []UUID{UUID{bridgeUuid}}
- mutateSet, _ := NewOvsSet(mutateUuid)
- mutation := NewMutation("bridges", "delete", mutateSet)
- // hacked Condition till we get Monitor / Select working
- condition = NewCondition("_uuid", "!=", UUID{"2f77b348-9768-4866-b761-89d5177ecdab"})
-
- // simple mutate operation
- mutateOp := Operation{
- Op: "mutate",
- Table: "Open_vSwitch",
- Mutations: []interface{}{mutation},
- Where: []interface{}{condition},
- }
-
- operations := []Operation{deleteOp, mutateOp}
- reply, err := ovs.Transact("Open_vSwitch", operations...)
-
- if len(reply) < len(operations) {
- t.Error("Number of Replies should be atleast equal to number of Operations")
- }
- ok := true
- for i, o := range reply {
- if o.Error != "" && i < len(operations) {
- t.Error("Transaction Failed due to an error :", o.Error, " in ", operations[i])
- ok = false
- } else if o.Error != "" {
- t.Error("Transaction Failed due to an error :", o.Error)
- ok = false
- }
- }
- if ok {
- fmt.Println("Bridge Delete Successful", reply[0].Count)
- }
- ovs.Disconnect()
-}
-
-func TestMonitor(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- if err != nil {
- log.Fatal("Failed to Connect. error:", err)
- panic(err)
- }
-
- reply, err := ovs.MonitorAll("Open_vSwitch", nil)
-
- if reply == nil || err != nil {
- t.Error("Monitor operation failed with reply=", reply, " and error=", err)
- }
- ovs.Disconnect()
-}
-
-func TestNotify(t *testing.T) {
- if testing.Short() {
- t.Skip()
- }
-
- ovs, err := getOvsClient()
- if err != nil {
- log.Fatal("Failed to Connect. error:", err)
- panic(err)
- }
-
- notifyEchoChan := make(chan bool)
-
- notifier := Notifier{notifyEchoChan}
- ovs.Register(notifier)
-
- timeoutChan := make(chan bool)
- go func() {
- time.Sleep(10 * time.Second)
- timeoutChan <- true
- }()
-
- select {
- case <-timeoutChan:
- t.Error("No Echo message notify in 10 seconds")
- case <-notifyEchoChan:
- break
- }
- ovs.Disconnect()
-}
-
-type Notifier struct {
- echoChan chan bool
-}
-
-func (n Notifier) Update(context interface{}, tableUpdates TableUpdates) {
-}
-func (n Notifier) Locked([]interface{}) {
-}
-func (n Notifier) Stolen([]interface{}) {
-}
-func (n Notifier) Echo([]interface{}) {
- n.echoChan <- true
-}
-
-func TestDBSchemaValidation(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, e := getOvsClient()
- if e != nil {
- log.Fatal("Failed to Connect. error:", e)
- panic(e)
- }
-
- bridge := make(map[string]interface{})
- bridge["name"] = "docker-ovs"
-
- operation := Operation{
- Op: "insert",
- Table: "Bridge",
- Row: bridge,
- }
-
- _, err := ovs.Transact("Invalid_DB", operation)
- if err == nil {
- t.Error("Invalid DB operation Validation failed")
- }
-
- ovs.Disconnect()
-}
-
-func TestTableSchemaValidation(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, e := getOvsClient()
- if e != nil {
- log.Fatal("Failed to Connect. error:", e)
- panic(e)
- }
-
- bridge := make(map[string]interface{})
- bridge["name"] = "docker-ovs"
-
- operation := Operation{
- Op: "insert",
- Table: "InvalidTable",
- Row: bridge,
- }
- _, err := ovs.Transact("Open_vSwitch", operation)
-
- if err == nil {
- t.Error("Invalid Table Name Validation failed")
- }
-
- ovs.Disconnect()
-}
-
-func TestColumnSchemaInRowValidation(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, e := getOvsClient()
- if e != nil {
- log.Fatal("Failed to Connect. error:", e)
- panic(e)
- }
-
- bridge := make(map[string]interface{})
- bridge["name"] = "docker-ovs"
- bridge["invalid_column"] = "invalid_column"
-
- operation := Operation{
- Op: "insert",
- Table: "Bridge",
- Row: bridge,
- }
-
- _, err := ovs.Transact("Open_vSwitch", operation)
-
- if err == nil {
- t.Error("Invalid Column Name Validation failed")
- }
-
- ovs.Disconnect()
-}
-
-func TestColumnSchemaInMultipleRowsValidation(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, e := getOvsClient()
- if e != nil {
- log.Fatal("Failed to Connect. error:", e)
- panic(e)
- }
-
- rows := make([]map[string]interface{}, 2)
-
- invalidBridge := make(map[string]interface{})
- invalidBridge["invalid_column"] = "invalid_column"
-
- bridge := make(map[string]interface{})
- bridge["name"] = "docker-ovs"
-
- rows[0] = invalidBridge
- rows[1] = bridge
- operation := Operation{
- Op: "insert",
- Table: "Bridge",
- Rows: rows,
- }
- _, err := ovs.Transact("Open_vSwitch", operation)
-
- if err == nil {
- t.Error("Invalid Column Name Validation failed")
- }
-
- ovs.Disconnect()
-}
-
-func TestColumnSchemaValidation(t *testing.T) {
-
- if testing.Short() {
- t.Skip()
- }
-
- ovs, e := getOvsClient()
- if e != nil {
- log.Fatal("Failed to Connect. error:", e)
- panic(e)
- }
-
- operation := Operation{
- Op: "select",
- Table: "Bridge",
- Columns: []string{"name", "invalidColumn"},
- }
- _, err := ovs.Transact("Open_vSwitch", operation)
-
- if err == nil {
- t.Error("Invalid Column Name Validation failed")
- }
-
- ovs.Disconnect()
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/libovsdb/rpc_test.go b/Godeps/_workspace/src/github.com/contiv/libovsdb/rpc_test.go
deleted file mode 100644
index b2da4a434..000000000
--- a/Godeps/_workspace/src/github.com/contiv/libovsdb/rpc_test.go
+++ /dev/null
@@ -1,129 +0,0 @@
-package libovsdb
-
-import (
- "encoding/json"
- "reflect"
- "testing"
-)
-
-func TestNewGetSchemaArgs(t *testing.T) {
- database := "Open_vSwitch"
- args := NewGetSchemaArgs(database)
- argString, _ := json.Marshal(args)
- expected := `["Open_vSwitch"]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewTransactArgs(t *testing.T) {
- database := "Open_vSwitch"
- operation := Operation{Op: "insert", Table: "Bridge"}
- args := NewTransactArgs(database, operation)
- argString, _ := json.Marshal(args)
- expected := `["Open_vSwitch",{"op":"insert","table":"Bridge"}]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewMultipleTransactArgs(t *testing.T) {
- database := "Open_vSwitch"
- operation1 := Operation{Op: "insert", Table: "Bridge"}
- operation2 := Operation{Op: "delete", Table: "Bridge"}
- args := NewTransactArgs(database, operation1, operation2)
- argString, _ := json.Marshal(args)
- expected := `["Open_vSwitch",{"op":"insert","table":"Bridge"},{"op":"delete","table":"Bridge"}]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewCancelArgs(t *testing.T) {
- id := 1
- args := NewCancelArgs(id)
- argString, _ := json.Marshal(args)
- expected := `[1]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewMonitorArgs(t *testing.T) {
- database := "Open_vSwitch"
- value := 1
- r := MonitorRequest{
- Columns: []string{"name", "ports", "external_ids"},
- Select: MonitorSelect{
- Initial: true,
- Insert: true,
- Delete: true,
- Modify: true,
- },
- }
- requests := make(map[string]MonitorRequest)
- requests["Bridge"] = r
-
- args := NewMonitorArgs(database, value, requests)
- argString, _ := json.Marshal(args)
- expected := `["Open_vSwitch",1,{"Bridge":{"columns":["name","ports","external_ids"],"select":{"initial":true,"insert":true,"delete":true,"modify":true}}}]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewMonitorCancelArgs(t *testing.T) {
- value := 1
- args := NewMonitorCancelArgs(value)
- argString, _ := json.Marshal(args)
- expected := `[1]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestNewLockArgs(t *testing.T) {
- id := "testId"
- args := NewLockArgs(id)
- argString, _ := json.Marshal(args)
- expected := `["testId"]`
- if string(argString) != expected {
- t.Error("Expected: ", expected, " Got: ", string(argString))
- }
-}
-
-func TestEcho(t *testing.T) {
- req := []interface{}{"hi"}
- var reply []interface{}
- echo(nil, req, &reply)
- if !reflect.DeepEqual(req, reply) {
- t.Error("Expected: ", req, " Got: ", reply)
- }
-}
-
-func TestUpdate(t *testing.T) {
- var reply interface{}
-
- // Update notification should fail for arrays of size < 2
- err := update(nil, []interface{}{"hello"}, &reply)
- if err == nil {
- t.Error("Expected: error for a dummy request")
- }
-
- // Update notification should fail if arg[1] is not map[string]map[string]RowUpdate type
- err = update(nil, []interface{}{"hello", "gophers"}, &reply)
- if err == nil {
- t.Error("Expected: error for a dummy request")
- }
-
- // Valid dummy update should pass
- validUpdate := make(map[string]interface{})
- validRowUpdate := make(map[string]RowUpdate)
- validRowUpdate["uuid"] = RowUpdate{}
- validUpdate["table"] = validRowUpdate
-
- err = update(nil, []interface{}{"hello", validUpdate}, &reply)
- if err != nil {
- t.Error(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Godeps.json b/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Godeps.json
deleted file mode 100644
index 2362c0f30..000000000
--- a/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Godeps.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "ImportPath": "github.com/contiv/objdb",
- "GoVersion": "go1.5",
- "Packages": [
- "./..."
- ],
- "Deps": [
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.6.4-12-g467d9d5",
- "Rev": "467d9d55c2d2c17248441a8fc661561161f40d5e"
- },
- {
- "ImportPath": "github.com/contiv/go-etcd/etcd",
- "Comment": "v0.4.6-6-g4734e7a",
- "Rev": "4734e7aca379f0d7fcdf04fbb2101696a4b45ce8"
- },
- {
- "ImportPath": "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes",
- "Comment": "v2.1.0-alpha.0-51-gb24dd8e",
- "Rev": "b24dd8e4e67d7203c5a68cd43de4f6ffcfff5e66"
- },
- {
- "ImportPath": "github.com/coreos/etcd/pkg/types",
- "Comment": "v2.1.0-alpha.0-51-gb24dd8e",
- "Rev": "b24dd8e4e67d7203c5a68cd43de4f6ffcfff5e66"
- },
- {
- "ImportPath": "github.com/coreos/go-systemd/journal",
- "Comment": "v4-40-g2ed5b50",
- "Rev": "2ed5b5012ccde5f057c197890a2c801295941149"
- },
- {
- "ImportPath": "github.com/coreos/pkg/capnslog",
- "Rev": "fa92df939cff437b00010275644a10882beaeca8"
- },
- {
- "ImportPath": "github.com/hashicorp/consul/api",
- "Comment": "v0.6.3-19-gc353aa9",
- "Rev": "c353aa9260b695987d45e4e975be52f60da348ed"
- },
- {
- "ImportPath": "github.com/hashicorp/go-cleanhttp",
- "Rev": "ce617e79981a8fff618bb643d155133a8f38db96"
- },
- {
- "ImportPath": "github.com/hashicorp/serf/coordinate",
- "Comment": "v0.7.0-10-g64d10e9",
- "Rev": "64d10e9428bd70dbcd831ad087573b66731c014b"
- },
- {
- "ImportPath": "golang.org/x/sys/unix",
- "Rev": "20457ee8ea8546920d3f4e19e405da45250dc5a5"
- }
- ]
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Readme b/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Readme
deleted file mode 100644
index 4cdaa53d5..000000000
--- a/Godeps/_workspace/src/github.com/contiv/objdb/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Godeps.json b/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Godeps.json
deleted file mode 100644
index 197e8d4a4..000000000
--- a/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Godeps.json
+++ /dev/null
@@ -1,130 +0,0 @@
-{
- "ImportPath": "github.com/contiv/ofnet",
- "GoVersion": "go1.5",
- "GodepVersion": "v61",
- "Packages": [
- "./..."
- ],
- "Deps": [
- {
- "ImportPath": "github.com/BurntSushi/toml",
- "Comment": "v0.1.0-21-g056c9bc",
- "Rev": "056c9bc7be7190eaa7715723883caffa5f8fa3e4"
- },
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.8.7-55-gf7f79f7",
- "Rev": "f7f79f729e0fbe2fcc061db48a9ba0263f588252"
- },
- {
- "ImportPath": "github.com/armon/go-radix",
- "Rev": "fbd82e84e2b13651f3abc5ffd26b65ba71bc8f93"
- },
- {
- "ImportPath": "github.com/cenkalti/hub",
- "Comment": "v1.0.0-12-g7be60e1",
- "Rev": "7be60e186e66cd86db2d50ef2ca3778e281c87b4"
- },
- {
- "ImportPath": "github.com/cenkalti/rpc2",
- "Rev": "44d0d95e4f529a0fe230c90d2126bd597c61148c"
- },
- {
- "ImportPath": "github.com/contiv/libovsdb",
- "Comment": "v0.1-7-gbbc744d",
- "Rev": "bbc744d8ddc88c6a997e600b19736055c24d87d5"
- },
- {
- "ImportPath": "github.com/golang/protobuf/proto",
- "Rev": "221834dcb89c96e4b057ed8bb878bfe569dfacf4"
- },
- {
- "ImportPath": "github.com/google/gopacket",
- "Comment": "v1.1.10-132-g7abd91e",
- "Rev": "7abd91e1d374797e8c5b9a85a44bea266a62d7c5"
- },
- {
- "ImportPath": "github.com/jainvipin/bitset",
- "Comment": "v1.0.0-12-g1f0c6de",
- "Rev": "1f0c6de81a62732e75f6c97f1e28e5a009b5df68"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/api",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/config",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/packet",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/server",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/table",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/osrg/gobgp/zebra",
- "Comment": "v1.2",
- "Rev": "e84989706157ffd7b895f42e4057e3f8ca382b3d"
- },
- {
- "ImportPath": "github.com/shaleman/libOpenflow/common",
- "Rev": "b692b84c96349d6f30d0cd2114196ef508847f9a"
- },
- {
- "ImportPath": "github.com/shaleman/libOpenflow/openflow13",
- "Rev": "b692b84c96349d6f30d0cd2114196ef508847f9a"
- },
- {
- "ImportPath": "github.com/shaleman/libOpenflow/protocol",
- "Rev": "b692b84c96349d6f30d0cd2114196ef508847f9a"
- },
- {
- "ImportPath": "github.com/shaleman/libOpenflow/util",
- "Rev": "b692b84c96349d6f30d0cd2114196ef508847f9a"
- },
- {
- "ImportPath": "github.com/vishvananda/netlink",
- "Rev": "4b5dce31de6d42af5bb9811c6d265472199e0fec"
- },
- {
- "ImportPath": "golang.org/x/net/context",
- "Rev": "195180cfebf7362bd243a52477697895128c8777"
- },
- {
- "ImportPath": "golang.org/x/net/http2",
- "Rev": "195180cfebf7362bd243a52477697895128c8777"
- },
- {
- "ImportPath": "golang.org/x/net/internal/timeseries",
- "Rev": "195180cfebf7362bd243a52477697895128c8777"
- },
- {
- "ImportPath": "golang.org/x/net/trace",
- "Rev": "195180cfebf7362bd243a52477697895128c8777"
- },
- {
- "ImportPath": "golang.org/x/sys/unix",
- "Rev": "342d6a85aa15bcd2ec54803cdffe90d52b6f35a7"
- },
- {
- "ImportPath": "google.golang.org/grpc",
- "Rev": "a202995ce9a99c7d65875ba9f0cf04ff43169dd5"
- },
- {
- "ImportPath": "gopkg.in/tomb.v2",
- "Rev": "14b3d72120e8d10ea6e6b7f87f7175734b1faab8"
- }
- ]
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Readme b/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Readme
deleted file mode 100644
index 4cdaa53d5..000000000
--- a/Godeps/_workspace/src/github.com/contiv/ofnet/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Godeps/_workspace/src/github.com/contiv/ofnet/libpkt/libpkt.go b/Godeps/_workspace/src/github.com/contiv/ofnet/libpkt/libpkt.go
deleted file mode 100644
index 5047534c0..000000000
--- a/Godeps/_workspace/src/github.com/contiv/ofnet/libpkt/libpkt.go
+++ /dev/null
@@ -1,386 +0,0 @@
-package libpkt
-
-import (
- "bytes"
- "fmt"
- log "github.com/Sirupsen/logrus"
- "github.com/contiv/ofnet/ovsdbDriver"
- "github.com/google/gopacket"
- "github.com/google/gopacket/layers"
- "github.com/google/gopacket/pcap"
- "net"
- "time"
-)
-
-var (
- snapshot_len int32 = 1024
- err error
- timeout time.Duration = 30 * time.Second
- handle *pcap.Handle
- // Will reuse these for each packet
- ethLayer layers.Ethernet
- ipLayer layers.IPv4
- tcpLayer layers.TCP
- vlanLayer layers.Dot1Q
- options gopacket.SerializeOptions
-)
-
-type Packet struct {
- SrcMAC string // src mac
- DstMAC string // dst mac
- IPv4 *IPv4Layer
- IPv6 *IPv6Layer
- Arp *ArpLayer
-}
-
-type IPv4Layer struct {
- SrcIP string // Src ip address
- DstIP string // dst ip address
- srcPort int // src tcp port
- dstPort int // dst tcp port
- TTL uint8 // ip TTL
- IHL uint8
- TOS uint8
- Length uint16
- Id uint16
- Flags uint8
- FragOffset uint16
- Protocol layers.IPProtocol
- Checksum uint16
- Options []layers.IPv4Option
- Padding []byte
-}
-type IPv6Layer struct {
- SrcIP string // Src ip address
- DstIP string // dst ip address
- srcPort int // src tcp port
- dstPort int // dst tcp port
- TrafficClass uint8
- FlowLabel uint32
- Length uint16
- Protocol uint8
- HopLimit uint8
- NextHeader layers.IPProtocol
-}
-
-type ArpLayer struct {
- AddrType layers.LinkType
- Protocol layers.EthernetType
- HwAddressSize uint8
- ProtAddressSize uint8
- Operation uint16
- SourceHwAddress string
- SourceProtAddress string
- DstHwAddress string
- DstProtAddress string
-}
-
-func compareIP(A net.IP, B net.IP) bool {
-
- return bytes.Equal(A, B)
-}
-func buildIpv4(ipv4Layer *IPv4Layer) (ip *layers.IPv4) {
-
- ip = &layers.IPv4{
- Id: 1,
- TTL: 64,
- IHL: 20,
- SrcIP: net.ParseIP(ipv4Layer.SrcIP),
- DstIP: net.ParseIP(ipv4Layer.DstIP),
- Version: 4,
- Length: 0,
- Protocol: 255,
- Checksum: 0,
- }
- switch {
- case ipv4Layer.Id > 0:
- ip.Id = ipv4Layer.Id
- case ipv4Layer.TTL > 0:
- ip.TTL = ipv4Layer.TTL
- case ipv4Layer.IHL > 0:
- ip.IHL = ipv4Layer.IHL
- }
- return
-}
-
-func buildIpv6(ipv6Layer *IPv6Layer) (ip *layers.IPv6) {
-
- ip = &layers.IPv6{
- SrcIP: net.ParseIP(ipv6Layer.SrcIP),
- DstIP: net.ParseIP(ipv6Layer.DstIP),
- Version: 6,
- Length: 46,
- NextHeader: layers.IPProtocolNoNextHeader,
- HopLimit: 64,
- }
- return
-}
-
-func buildArp(arpLayer *ArpLayer) (arp *layers.ARP) {
-
- SourceHwAddress, _ := net.ParseMAC(arpLayer.SourceHwAddress)
- DstHwAddress, _ := net.ParseMAC(arpLayer.DstHwAddress)
-
- arp = &layers.ARP{
- AddrType: layers.LinkTypeEthernet,
- Protocol: layers.EthernetTypeIPv4,
- HwAddressSize: 6,
- ProtAddressSize: 4,
- Operation: arpLayer.Operation,
- SourceHwAddress: SourceHwAddress,
- SourceProtAddress: net.ParseIP(arpLayer.SourceProtAddress),
- DstHwAddress: DstHwAddress,
- DstProtAddress: net.ParseIP(arpLayer.DstProtAddress),
- }
- return
-}
-
-func SendPacket(ovsDriver *ovsdbDriver.OvsDriver, srcPort string, pkt *Packet, numPkts int) error {
-
- options = gopacket.SerializeOptions{}
- var buffer gopacket.SerializeBuffer
- handle, err = pcap.OpenLive("port12", snapshot_len, true, pcap.BlockForever)
- if err != nil {
- log.Errorf("openlive: %v", err)
- return err
- }
- defer handle.Close()
-
- buffer = gopacket.NewSerializeBuffer()
- options.FixLengths = true
- options.ComputeChecksums = true
-
- sMac, _ := net.ParseMAC(pkt.SrcMAC)
- dMac, _ := net.ParseMAC(pkt.DstMAC)
- ethLayer := &layers.Ethernet{
- SrcMAC: sMac,
- DstMAC: dMac,
- }
- switch {
- case pkt.Arp != nil:
- arpLayer := buildArp(pkt.Arp)
- log.Infof("Sending an ARP packet on %s", srcPort)
- ethLayer.EthernetType = layers.EthernetTypeARP
- gopacket.SerializeLayers(buffer,
- options,
- ethLayer,
- arpLayer)
- case pkt.IPv4 != nil:
- ipLayer := buildIpv4(pkt.IPv4)
- log.Infof("Sending an IPv4 packer on %s", srcPort)
- ethLayer.EthernetType = layers.EthernetTypeIPv4
- gopacket.SerializeLayers(buffer,
- options,
- ethLayer,
- ipLayer)
- case pkt.IPv6 != nil:
- fmt.Println("ipv6")
- log.Infof("Sending an IPv6 packet on %s", srcPort)
- ipLayer := buildIpv6(pkt.IPv6)
- ethLayer.EthernetType = layers.EthernetTypeIPv6
- gopacket.SerializeLayers(buffer,
- options,
- ethLayer,
- ipLayer)
- default:
- ethLayer.EthernetType = 0xFFFF
- log.Infof("Sending an Ethernet packet on %s", srcPort)
- gopacket.SerializeLayers(buffer,
- options,
- ethLayer)
- }
-
- outgoingPacket := buffer.Bytes()
- for i := 0; i < numPkts; i++ {
- fmt.Println(outgoingPacket)
- handle.WritePacketData(outgoingPacket)
- }
-
- return err
-}
-
-/*
-func readPacket(handle *pcap.Handle, pkt *Packet, dstPort string) int {
- log.Infof("Received: Decoding the packet ")
- pktTimer := time.NewTimer(time.Second * 120)
- verifiedCount := 0
- count := 0
- src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
- for {
- select {
- case <-pktTimer.C:
- fmt.Println("Verified count --->", verifiedCount)
- return verifiedCount
- case packet := <-src.Packets():
- count++
- fmt.Println("This is the loop no:", count)
- switch {
- case pkt.Arp != nil:
- arpLayer := packet.Layer(layers.LayerTypeARP)
- if arpLayer == nil {
- continue
- }
- arp := arpLayer.(*layers.ARP)
- if compareIP(arp.SourceProtAddress, net.ParseIP(pkt.Arp.SourceProtAddress)) {
- if compareIP(arp.DstProtAddress, net.ParseIP(pkt.Arp.DstProtAddress)) {
- log.Infof("Verified: Received ARP packetfrom %v", arp.SourceProtAddress)
- verifiedCount++
- }
- }
- case pkt.IPv4 != nil:
- ipLayer := packet.Layer(layers.LayerTypeIPv4)
- if ipLayer == nil {
- continue
- }
- ip := ipLayer.(*layers.IPv4)
- fmt.Println("Received IPv4 packet from %v on %s", ip.SrcIP, dstPort)
- if compareIP(ip.SrcIP.To16(), net.ParseIP(pkt.IPv4.SrcIP)) {
- if compareIP(ip.DstIP.To16(), net.ParseIP(pkt.IPv4.DstIP)) {
- fmt.Println("Incrementing the count")
- fmt.Println("Verified: Received IPv4 packet from %v on %s", ip.SrcIP, dstPort)
- verifiedCount++
- }
- }
- case pkt.IPv6 != nil:
- ipLayer := packet.Layer(layers.LayerTypeIPv6)
- if ipLayer == nil {
- continue
- }
- ip := ipLayer.(*layers.IPv6)
- if compareIP(ip.SrcIP, net.ParseIP(pkt.IPv6.SrcIP)) {
- if compareIP(ip.DstIP, net.ParseIP(pkt.IPv6.DstIP)) {
- log.Infof("Verified: Received IPv6 Packet from %v on %s", ip.SrcIP, dstPort)
- verifiedCount++
- }
- }
- default:
- ethLayer := packet.Layer(layers.LayerTypeEthernet)
- eth := ethLayer.(*layers.Ethernet)
- log.Infof("Verified: Received ethernet packet from %v", eth.SrcMAC)
- }
- }
- }
-}
-func VerifyPacket(ovsDriver *ovsdbDriver.OvsDriver, dstPort string, pkt *Packet, ch chan bool, timeout int, numPkts int) {
- pktTimer := time.NewTimer(time.Second * 120)
- verifiedCountTotal := 0
- handle, err := pcap.OpenLive(dstPort, 1024, true, pcap.BlockForever)
- if err != nil {
- fmt.Println("Error capturing packet")
- continue
- }
- if handle == nil {
- continue
- }
- defer handle.Close()
- // Start up a goroutine to read in packet data.
- // stop := make(chan struct{}, 1)
- //defer close(stop)
- //done := make(chan int, 1000)
- for {
- fmt.Println("Calling Go routine Read packet", numPkts)
- verifiedCountTotal += readPacket(handle, pkt, dstPort)
- select {
- case <-pktTimer.C:
- fmt.Println(verifiedCountTotal)
- ch <- (verifiedCountTotal == numPkts)
- //close(stop)
- return
- default:
- continue
- }
- }
-}*/
-func readPacket(handle *pcap.Handle, pkt *Packet, dstPort string, done chan int) {
- log.Infof("Received: Decoding the packet ")
-
- pktTimer := time.NewTimer(time.Second * 20)
- verifiedCount := 0
- count := 0
- src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
- for {
- select {
- case <-pktTimer.C:
- fmt.Println("Verified count --->", verifiedCount)
- done <- verifiedCount
- case packet := <-src.Packets():
- count++
- fmt.Println("This is the loop no:", count)
- switch {
- case pkt.Arp != nil:
- arpLayer := packet.Layer(layers.LayerTypeARP)
- if arpLayer == nil {
- continue
- }
- arp := arpLayer.(*layers.ARP)
- if compareIP(arp.SourceProtAddress, net.ParseIP(pkt.Arp.SourceProtAddress)) {
- if compareIP(arp.DstProtAddress, net.ParseIP(pkt.Arp.DstProtAddress)) {
- log.Infof("Verified: Received ARP packetfrom %v", arp.SourceProtAddress)
- verifiedCount++
- }
- }
- case pkt.IPv4 != nil:
- ipLayer := packet.Layer(layers.LayerTypeIPv4)
- if ipLayer == nil {
- continue
- }
- ip := ipLayer.(*layers.IPv4)
-
- fmt.Println("Received IPv4 packet from %v on %s", ip.SrcIP, dstPort)
- if compareIP(ip.SrcIP.To16(), net.ParseIP(pkt.IPv4.SrcIP)) {
- if compareIP(ip.DstIP.To16(), net.ParseIP(pkt.IPv4.DstIP)) {
- fmt.Println("Incrementing the count")
- fmt.Println("Verified: Received IPv4 packet from %v on %s", ip.SrcIP, dstPort)
- verifiedCount++
- }
- }
- case pkt.IPv6 != nil:
- ipLayer := packet.Layer(layers.LayerTypeIPv6)
- if ipLayer == nil {
- continue
- }
- ip := ipLayer.(*layers.IPv6)
- if compareIP(ip.SrcIP, net.ParseIP(pkt.IPv6.SrcIP)) {
- if compareIP(ip.DstIP, net.ParseIP(pkt.IPv6.DstIP)) {
- log.Infof("Verified: Received IPv6 Packet from %v on %s", ip.SrcIP, dstPort)
- verifiedCount++
- }
- }
- default:
- ethLayer := packet.Layer(layers.LayerTypeEthernet)
- eth := ethLayer.(*layers.Ethernet)
- if eth.SrcMAC.String() == pkt.SrcMAC && eth.DstMAC.String() == pkt.DstMAC {
- log.Infof("Verified: Received Eth Packet from %v on %s", eth.SrcMAC, dstPort)
- verifiedCount++
- }
- }
- }
- }
-}
-
-func VerifyPacket(ovsDriver *ovsdbDriver.OvsDriver, dstPort string, pkt *Packet, ch chan bool, timeout int, numPkts int) {
- verifiedCountTotal := 0
- handle, err := pcap.OpenLive(dstPort, 1024, true, pcap.BlockForever)
-
- if err != nil {
- fmt.Println("Error capturing packet")
- ch <- false
- }
-
- if handle == nil {
- ch <- false
- }
- defer handle.Close()
- // Start up a goroutine to read in packet data.
- // stop := make(chan struct{}, 1)
- //defer close(stop)
- done := make(chan int)
-
- fmt.Println("Calling Go routine Read packet", numPkts)
- go readPacket(handle, pkt, dstPort, done)
- verifiedCountTotal = <-done
- fmt.Println(verifiedCountTotal)
- ch <- (verifiedCountTotal == numPkts)
- close(done)
- return
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/ovsSwitch.go b/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/ovsSwitch.go
deleted file mode 100644
index a0fa8775b..000000000
--- a/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/ovsSwitch.go
+++ /dev/null
@@ -1,369 +0,0 @@
-/***
-Copyright 2014 Cisco Systems Inc. All rights reserved.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package ovsSwitch
-
-import (
- "net"
- "strings"
- "time"
-
- "github.com/contiv/ofnet"
- "github.com/contiv/ofnet/ovsdbDriver"
-
- log "github.com/Sirupsen/logrus"
-)
-
-const OVS_CTRLER_PORT = 6633
-const OVS_CTRLER_IP = "127.0.0.1"
-
-const USE_VETH_PAIR = true
-
-// OvsSwitch represents on OVS bridge instance
-type OvsSwitch struct {
- bridgeName string
- netType string
- ovsdbDriver *ovsdbDriver.OvsDriver
- ofnetAgent *ofnet.OfnetAgent
-}
-
-// NewOvsSwitch Creates a new OVS switch instance
-func NewOvsSwitch(bridgeName, netType, localIP string) (*OvsSwitch, error) {
- var err error
-
- sw := new(OvsSwitch)
- sw.bridgeName = bridgeName
- sw.netType = netType
-
- // Create OVS db driver
- sw.ovsdbDriver = ovsdbDriver.NewOvsDriver(bridgeName)
-
- // Create an ofnet agent
- sw.ofnetAgent, err = ofnet.NewOfnetAgent(netType, net.ParseIP(localIP), ofnet.OFNET_AGENT_PORT, OVS_CTRLER_PORT)
- if err != nil {
- log.Fatalf("Error initializing ofnet")
- return nil, err
- }
-
- // Add controller to the OVS
- if !sw.ovsdbDriver.IsControllerPresent(OVS_CTRLER_IP, OVS_CTRLER_PORT) {
- err = sw.ovsdbDriver.AddController(OVS_CTRLER_IP, OVS_CTRLER_PORT)
- if err != nil {
- log.Fatalf("Error adding controller to OVS. Err: %v", err)
- return nil, err
- }
- }
-
- // Wait a little for master to be ready before we connect
- time.Sleep(300 * time.Millisecond)
-
- log.Infof("Waiting for OVS switch to connect..")
-
- // Wait for a while for OVS switch to connect to ofnet agent
- for i := 0; i < 10; i++ {
- time.Sleep(1 * time.Second)
- if sw.ofnetAgent.IsSwitchConnected() {
- break
- }
- }
-
- log.Infof("Switch connected.")
-
- return sw, nil
-}
-
-// Delete performs cleanup prior to destruction of the OvsDriver
-func (sw *OvsSwitch) Delete() {
- if sw.ofnetAgent != nil {
- sw.ofnetAgent.Delete()
- }
-
- if sw.ovsdbDriver != nil {
- sw.ovsdbDriver.Delete()
-
- // Wait a little for OVS switch to be deleted
- time.Sleep(300 * time.Millisecond)
- }
-}
-
-// CreateNetwork creates a new network/vlan
-func (sw *OvsSwitch) CreateNetwork(pktTag uint16, extPktTag uint32) error {
- // Add the vlan/vni to ofnet
- err := sw.ofnetAgent.AddVlan(pktTag, extPktTag)
- if err != nil {
- log.Errorf("Error adding vlan/vni %d/%d. Err: %v", pktTag, extPktTag, err)
- return err
- }
-
- return nil
-}
-
-// DeleteNetwork deletes a network/vlan
-func (sw *OvsSwitch) DeleteNetwork(pktTag uint16, extPktTag uint32) error {
- // Delete vlan/vni mapping
- err := sw.ofnetAgent.RemoveVlan(pktTag, extPktTag)
- if err != nil {
- log.Errorf("Error removing vlan/vni %d/%d. Err: %v", pktTag, extPktTag, err)
- return err
- }
-
- return nil
-}
-
-// CreateEndpoint creates a port in ovs switch
-func (sw *OvsSwitch) CreateEndpoint(intfName, macAddr, ipAddr string, pktTag int) error {
- var ovsPortName string
- var ovsIntfType string
- if USE_VETH_PAIR {
- // Generate interface
- ovsPortName = strings.Replace(intfName, "port", "vport", 1)
- ovsIntfType = ""
-
- // Create a Veth pair
- err := createVethPair(intfName, ovsPortName)
- if err != nil {
- log.Errorf("Error creating veth pairs. Err: %v", err)
- return err
- }
-
- // Set the OVS side of the port as up
- err = setLinkUp(ovsPortName)
- if err != nil {
- log.Errorf("Error setting link %s up. Err: %v", ovsPortName, err)
- return err
- }
- } else {
- ovsPortName = intfName
- ovsIntfType = "internal"
-
- }
-
- // Ask OVSDB driver to add the port
- err := sw.ovsdbDriver.CreatePort(ovsPortName, ovsIntfType, uint(pktTag))
- if err != nil {
- return err
- }
- defer func() {
- if err != nil {
- sw.ovsdbDriver.DeletePort(ovsPortName)
- }
- }()
-
- // Wait a little for OVS to create the interface
- time.Sleep(300 * time.Millisecond)
-
- // Set the interface mac address
- err = setInterfaceMac(intfName, macAddr)
- if err != nil {
- log.Errorf("Error setting interface Mac %s on port %s", macAddr, intfName)
- return err
- }
-
- // Add the endpoint to ofnet
- // Get the openflow port number for the interface
- ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(ovsPortName)
- if err != nil {
- log.Errorf("Could not find the OVS port %s. Err: %v", ovsPortName, err)
- return err
- }
-
- mAddr, _ := net.ParseMAC(macAddr)
-
- // Build the endpoint info
- endpoint := ofnet.EndpointInfo{
- PortNo: ofpPort,
- MacAddr: mAddr,
- Vlan: uint16(pktTag),
- IpAddr: net.ParseIP(ipAddr),
- }
-
- // Add the local port to ofnet
- err = sw.ofnetAgent.AddLocalEndpoint(endpoint)
- if err != nil {
- log.Errorf("Error adding local port %s to ofnet. Err: %v", ovsPortName, err)
- return err
- }
-
- return nil
-}
-
-// UpdateEndpoint updates an OVS port without creating it
-func (sw *OvsSwitch) UpdateEndpoint(intfName, macAddr, ipAddr string, pktTag int) error {
- var ovsPortName string
- if USE_VETH_PAIR {
- // Generate interface
- ovsPortName = strings.Replace(intfName, "port", "vport", 1)
- } else {
- ovsPortName = intfName
- }
-
- // Add the endpoint to ofnet
- // Get the openflow port number for the interface
- ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(ovsPortName)
- if err != nil {
- log.Errorf("Could not find the OVS port %s. Err: %v", ovsPortName, err)
- return err
- }
-
- mAddr, _ := net.ParseMAC(macAddr)
-
- // Build the endpoint info
- endpoint := ofnet.EndpointInfo{
- PortNo: ofpPort,
- MacAddr: mAddr,
- Vlan: uint16(pktTag),
- IpAddr: net.ParseIP(ipAddr),
- }
-
- // Add the local port to ofnet
- err = sw.ofnetAgent.AddLocalEndpoint(endpoint)
- if err != nil {
- log.Errorf("Error adding local port %s to ofnet. Err: %v", intfName, err)
- return err
- }
-
- return nil
-}
-
-// DeleteEndpoint removes a port from OVS
-func (sw *OvsSwitch) DeleteEndpoint(intfName string) error {
- var ovsPortName string
- if USE_VETH_PAIR {
- // Generate interface
- ovsPortName = strings.Replace(intfName, "port", "vport", 1)
- } else {
- ovsPortName = intfName
- }
-
- // Remove info from ofnet
- // Get the openflow port number for the interface
- ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(ovsPortName)
- if err != nil {
- log.Errorf("Could not find the OVS port %s. Err: %v", ovsPortName, err)
- return err
- }
-
- err = sw.ofnetAgent.RemoveLocalEndpoint(ofpPort)
- if err != nil {
- log.Errorf("Error removing port %s from ofnet. Err: %v", ovsPortName, err)
- }
-
- // Delete it from ovsdb
- err = sw.ovsdbDriver.DeletePort(ovsPortName)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// AddPeer creates a VTEP interface
-func (sw *OvsSwitch) AddPeer(vtepIP string) error {
- // Setup VTEPs only in vxlan and vrouter mode
- if sw.netType != "vxlan" || sw.netType != "vrouter" {
- return nil
- }
-
- // Create interface name for VTEP
- intfName := vxlanIfName(vtepIP)
-
- log.Infof("Creating VTEP intf %s for IP %s", intfName, vtepIP)
-
- // Check if it already exists
- isPresent, vsifName := sw.ovsdbDriver.IsVtepPresent(vtepIP)
- if !isPresent || (vsifName != intfName) {
- // Ask ovsdb to create it
- err := sw.ovsdbDriver.CreateVtep(intfName, vtepIP)
- if err != nil {
- log.Errorf("Error creating VTEP port %s. Err: %v", intfName, err)
- }
- }
-
- // Get the openflow port number for the interface
- ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(intfName)
- if err != nil {
- log.Errorf("Could not find the OVS port %s. Err: %v", intfName, err)
- return err
- }
-
- // Add info about VTEP port to ofnet
- err = sw.ofnetAgent.AddVtepPort(ofpPort, net.ParseIP(vtepIP))
- if err != nil {
- log.Errorf("Error adding VTEP port %s to ofnet. Err: %v", intfName, err)
- return err
- }
-
- return nil
-}
-
-// RemovePeer deletes a VTEP
-func (sw *OvsSwitch) RemovePeer(vtepIP string) error {
- // delete VTEPs only in vxlan and vrouter mode
- if sw.netType != "vxlan" || sw.netType != "vrouter" {
- return nil
- }
-
- // Build vtep interface name
- intfName := vxlanIfName(vtepIP)
-
- log.Infof("Deleting VTEP intf %s for IP %s", intfName, vtepIP)
-
- // Get the openflow port number for the interface
- ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(intfName)
- if err != nil {
- log.Errorf("Could not find the OVS port %s. Err: %v", intfName, err)
- return err
- }
-
- // Add info about VTEP port to ofnet
- err = sw.ofnetAgent.RemoveVtepPort(ofpPort, net.ParseIP(vtepIP))
- if err != nil {
- log.Errorf("Error deleting VTEP port %s to ofnet. Err: %v", intfName, err)
- return err
- }
-
- // ask ovsdb to delete the VTEP
- return sw.ovsdbDriver.DeleteVtep(intfName)
-}
-
-// AddUplinkPort adds uplink port to the OVS
-func (sw *OvsSwitch) AddUplinkPort(intfName string) error {
- var err error
-
- // some error checking
- if sw.netType != "vlan" {
- log.Fatalf("Can not add uplink to OVS type %s.", sw.netType)
- }
-
- // Check if port is already part of the OVS and add it
- if !sw.ovsdbDriver.IsPortNamePresent(intfName) {
- // Ask OVSDB driver to add the port as a trunk port
- err = sw.ovsdbDriver.CreatePort(intfName, "", 0)
- if err != nil {
- log.Errorf("Error adding uplink %s to OVS. Err: %v", intfName, err)
- return err
- }
- }
-
- log.Infof("Added uplink %s to OVS switch %s.", intfName, sw.bridgeName)
-
- defer func() {
- if err != nil {
- sw.ovsdbDriver.DeletePort(intfName)
- }
- }()
-
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/utils.go b/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/utils.go
deleted file mode 100644
index 1d0498929..000000000
--- a/Godeps/_workspace/src/github.com/contiv/ofnet/ovsSwitch/utils.go
+++ /dev/null
@@ -1,74 +0,0 @@
-/***
-Copyright 2014 Cisco Systems Inc. All rights reserved.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package ovsSwitch
-
-import (
- "fmt"
- "net"
- "strings"
-
- log "github.com/Sirupsen/logrus"
- "github.com/vishvananda/netlink"
-)
-
-// createVethPair creates veth interface pairs with specified name
-func createVethPair(name1, name2 string) error {
- log.Infof("Creating Veth pairs with name: %s, %s", name1, name2)
-
- // Veth pair params
- veth := &netlink.Veth{
- LinkAttrs: netlink.LinkAttrs{
- Name: name1,
- TxQLen: 0,
- },
- PeerName: name2,
- }
-
- // Create the veth pair
- if err := netlink.LinkAdd(veth); err != nil {
- log.Errorf("error creating veth pair: %v", err)
- return err
- }
-
- return nil
-}
-
-// setLinkUp sets the link up
-func setLinkUp(name string) error {
- iface, err := netlink.LinkByName(name)
- if err != nil {
- return err
- }
- return netlink.LinkSetUp(iface)
-}
-
-// setInterfaceMac : Set mac address of an interface
-func setInterfaceMac(name string, macaddr string) error {
- iface, err := netlink.LinkByName(name)
- if err != nil {
- return err
- }
- hwaddr, err := net.ParseMAC(macaddr)
- if err != nil {
- return err
- }
- return netlink.LinkSetHardwareAddr(iface, hwaddr)
-}
-
-// vxlanIfName returns formatted vxlan interface name
-func vxlanIfName(vtepIP string) string {
- return fmt.Sprintf("vxif%s", strings.Replace(vtepIP, ".", "", -1))
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Godeps.json b/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Godeps.json
deleted file mode 100644
index e3f59de67..000000000
--- a/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Godeps.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "ImportPath": "github.com/contiv/vagrant_ssh",
- "GoVersion": "go1.5.1",
- "Packages": [
- "./..."
- ],
- "Deps": [
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.6.4-12-g467d9d5",
- "Rev": "467d9d55c2d2c17248441a8fc661561161f40d5e"
- },
- {
- "ImportPath": "golang.org/x/crypto/ssh",
- "Rev": "83f1503f771a82af8a31f358eb825e9efb5dae6c"
- },
- {
- "ImportPath": "gopkg.in/check.v1",
- "Rev": "11d3bc7aa68e238947792f30573146a3231fc0f1"
- }
- ]
-}
diff --git a/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Readme b/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Readme
deleted file mode 100644
index 4cdaa53d5..000000000
--- a/Godeps/_workspace/src/github.com/contiv/vagrantssh/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/LICENSE b/Godeps/_workspace/src/github.com/coreos/etcd/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/coreos/etcd/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/NOTICE b/Godeps/_workspace/src/github.com/coreos/etcd/NOTICE
new file mode 100644
index 000000000..b39ddfa5c
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/coreos/etcd/NOTICE
@@ -0,0 +1,5 @@
+CoreOS Project
+Copyright 2014 CoreOS, Inc
+
+This product includes software developed at CoreOS, Inc.
+(http://www.coreos.com/).
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/errors_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/errors_test.go
deleted file mode 100644
index f5cec6d45..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/errors_test.go
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package httptypes
-
-import (
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
-)
-
-func TestHTTPErrorWriteTo(t *testing.T) {
- err := NewHTTPError(http.StatusBadRequest, "what a bad request you made!")
- rr := httptest.NewRecorder()
- err.WriteTo(rr)
-
- wcode := http.StatusBadRequest
- wheader := http.Header(map[string][]string{
- "Content-Type": []string{"application/json"},
- })
- wbody := `{"message":"what a bad request you made!"}`
-
- if wcode != rr.Code {
- t.Errorf("HTTP status code %d, want %d", rr.Code, wcode)
- }
-
- if !reflect.DeepEqual(wheader, rr.HeaderMap) {
- t.Errorf("HTTP headers %v, want %v", rr.HeaderMap, wheader)
- }
-
- gbody := rr.Body.String()
- if wbody != gbody {
- t.Errorf("HTTP body %q, want %q", gbody, wbody)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/member_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/member_test.go
deleted file mode 100644
index cfff78381..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/httptypes/member_test.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package httptypes
-
-import (
- "encoding/json"
- "net/url"
- "reflect"
- "testing"
-
- "github.com/coreos/etcd/pkg/types"
-)
-
-func TestMemberUnmarshal(t *testing.T) {
- tests := []struct {
- body []byte
- wantMember Member
- wantError bool
- }{
- // no URLs, just check ID & Name
- {
- body: []byte(`{"id": "c", "name": "dungarees"}`),
- wantMember: Member{ID: "c", Name: "dungarees", PeerURLs: nil, ClientURLs: nil},
- },
-
- // both client and peer URLs
- {
- body: []byte(`{"peerURLs": ["http://127.0.0.1:2379"], "clientURLs": ["http://127.0.0.1:2379"]}`),
- wantMember: Member{
- PeerURLs: []string{
- "http://127.0.0.1:2379",
- },
- ClientURLs: []string{
- "http://127.0.0.1:2379",
- },
- },
- },
-
- // multiple peer URLs
- {
- body: []byte(`{"peerURLs": ["http://127.0.0.1:2379", "https://example.com"]}`),
- wantMember: Member{
- PeerURLs: []string{
- "http://127.0.0.1:2379",
- "https://example.com",
- },
- ClientURLs: nil,
- },
- },
-
- // multiple client URLs
- {
- body: []byte(`{"clientURLs": ["http://127.0.0.1:2379", "https://example.com"]}`),
- wantMember: Member{
- PeerURLs: nil,
- ClientURLs: []string{
- "http://127.0.0.1:2379",
- "https://example.com",
- },
- },
- },
-
- // invalid JSON
- {
- body: []byte(`{"peerU`),
- wantError: true,
- },
- }
-
- for i, tt := range tests {
- got := Member{}
- err := json.Unmarshal(tt.body, &got)
- if tt.wantError != (err != nil) {
- t.Errorf("#%d: want error %t, got %v", i, tt.wantError, err)
- continue
- }
-
- if !reflect.DeepEqual(tt.wantMember, got) {
- t.Errorf("#%d: incorrect output: want=%#v, got=%#v", i, tt.wantMember, got)
- }
- }
-}
-
-func TestMemberCreateRequestUnmarshal(t *testing.T) {
- body := []byte(`{"peerURLs": ["http://127.0.0.1:8081", "https://127.0.0.1:8080"]}`)
- want := MemberCreateRequest{
- PeerURLs: types.URLs([]url.URL{
- url.URL{Scheme: "http", Host: "127.0.0.1:8081"},
- url.URL{Scheme: "https", Host: "127.0.0.1:8080"},
- }),
- }
-
- var req MemberCreateRequest
- if err := json.Unmarshal(body, &req); err != nil {
- t.Fatalf("Unmarshal returned unexpected err=%v", err)
- }
-
- if !reflect.DeepEqual(want, req) {
- t.Fatalf("Failed to unmarshal MemberCreateRequest: want=%#v, got=%#v", want, req)
- }
-}
-
-func TestMemberCreateRequestUnmarshalFail(t *testing.T) {
- tests := [][]byte{
- // invalid JSON
- []byte(``),
- []byte(`{`),
-
- // spot-check validation done in types.NewURLs
- []byte(`{"peerURLs": "foo"}`),
- []byte(`{"peerURLs": ["."]}`),
- []byte(`{"peerURLs": []}`),
- []byte(`{"peerURLs": ["http://127.0.0.1:2379/foo"]}`),
- []byte(`{"peerURLs": ["http://127.0.0.1"]}`),
- }
-
- for i, tt := range tests {
- var req MemberCreateRequest
- if err := json.Unmarshal(tt, &req); err == nil {
- t.Errorf("#%d: expected err, got nil", i)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/id_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/id_test.go
deleted file mode 100644
index 97d168f58..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/id_test.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package types
-
-import (
- "reflect"
- "sort"
- "testing"
-)
-
-func TestIDString(t *testing.T) {
- tests := []struct {
- input ID
- want string
- }{
- {
- input: 12,
- want: "c",
- },
- {
- input: 4918257920282737594,
- want: "444129853c343bba",
- },
- }
-
- for i, tt := range tests {
- got := tt.input.String()
- if tt.want != got {
- t.Errorf("#%d: ID.String failure: want=%v, got=%v", i, tt.want, got)
- }
- }
-}
-
-func TestIDFromString(t *testing.T) {
- tests := []struct {
- input string
- want ID
- }{
- {
- input: "17",
- want: 23,
- },
- {
- input: "612840dae127353",
- want: 437557308098245459,
- },
- }
-
- for i, tt := range tests {
- got, err := IDFromString(tt.input)
- if err != nil {
- t.Errorf("#%d: IDFromString failure: err=%v", i, err)
- continue
- }
- if tt.want != got {
- t.Errorf("#%d: IDFromString failure: want=%v, got=%v", i, tt.want, got)
- }
- }
-}
-
-func TestIDFromStringFail(t *testing.T) {
- tests := []string{
- "",
- "XXX",
- "612840dae127353612840dae127353",
- }
-
- for i, tt := range tests {
- _, err := IDFromString(tt)
- if err == nil {
- t.Fatalf("#%d: IDFromString expected error, but err=nil", i)
- }
- }
-}
-
-func TestIDSlice(t *testing.T) {
- g := []ID{10, 500, 5, 1, 100, 25}
- w := []ID{1, 5, 10, 25, 100, 500}
- sort.Sort(IDSlice(g))
- if !reflect.DeepEqual(g, w) {
- t.Errorf("slice after sort = %#v, want %#v", g, w)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/set_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/set_test.go
deleted file mode 100644
index ff1ecc68d..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/set_test.go
+++ /dev/null
@@ -1,186 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package types
-
-import (
- "reflect"
- "sort"
- "testing"
-)
-
-func TestUnsafeSet(t *testing.T) {
- driveSetTests(t, NewUnsafeSet())
-}
-
-func TestThreadsafeSet(t *testing.T) {
- driveSetTests(t, NewThreadsafeSet())
-}
-
-// Check that two slices contents are equal; order is irrelevant
-func equal(a, b []string) bool {
- as := sort.StringSlice(a)
- bs := sort.StringSlice(b)
- as.Sort()
- bs.Sort()
- return reflect.DeepEqual(as, bs)
-}
-
-func driveSetTests(t *testing.T, s Set) {
- // Verify operations on an empty set
- eValues := []string{}
- values := s.Values()
- if !reflect.DeepEqual(values, eValues) {
- t.Fatalf("Expect values=%v got %v", eValues, values)
- }
- if l := s.Length(); l != 0 {
- t.Fatalf("Expected length=0, got %d", l)
- }
- for _, v := range []string{"foo", "bar", "baz"} {
- if s.Contains(v) {
- t.Fatalf("Expect s.Contains(%q) to be fale, got true", v)
- }
- }
-
- // Add three items, ensure they show up
- s.Add("foo")
- s.Add("bar")
- s.Add("baz")
-
- eValues = []string{"foo", "bar", "baz"}
- values = s.Values()
- if !equal(values, eValues) {
- t.Fatalf("Expect values=%v got %v", eValues, values)
- }
-
- for _, v := range eValues {
- if !s.Contains(v) {
- t.Fatalf("Expect s.Contains(%q) to be true, got false", v)
- }
- }
-
- if l := s.Length(); l != 3 {
- t.Fatalf("Expected length=3, got %d", l)
- }
-
- // Add the same item a second time, ensuring it is not duplicated
- s.Add("foo")
-
- values = s.Values()
- if !equal(values, eValues) {
- t.Fatalf("Expect values=%v got %v", eValues, values)
- }
- if l := s.Length(); l != 3 {
- t.Fatalf("Expected length=3, got %d", l)
- }
-
- // Remove all items, ensure they are gone
- s.Remove("foo")
- s.Remove("bar")
- s.Remove("baz")
-
- eValues = []string{}
- values = s.Values()
- if !equal(values, eValues) {
- t.Fatalf("Expect values=%v got %v", eValues, values)
- }
-
- if l := s.Length(); l != 0 {
- t.Fatalf("Expected length=0, got %d", l)
- }
-
- // Create new copies of the set, and ensure they are unlinked to the
- // original Set by making modifications
- s.Add("foo")
- s.Add("bar")
- cp1 := s.Copy()
- cp2 := s.Copy()
- s.Remove("foo")
- cp3 := s.Copy()
- cp1.Add("baz")
-
- for i, tt := range []struct {
- want []string
- got []string
- }{
- {[]string{"bar"}, s.Values()},
- {[]string{"foo", "bar", "baz"}, cp1.Values()},
- {[]string{"foo", "bar"}, cp2.Values()},
- {[]string{"bar"}, cp3.Values()},
- } {
- if !equal(tt.want, tt.got) {
- t.Fatalf("case %d: expect values=%v got %v", i, tt.want, tt.got)
- }
- }
-
- for i, tt := range []struct {
- want bool
- got bool
- }{
- {true, s.Equals(cp3)},
- {true, cp3.Equals(s)},
- {false, s.Equals(cp2)},
- {false, s.Equals(cp1)},
- {false, cp1.Equals(s)},
- {false, cp2.Equals(s)},
- {false, cp2.Equals(cp1)},
- } {
- if tt.got != tt.want {
- t.Fatalf("case %d: want %t, got %t", i, tt.want, tt.got)
-
- }
- }
-
- // Subtract values from a Set, ensuring a new Set is created and
- // the original Sets are unmodified
- sub1 := cp1.Sub(s)
- sub2 := cp2.Sub(cp1)
-
- for i, tt := range []struct {
- want []string
- got []string
- }{
- {[]string{"foo", "bar", "baz"}, cp1.Values()},
- {[]string{"foo", "bar"}, cp2.Values()},
- {[]string{"bar"}, s.Values()},
- {[]string{"foo", "baz"}, sub1.Values()},
- {[]string{}, sub2.Values()},
- } {
- if !equal(tt.want, tt.got) {
- t.Fatalf("case %d: expect values=%v got %v", i, tt.want, tt.got)
- }
- }
-}
-
-func TestUnsafeSetContainsAll(t *testing.T) {
- vals := []string{"foo", "bar", "baz"}
- s := NewUnsafeSet(vals...)
-
- tests := []struct {
- strs []string
- wcontain bool
- }{
- {[]string{}, true},
- {vals[:1], true},
- {vals[:2], true},
- {vals, true},
- {[]string{"cuz"}, false},
- {[]string{vals[0], "cuz"}, false},
- }
- for i, tt := range tests {
- if g := s.ContainsAll(tt.strs); g != tt.wcontain {
- t.Errorf("#%d: ok = %v, want %v", i, g, tt.wcontain)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/slice_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/slice_test.go
deleted file mode 100644
index 95e37e04d..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/slice_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package types
-
-import (
- "reflect"
- "sort"
- "testing"
-)
-
-func TestUint64Slice(t *testing.T) {
- g := Uint64Slice{10, 500, 5, 1, 100, 25}
- w := Uint64Slice{1, 5, 10, 25, 100, 500}
- sort.Sort(g)
- if !reflect.DeepEqual(g, w) {
- t.Errorf("slice after sort = %#v, want %#v", g, w)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/urls_test.go b/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/urls_test.go
deleted file mode 100644
index ffa2cf007..000000000
--- a/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types/urls_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package types
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/etcd/pkg/testutil"
-)
-
-func TestNewURLs(t *testing.T) {
- tests := []struct {
- strs []string
- wurls URLs
- }{
- {
- []string{"http://127.0.0.1:2379"},
- testutil.MustNewURLs(t, []string{"http://127.0.0.1:2379"}),
- },
- // it can trim space
- {
- []string{" http://127.0.0.1:2379 "},
- testutil.MustNewURLs(t, []string{"http://127.0.0.1:2379"}),
- },
- // it does sort
- {
- []string{
- "http://127.0.0.2:2379",
- "http://127.0.0.1:2379",
- },
- testutil.MustNewURLs(t, []string{
- "http://127.0.0.1:2379",
- "http://127.0.0.2:2379",
- }),
- },
- }
- for i, tt := range tests {
- urls, _ := NewURLs(tt.strs)
- if !reflect.DeepEqual(urls, tt.wurls) {
- t.Errorf("#%d: urls = %+v, want %+v", i, urls, tt.wurls)
- }
- }
-}
-
-func TestURLsString(t *testing.T) {
- tests := []struct {
- us URLs
- wstr string
- }{
- {
- URLs{},
- "",
- },
- {
- testutil.MustNewURLs(t, []string{"http://127.0.0.1:2379"}),
- "http://127.0.0.1:2379",
- },
- {
- testutil.MustNewURLs(t, []string{
- "http://127.0.0.1:2379",
- "http://127.0.0.2:2379",
- }),
- "http://127.0.0.1:2379,http://127.0.0.2:2379",
- },
- {
- testutil.MustNewURLs(t, []string{
- "http://127.0.0.2:2379",
- "http://127.0.0.1:2379",
- }),
- "http://127.0.0.2:2379,http://127.0.0.1:2379",
- },
- }
- for i, tt := range tests {
- g := tt.us.String()
- if g != tt.wstr {
- t.Errorf("#%d: string = %s, want %s", i, g, tt.wstr)
- }
- }
-}
-
-func TestURLsSort(t *testing.T) {
- g := testutil.MustNewURLs(t, []string{
- "http://127.0.0.4:2379",
- "http://127.0.0.2:2379",
- "http://127.0.0.1:2379",
- "http://127.0.0.3:2379",
- })
- w := testutil.MustNewURLs(t, []string{
- "http://127.0.0.1:2379",
- "http://127.0.0.2:2379",
- "http://127.0.0.3:2379",
- "http://127.0.0.4:2379",
- })
- gurls := URLs(g)
- gurls.Sort()
- if !reflect.DeepEqual(g, w) {
- t.Errorf("URLs after sort = %#v, want %#v", g, w)
- }
-}
-
-func TestURLsStringSlice(t *testing.T) {
- tests := []struct {
- us URLs
- wstr []string
- }{
- {
- URLs{},
- []string{},
- },
- {
- testutil.MustNewURLs(t, []string{"http://127.0.0.1:2379"}),
- []string{"http://127.0.0.1:2379"},
- },
- {
- testutil.MustNewURLs(t, []string{
- "http://127.0.0.1:2379",
- "http://127.0.0.2:2379",
- }),
- []string{"http://127.0.0.1:2379", "http://127.0.0.2:2379"},
- },
- {
- testutil.MustNewURLs(t, []string{
- "http://127.0.0.2:2379",
- "http://127.0.0.1:2379",
- }),
- []string{"http://127.0.0.2:2379", "http://127.0.0.1:2379"},
- },
- }
- for i, tt := range tests {
- g := tt.us.StringSlice()
- if !reflect.DeepEqual(g, tt.wstr) {
- t.Errorf("#%d: string slice = %+v, want %+v", i, g, tt.wstr)
- }
- }
-}
-
-func TestNewURLsFail(t *testing.T) {
- tests := [][]string{
- // no urls given
- {},
- // missing protocol scheme
- {"://127.0.0.1:2379"},
- // unsupported scheme
- {"mailto://127.0.0.1:2379"},
- // not conform to host:port
- {"http://127.0.0.1"},
- // contain a path
- {"http://127.0.0.1:2379/path"},
- }
- for i, tt := range tests {
- _, err := NewURLs(tt)
- if err == nil {
- t.Errorf("#%d: err = nil, but error", i)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/LICENSE b/Godeps/_workspace/src/github.com/coreos/go-etcd/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go
deleted file mode 100644
index 26223ff1c..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/add_child_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package etcd
-
-import "testing"
-
-func TestAddChild(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- c.Delete("nonexistentDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
-
- _, err := c.AddChild("fooDir", "v0", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = c.AddChild("fooDir", "v1", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := c.Get("fooDir", true, false)
- // The child with v0 should proceed the child with v1 because it's added
- // earlier, so it should have a lower key.
- if !(len(resp.Node.Nodes) == 2 && (resp.Node.Nodes[0].Value == "v0" && resp.Node.Nodes[1].Value == "v1")) {
- t.Fatalf("AddChild 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+
- " The response was: %#v", resp)
- }
-
- // Creating a child under a nonexistent directory should succeed.
- // The directory should be created.
- resp, err = c.AddChild("nonexistentDir", "foo", 5)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestAddChildDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- c.Delete("nonexistentDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
-
- _, err := c.AddChildDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = c.AddChildDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- resp, err := c.Get("fooDir", true, false)
- // The child with v0 should proceed the child with v1 because it's added
- // earlier, so it should have a lower key.
- if !(len(resp.Node.Nodes) == 2 && (len(resp.Node.Nodes[0].Nodes) == 0 && len(resp.Node.Nodes[1].Nodes) == 0)) {
- t.Fatalf("AddChildDir 1 failed. There should be two chlidren whose values are v0 and v1, respectively."+
- " The response was: %#v", resp)
- }
-
- // Creating a child under a nonexistent directory should succeed.
- // The directory should be created.
- resp, err = c.AddChildDir("nonexistentDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go
deleted file mode 100644
index 4720d8d69..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client_test.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package etcd
-
-import (
- "encoding/json"
- "fmt"
- "net"
- "net/url"
- "os"
- "testing"
-)
-
-// To pass this test, we need to create a cluster of 3 machines
-// The server should be listening on localhost:4001, 4002, 4003
-func TestSync(t *testing.T) {
- fmt.Println("Make sure there are three nodes at 0.0.0.0:4001-4003")
-
- // Explicit trailing slash to ensure this doesn't reproduce:
- // https://github.com/coreos/go-etcd/issues/82
- c := NewClient([]string{"http://127.0.0.1:4001/"})
-
- success := c.SyncCluster()
- if !success {
- t.Fatal("cannot sync machines")
- }
-
- for _, m := range c.GetCluster() {
- u, err := url.Parse(m)
- if err != nil {
- t.Fatal(err)
- }
- if u.Scheme != "http" {
- t.Fatal("scheme must be http")
- }
-
- host, _, err := net.SplitHostPort(u.Host)
- if err != nil {
- t.Fatal(err)
- }
- if host != "localhost" {
- t.Fatal("Host must be localhost")
- }
- }
-
- badMachines := []string{"abc", "edef"}
-
- success = c.SetCluster(badMachines)
-
- if success {
- t.Fatal("should not sync on bad machines")
- }
-
- goodMachines := []string{"127.0.0.1:4002"}
-
- success = c.SetCluster(goodMachines)
-
- if !success {
- t.Fatal("cannot sync machines")
- } else {
- fmt.Println(c.cluster.Machines)
- }
-
-}
-
-func TestPersistence(t *testing.T) {
- c := NewClient(nil)
- c.SyncCluster()
-
- fo, err := os.Create("config.json")
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- if err := fo.Close(); err != nil {
- panic(err)
- }
- }()
-
- c.SetPersistence(fo)
- err = c.saveConfig()
- if err != nil {
- t.Fatal(err)
- }
-
- c2, err := NewClientFromFile("config.json")
- if err != nil {
- t.Fatal(err)
- }
-
- // Verify that the two clients have the same config
- b1, _ := json.Marshal(c)
- b2, _ := json.Marshal(c2)
-
- if string(b1) != string(b2) {
- t.Fatalf("The two configs should be equal!")
- }
-}
-
-func TestClientRetry(t *testing.T) {
- c := NewClient([]string{"http://strange", "http://127.0.0.1:4001"})
- // use first endpoint as the picked url
- c.cluster.picked = 0
- if _, err := c.Set("foo", "bar", 5); err != nil {
- t.Fatal(err)
- }
- if _, err := c.Delete("foo", true); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go
deleted file mode 100644
index 223e50f29..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_delete_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestCompareAndDelete(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- // This should succeed an correct prevValue
- resp, err := c.CompareAndDelete("foo", "bar", 0)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndDelete 1 prevNode failed: %#v", resp)
- }
-
- resp, _ = c.Set("foo", "bar", 5)
- // This should fail because it gives an incorrect prevValue
- _, err = c.CompareAndDelete("foo", "xxx", 0)
- if err == nil {
- t.Fatalf("CompareAndDelete 2 should have failed. The response is: %#v", resp)
- }
-
- // This should succeed because it gives an correct prevIndex
- resp, err = c.CompareAndDelete("foo", "", resp.Node.ModifiedIndex)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp)
- }
-
- c.Set("foo", "bar", 5)
- // This should fail because it gives an incorrect prevIndex
- resp, err = c.CompareAndDelete("foo", "", 29817514)
- if err == nil {
- t.Fatalf("CompareAndDelete 4 should have failed. The response is: %#v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go
deleted file mode 100644
index 14a1b00f5..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/compare_and_swap_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestCompareAndSwap(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- // This should succeed
- resp, err := c.CompareAndSwap("foo", "bar2", 5, "bar", 0)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("CompareAndSwap 1 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 1 prevNode failed: %#v", resp)
- }
-
- // This should fail because it gives an incorrect prevValue
- resp, err = c.CompareAndSwap("foo", "bar3", 5, "xxx", 0)
- if err == nil {
- t.Fatalf("CompareAndSwap 2 should have failed. The response is: %#v", resp)
- }
-
- resp, err = c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed
- resp, err = c.CompareAndSwap("foo", "bar2", 5, "", resp.Node.ModifiedIndex)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Value == "bar2" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Value == "bar" && resp.PrevNode.Key == "/foo" && resp.PrevNode.TTL == 5) {
- t.Fatalf("CompareAndSwap 3 prevNode failed: %#v", resp)
- }
-
- // This should fail because it gives an incorrect prevIndex
- resp, err = c.CompareAndSwap("foo", "bar3", 5, "", 29817514)
- if err == nil {
- t.Fatalf("CompareAndSwap 4 should have failed. The response is: %#v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go
deleted file mode 100644
index 97f6d1110..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/debug_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-type Foo struct{}
-type Bar struct {
- one string
- two int
-}
-
-// Tests that logs don't panic with arbitrary interfaces
-func TestDebug(t *testing.T) {
- f := &Foo{}
- b := &Bar{"asfd", 3}
- for _, test := range []interface{}{
- 1234,
- "asdf",
- f,
- b,
- } {
- logger.Debug(test)
- logger.Debugf("something, %s", test)
- logger.Warning(test)
- logger.Warningf("something, %s", test)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go
deleted file mode 100644
index 590497155..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/delete_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestDelete(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
- resp, err := c.Delete("foo", false)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("Delete failed with %s", resp.Node.Value)
- }
-
- if !(resp.PrevNode.Value == "bar") {
- t.Fatalf("Delete PrevNode failed with %s", resp.Node.Value)
- }
-
- resp, err = c.Delete("foo", false)
- if err == nil {
- t.Fatalf("Delete should have failed because the key foo did not exist. "+
- "The response was: %v", resp)
- }
-}
-
-func TestDeleteAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("fooDir", true)
- }()
-
- c.SetDir("foo", 5)
- // test delete an empty dir
- resp, err := c.DeleteDir("foo")
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("DeleteAll 1 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") {
- t.Fatalf("DeleteAll 1 PrevNode failed: %#v", resp)
- }
-
- c.CreateDir("fooDir", 5)
- c.Set("fooDir/foo", "bar", 5)
- _, err = c.DeleteDir("fooDir")
- if err == nil {
- t.Fatal("should not able to delete a non-empty dir with deletedir")
- }
-
- resp, err = c.Delete("fooDir", true)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Node.Value == "") {
- t.Fatalf("DeleteAll 2 failed: %#v", resp)
- }
-
- if !(resp.PrevNode.Dir == true && resp.PrevNode.Value == "") {
- t.Fatalf("DeleteAll 2 PrevNode failed: %#v", resp)
- }
-
- resp, err = c.Delete("foo", true)
- if err == nil {
- t.Fatalf("DeleteAll should have failed because the key foo did not exist. "+
- "The response was: %v", resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go
deleted file mode 100644
index 279c4e26f..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/get_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package etcd
-
-import (
- "reflect"
- "testing"
-)
-
-// cleanNode scrubs Expiration, ModifiedIndex and CreatedIndex of a node.
-func cleanNode(n *Node) {
- n.Expiration = nil
- n.ModifiedIndex = 0
- n.CreatedIndex = 0
-}
-
-// cleanResult scrubs a result object two levels deep of Expiration,
-// ModifiedIndex and CreatedIndex.
-func cleanResult(result *Response) {
- // TODO(philips): make this recursive.
- cleanNode(result.Node)
- for i, _ := range result.Node.Nodes {
- cleanNode(result.Node.Nodes[i])
- for j, _ := range result.Node.Nodes[i].Nodes {
- cleanNode(result.Node.Nodes[i].Nodes[j])
- }
- }
-}
-
-func TestGet(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- c.Set("foo", "bar", 5)
-
- result, err := c.Get("foo", false, false)
-
- if err != nil {
- t.Fatal(err)
- }
-
- if result.Node.Key != "/foo" || result.Node.Value != "bar" {
- t.Fatalf("Get failed with %s %s %v", result.Node.Key, result.Node.Value, result.Node.TTL)
- }
-
- result, err = c.Get("goo", false, false)
- if err == nil {
- t.Fatalf("should not be able to get non-exist key")
- }
-}
-
-func TestGetAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- c.CreateDir("fooDir", 5)
- c.Set("fooDir/k0", "v0", 5)
- c.Set("fooDir/k1", "v1", 5)
-
- // Return kv-pairs in sorted order
- result, err := c.Get("fooDir", true, false)
-
- if err != nil {
- t.Fatal(err)
- }
-
- expected := Nodes{
- &Node{
- Key: "/fooDir/k0",
- Value: "v0",
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k1",
- Value: "v1",
- TTL: 5,
- },
- }
-
- cleanResult(result)
-
- if !reflect.DeepEqual(result.Node.Nodes, expected) {
- t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected)
- }
-
- // Test the `recursive` option
- c.CreateDir("fooDir/childDir", 5)
- c.Set("fooDir/childDir/k2", "v2", 5)
-
- // Return kv-pairs in sorted order
- result, err = c.Get("fooDir", true, true)
-
- cleanResult(result)
-
- if err != nil {
- t.Fatal(err)
- }
-
- expected = Nodes{
- &Node{
- Key: "/fooDir/childDir",
- Dir: true,
- Nodes: Nodes{
- &Node{
- Key: "/fooDir/childDir/k2",
- Value: "v2",
- TTL: 5,
- },
- },
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k0",
- Value: "v0",
- TTL: 5,
- },
- &Node{
- Key: "/fooDir/k1",
- Value: "v1",
- TTL: 5,
- },
- }
-
- cleanResult(result)
-
- if !reflect.DeepEqual(result.Node.Nodes, expected) {
- t.Fatalf("(actual) %v != (expected) %v", result.Node.Nodes, expected)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go
deleted file mode 100644
index 53ebdd4bf..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/member_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package etcd
-
-import (
- "encoding/json"
- "reflect"
- "testing"
-)
-
-func TestMemberCollectionUnmarshal(t *testing.T) {
- tests := []struct {
- body []byte
- want memberCollection
- }{
- {
- body: []byte(`{"members":[]}`),
- want: memberCollection([]Member{}),
- },
- {
- body: []byte(`{"members":[{"id":"2745e2525fce8fe","peerURLs":["http://127.0.0.1:7003"],"name":"node3","clientURLs":["http://127.0.0.1:4003"]},{"id":"42134f434382925","peerURLs":["http://127.0.0.1:2380","http://127.0.0.1:7001"],"name":"node1","clientURLs":["http://127.0.0.1:2379","http://127.0.0.1:4001"]},{"id":"94088180e21eb87b","peerURLs":["http://127.0.0.1:7002"],"name":"node2","clientURLs":["http://127.0.0.1:4002"]}]}`),
- want: memberCollection(
- []Member{
- {
- ID: "2745e2525fce8fe",
- Name: "node3",
- PeerURLs: []string{
- "http://127.0.0.1:7003",
- },
- ClientURLs: []string{
- "http://127.0.0.1:4003",
- },
- },
- {
- ID: "42134f434382925",
- Name: "node1",
- PeerURLs: []string{
- "http://127.0.0.1:2380",
- "http://127.0.0.1:7001",
- },
- ClientURLs: []string{
- "http://127.0.0.1:2379",
- "http://127.0.0.1:4001",
- },
- },
- {
- ID: "94088180e21eb87b",
- Name: "node2",
- PeerURLs: []string{
- "http://127.0.0.1:7002",
- },
- ClientURLs: []string{
- "http://127.0.0.1:4002",
- },
- },
- },
- ),
- },
- }
-
- for i, tt := range tests {
- var got memberCollection
- err := json.Unmarshal(tt.body, &got)
- if err != nil {
- t.Errorf("#%d: unexpected error: %v", i, err)
- continue
- }
-
- if !reflect.DeepEqual(tt.want, got) {
- t.Errorf("#%d: incorrect output: want=%#v, got=%#v", i, tt.want, got)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go
deleted file mode 100644
index 7a2bd190a..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/requests_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package etcd
-
-import "testing"
-
-func TestKeyToPath(t *testing.T) {
- tests := []struct {
- key string
- wpath string
- }{
- {"", "keys/"},
- {"foo", "keys/foo"},
- {"foo/bar", "keys/foo/bar"},
- {"%z", "keys/%25z"},
- {"/", "keys/"},
- }
- for i, tt := range tests {
- path := keyToPath(tt.key)
- if path != tt.wpath {
- t.Errorf("#%d: path = %s, want %s", i, path, tt.wpath)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go
deleted file mode 100644
index 87c86b830..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_curl_chan_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package etcd
-
-import (
- "fmt"
- "testing"
-)
-
-func TestSetCurlChan(t *testing.T) {
- c := NewClient(nil)
- c.OpenCURL()
-
- defer func() {
- c.Delete("foo", true)
- }()
-
- _, err := c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- expected := fmt.Sprintf("curl -X PUT %s/v2/keys/foo -d value=bar -d ttl=5",
- c.cluster.pick())
- actual := c.RecvCURL()
- if expected != actual {
- t.Fatalf(`Command "%s" is not equal to expected value "%s"`,
- actual, expected)
- }
-
- c.SetConsistency(STRONG_CONSISTENCY)
- _, err = c.Get("foo", false, false)
- if err != nil {
- t.Fatal(err)
- }
-
- expected = fmt.Sprintf("curl -X GET %s/v2/keys/foo?quorum=true&recursive=false&sorted=false",
- c.cluster.pick())
- actual = c.RecvCURL()
- if expected != actual {
- t.Fatalf(`Command "%s" is not equal to expected value "%s"`,
- actual, expected)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go
deleted file mode 100644
index ced0f06e7..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/set_update_create_test.go
+++ /dev/null
@@ -1,241 +0,0 @@
-package etcd
-
-import (
- "testing"
-)
-
-func TestSet(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- }()
-
- resp, err := c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
- if resp.Node.Key != "/foo" || resp.Node.Value != "bar" || resp.Node.TTL != 5 {
- t.Fatalf("Set 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("Set 1 PrevNode failed: %#v", resp)
- }
-
- resp, err = c.Set("foo", "bar2", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/foo" && resp.Node.Value == "bar2" && resp.Node.TTL == 5) {
- t.Fatalf("Set 2 failed: %#v", resp)
- }
- if resp.PrevNode.Key != "/foo" || resp.PrevNode.Value != "bar" || resp.Node.TTL != 5 {
- t.Fatalf("Set 2 PrevNode failed: %#v", resp)
- }
-}
-
-func TestUpdate(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("nonexistent", true)
- }()
-
- resp, err := c.Set("foo", "bar", 5)
-
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed.
- resp, err = c.Update("foo", "wakawaka", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "update" && resp.Node.Key == "/foo" && resp.Node.TTL == 5) {
- t.Fatalf("Update 1 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.Node.TTL == 5) {
- t.Fatalf("Update 1 prevValue failed: %#v", resp)
- }
-
- // This should fail because the key does not exist.
- resp, err = c.Update("nonexistent", "whatever", 5)
- if err == nil {
- t.Fatalf("The key %v did not exist, so the update should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreate(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("newKey", true)
- }()
-
- newKey := "/newKey"
- newValue := "/newValue"
-
- // This should succeed
- resp, err := c.Create(newKey, newValue, 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Key == newKey &&
- resp.Node.Value == newValue && resp.Node.TTL == 5) {
- t.Fatalf("Create 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("Create 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail, because the key is already there
- resp, err = c.Create(newKey, newValue, 5)
- if err == nil {
- t.Fatalf("The key %v did exist, so the creation should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreateInOrder(t *testing.T) {
- c := NewClient(nil)
- dir := "/queue"
- defer func() {
- c.DeleteDir(dir)
- }()
-
- var firstKey, secondKey string
-
- resp, err := c.CreateInOrder(dir, "1", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Value == "1" && resp.Node.TTL == 5) {
- t.Fatalf("Create 1 failed: %#v", resp)
- }
-
- firstKey = resp.Node.Key
-
- resp, err = c.CreateInOrder(dir, "2", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Value == "2" && resp.Node.TTL == 5) {
- t.Fatalf("Create 2 failed: %#v", resp)
- }
-
- secondKey = resp.Node.Key
-
- if firstKey >= secondKey {
- t.Fatalf("Expected first key to be greater than second key, but %s is not greater than %s",
- firstKey, secondKey)
- }
-}
-
-func TestSetDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("foo", true)
- c.Delete("fooDir", true)
- }()
-
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/fooDir" && resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("SetDir 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("SetDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail because /fooDir already points to a directory
- resp, err = c.CreateDir("/fooDir", 5)
- if err == nil {
- t.Fatalf("fooDir already points to a directory, so SetDir should have failed."+
- "The response was: %#v", resp)
- }
-
- _, err = c.Set("foo", "bar", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed
- // It should replace the key
- resp, err = c.SetDir("foo", 5)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/foo" && resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("SetDir 2 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/foo" && resp.PrevNode.Value == "bar" && resp.PrevNode.TTL == 5) {
- t.Fatalf("SetDir 2 failed: %#v", resp)
- }
-}
-
-func TestUpdateDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- // This should succeed.
- resp, err = c.UpdateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "update" && resp.Node.Key == "/fooDir" &&
- resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("UpdateDir 1 failed: %#v", resp)
- }
- if !(resp.PrevNode.Key == "/fooDir" && resp.PrevNode.Dir == true && resp.PrevNode.TTL == 5) {
- t.Fatalf("UpdateDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail because the key does not exist.
- resp, err = c.UpdateDir("nonexistentDir", 5)
- if err == nil {
- t.Fatalf("The key %v did not exist, so the update should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
-
-func TestCreateDir(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("fooDir", true)
- }()
-
- // This should succeed
- resp, err := c.CreateDir("fooDir", 5)
- if err != nil {
- t.Fatal(err)
- }
-
- if !(resp.Action == "create" && resp.Node.Key == "/fooDir" &&
- resp.Node.Value == "" && resp.Node.TTL == 5) {
- t.Fatalf("CreateDir 1 failed: %#v", resp)
- }
- if resp.PrevNode != nil {
- t.Fatalf("CreateDir 1 PrevNode failed: %#v", resp)
- }
-
- // This should fail, because the key is already there
- resp, err = c.CreateDir("fooDir", 5)
- if err == nil {
- t.Fatalf("The key %v did exist, so the creation should have failed."+
- "The response was: %#v", resp.Node.Key, resp)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go
deleted file mode 100644
index 43e1dfeb8..000000000
--- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/watch_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package etcd
-
-import (
- "fmt"
- "runtime"
- "testing"
- "time"
-)
-
-func TestWatch(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("watch_foo", true)
- }()
-
- go setHelper("watch_foo", "bar", c)
-
- resp, err := c.Watch("watch_foo", 0, false, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") {
- t.Fatalf("Watch 1 failed: %#v", resp)
- }
-
- go setHelper("watch_foo", "bar", c)
-
- resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, false, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo" && resp.Node.Value == "bar") {
- t.Fatalf("Watch 2 failed: %#v", resp)
- }
-
- routineNum := runtime.NumGoroutine()
-
- ch := make(chan *Response, 10)
- stop := make(chan bool, 1)
-
- go setLoop("watch_foo", "bar", c)
-
- go receiver(ch, stop)
-
- _, err = c.Watch("watch_foo", 0, false, ch, stop)
- if err != ErrWatchStoppedByUser {
- t.Fatalf("Watch returned a non-user stop error")
- }
-
- if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum {
- t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum)
- }
-}
-
-func TestWatchAll(t *testing.T) {
- c := NewClient(nil)
- defer func() {
- c.Delete("watch_foo", true)
- }()
-
- go setHelper("watch_foo/foo", "bar", c)
-
- resp, err := c.Watch("watch_foo", 0, true, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") {
- t.Fatalf("WatchAll 1 failed: %#v", resp)
- }
-
- go setHelper("watch_foo/foo", "bar", c)
-
- resp, err = c.Watch("watch_foo", resp.Node.ModifiedIndex+1, true, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
- if !(resp.Node.Key == "/watch_foo/foo" && resp.Node.Value == "bar") {
- t.Fatalf("WatchAll 2 failed: %#v", resp)
- }
-
- ch := make(chan *Response, 10)
- stop := make(chan bool, 1)
-
- routineNum := runtime.NumGoroutine()
-
- go setLoop("watch_foo/foo", "bar", c)
-
- go receiver(ch, stop)
-
- _, err = c.Watch("watch_foo", 0, true, ch, stop)
- if err != ErrWatchStoppedByUser {
- t.Fatalf("Watch returned a non-user stop error")
- }
-
- if newRoutineNum := runtime.NumGoroutine(); newRoutineNum != routineNum {
- t.Fatalf("Routine numbers differ after watch stop: %v, %v", routineNum, newRoutineNum)
- }
-}
-
-func setHelper(key, value string, c *Client) {
- time.Sleep(time.Second)
- c.Set(key, value, 100)
-}
-
-func setLoop(key, value string, c *Client) {
- time.Sleep(time.Second)
- for i := 0; i < 10; i++ {
- newValue := fmt.Sprintf("%s_%v", value, i)
- c.Set(key, newValue, 100)
- time.Sleep(time.Second / 10)
- }
-}
-
-func receiver(c chan *Response, stop chan bool) {
- for i := 0; i < 10; i++ {
- <-c
- }
- stop <- true
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/client_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/client_test.go
deleted file mode 100644
index 6a2c96f71..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/client_test.go
+++ /dev/null
@@ -1,107 +0,0 @@
-package plugins
-
-import (
- "io"
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
- "time"
-
- "github.com/docker/docker/pkg/tlsconfig"
-)
-
-var (
- mux *http.ServeMux
- server *httptest.Server
-)
-
-func setupRemotePluginServer() string {
- mux = http.NewServeMux()
- server = httptest.NewServer(mux)
- return server.URL
-}
-
-func teardownRemotePluginServer() {
- if server != nil {
- server.Close()
- }
-}
-
-func TestFailedConnection(t *testing.T) {
- c, _ := NewClient("tcp://127.0.0.1:1", tlsconfig.Options{InsecureSkipVerify: true})
- err := c.callWithRetry("Service.Method", nil, nil, false)
- if err == nil {
- t.Fatal("Unexpected successful connection")
- }
-}
-
-func TestEchoInputOutput(t *testing.T) {
- addr := setupRemotePluginServer()
- defer teardownRemotePluginServer()
-
- m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}}
-
- mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != "POST" {
- t.Fatalf("Expected POST, got %s\n", r.Method)
- }
-
- header := w.Header()
- header.Set("Content-Type", versionMimetype)
-
- io.Copy(w, r.Body)
- })
-
- c, _ := NewClient(addr, tlsconfig.Options{InsecureSkipVerify: true})
- var output Manifest
- err := c.Call("Test.Echo", m, &output)
- if err != nil {
- t.Fatal(err)
- }
-
- if !reflect.DeepEqual(output, m) {
- t.Fatalf("Expected %v, was %v\n", m, output)
- }
-}
-
-func TestBackoff(t *testing.T) {
- cases := []struct {
- retries int
- expTimeOff time.Duration
- }{
- {0, time.Duration(1)},
- {1, time.Duration(2)},
- {2, time.Duration(4)},
- {4, time.Duration(16)},
- {6, time.Duration(30)},
- {10, time.Duration(30)},
- }
-
- for _, c := range cases {
- s := c.expTimeOff * time.Second
- if d := backoff(c.retries); d != s {
- t.Fatalf("Retry %v, expected %v, was %v\n", c.retries, s, d)
- }
- }
-}
-
-func TestAbortRetry(t *testing.T) {
- cases := []struct {
- timeOff time.Duration
- expAbort bool
- }{
- {time.Duration(1), false},
- {time.Duration(2), false},
- {time.Duration(10), false},
- {time.Duration(30), true},
- {time.Duration(40), true},
- }
-
- for _, c := range cases {
- s := c.timeOff * time.Second
- if a := abort(time.Now(), s); a != c.expAbort {
- t.Fatalf("Duration %v, expected %v, was %v\n", c.timeOff, s, a)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/discovery_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/discovery_test.go
deleted file mode 100644
index 5610fe1e9..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/discovery_test.go
+++ /dev/null
@@ -1,169 +0,0 @@
-package plugins
-
-import (
- "fmt"
- "io/ioutil"
- "net"
- "os"
- "path/filepath"
- "reflect"
- "testing"
-)
-
-func setup(t *testing.T) (string, func()) {
- tmpdir, err := ioutil.TempDir("", "docker-test")
- if err != nil {
- t.Fatal(err)
- }
- backup := socketsPath
- socketsPath = tmpdir
- specsPaths = []string{tmpdir}
-
- return tmpdir, func() {
- socketsPath = backup
- os.RemoveAll(tmpdir)
- }
-}
-
-func TestLocalSocket(t *testing.T) {
- tmpdir, unregister := setup(t)
- defer unregister()
-
- cases := []string{
- filepath.Join(tmpdir, "echo.sock"),
- filepath.Join(tmpdir, "echo", "echo.sock"),
- }
-
- for _, c := range cases {
- if err := os.MkdirAll(filepath.Dir(c), 0755); err != nil {
- t.Fatal(err)
- }
-
- l, err := net.Listen("unix", c)
- if err != nil {
- t.Fatal(err)
- }
-
- r := newLocalRegistry()
- p, err := r.Plugin("echo")
- if err != nil {
- t.Fatal(err)
- }
-
- pp, err := r.Plugin("echo")
- if err != nil {
- t.Fatal(err)
- }
- if !reflect.DeepEqual(p, pp) {
- t.Fatalf("Expected %v, was %v\n", p, pp)
- }
-
- if p.Name != "echo" {
- t.Fatalf("Expected plugin `echo`, got %s\n", p.Name)
- }
-
- addr := fmt.Sprintf("unix://%s", c)
- if p.Addr != addr {
- t.Fatalf("Expected plugin addr `%s`, got %s\n", addr, p.Addr)
- }
- if p.TLSConfig.InsecureSkipVerify != true {
- t.Fatalf("Expected TLS verification to be skipped")
- }
- l.Close()
- }
-}
-
-func TestFileSpecPlugin(t *testing.T) {
- tmpdir, unregister := setup(t)
- defer unregister()
-
- cases := []struct {
- path string
- name string
- addr string
- fail bool
- }{
- {filepath.Join(tmpdir, "echo.spec"), "echo", "unix://var/lib/docker/plugins/echo.sock", false},
- {filepath.Join(tmpdir, "echo", "echo.spec"), "echo", "unix://var/lib/docker/plugins/echo.sock", false},
- {filepath.Join(tmpdir, "foo.spec"), "foo", "tcp://localhost:8080", false},
- {filepath.Join(tmpdir, "foo", "foo.spec"), "foo", "tcp://localhost:8080", false},
- {filepath.Join(tmpdir, "bar.spec"), "bar", "localhost:8080", true}, // unknown transport
- }
-
- for _, c := range cases {
- if err := os.MkdirAll(filepath.Dir(c.path), 0755); err != nil {
- t.Fatal(err)
- }
- if err := ioutil.WriteFile(c.path, []byte(c.addr), 0644); err != nil {
- t.Fatal(err)
- }
-
- r := newLocalRegistry()
- p, err := r.Plugin(c.name)
- if c.fail && err == nil {
- continue
- }
-
- if err != nil {
- t.Fatal(err)
- }
-
- if p.Name != c.name {
- t.Fatalf("Expected plugin `%s`, got %s\n", c.name, p.Name)
- }
-
- if p.Addr != c.addr {
- t.Fatalf("Expected plugin addr `%s`, got %s\n", c.addr, p.Addr)
- }
-
- if p.TLSConfig.InsecureSkipVerify != true {
- t.Fatalf("Expected TLS verification to be skipped")
- }
- }
-}
-
-func TestFileJSONSpecPlugin(t *testing.T) {
- tmpdir, unregister := setup(t)
- defer unregister()
-
- p := filepath.Join(tmpdir, "example.json")
- spec := `{
- "Name": "plugin-example",
- "Addr": "https://example.com/docker/plugin",
- "TLSConfig": {
- "CAFile": "/usr/shared/docker/certs/example-ca.pem",
- "CertFile": "/usr/shared/docker/certs/example-cert.pem",
- "KeyFile": "/usr/shared/docker/certs/example-key.pem"
- }
-}`
-
- if err := ioutil.WriteFile(p, []byte(spec), 0644); err != nil {
- t.Fatal(err)
- }
-
- r := newLocalRegistry()
- plugin, err := r.Plugin("example")
- if err != nil {
- t.Fatal(err)
- }
-
- if plugin.Name != "example" {
- t.Fatalf("Expected plugin `plugin-example`, got %s\n", plugin.Name)
- }
-
- if plugin.Addr != "https://example.com/docker/plugin" {
- t.Fatalf("Expected plugin addr `https://example.com/docker/plugin`, got %s\n", plugin.Addr)
- }
-
- if plugin.TLSConfig.CAFile != "/usr/shared/docker/certs/example-ca.pem" {
- t.Fatalf("Expected plugin CA `/usr/shared/docker/certs/example-ca.pem`, got %s\n", plugin.TLSConfig.CAFile)
- }
-
- if plugin.TLSConfig.CertFile != "/usr/shared/docker/certs/example-cert.pem" {
- t.Fatalf("Expected plugin Certificate `/usr/shared/docker/certs/example-cert.pem`, got %s\n", plugin.TLSConfig.CertFile)
- }
-
- if plugin.TLSConfig.KeyFile != "/usr/shared/docker/certs/example-key.pem" {
- t.Fatalf("Expected plugin Key `/usr/shared/docker/certs/example-key.pem`, got %s\n", plugin.TLSConfig.KeyFile)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/fixtures/foo.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/fixtures/foo.go
deleted file mode 100644
index 4e73fc10e..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/fixtures/foo.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package foo
-
-type wobble struct {
- Some string
- Val string
- Inception *wobble
-}
-
-type Fooer interface{}
-
-type Fooer2 interface {
- Foo()
-}
-
-type Fooer3 interface {
- Foo()
- Bar(a string)
- Baz(a string) (err error)
- Qux(a, b string) (val string, err error)
- Wobble() (w *wobble)
- Wiggle() (w wobble)
-}
-
-type Fooer4 interface {
- Foo() error
-}
-
-type Bar interface {
- Boo(a string, b string) (s string, err error)
-}
-
-type Fooer5 interface {
- Foo()
- Bar
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/main.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/main.go
deleted file mode 100644
index 2130af124..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/main.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package main
-
-import (
- "bytes"
- "flag"
- "fmt"
- "go/format"
- "io/ioutil"
- "os"
- "unicode"
- "unicode/utf8"
-)
-
-type stringSet struct {
- values map[string]struct{}
-}
-
-func (s stringSet) String() string {
- return ""
-}
-
-func (s stringSet) Set(value string) error {
- s.values[value] = struct{}{}
- return nil
-}
-func (s stringSet) GetValues() map[string]struct{} {
- return s.values
-}
-
-var (
- typeName = flag.String("type", "", "interface type to generate plugin rpc proxy for")
- rpcName = flag.String("name", *typeName, "RPC name, set if different from type")
- inputFile = flag.String("i", "", "input file path")
- outputFile = flag.String("o", *inputFile+"_proxy.go", "output file path")
-
- skipFuncs map[string]struct{}
- flSkipFuncs = stringSet{make(map[string]struct{})}
-
- flBuildTags = stringSet{make(map[string]struct{})}
-)
-
-func errorOut(msg string, err error) {
- if err == nil {
- return
- }
- fmt.Fprintf(os.Stderr, "%s: %v\n", msg, err)
- os.Exit(1)
-}
-
-func checkFlags() error {
- if *outputFile == "" {
- return fmt.Errorf("missing required flag `-o`")
- }
- if *inputFile == "" {
- return fmt.Errorf("missing required flag `-i`")
- }
- return nil
-}
-
-func main() {
- flag.Var(flSkipFuncs, "skip", "skip parsing for function")
- flag.Var(flBuildTags, "tag", "build tags to add to generated files")
- flag.Parse()
- skipFuncs = flSkipFuncs.GetValues()
-
- errorOut("error", checkFlags())
-
- pkg, err := Parse(*inputFile, *typeName)
- errorOut(fmt.Sprintf("error parsing requested type %s", *typeName), err)
-
- var analysis = struct {
- InterfaceType string
- RPCName string
- BuildTags map[string]struct{}
- *parsedPkg
- }{toLower(*typeName), *rpcName, flBuildTags.GetValues(), pkg}
- var buf bytes.Buffer
-
- errorOut("parser error", generatedTempl.Execute(&buf, analysis))
- src, err := format.Source(buf.Bytes())
- errorOut("error formating generated source", err)
- errorOut("error writing file", ioutil.WriteFile(*outputFile, src, 0644))
-}
-
-func toLower(s string) string {
- if s == "" {
- return ""
- }
- r, n := utf8.DecodeRuneInString(s)
- return string(unicode.ToLower(r)) + s[n:]
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser.go
deleted file mode 100644
index b9746f878..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package main
-
-import (
- "errors"
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "reflect"
- "strings"
-)
-
-var ErrBadReturn = errors.New("found return arg with no name: all args must be named")
-
-type ErrUnexpectedType struct {
- expected string
- actual interface{}
-}
-
-func (e ErrUnexpectedType) Error() string {
- return fmt.Sprintf("got wrong type expecting %s, got: %v", e.expected, reflect.TypeOf(e.actual))
-}
-
-type parsedPkg struct {
- Name string
- Functions []function
-}
-
-type function struct {
- Name string
- Args []arg
- Returns []arg
- Doc string
-}
-
-type arg struct {
- Name string
- ArgType string
-}
-
-func (a *arg) String() string {
- return strings.ToLower(a.Name) + " " + strings.ToLower(a.ArgType)
-}
-
-// Parses the given file for an interface definition with the given name
-func Parse(filePath string, objName string) (*parsedPkg, error) {
- fs := token.NewFileSet()
- pkg, err := parser.ParseFile(fs, filePath, nil, parser.AllErrors)
- if err != nil {
- return nil, err
- }
- p := &parsedPkg{}
- p.Name = pkg.Name.Name
- obj, exists := pkg.Scope.Objects[objName]
- if !exists {
- return nil, fmt.Errorf("could not find object %s in %s", objName, filePath)
- }
- if obj.Kind != ast.Typ {
- return nil, fmt.Errorf("exected type, got %s", obj.Kind)
- }
- spec, ok := obj.Decl.(*ast.TypeSpec)
- if !ok {
- return nil, ErrUnexpectedType{"*ast.TypeSpec", obj.Decl}
- }
- iface, ok := spec.Type.(*ast.InterfaceType)
- if !ok {
- return nil, ErrUnexpectedType{"*ast.InterfaceType", spec.Type}
- }
-
- p.Functions, err = parseInterface(iface)
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-func parseInterface(iface *ast.InterfaceType) ([]function, error) {
- var functions []function
- for _, field := range iface.Methods.List {
- switch f := field.Type.(type) {
- case *ast.FuncType:
- method, err := parseFunc(field)
- if err != nil {
- return nil, err
- }
- if method == nil {
- continue
- }
- functions = append(functions, *method)
- case *ast.Ident:
- spec, ok := f.Obj.Decl.(*ast.TypeSpec)
- if !ok {
- return nil, ErrUnexpectedType{"*ast.TypeSpec", f.Obj.Decl}
- }
- iface, ok := spec.Type.(*ast.InterfaceType)
- if !ok {
- return nil, ErrUnexpectedType{"*ast.TypeSpec", spec.Type}
- }
- funcs, err := parseInterface(iface)
- if err != nil {
- fmt.Println(err)
- continue
- }
- functions = append(functions, funcs...)
- default:
- return nil, ErrUnexpectedType{"*astFuncType or *ast.Ident", f}
- }
- }
- return functions, nil
-}
-
-func parseFunc(field *ast.Field) (*function, error) {
- f := field.Type.(*ast.FuncType)
- method := &function{Name: field.Names[0].Name}
- if _, exists := skipFuncs[method.Name]; exists {
- fmt.Println("skipping:", method.Name)
- return nil, nil
- }
- if f.Params != nil {
- args, err := parseArgs(f.Params.List)
- if err != nil {
- return nil, err
- }
- method.Args = args
- }
- if f.Results != nil {
- returns, err := parseArgs(f.Results.List)
- if err != nil {
- return nil, fmt.Errorf("error parsing function returns for %q: %v", method.Name, err)
- }
- method.Returns = returns
- }
- return method, nil
-}
-
-func parseArgs(fields []*ast.Field) ([]arg, error) {
- var args []arg
- for _, f := range fields {
- if len(f.Names) == 0 {
- return nil, ErrBadReturn
- }
- for _, name := range f.Names {
- var typeName string
- switch argType := f.Type.(type) {
- case *ast.Ident:
- typeName = argType.Name
- case *ast.StarExpr:
- i, ok := argType.X.(*ast.Ident)
- if !ok {
- return nil, ErrUnexpectedType{"*ast.Ident", f.Type}
- }
- typeName = "*" + i.Name
- default:
- return nil, ErrUnexpectedType{"*ast.Ident or *ast.StarExpr", f.Type}
- }
-
- args = append(args, arg{name.Name, typeName})
- }
- }
- return args, nil
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser_test.go
deleted file mode 100644
index 6c5665fe2..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package main
-
-import (
- "fmt"
- "path/filepath"
- "runtime"
- "strings"
- "testing"
-)
-
-const testFixture = "fixtures/foo.go"
-
-func TestParseEmptyInterface(t *testing.T) {
- pkg, err := Parse(testFixture, "Fooer")
- if err != nil {
- t.Fatal(err)
- }
-
- assertName(t, "foo", pkg.Name)
- assertNum(t, 0, len(pkg.Functions))
-}
-
-func TestParseNonInterfaceType(t *testing.T) {
- _, err := Parse(testFixture, "wobble")
- if _, ok := err.(ErrUnexpectedType); !ok {
- t.Fatal("expected type error when parsing non-interface type")
- }
-}
-
-func TestParseWithOneFunction(t *testing.T) {
- pkg, err := Parse(testFixture, "Fooer2")
- if err != nil {
- t.Fatal(err)
- }
-
- assertName(t, "foo", pkg.Name)
- assertNum(t, 1, len(pkg.Functions))
- assertName(t, "Foo", pkg.Functions[0].Name)
- assertNum(t, 0, len(pkg.Functions[0].Args))
- assertNum(t, 0, len(pkg.Functions[0].Returns))
-}
-
-func TestParseWithMultipleFuncs(t *testing.T) {
- pkg, err := Parse(testFixture, "Fooer3")
- if err != nil {
- t.Fatal(err)
- }
-
- assertName(t, "foo", pkg.Name)
- assertNum(t, 6, len(pkg.Functions))
-
- f := pkg.Functions[0]
- assertName(t, "Foo", f.Name)
- assertNum(t, 0, len(f.Args))
- assertNum(t, 0, len(f.Returns))
-
- f = pkg.Functions[1]
- assertName(t, "Bar", f.Name)
- assertNum(t, 1, len(f.Args))
- assertNum(t, 0, len(f.Returns))
- arg := f.Args[0]
- assertName(t, "a", arg.Name)
- assertName(t, "string", arg.ArgType)
-
- f = pkg.Functions[2]
- assertName(t, "Baz", f.Name)
- assertNum(t, 1, len(f.Args))
- assertNum(t, 1, len(f.Returns))
- arg = f.Args[0]
- assertName(t, "a", arg.Name)
- assertName(t, "string", arg.ArgType)
- arg = f.Returns[0]
- assertName(t, "err", arg.Name)
- assertName(t, "error", arg.ArgType)
-
- f = pkg.Functions[3]
- assertName(t, "Qux", f.Name)
- assertNum(t, 2, len(f.Args))
- assertNum(t, 2, len(f.Returns))
- arg = f.Args[0]
- assertName(t, "a", f.Args[0].Name)
- assertName(t, "string", f.Args[0].ArgType)
- arg = f.Args[1]
- assertName(t, "b", arg.Name)
- assertName(t, "string", arg.ArgType)
- arg = f.Returns[0]
- assertName(t, "val", arg.Name)
- assertName(t, "string", arg.ArgType)
- arg = f.Returns[1]
- assertName(t, "err", arg.Name)
- assertName(t, "error", arg.ArgType)
-
- f = pkg.Functions[4]
- assertName(t, "Wobble", f.Name)
- assertNum(t, 0, len(f.Args))
- assertNum(t, 1, len(f.Returns))
- arg = f.Returns[0]
- assertName(t, "w", arg.Name)
- assertName(t, "*wobble", arg.ArgType)
-
- f = pkg.Functions[5]
- assertName(t, "Wiggle", f.Name)
- assertNum(t, 0, len(f.Args))
- assertNum(t, 1, len(f.Returns))
- arg = f.Returns[0]
- assertName(t, "w", arg.Name)
- assertName(t, "wobble", arg.ArgType)
-}
-
-func TestParseWithUnamedReturn(t *testing.T) {
- _, err := Parse(testFixture, "Fooer4")
- if !strings.HasSuffix(err.Error(), ErrBadReturn.Error()) {
- t.Fatalf("expected ErrBadReturn, got %v", err)
- }
-}
-
-func TestEmbeddedInterface(t *testing.T) {
- pkg, err := Parse(testFixture, "Fooer5")
- if err != nil {
- t.Fatal(err)
- }
-
- assertName(t, "foo", pkg.Name)
- assertNum(t, 2, len(pkg.Functions))
-
- f := pkg.Functions[0]
- assertName(t, "Foo", f.Name)
- assertNum(t, 0, len(f.Args))
- assertNum(t, 0, len(f.Returns))
-
- f = pkg.Functions[1]
- assertName(t, "Boo", f.Name)
- assertNum(t, 2, len(f.Args))
- assertNum(t, 2, len(f.Returns))
-
- arg := f.Args[0]
- assertName(t, "a", arg.Name)
- assertName(t, "string", arg.ArgType)
-
- arg = f.Args[1]
- assertName(t, "b", arg.Name)
- assertName(t, "string", arg.ArgType)
-
- arg = f.Returns[0]
- assertName(t, "s", arg.Name)
- assertName(t, "string", arg.ArgType)
-
- arg = f.Returns[1]
- assertName(t, "err", arg.Name)
- assertName(t, "error", arg.ArgType)
-}
-
-func assertName(t *testing.T, expected, actual string) {
- if expected != actual {
- fatalOut(t, fmt.Sprintf("expected name to be `%s`, got: %s", expected, actual))
- }
-}
-
-func assertNum(t *testing.T, expected, actual int) {
- if expected != actual {
- fatalOut(t, fmt.Sprintf("expected number to be %d, got: %d", expected, actual))
- }
-}
-
-func fatalOut(t *testing.T, msg string) {
- _, file, ln, _ := runtime.Caller(2)
- t.Fatalf("%s:%d: %s", filepath.Base(file), ln, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/template.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/template.go
deleted file mode 100644
index 704030cf0..000000000
--- a/Godeps/_workspace/src/github.com/docker/docker/pkg/plugins/pluginrpc-gen/template.go
+++ /dev/null
@@ -1,97 +0,0 @@
-package main
-
-import (
- "strings"
- "text/template"
-)
-
-func printArgs(args []arg) string {
- var argStr []string
- for _, arg := range args {
- argStr = append(argStr, arg.String())
- }
- return strings.Join(argStr, ", ")
-}
-
-func marshalType(t string) string {
- switch t {
- case "error":
- // convert error types to plain strings to ensure the values are encoded/decoded properly
- return "string"
- default:
- return t
- }
-}
-
-func isErr(t string) bool {
- switch t {
- case "error":
- return true
- default:
- return false
- }
-}
-
-// Need to use this helper due to issues with go-vet
-func buildTag(s string) string {
- return "+build " + s
-}
-
-var templFuncs = template.FuncMap{
- "printArgs": printArgs,
- "marshalType": marshalType,
- "isErr": isErr,
- "lower": strings.ToLower,
- "title": strings.Title,
- "tag": buildTag,
-}
-
-var generatedTempl = template.Must(template.New("rpc_cient").Funcs(templFuncs).Parse(`
-// generated code - DO NOT EDIT
-{{ range $k, $v := .BuildTags }}
- // {{ tag $k }} {{ end }}
-
-package {{ .Name }}
-
-import "errors"
-
-type client interface{
- Call(string, interface{}, interface{}) error
-}
-
-type {{ .InterfaceType }}Proxy struct {
- client
-}
-
-{{ range .Functions }}
- type {{ $.InterfaceType }}Proxy{{ .Name }}Request struct{
- {{ range .Args }}
- {{ title .Name }} {{ .ArgType }} {{ end }}
- }
-
- type {{ $.InterfaceType }}Proxy{{ .Name }}Response struct{
- {{ range .Returns }}
- {{ title .Name }} {{ marshalType .ArgType }} {{ end }}
- }
-
- func (pp *{{ $.InterfaceType }}Proxy) {{ .Name }}({{ printArgs .Args }}) ({{ printArgs .Returns }}) {
- var(
- req {{ $.InterfaceType }}Proxy{{ .Name }}Request
- ret {{ $.InterfaceType }}Proxy{{ .Name }}Response
- )
- {{ range .Args }}
- req.{{ title .Name }} = {{ lower .Name }} {{ end }}
- if err = pp.Call("{{ $.RPCName }}.{{ .Name }}", req, &ret); err != nil {
- return
- }
- {{ range $r := .Returns }}
- {{ if isErr .ArgType }}
- if ret.{{ title .Name }} != "" {
- {{ lower .Name }} = errors.New(ret.{{ title .Name }})
- } {{ end }}
- {{ if isErr .ArgType | not }} {{ lower .Name }} = ret.{{ title .Name }} {{ end }} {{ end }}
-
- return
- }
-{{ end }}
-`))
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
deleted file mode 100644
index 37c778209..000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
+++ /dev/null
@@ -1,122 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: proto3_proto/proto3.proto
-// DO NOT EDIT!
-
-/*
-Package proto3_proto is a generated protocol buffer package.
-
-It is generated from these files:
- proto3_proto/proto3.proto
-
-It has these top-level messages:
- Message
- Nested
- MessageWithMap
-*/
-package proto3_proto
-
-import proto "github.com/golang/protobuf/proto"
-import testdata "github.com/golang/protobuf/proto/testdata"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-
-type Message_Humour int32
-
-const (
- Message_UNKNOWN Message_Humour = 0
- Message_PUNS Message_Humour = 1
- Message_SLAPSTICK Message_Humour = 2
- Message_BILL_BAILEY Message_Humour = 3
-)
-
-var Message_Humour_name = map[int32]string{
- 0: "UNKNOWN",
- 1: "PUNS",
- 2: "SLAPSTICK",
- 3: "BILL_BAILEY",
-}
-var Message_Humour_value = map[string]int32{
- "UNKNOWN": 0,
- "PUNS": 1,
- "SLAPSTICK": 2,
- "BILL_BAILEY": 3,
-}
-
-func (x Message_Humour) String() string {
- return proto.EnumName(Message_Humour_name, int32(x))
-}
-
-type Message struct {
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"`
- HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm" json:"height_in_cm,omitempty"`
- Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
- ResultCount int64 `protobuf:"varint,7,opt,name=result_count" json:"result_count,omitempty"`
- TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman" json:"true_scotsman,omitempty"`
- Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"`
- Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"`
- Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"`
- Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"`
- Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
-}
-
-func (m *Message) Reset() { *m = Message{} }
-func (m *Message) String() string { return proto.CompactTextString(m) }
-func (*Message) ProtoMessage() {}
-
-func (m *Message) GetNested() *Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *Message) GetTerrain() map[string]*Nested {
- if m != nil {
- return m.Terrain
- }
- return nil
-}
-
-func (m *Message) GetProto2Field() *testdata.SubDefaults {
- if m != nil {
- return m.Proto2Field
- }
- return nil
-}
-
-func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults {
- if m != nil {
- return m.Proto2Value
- }
- return nil
-}
-
-type Nested struct {
- Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"`
-}
-
-func (m *Nested) Reset() { *m = Nested{} }
-func (m *Nested) String() string { return proto.CompactTextString(m) }
-func (*Nested) ProtoMessage() {}
-
-type MessageWithMap struct {
- ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
-}
-
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
-
-func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
- if m != nil {
- return m.ByteMapping
- }
- return nil
-}
-
-func init() {
- proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value)
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
deleted file mode 100644
index e2311d929..000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
+++ /dev/null
@@ -1,68 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-import "testdata/test.proto";
-
-package proto3_proto;
-
-message Message {
- enum Humour {
- UNKNOWN = 0;
- PUNS = 1;
- SLAPSTICK = 2;
- BILL_BAILEY = 3;
- }
-
- string name = 1;
- Humour hilarity = 2;
- uint32 height_in_cm = 3;
- bytes data = 4;
- int64 result_count = 7;
- bool true_scotsman = 8;
- float score = 9;
-
- repeated uint64 key = 5;
- Nested nested = 6;
-
- map terrain = 10;
- testdata.SubDefaults proto2_field = 11;
- map proto2_value = 13;
-}
-
-message Nested {
- string bunny = 1;
-}
-
-message MessageWithMap {
- map byte_mapping = 1;
-}
diff --git a/Godeps/_workspace/src/github.com/gorilla/context/context_test.go b/Godeps/_workspace/src/github.com/gorilla/context/context_test.go
deleted file mode 100644
index 9814c501e..000000000
--- a/Godeps/_workspace/src/github.com/gorilla/context/context_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package context
-
-import (
- "net/http"
- "testing"
-)
-
-type keyType int
-
-const (
- key1 keyType = iota
- key2
-)
-
-func TestContext(t *testing.T) {
- assertEqual := func(val interface{}, exp interface{}) {
- if val != exp {
- t.Errorf("Expected %v, got %v.", exp, val)
- }
- }
-
- r, _ := http.NewRequest("GET", "http://localhost:8080/", nil)
- emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil)
-
- // Get()
- assertEqual(Get(r, key1), nil)
-
- // Set()
- Set(r, key1, "1")
- assertEqual(Get(r, key1), "1")
- assertEqual(len(data[r]), 1)
-
- Set(r, key2, "2")
- assertEqual(Get(r, key2), "2")
- assertEqual(len(data[r]), 2)
-
- //GetOk
- value, ok := GetOk(r, key1)
- assertEqual(value, "1")
- assertEqual(ok, true)
-
- value, ok = GetOk(r, "not exists")
- assertEqual(value, nil)
- assertEqual(ok, false)
-
- Set(r, "nil value", nil)
- value, ok = GetOk(r, "nil value")
- assertEqual(value, nil)
- assertEqual(ok, true)
-
- // GetAll()
- values := GetAll(r)
- assertEqual(len(values), 3)
-
- // GetAll() for empty request
- values = GetAll(emptyR)
- if values != nil {
- t.Error("GetAll didn't return nil value for invalid request")
- }
-
- // GetAllOk()
- values, ok = GetAllOk(r)
- assertEqual(len(values), 3)
- assertEqual(ok, true)
-
- // GetAllOk() for empty request
- values, ok = GetAllOk(emptyR)
- assertEqual(value, nil)
- assertEqual(ok, false)
-
- // Delete()
- Delete(r, key1)
- assertEqual(Get(r, key1), nil)
- assertEqual(len(data[r]), 2)
-
- Delete(r, key2)
- assertEqual(Get(r, key2), nil)
- assertEqual(len(data[r]), 1)
-
- // Clear()
- Clear(r)
- assertEqual(len(data), 0)
-}
-
-func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) {
- <-wait
- for i := 0; i < iterations; i++ {
- Get(r, key)
- }
- done <- struct{}{}
-
-}
-
-func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) {
- <-wait
- for i := 0; i < iterations; i++ {
- Set(r, key, value)
- }
- done <- struct{}{}
-
-}
-
-func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) {
-
- b.StopTimer()
- r, _ := http.NewRequest("GET", "http://localhost:8080/", nil)
- done := make(chan struct{})
- b.StartTimer()
-
- for i := 0; i < b.N; i++ {
- wait := make(chan struct{})
-
- for i := 0; i < numReaders; i++ {
- go parallelReader(r, "test", iterations, wait, done)
- }
-
- for i := 0; i < numWriters; i++ {
- go parallelWriter(r, "test", "123", iterations, wait, done)
- }
-
- close(wait)
-
- for i := 0; i < numReaders+numWriters; i++ {
- <-done
- }
-
- }
-
-}
-
-func BenchmarkMutexSameReadWrite1(b *testing.B) {
- benchmarkMutex(b, 1, 1, 32)
-}
-func BenchmarkMutexSameReadWrite2(b *testing.B) {
- benchmarkMutex(b, 2, 2, 32)
-}
-func BenchmarkMutexSameReadWrite4(b *testing.B) {
- benchmarkMutex(b, 4, 4, 32)
-}
-func BenchmarkMutex1(b *testing.B) {
- benchmarkMutex(b, 2, 8, 32)
-}
-func BenchmarkMutex2(b *testing.B) {
- benchmarkMutex(b, 16, 4, 64)
-}
-func BenchmarkMutex3(b *testing.B) {
- benchmarkMutex(b, 1, 2, 128)
-}
-func BenchmarkMutex4(b *testing.B) {
- benchmarkMutex(b, 128, 32, 256)
-}
-func BenchmarkMutex5(b *testing.B) {
- benchmarkMutex(b, 1024, 2048, 64)
-}
-func BenchmarkMutex6(b *testing.B) {
- benchmarkMutex(b, 2048, 1024, 512)
-}
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go
deleted file mode 100644
index c5f97b2b2..000000000
--- a/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2012 The Gorilla 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 mux
-
-import (
- "net/http"
- "testing"
-)
-
-func BenchmarkMux(b *testing.B) {
- router := new(Router)
- handler := func(w http.ResponseWriter, r *http.Request) {}
- router.HandleFunc("/v1/{v1}", handler)
-
- request, _ := http.NewRequest("GET", "/v1/anything", nil)
- for i := 0; i < b.N; i++ {
- router.ServeHTTP(nil, request)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
deleted file mode 100644
index 075dedba4..000000000
--- a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go
+++ /dev/null
@@ -1,1003 +0,0 @@
-// Copyright 2012 The Gorilla 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 mux
-
-import (
- "fmt"
- "net/http"
- "testing"
-
- "github.com/gorilla/context"
-)
-
-type routeTest struct {
- title string // title of the test
- route *Route // the route being tested
- request *http.Request // a request to test the route
- vars map[string]string // the expected vars of the match
- host string // the expected host of the match
- path string // the expected path of the match
- shouldMatch bool // whether the request is expected to match the route at all
- shouldRedirect bool // whether the request should result in a redirect
-}
-
-func TestHost(t *testing.T) {
- // newRequestHost a new request with a method, url, and host header
- newRequestHost := func(method, url, host string) *http.Request {
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- panic(err)
- }
- req.Host = host
- return req
- }
-
- tests := []routeTest{
- {
- title: "Host route match",
- route: new(Route).Host("aaa.bbb.ccc"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host route, wrong host in request URL",
- route: new(Route).Host("aaa.bbb.ccc"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Host route with port, match",
- route: new(Route).Host("aaa.bbb.ccc:1234"),
- request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc:1234",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host route with port, wrong port in request URL",
- route: new(Route).Host("aaa.bbb.ccc:1234"),
- request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc:1234",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Host route, match with host in request header",
- route: new(Route).Host("aaa.bbb.ccc"),
- request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host route, wrong host in request header",
- route: new(Route).Host("aaa.bbb.ccc"),
- request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
- },
- // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true},
- {
- title: "Host route with port, wrong host in request header",
- route: new(Route).Host("aaa.bbb.ccc:1234"),
- request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"),
- vars: map[string]string{},
- host: "aaa.bbb.ccc:1234",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Host route with pattern, match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host route with pattern, wrong host in request URL",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Host route with multiple patterns, match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host route with multiple patterns, wrong host in request URL",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/a"),
- vars: map[string]string{"category": "a"},
- host: "",
- path: "/a",
- shouldMatch: true,
- },
- {
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/b/c"),
- vars: map[string]string{"category": "b/c"},
- host: "",
- path: "/b/c",
- shouldMatch: true,
- },
- {
- title: "Path route with multiple patterns with pipe, match",
- route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
- request: newRequest("GET", "http://localhost/a/product_name/1"),
- vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
- host: "",
- path: "/a/product_name/1",
- shouldMatch: true,
- },
- }
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestPath(t *testing.T) {
- tests := []routeTest{
- {
- title: "Path route, match",
- route: new(Route).Path("/111/222/333"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "/111/222/333",
- shouldMatch: true,
- },
- {
- title: "Path route, match with trailing slash in request and path",
- route: new(Route).Path("/111/"),
- request: newRequest("GET", "http://localhost/111/"),
- vars: map[string]string{},
- host: "",
- path: "/111/",
- shouldMatch: true,
- },
- {
- title: "Path route, do not match with trailing slash in path",
- route: new(Route).Path("/111/"),
- request: newRequest("GET", "http://localhost/111"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: false,
- },
- {
- title: "Path route, do not match with trailing slash in request",
- route: new(Route).Path("/111"),
- request: newRequest("GET", "http://localhost/111/"),
- vars: map[string]string{},
- host: "",
- path: "/111/",
- shouldMatch: false,
- },
- {
- title: "Path route, wrong path in request in request URL",
- route: new(Route).Path("/111/222/333"),
- request: newRequest("GET", "http://localhost/1/2/3"),
- vars: map[string]string{},
- host: "",
- path: "/111/222/333",
- shouldMatch: false,
- },
- {
- title: "Path route with pattern, match",
- route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222/333",
- shouldMatch: true,
- },
- {
- title: "Path route with pattern, URL in request does not match",
- route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222/333",
- shouldMatch: false,
- },
- {
- title: "Path route with multiple patterns, match",
- route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
- host: "",
- path: "/111/222/333",
- shouldMatch: true,
- },
- {
- title: "Path route with multiple patterns, URL in request does not match",
- route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
- host: "",
- path: "/111/222/333",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestPathPrefix(t *testing.T) {
- tests := []routeTest{
- {
- title: "PathPrefix route, match",
- route: new(Route).PathPrefix("/111"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: true,
- },
- {
- title: "PathPrefix route, match substring",
- route: new(Route).PathPrefix("/1"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "/1",
- shouldMatch: true,
- },
- {
- title: "PathPrefix route, URL prefix in request does not match",
- route: new(Route).PathPrefix("/111"),
- request: newRequest("GET", "http://localhost/1/2/3"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: false,
- },
- {
- title: "PathPrefix route with pattern, match",
- route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: true,
- },
- {
- title: "PathPrefix route with pattern, URL prefix in request does not match",
- route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: false,
- },
- {
- title: "PathPrefix route with multiple patterns, match",
- route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "111", "v2": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: true,
- },
- {
- title: "PathPrefix route with multiple patterns, URL prefix in request does not match",
- route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "111", "v2": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestHostPath(t *testing.T) {
- tests := []routeTest{
- {
- title: "Host and Path route, match",
- route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Host and Path route, wrong host in request URL",
- route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Host and Path route with pattern, match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb", "v2": "222"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: true,
- },
- {
- title: "Host and Path route with pattern, URL in request does not match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb", "v2": "222"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: false,
- },
- {
- title: "Host and Path route with multiple patterns, match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: true,
- },
- {
- title: "Host and Path route with multiple patterns, URL in request does not match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestHeaders(t *testing.T) {
- // newRequestHeaders creates a new request with a method, url, and headers
- newRequestHeaders := func(method, url string, headers map[string]string) *http.Request {
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- panic(err)
- }
- for k, v := range headers {
- req.Header.Add(k, v)
- }
- return req
- }
-
- tests := []routeTest{
- {
- title: "Headers route, match",
- route: new(Route).Headers("foo", "bar", "baz", "ding"),
- request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Headers route, bad header values",
- route: new(Route).Headers("foo", "bar", "baz", "ding"),
- request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-
-}
-
-func TestMethods(t *testing.T) {
- tests := []routeTest{
- {
- title: "Methods route, match GET",
- route: new(Route).Methods("GET", "POST"),
- request: newRequest("GET", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Methods route, match POST",
- route: new(Route).Methods("GET", "POST"),
- request: newRequest("POST", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Methods route, bad method",
- route: new(Route).Methods("GET", "POST"),
- request: newRequest("PUT", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestQueries(t *testing.T) {
- tests := []routeTest{
- {
- title: "Queries route, match",
- route: new(Route).Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route, match with a query string",
- route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route, match with a query string out of order",
- route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route, bad query",
- route: new(Route).Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://localhost?foo=bar&baz=dong"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- {
- title: "Queries route with pattern, match",
- route: new(Route).Queries("foo", "{v1}"),
- request: newRequest("GET", "http://localhost?foo=bar"),
- vars: map[string]string{"v1": "bar"},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route with multiple patterns, match",
- route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"),
- request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
- vars: map[string]string{"v1": "bar", "v2": "ding"},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route with regexp pattern, match",
- route: new(Route).Queries("foo", "{v1:[0-9]+}"),
- request: newRequest("GET", "http://localhost?foo=10"),
- vars: map[string]string{"v1": "10"},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Queries route with regexp pattern, regexp does not match",
- route: new(Route).Queries("foo", "{v1:[0-9]+}"),
- request: newRequest("GET", "http://localhost?foo=a"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestSchemes(t *testing.T) {
- tests := []routeTest{
- // Schemes
- {
- title: "Schemes route, match https",
- route: new(Route).Schemes("https", "ftp"),
- request: newRequest("GET", "https://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Schemes route, match ftp",
- route: new(Route).Schemes("https", "ftp"),
- request: newRequest("GET", "ftp://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "Schemes route, bad scheme",
- route: new(Route).Schemes("https", "ftp"),
- request: newRequest("GET", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- }
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestMatcherFunc(t *testing.T) {
- m := func(r *http.Request, m *RouteMatch) bool {
- if r.URL.Host == "aaa.bbb.ccc" {
- return true
- }
- return false
- }
-
- tests := []routeTest{
- {
- title: "MatchFunc route, match",
- route: new(Route).MatcherFunc(m),
- request: newRequest("GET", "http://aaa.bbb.ccc"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
- },
- {
- title: "MatchFunc route, non-match",
- route: new(Route).MatcherFunc(m),
- request: newRequest("GET", "http://aaa.222.ccc"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestBuildVarsFunc(t *testing.T) {
- tests := []routeTest{
- {
- title: "BuildVarsFunc set on route",
- route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
- vars["v1"] = "3"
- vars["v2"] = "a"
- return vars
- }),
- request: newRequest("GET", "http://localhost/111/2"),
- path: "/111/3a",
- shouldMatch: true,
- },
- {
- title: "BuildVarsFunc set on route and parent route",
- route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
- vars["v1"] = "2"
- return vars
- }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string {
- vars["v2"] = "b"
- return vars
- }),
- request: newRequest("GET", "http://localhost/1/a"),
- path: "/2/b",
- shouldMatch: true,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestSubRouter(t *testing.T) {
- subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter()
- subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter()
-
- tests := []routeTest{
- {
- route: subrouter1.Path("/{v2:[a-z]+}"),
- request: newRequest("GET", "http://aaa.google.com/bbb"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb"},
- host: "aaa.google.com",
- path: "/bbb",
- shouldMatch: true,
- },
- {
- route: subrouter1.Path("/{v2:[a-z]+}"),
- request: newRequest("GET", "http://111.google.com/111"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb"},
- host: "aaa.google.com",
- path: "/bbb",
- shouldMatch: false,
- },
- {
- route: subrouter2.Path("/baz/{v2}"),
- request: newRequest("GET", "http://localhost/foo/bar/baz/ding"),
- vars: map[string]string{"v1": "bar", "v2": "ding"},
- host: "",
- path: "/foo/bar/baz/ding",
- shouldMatch: true,
- },
- {
- route: subrouter2.Path("/baz/{v2}"),
- request: newRequest("GET", "http://localhost/foo/bar"),
- vars: map[string]string{"v1": "bar", "v2": "ding"},
- host: "",
- path: "/foo/bar/baz/ding",
- shouldMatch: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-func TestNamedRoutes(t *testing.T) {
- r1 := NewRouter()
- r1.NewRoute().Name("a")
- r1.NewRoute().Name("b")
- r1.NewRoute().Name("c")
-
- r2 := r1.NewRoute().Subrouter()
- r2.NewRoute().Name("d")
- r2.NewRoute().Name("e")
- r2.NewRoute().Name("f")
-
- r3 := r2.NewRoute().Subrouter()
- r3.NewRoute().Name("g")
- r3.NewRoute().Name("h")
- r3.NewRoute().Name("i")
-
- if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 {
- t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes)
- } else if r1.Get("i") == nil {
- t.Errorf("Subroute name not registered")
- }
-}
-
-func TestStrictSlash(t *testing.T) {
- r := NewRouter()
- r.StrictSlash(true)
-
- tests := []routeTest{
- {
- title: "Redirect path without slash",
- route: r.NewRoute().Path("/111/"),
- request: newRequest("GET", "http://localhost/111"),
- vars: map[string]string{},
- host: "",
- path: "/111/",
- shouldMatch: true,
- shouldRedirect: true,
- },
- {
- title: "Do not redirect path with slash",
- route: r.NewRoute().Path("/111/"),
- request: newRequest("GET", "http://localhost/111/"),
- vars: map[string]string{},
- host: "",
- path: "/111/",
- shouldMatch: true,
- shouldRedirect: false,
- },
- {
- title: "Redirect path with slash",
- route: r.NewRoute().Path("/111"),
- request: newRequest("GET", "http://localhost/111/"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: true,
- shouldRedirect: true,
- },
- {
- title: "Do not redirect path without slash",
- route: r.NewRoute().Path("/111"),
- request: newRequest("GET", "http://localhost/111"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: true,
- shouldRedirect: false,
- },
- {
- title: "Propagate StrictSlash to subrouters",
- route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"),
- request: newRequest("GET", "http://localhost/static/images"),
- vars: map[string]string{},
- host: "",
- path: "/static/images/",
- shouldMatch: true,
- shouldRedirect: true,
- },
- {
- title: "Ignore StrictSlash for path prefix",
- route: r.NewRoute().PathPrefix("/static/"),
- request: newRequest("GET", "http://localhost/static/logo.png"),
- vars: map[string]string{},
- host: "",
- path: "/static/",
- shouldMatch: true,
- shouldRedirect: false,
- },
- }
-
- for _, test := range tests {
- testRoute(t, test)
- }
-}
-
-// ----------------------------------------------------------------------------
-// Helpers
-// ----------------------------------------------------------------------------
-
-func getRouteTemplate(route *Route) string {
- host, path := "none", "none"
- if route.regexp != nil {
- if route.regexp.host != nil {
- host = route.regexp.host.template
- }
- if route.regexp.path != nil {
- path = route.regexp.path.template
- }
- }
- return fmt.Sprintf("Host: %v, Path: %v", host, path)
-}
-
-func testRoute(t *testing.T, test routeTest) {
- request := test.request
- route := test.route
- vars := test.vars
- shouldMatch := test.shouldMatch
- host := test.host
- path := test.path
- url := test.host + test.path
- shouldRedirect := test.shouldRedirect
-
- var match RouteMatch
- ok := route.Match(request, &match)
- if ok != shouldMatch {
- msg := "Should match"
- if !shouldMatch {
- msg = "Should not match"
- }
- t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars)
- return
- }
- if shouldMatch {
- if test.vars != nil && !stringMapEqual(test.vars, match.Vars) {
- t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars)
- return
- }
- if host != "" {
- u, _ := test.route.URLHost(mapToPairs(match.Vars)...)
- if host != u.Host {
- t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route))
- return
- }
- }
- if path != "" {
- u, _ := route.URLPath(mapToPairs(match.Vars)...)
- if path != u.Path {
- t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route))
- return
- }
- }
- if url != "" {
- u, _ := route.URL(mapToPairs(match.Vars)...)
- if url != u.Host+u.Path {
- t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route))
- return
- }
- }
- if shouldRedirect && match.Handler == nil {
- t.Errorf("(%v) Did not redirect", test.title)
- return
- }
- if !shouldRedirect && match.Handler != nil {
- t.Errorf("(%v) Unexpected redirect", test.title)
- return
- }
- }
-}
-
-// Tests that the context is cleared or not cleared properly depending on
-// the configuration of the router
-func TestKeepContext(t *testing.T) {
- func1 := func(w http.ResponseWriter, r *http.Request) {}
-
- r := NewRouter()
- r.HandleFunc("/", func1).Name("func1")
-
- req, _ := http.NewRequest("GET", "http://localhost/", nil)
- context.Set(req, "t", 1)
-
- res := new(http.ResponseWriter)
- r.ServeHTTP(*res, req)
-
- if _, ok := context.GetOk(req, "t"); ok {
- t.Error("Context should have been cleared at end of request")
- }
-
- r.KeepContext = true
-
- req, _ = http.NewRequest("GET", "http://localhost/", nil)
- context.Set(req, "t", 1)
-
- r.ServeHTTP(*res, req)
- if _, ok := context.GetOk(req, "t"); !ok {
- t.Error("Context should NOT have been cleared at end of request")
- }
-
-}
-
-type TestA301ResponseWriter struct {
- hh http.Header
- status int
-}
-
-func (ho TestA301ResponseWriter) Header() http.Header {
- return http.Header(ho.hh)
-}
-
-func (ho TestA301ResponseWriter) Write(b []byte) (int, error) {
- return 0, nil
-}
-
-func (ho TestA301ResponseWriter) WriteHeader(code int) {
- ho.status = code
-}
-
-func Test301Redirect(t *testing.T) {
- m := make(http.Header)
-
- func1 := func(w http.ResponseWriter, r *http.Request) {}
- func2 := func(w http.ResponseWriter, r *http.Request) {}
-
- r := NewRouter()
- r.HandleFunc("/api/", func2).Name("func2")
- r.HandleFunc("/", func1).Name("func1")
-
- req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil)
-
- res := TestA301ResponseWriter{
- hh: m,
- status: 0,
- }
- r.ServeHTTP(&res, req)
-
- if "http://localhost/api/?abc=def" != res.hh["Location"][0] {
- t.Errorf("Should have complete URL with query string")
- }
-}
-
-// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW
-func TestSubrouterHeader(t *testing.T) {
- expected := "func1 response"
- func1 := func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, expected)
- }
- func2 := func(http.ResponseWriter, *http.Request) {}
-
- r := NewRouter()
- s := r.Headers("SomeSpecialHeader", "").Subrouter()
- s.HandleFunc("/", func1).Name("func1")
- r.HandleFunc("/", func2).Name("func2")
-
- req, _ := http.NewRequest("GET", "http://localhost/", nil)
- req.Header.Add("SomeSpecialHeader", "foo")
- match := new(RouteMatch)
- matched := r.Match(req, match)
- if !matched {
- t.Errorf("Should match request")
- }
- if match.Route.GetName() != "func1" {
- t.Errorf("Expecting func1 handler, got %s", match.Route.GetName())
- }
- resp := NewRecorder()
- match.Handler.ServeHTTP(resp, req)
- if resp.Body.String() != expected {
- t.Errorf("Expecting %q", expected)
- }
-}
-
-// mapToPairs converts a string map to a slice of string pairs
-func mapToPairs(m map[string]string) []string {
- var i int
- p := make([]string, len(m)*2)
- for k, v := range m {
- p[i] = k
- p[i+1] = v
- i += 2
- }
- return p
-}
-
-// stringMapEqual checks the equality of two string maps
-func stringMapEqual(m1, m2 map[string]string) bool {
- nil1 := m1 == nil
- nil2 := m2 == nil
- if nil1 != nil2 || len(m1) != len(m2) {
- return false
- }
- for k, v := range m1 {
- if v != m2[k] {
- return false
- }
- }
- return true
-}
-
-// newRequest is a helper function to create a new request with a method and url
-func newRequest(method, url string) *http.Request {
- req, err := http.NewRequest(method, url, nil)
- if err != nil {
- panic(err)
- }
- return req
-}
diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
deleted file mode 100644
index 1f7c190c0..000000000
--- a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go
+++ /dev/null
@@ -1,714 +0,0 @@
-// Old tests ported to Go1. This is a mess. Want to drop it one day.
-
-// Copyright 2011 Gorilla 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 mux
-
-import (
- "bytes"
- "net/http"
- "testing"
-)
-
-// ----------------------------------------------------------------------------
-// ResponseRecorder
-// ----------------------------------------------------------------------------
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// ResponseRecorder is an implementation of http.ResponseWriter that
-// records its mutations for later inspection in tests.
-type ResponseRecorder struct {
- Code int // the HTTP response code from WriteHeader
- HeaderMap http.Header // the HTTP response headers
- Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
- Flushed bool
-}
-
-// NewRecorder returns an initialized ResponseRecorder.
-func NewRecorder() *ResponseRecorder {
- return &ResponseRecorder{
- HeaderMap: make(http.Header),
- Body: new(bytes.Buffer),
- }
-}
-
-// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
-// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
-const DefaultRemoteAddr = "1.2.3.4"
-
-// Header returns the response headers.
-func (rw *ResponseRecorder) Header() http.Header {
- return rw.HeaderMap
-}
-
-// Write always succeeds and writes to rw.Body, if not nil.
-func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
- if rw.Body != nil {
- rw.Body.Write(buf)
- }
- if rw.Code == 0 {
- rw.Code = http.StatusOK
- }
- return len(buf), nil
-}
-
-// WriteHeader sets rw.Code.
-func (rw *ResponseRecorder) WriteHeader(code int) {
- rw.Code = code
-}
-
-// Flush sets rw.Flushed to true.
-func (rw *ResponseRecorder) Flush() {
- rw.Flushed = true
-}
-
-// ----------------------------------------------------------------------------
-
-func TestRouteMatchers(t *testing.T) {
- var scheme, host, path, query, method string
- var headers map[string]string
- var resultVars map[bool]map[string]string
-
- router := NewRouter()
- router.NewRoute().Host("{var1}.google.com").
- Path("/{var2:[a-z]+}/{var3:[0-9]+}").
- Queries("foo", "bar").
- Methods("GET").
- Schemes("https").
- Headers("x-requested-with", "XMLHttpRequest")
- router.NewRoute().Host("www.{var4}.com").
- PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}").
- Queries("baz", "ding").
- Methods("POST").
- Schemes("http").
- Headers("Content-Type", "application/json")
-
- reset := func() {
- // Everything match.
- scheme = "https"
- host = "www.google.com"
- path = "/product/42"
- query = "?foo=bar"
- method = "GET"
- headers = map[string]string{"X-Requested-With": "XMLHttpRequest"}
- resultVars = map[bool]map[string]string{
- true: {"var1": "www", "var2": "product", "var3": "42"},
- false: {},
- }
- }
-
- reset2 := func() {
- // Everything match.
- scheme = "http"
- host = "www.google.com"
- path = "/foo/product/42/path/that/is/ignored"
- query = "?baz=ding"
- method = "POST"
- headers = map[string]string{"Content-Type": "application/json"}
- resultVars = map[bool]map[string]string{
- true: {"var4": "google", "var5": "product", "var6": "42"},
- false: {},
- }
- }
-
- match := func(shouldMatch bool) {
- url := scheme + "://" + host + path + query
- request, _ := http.NewRequest(method, url, nil)
- for key, value := range headers {
- request.Header.Add(key, value)
- }
-
- 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.")
- }
- }
-
- if matched {
- currentRoute := routeMatch.Route
- if currentRoute == nil {
- t.Errorf("Expected a current route.")
- }
- vars := routeMatch.Vars
- expectedVars := resultVars[shouldMatch]
- if len(vars) != len(expectedVars) {
- t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars)
- }
- for name, value := range vars {
- if expectedVars[name] != value {
- t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars)
- }
- }
- }
- }
-
- // 1st route --------------------------------------------------------------
-
- // Everything match.
- reset()
- match(true)
-
- // Scheme doesn't match.
- reset()
- scheme = "http"
- match(false)
-
- // Host doesn't match.
- reset()
- host = "www.mygoogle.com"
- match(false)
-
- // Path doesn't match.
- reset()
- path = "/product/notdigits"
- match(false)
-
- // Query doesn't match.
- reset()
- query = "?foo=baz"
- match(false)
-
- // Method doesn't match.
- reset()
- method = "POST"
- match(false)
-
- // Header doesn't match.
- reset()
- headers = map[string]string{}
- match(false)
-
- // Everything match, again.
- reset()
- match(true)
-
- // 2nd route --------------------------------------------------------------
-
- // Everything match.
- reset2()
- match(true)
-
- // Scheme doesn't match.
- reset2()
- scheme = "https"
- match(false)
-
- // Host doesn't match.
- reset2()
- host = "sub.google.com"
- match(false)
-
- // Path doesn't match.
- reset2()
- path = "/bar/product/42"
- match(false)
-
- // Query doesn't match.
- reset2()
- query = "?foo=baz"
- match(false)
-
- // Method doesn't match.
- reset2()
- method = "GET"
- match(false)
-
- // Header doesn't match.
- reset2()
- headers = map[string]string{}
- match(false)
-
- // Everything match, again.
- reset2()
- match(true)
-}
-
-type headerMatcherTest struct {
- matcher headerMatcher
- headers map[string]string
- result bool
-}
-
-var headerMatcherTests = []headerMatcherTest{
- {
- matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}),
- headers: map[string]string{"X-Requested-With": "XMLHttpRequest"},
- result: true,
- },
- {
- matcher: headerMatcher(map[string]string{"x-requested-with": ""}),
- headers: map[string]string{"X-Requested-With": "anything"},
- result: true,
- },
- {
- matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}),
- headers: map[string]string{},
- result: false,
- },
-}
-
-type hostMatcherTest struct {
- matcher *Route
- url string
- vars map[string]string
- result bool
-}
-
-var hostMatcherTests = []hostMatcherTest{
- {
- matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"),
- url: "http://abc.def.ghi/",
- vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"},
- result: true,
- },
- {
- matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"),
- url: "http://a.b.c/",
- vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"},
- result: false,
- },
-}
-
-type methodMatcherTest struct {
- matcher methodMatcher
- method string
- result bool
-}
-
-var methodMatcherTests = []methodMatcherTest{
- {
- matcher: methodMatcher([]string{"GET", "POST", "PUT"}),
- method: "GET",
- result: true,
- },
- {
- matcher: methodMatcher([]string{"GET", "POST", "PUT"}),
- method: "POST",
- result: true,
- },
- {
- matcher: methodMatcher([]string{"GET", "POST", "PUT"}),
- method: "PUT",
- result: true,
- },
- {
- matcher: methodMatcher([]string{"GET", "POST", "PUT"}),
- method: "DELETE",
- result: false,
- },
-}
-
-type pathMatcherTest struct {
- matcher *Route
- url string
- vars map[string]string
- result bool
-}
-
-var pathMatcherTests = []pathMatcherTest{
- {
- matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"),
- url: "http://localhost:8080/123/456/789",
- vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"},
- result: true,
- },
- {
- matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"),
- url: "http://localhost:8080/1/2/3",
- vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"},
- result: false,
- },
-}
-
-type schemeMatcherTest struct {
- matcher schemeMatcher
- url string
- result bool
-}
-
-var schemeMatcherTests = []schemeMatcherTest{
- {
- matcher: schemeMatcher([]string{"http", "https"}),
- url: "http://localhost:8080/",
- result: true,
- },
- {
- matcher: schemeMatcher([]string{"http", "https"}),
- url: "https://localhost:8080/",
- result: true,
- },
- {
- matcher: schemeMatcher([]string{"https"}),
- url: "http://localhost:8080/",
- result: false,
- },
- {
- matcher: schemeMatcher([]string{"http"}),
- url: "https://localhost:8080/",
- result: false,
- },
-}
-
-type urlBuildingTest struct {
- route *Route
- vars []string
- url string
-}
-
-var urlBuildingTests = []urlBuildingTest{
- {
- route: new(Route).Host("foo.domain.com"),
- vars: []string{},
- url: "http://foo.domain.com",
- },
- {
- route: new(Route).Host("{subdomain}.domain.com"),
- vars: []string{"subdomain", "bar"},
- url: "http://bar.domain.com",
- },
- {
- route: new(Route).Host("foo.domain.com").Path("/articles"),
- vars: []string{},
- url: "http://foo.domain.com/articles",
- },
- {
- route: new(Route).Path("/articles"),
- vars: []string{},
- url: "/articles",
- },
- {
- route: new(Route).Path("/articles/{category}/{id:[0-9]+}"),
- vars: []string{"category", "technology", "id", "42"},
- url: "/articles/technology/42",
- },
- {
- route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"),
- vars: []string{"subdomain", "foo", "category", "technology", "id", "42"},
- url: "http://foo.domain.com/articles/technology/42",
- },
-}
-
-func TestHeaderMatcher(t *testing.T) {
- for _, v := range headerMatcherTests {
- request, _ := http.NewRequest("GET", "http://localhost:8080/", nil)
- for key, value := range v.headers {
- request.Header.Add(key, value)
- }
- var routeMatch RouteMatch
- result := v.matcher.Match(request, &routeMatch)
- if result != v.result {
- if v.result {
- t.Errorf("%#v: should match %v.", v.matcher, request.Header)
- } else {
- t.Errorf("%#v: should not match %v.", v.matcher, request.Header)
- }
- }
- }
-}
-
-func TestHostMatcher(t *testing.T) {
- for _, v := range hostMatcherTests {
- request, _ := http.NewRequest("GET", v.url, nil)
- var routeMatch RouteMatch
- result := v.matcher.Match(request, &routeMatch)
- vars := routeMatch.Vars
- if result != v.result {
- if v.result {
- t.Errorf("%#v: should match %v.", v.matcher, v.url)
- } else {
- t.Errorf("%#v: should not match %v.", v.matcher, v.url)
- }
- }
- if result {
- if len(vars) != len(v.vars) {
- t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars))
- }
- for name, value := range vars {
- if v.vars[name] != value {
- t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value)
- }
- }
- } else {
- if len(vars) != 0 {
- t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars))
- }
- }
- }
-}
-
-func TestMethodMatcher(t *testing.T) {
- for _, v := range methodMatcherTests {
- request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil)
- var routeMatch RouteMatch
- result := v.matcher.Match(request, &routeMatch)
- if result != v.result {
- if v.result {
- t.Errorf("%#v: should match %v.", v.matcher, v.method)
- } else {
- t.Errorf("%#v: should not match %v.", v.matcher, v.method)
- }
- }
- }
-}
-
-func TestPathMatcher(t *testing.T) {
- for _, v := range pathMatcherTests {
- request, _ := http.NewRequest("GET", v.url, nil)
- var routeMatch RouteMatch
- result := v.matcher.Match(request, &routeMatch)
- vars := routeMatch.Vars
- if result != v.result {
- if v.result {
- t.Errorf("%#v: should match %v.", v.matcher, v.url)
- } else {
- t.Errorf("%#v: should not match %v.", v.matcher, v.url)
- }
- }
- if result {
- if len(vars) != len(v.vars) {
- t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars))
- }
- for name, value := range vars {
- if v.vars[name] != value {
- t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value)
- }
- }
- } else {
- if len(vars) != 0 {
- t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars))
- }
- }
- }
-}
-
-func TestSchemeMatcher(t *testing.T) {
- for _, v := range schemeMatcherTests {
- request, _ := http.NewRequest("GET", v.url, nil)
- var routeMatch RouteMatch
- result := v.matcher.Match(request, &routeMatch)
- if result != v.result {
- if v.result {
- t.Errorf("%#v: should match %v.", v.matcher, v.url)
- } else {
- t.Errorf("%#v: should not match %v.", v.matcher, v.url)
- }
- }
- }
-}
-
-func TestUrlBuilding(t *testing.T) {
-
- for _, v := range urlBuildingTests {
- u, _ := v.route.URL(v.vars...)
- url := u.String()
- if url != v.url {
- t.Errorf("expected %v, got %v", v.url, url)
- /*
- reversePath := ""
- reverseHost := ""
- if v.route.pathTemplate != nil {
- reversePath = v.route.pathTemplate.Reverse
- }
- if v.route.hostTemplate != nil {
- reverseHost = v.route.hostTemplate.Reverse
- }
-
- t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost)
- */
- }
- }
-
- ArticleHandler := func(w http.ResponseWriter, r *http.Request) {
- }
-
- router := NewRouter()
- router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article")
-
- url, _ := router.Get("article").URL("category", "technology", "id", "42")
- expected := "/articles/technology/42"
- if url.String() != expected {
- t.Errorf("Expected %v, got %v", expected, url.String())
- }
-}
-
-func TestMatchedRouteName(t *testing.T) {
- routeName := "stock"
- router := NewRouter()
- route := router.NewRoute().Path("/products/").Name(routeName)
-
- url := "http://www.domain.com/products/"
- request, _ := http.NewRequest("GET", url, nil)
- var rv RouteMatch
- ok := router.Match(request, &rv)
-
- if !ok || rv.Route != route {
- t.Errorf("Expected same route, got %+v.", rv.Route)
- }
-
- retName := rv.Route.GetName()
- if retName != routeName {
- t.Errorf("Expected %q, got %q.", routeName, retName)
- }
-}
-
-func TestSubRouting(t *testing.T) {
- // Example from docs.
- router := NewRouter()
- subrouter := router.NewRoute().Host("www.domain.com").Subrouter()
- route := subrouter.NewRoute().Path("/products/").Name("products")
-
- url := "http://www.domain.com/products/"
- request, _ := http.NewRequest("GET", url, nil)
- var rv RouteMatch
- ok := router.Match(request, &rv)
-
- if !ok || rv.Route != route {
- t.Errorf("Expected same route, got %+v.", rv.Route)
- }
-
- u, _ := router.Get("products").URL()
- builtUrl := u.String()
- // Yay, subroute aware of the domain when building!
- if builtUrl != url {
- t.Errorf("Expected %q, got %q.", url, builtUrl)
- }
-}
-
-func TestVariableNames(t *testing.T) {
- route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}")
- if route.err == nil {
- t.Errorf("Expected error for duplicated variable names")
- }
-}
-
-func TestRedirectSlash(t *testing.T) {
- var route *Route
- var routeMatch RouteMatch
- r := NewRouter()
-
- r.StrictSlash(false)
- route = r.NewRoute()
- if route.strictSlash != false {
- t.Errorf("Expected false redirectSlash.")
- }
-
- r.StrictSlash(true)
- route = r.NewRoute()
- if route.strictSlash != true {
- t.Errorf("Expected true redirectSlash.")
- }
-
- route = new(Route)
- route.strictSlash = true
- route.Path("/{arg1}/{arg2:[0-9]+}/")
- request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil)
- routeMatch = RouteMatch{}
- _ = route.Match(request, &routeMatch)
- vars := routeMatch.Vars
- if vars["arg1"] != "foo" {
- t.Errorf("Expected foo.")
- }
- if vars["arg2"] != "123" {
- t.Errorf("Expected 123.")
- }
- rsp := NewRecorder()
- routeMatch.Handler.ServeHTTP(rsp, request)
- if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" {
- t.Errorf("Expected redirect header.")
- }
-
- route = new(Route)
- route.strictSlash = true
- route.Path("/{arg1}/{arg2:[0-9]+}")
- request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil)
- routeMatch = RouteMatch{}
- _ = route.Match(request, &routeMatch)
- vars = routeMatch.Vars
- if vars["arg1"] != "foo" {
- t.Errorf("Expected foo.")
- }
- if vars["arg2"] != "123" {
- t.Errorf("Expected 123.")
- }
- rsp = NewRecorder()
- routeMatch.Handler.ServeHTTP(rsp, request)
- if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" {
- t.Errorf("Expected redirect header.")
- }
-}
-
-// Test for the new regexp library, still not available in stable Go.
-func TestNewRegexp(t *testing.T) {
- var p *routeRegexp
- var matches []string
-
- tests := map[string]map[string][]string{
- "/{foo:a{2}}": {
- "/a": nil,
- "/aa": {"aa"},
- "/aaa": nil,
- "/aaaa": nil,
- },
- "/{foo:a{2,}}": {
- "/a": nil,
- "/aa": {"aa"},
- "/aaa": {"aaa"},
- "/aaaa": {"aaaa"},
- },
- "/{foo:a{2,3}}": {
- "/a": nil,
- "/aa": {"aa"},
- "/aaa": {"aaa"},
- "/aaaa": nil,
- },
- "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": {
- "/a": nil,
- "/ab": nil,
- "/abc": nil,
- "/abcd": nil,
- "/abc/ab": {"abc", "ab"},
- "/abc/abc": nil,
- "/abcd/ab": nil,
- },
- `/{foo:\w{3,}}/{bar:\d{2,}}`: {
- "/a": nil,
- "/ab": nil,
- "/abc": nil,
- "/abc/1": nil,
- "/abc/12": {"abc", "12"},
- "/abcd/12": {"abcd", "12"},
- "/abcd/123": {"abcd", "123"},
- },
- }
-
- for pattern, paths := range tests {
- p, _ = newRouteRegexp(pattern, false, false, false, false)
- for path, result := range paths {
- matches = p.regexp.FindStringSubmatch(path)
- if result == nil {
- if matches != nil {
- t.Errorf("%v should not match %v.", pattern, path)
- }
- } else {
- if len(matches) != len(result)+1 {
- t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches))
- } else {
- for k, v := range result {
- if matches[k+1] != v {
- t.Errorf("Expected %v, got %v.", v, matches[k+1])
- }
- }
- }
- }
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/LICENSE b/Godeps/_workspace/src/github.com/hashicorp/consul/LICENSE
new file mode 100644
index 000000000..c33dcc7c9
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/hashicorp/consul/LICENSE
@@ -0,0 +1,354 @@
+Mozilla Public License, version 2.0
+
+1. Definitions
+
+1.1. “Contributor”
+
+ means each individual or legal entity that creates, contributes to the
+ creation of, or owns Covered Software.
+
+1.2. “Contributor Version”
+
+ means the combination of the Contributions of others (if any) used by a
+ Contributor and that particular Contributor’s Contribution.
+
+1.3. “Contribution”
+
+ means Covered Software of a particular Contributor.
+
+1.4. “Covered Software”
+
+ means Source Code Form to which the initial Contributor has attached the
+ notice in Exhibit A, the Executable Form of such Source Code Form, and
+ Modifications of such Source Code Form, in each case including portions
+ thereof.
+
+1.5. “Incompatible With Secondary Licenses”
+ means
+
+ a. that the initial Contributor has attached the notice described in
+ Exhibit B to the Covered Software; or
+
+ b. that the Covered Software was made available under the terms of version
+ 1.1 or earlier of the License, but not also under the terms of a
+ Secondary License.
+
+1.6. “Executable Form”
+
+ means any form of the work other than Source Code Form.
+
+1.7. “Larger Work”
+
+ means a work that combines Covered Software with other material, in a separate
+ file or files, that is not Covered Software.
+
+1.8. “License”
+
+ means this document.
+
+1.9. “Licensable”
+
+ means having the right to grant, to the maximum extent possible, whether at the
+ time of the initial grant or subsequently, any and all of the rights conveyed by
+ this License.
+
+1.10. “Modifications”
+
+ means any of the following:
+
+ a. any file in Source Code Form that results from an addition to, deletion
+ from, or modification of the contents of Covered Software; or
+
+ b. any new file in Source Code Form that contains any Covered Software.
+
+1.11. “Patent Claims” of a Contributor
+
+ means any patent claim(s), including without limitation, method, process,
+ and apparatus claims, in any patent Licensable by such Contributor that
+ would be infringed, but for the grant of the License, by the making,
+ using, selling, offering for sale, having made, import, or transfer of
+ either its Contributions or its Contributor Version.
+
+1.12. “Secondary License”
+
+ means either the GNU General Public License, Version 2.0, the GNU Lesser
+ General Public License, Version 2.1, the GNU Affero General Public
+ License, Version 3.0, or any later versions of those licenses.
+
+1.13. “Source Code Form”
+
+ means the form of the work preferred for making modifications.
+
+1.14. “You” (or “Your”)
+
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, “You” includes any entity that controls, is
+ controlled by, or is under common control with You. For purposes of this
+ definition, “control” means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+
+2. License Grants and Conditions
+
+2.1. Grants
+
+ Each Contributor hereby grants You a world-wide, royalty-free,
+ non-exclusive license:
+
+ a. under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or as
+ part of a Larger Work; and
+
+ b. under Patent Claims of such Contributor to make, use, sell, offer for
+ sale, have made, import, and otherwise transfer either its Contributions
+ or its Contributor Version.
+
+2.2. Effective Date
+
+ The licenses granted in Section 2.1 with respect to any Contribution become
+ effective for each Contribution on the date the Contributor first distributes
+ such Contribution.
+
+2.3. Limitations on Grant Scope
+
+ The licenses granted in this Section 2 are the only rights granted under this
+ License. No additional rights or licenses will be implied from the distribution
+ or licensing of Covered Software under this License. Notwithstanding Section
+ 2.1(b) above, no patent license is granted by a Contributor:
+
+ a. for any code that a Contributor has removed from Covered Software; or
+
+ b. for infringements caused by: (i) Your and any other third party’s
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+ c. under Patent Claims infringed by Covered Software in the absence of its
+ Contributions.
+
+ This License does not grant any rights in the trademarks, service marks, or
+ logos of any Contributor (except as may be necessary to comply with the
+ notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+ No Contributor makes additional grants as a result of Your choice to
+ distribute the Covered Software under a subsequent version of this License
+ (see Section 10.2) or under the terms of a Secondary License (if permitted
+ under the terms of Section 3.3).
+
+2.5. Representation
+
+ Each Contributor represents that the Contributor believes its Contributions
+ are its original creation(s) or it has sufficient rights to grant the
+ rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+ This License is not intended to limit any rights You have under applicable
+ copyright doctrines of fair use, fair dealing, or other equivalents.
+
+2.7. Conditions
+
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
+ Section 2.1.
+
+
+3. Responsibilities
+
+3.1. Distribution of Source Form
+
+ All distribution of Covered Software in Source Code Form, including any
+ Modifications that You create or to which You contribute, must be under the
+ terms of this License. You must inform recipients that the Source Code Form
+ of the Covered Software is governed by the terms of this License, and how
+ they can obtain a copy of this License. You may not attempt to alter or
+ restrict the recipients’ rights in the Source Code Form.
+
+3.2. Distribution of Executable Form
+
+ If You distribute Covered Software in Executable Form then:
+
+ a. such Covered Software must also be made available in Source Code Form,
+ as described in Section 3.1, and You must inform recipients of the
+ Executable Form how they can obtain a copy of such Source Code Form by
+ reasonable means in a timely manner, at a charge no more than the cost
+ of distribution to the recipient; and
+
+ b. You may distribute such Executable Form under the terms of this License,
+ or sublicense it under different terms, provided that the license for
+ the Executable Form does not attempt to limit or alter the recipients’
+ rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+ You may create and distribute a Larger Work under terms of Your choice,
+ provided that You also comply with the requirements of this License for the
+ Covered Software. If the Larger Work is a combination of Covered Software
+ with a work governed by one or more Secondary Licenses, and the Covered
+ Software is not Incompatible With Secondary Licenses, this License permits
+ You to additionally distribute such Covered Software under the terms of
+ such Secondary License(s), so that the recipient of the Larger Work may, at
+ their option, further distribute the Covered Software under the terms of
+ either this License or such Secondary License(s).
+
+3.4. Notices
+
+ You may not remove or alter the substance of any license notices (including
+ copyright notices, patent notices, disclaimers of warranty, or limitations
+ of liability) contained within the Source Code Form of the Covered
+ Software, except that You may alter any license notices to the extent
+ required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+ You may choose to offer, and to charge a fee for, warranty, support,
+ indemnity or liability obligations to one or more recipients of Covered
+ Software. However, You may do so only on Your own behalf, and not on behalf
+ of any Contributor. You must make it absolutely clear that any such
+ warranty, support, indemnity, or liability obligation is offered by You
+ alone, and You hereby agree to indemnify every Contributor for any
+ liability incurred by such Contributor as a result of warranty, support,
+ indemnity or liability terms You offer. You may include additional
+ disclaimers of warranty and limitations of liability specific to any
+ jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+ If it is impossible for You to comply with any of the terms of this License
+ with respect to some or all of the Covered Software due to statute, judicial
+ order, or regulation then You must: (a) comply with the terms of this License
+ to the maximum extent possible; and (b) describe the limitations and the code
+ they affect. Such description must be placed in a text file included with all
+ distributions of the Covered Software under this License. Except to the
+ extent prohibited by statute or regulation, such description must be
+ sufficiently detailed for a recipient of ordinary skill to be able to
+ understand it.
+
+5. Termination
+
+5.1. The rights granted under this License will terminate automatically if You
+ fail to comply with any of its terms. However, if You become compliant,
+ then the rights granted under this License from a particular Contributor
+ are reinstated (a) provisionally, unless and until such Contributor
+ explicitly and finally terminates Your grants, and (b) on an ongoing basis,
+ if such Contributor fails to notify You of the non-compliance by some
+ reasonable means prior to 60 days after You have come back into compliance.
+ Moreover, Your grants from a particular Contributor are reinstated on an
+ ongoing basis if such Contributor notifies You of the non-compliance by
+ some reasonable means, this is the first time You have received notice of
+ non-compliance with this License from such Contributor, and You become
+ compliant prior to 30 days after Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+ infringement claim (excluding declaratory judgment actions, counter-claims,
+ and cross-claims) alleging that a Contributor Version directly or
+ indirectly infringes any patent, then the rights granted to You by any and
+ all Contributors for the Covered Software under Section 2.1 of this License
+ shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
+ license agreements (excluding distributors and resellers) which have been
+ validly granted by You or Your distributors under this License prior to
+ termination shall survive termination.
+
+6. Disclaimer of Warranty
+
+ Covered Software is provided under this License on an “as is” basis, without
+ warranty of any kind, either expressed, implied, or statutory, including,
+ without limitation, warranties that the Covered Software is free of defects,
+ merchantable, fit for a particular purpose or non-infringing. The entire
+ risk as to the quality and performance of the Covered Software is with You.
+ Should any Covered Software prove defective in any respect, You (not any
+ Contributor) assume the cost of any necessary servicing, repair, or
+ correction. This disclaimer of warranty constitutes an essential part of this
+ License. No use of any Covered Software is authorized under this License
+ except under this disclaimer.
+
+7. Limitation of Liability
+
+ Under no circumstances and under no legal theory, whether tort (including
+ negligence), contract, or otherwise, shall any Contributor, or anyone who
+ distributes Covered Software as permitted above, be liable to You for any
+ direct, indirect, special, incidental, or consequential damages of any
+ character including, without limitation, damages for lost profits, loss of
+ goodwill, work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses, even if such party shall have been
+ informed of the possibility of such damages. This limitation of liability
+ shall not apply to liability for death or personal injury resulting from such
+ party’s negligence to the extent applicable law prohibits such limitation.
+ Some jurisdictions do not allow the exclusion or limitation of incidental or
+ consequential damages, so this exclusion and limitation may not apply to You.
+
+8. Litigation
+
+ Any litigation relating to this License may be brought only in the courts of
+ a jurisdiction where the defendant maintains its principal place of business
+ and such litigation shall be governed by laws of that jurisdiction, without
+ reference to its conflict-of-law provisions. Nothing in this Section shall
+ prevent a party’s ability to bring cross-claims or counter-claims.
+
+9. Miscellaneous
+
+ This License represents the complete agreement concerning the subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. Any law or regulation which provides that the language of a
+ contract shall be construed against the drafter shall not be used to construe
+ this License against a Contributor.
+
+
+10. Versions of the License
+
+10.1. New Versions
+
+ Mozilla Foundation is the license steward. Except as provided in Section
+ 10.3, no one other than the license steward has the right to modify or
+ publish new versions of this License. Each version will be given a
+ distinguishing version number.
+
+10.2. Effect of New Versions
+
+ You may distribute the Covered Software under the terms of the version of
+ the License under which You originally received the Covered Software, or
+ under the terms of any subsequent version published by the license
+ steward.
+
+10.3. Modified Versions
+
+ If you create software not governed by this License, and you want to
+ create a new license for such software, you may create and use a modified
+ version of this License if you rename the license and remove any
+ references to the name of the license steward (except to note that such
+ modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
+ If You choose to distribute Source Code Form that is Incompatible With
+ Secondary Licenses under the terms of this version of the License, the
+ notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+
+ This Source Code Form is subject to the
+ terms of the Mozilla Public License, v.
+ 2.0. If a copy of the MPL was not
+ distributed with this file, You can
+ obtain one at
+ http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular file, then
+You may include the notice in a location (such as a LICENSE file in a relevant
+directory) where a recipient would be likely to look for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - “Incompatible With Secondary Licenses” Notice
+
+ This Source Code Form is “Incompatible
+ With Secondary Licenses”, as defined by
+ the Mozilla Public License, v. 2.0.
+
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go
deleted file mode 100644
index b896a1895..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package api
-
-import (
- "os"
- "testing"
-)
-
-// ROOT is a management token for the tests
-var CONSUL_ROOT string
-
-func init() {
- CONSUL_ROOT = os.Getenv("CONSUL_ROOT")
-}
-
-func TestACL_CreateDestroy(t *testing.T) {
- t.Parallel()
- if CONSUL_ROOT == "" {
- t.SkipNow()
- }
- c, s := makeClient(t)
- defer s.Stop()
-
- c.config.Token = CONSUL_ROOT
- acl := c.ACL()
-
- ae := ACLEntry{
- Name: "API test",
- Type: ACLClientType,
- Rules: `key "" { policy = "deny" }`,
- }
-
- id, wm, err := acl.Create(&ae, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- ae2, _, err := acl.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if ae2.Name != ae.Name || ae2.Type != ae.Type || ae2.Rules != ae.Rules {
- t.Fatalf("Bad: %#v", ae2)
- }
-
- wm, err = acl.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-}
-
-func TestACL_CloneDestroy(t *testing.T) {
- t.Parallel()
- if CONSUL_ROOT == "" {
- t.SkipNow()
- }
- c, s := makeClient(t)
- defer s.Stop()
-
- c.config.Token = CONSUL_ROOT
- acl := c.ACL()
-
- id, wm, err := acl.Clone(CONSUL_ROOT, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- wm, err = acl.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-}
-
-func TestACL_Info(t *testing.T) {
- t.Parallel()
- if CONSUL_ROOT == "" {
- t.SkipNow()
- }
- c, s := makeClient(t)
- defer s.Stop()
-
- c.config.Token = CONSUL_ROOT
- acl := c.ACL()
-
- ae, qm, err := acl.Info(CONSUL_ROOT, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-
- if ae == nil || ae.ID != CONSUL_ROOT || ae.Type != ACLManagementType {
- t.Fatalf("bad: %#v", ae)
- }
-}
-
-func TestACL_List(t *testing.T) {
- t.Parallel()
- if CONSUL_ROOT == "" {
- t.SkipNow()
- }
- c, s := makeClient(t)
- defer s.Stop()
-
- c.config.Token = CONSUL_ROOT
- acl := c.ACL()
-
- acls, qm, err := acl.List(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(acls) < 2 {
- t.Fatalf("bad: %v", acls)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go
deleted file mode 100644
index 358c12a6c..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go
+++ /dev/null
@@ -1,524 +0,0 @@
-package api
-
-import (
- "strings"
- "testing"
-)
-
-func TestAgent_Self(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- name := info["Config"]["NodeName"]
- if name == "" {
- t.Fatalf("bad: %v", info)
- }
-}
-
-func TestAgent_Members(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- members, err := agent.Members(false)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(members) != 1 {
- t.Fatalf("bad: %v", members)
- }
-}
-
-func TestAgent_Services(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
-
- // Checks should default to critical
- if chk.Status != "critical" {
- t.Fatalf("Bad: %#v", chk)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_CheckPassing(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- Status: "passing",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
-
- if chk.Status != "passing" {
- t.Fatalf("Bad: %#v", chk)
- }
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_CheckBadStatus(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- Status: "fluffy",
- },
- }
- if err := agent.ServiceRegister(reg); err == nil {
- t.Fatalf("bad status accepted")
- }
-}
-
-func TestAgent_ServiceAddress(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg1 := &AgentServiceRegistration{
- Name: "foo1",
- Port: 8000,
- Address: "192.168.0.42",
- }
- reg2 := &AgentServiceRegistration{
- Name: "foo2",
- Port: 8000,
- }
- if err := agent.ServiceRegister(reg1); err != nil {
- t.Fatalf("err: %v", err)
- }
- if err := agent.ServiceRegister(reg2); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if _, ok := services["foo1"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
- if _, ok := services["foo2"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- if services["foo1"].Address != "192.168.0.42" {
- t.Fatalf("missing Address field in service foo1: %v", services)
- }
- if services["foo2"].Address != "" {
- t.Fatalf("missing Address field in service foo2: %v", services)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_MultipleChecks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Checks: AgentServiceChecks{
- &AgentServiceCheck{
- TTL: "15s",
- },
- &AgentServiceCheck{
- TTL: "30s",
- },
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := checks["service:foo:1"]; !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if _, ok := checks["service:foo:2"]; !ok {
- t.Fatalf("missing check: %v", checks)
- }
-}
-
-func TestAgent_SetTTLStatus(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if err := agent.WarnTTL("service:foo", "test"); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "warning" {
- t.Fatalf("Bad: %#v", chk)
- }
- if chk.Output != "test" {
- t.Fatalf("Bad: %#v", chk)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Checks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentCheckRegistration{
- Name: "foo",
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "critical" {
- t.Fatalf("check not critical: %v", chk)
- }
-
- if err := agent.CheckDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_CheckStartPassing(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentCheckRegistration{
- Name: "foo",
- AgentServiceCheck: AgentServiceCheck{
- Status: "passing",
- },
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "passing" {
- t.Fatalf("check not passing: %v", chk)
- }
-
- if err := agent.CheckDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Checks_serviceBound(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // First register a service
- serviceReg := &AgentServiceRegistration{
- Name: "redis",
- }
- if err := agent.ServiceRegister(serviceReg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Register a check bound to the service
- reg := &AgentCheckRegistration{
- Name: "redischeck",
- ServiceID: "redis",
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- check, ok := checks["redischeck"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if check.ServiceID != "redis" {
- t.Fatalf("missing service association for check: %v", check)
- }
-}
-
-func TestAgent_Join(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Join ourself
- addr := info["Config"]["AdvertiseAddr"].(string)
- err = agent.Join(addr, false)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_ForceLeave(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // Eject somebody
- err := agent.ForceLeave("foo")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestServiceMaintenance(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // First register a service
- serviceReg := &AgentServiceRegistration{
- Name: "redis",
- }
- if err := agent.ServiceRegister(serviceReg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Enable maintenance mode
- if err := agent.EnableServiceMaintenance("redis", "broken"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure a critical check was added
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- found := false
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- found = true
- if check.Status != "critical" || check.Notes != "broken" {
- t.Fatalf("bad: %#v", checks)
- }
- }
- }
- if !found {
- t.Fatalf("bad: %#v", checks)
- }
-
- // Disable maintenance mode
- if err := agent.DisableServiceMaintenance("redis"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure the critical health check was removed
- checks, err = agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- t.Fatalf("should have removed health check")
- }
- }
-}
-
-func TestNodeMaintenance(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // Enable maintenance mode
- if err := agent.EnableNodeMaintenance("broken"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Check that a critical check was added
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- found := false
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- found = true
- if check.Status != "critical" || check.Notes != "broken" {
- t.Fatalf("bad: %#v", checks)
- }
- }
- }
- if !found {
- t.Fatalf("bad: %#v", checks)
- }
-
- // Disable maintenance mode
- if err := agent.DisableNodeMaintenance(); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure the check was removed
- checks, err = agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- t.Fatalf("should have removed health check")
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go
deleted file mode 100644
index 283ebe358..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go
+++ /dev/null
@@ -1,242 +0,0 @@
-package api
-
-import (
- crand "crypto/rand"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "path/filepath"
- "runtime"
- "testing"
- "time"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-type configCallback func(c *Config)
-
-func makeClient(t *testing.T) (*Client, *testutil.TestServer) {
- return makeClientWithConfig(t, nil, nil)
-}
-
-func makeClientWithConfig(
- t *testing.T,
- cb1 configCallback,
- cb2 testutil.ServerConfigCallback) (*Client, *testutil.TestServer) {
-
- // Make client config
- conf := DefaultConfig()
- if cb1 != nil {
- cb1(conf)
- }
-
- // Create server
- server := testutil.NewTestServerConfig(t, cb2)
- conf.Address = server.HTTPAddr
-
- // Create client
- client, err := NewClient(conf)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- return client, server
-}
-
-func testKey() string {
- buf := make([]byte, 16)
- if _, err := crand.Read(buf); err != nil {
- panic(fmt.Errorf("Failed to read random bytes: %v", err))
- }
-
- return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
- buf[0:4],
- buf[4:6],
- buf[6:8],
- buf[8:10],
- buf[10:16])
-}
-
-func TestDefaultConfig_env(t *testing.T) {
- t.Parallel()
- addr := "1.2.3.4:5678"
- token := "abcd1234"
- auth := "username:password"
-
- os.Setenv("CONSUL_HTTP_ADDR", addr)
- defer os.Setenv("CONSUL_HTTP_ADDR", "")
- os.Setenv("CONSUL_HTTP_TOKEN", token)
- defer os.Setenv("CONSUL_HTTP_TOKEN", "")
- os.Setenv("CONSUL_HTTP_AUTH", auth)
- defer os.Setenv("CONSUL_HTTP_AUTH", "")
- os.Setenv("CONSUL_HTTP_SSL", "1")
- defer os.Setenv("CONSUL_HTTP_SSL", "")
- os.Setenv("CONSUL_HTTP_SSL_VERIFY", "0")
- defer os.Setenv("CONSUL_HTTP_SSL_VERIFY", "")
-
- config := DefaultConfig()
-
- if config.Address != addr {
- t.Errorf("expected %q to be %q", config.Address, addr)
- }
-
- if config.Token != token {
- t.Errorf("expected %q to be %q", config.Token, token)
- }
-
- if config.HttpAuth == nil {
- t.Fatalf("expected HttpAuth to be enabled")
- }
- if config.HttpAuth.Username != "username" {
- t.Errorf("expected %q to be %q", config.HttpAuth.Username, "username")
- }
- if config.HttpAuth.Password != "password" {
- t.Errorf("expected %q to be %q", config.HttpAuth.Password, "password")
- }
-
- if config.Scheme != "https" {
- t.Errorf("expected %q to be %q", config.Scheme, "https")
- }
-
- if !config.HttpClient.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify {
- t.Errorf("expected SSL verification to be off")
- }
-}
-
-func TestSetQueryOptions(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("GET", "/v1/kv/foo")
- q := &QueryOptions{
- Datacenter: "foo",
- AllowStale: true,
- RequireConsistent: true,
- WaitIndex: 1000,
- WaitTime: 100 * time.Second,
- Token: "12345",
- }
- r.setQueryOptions(q)
-
- if r.params.Get("dc") != "foo" {
- t.Fatalf("bad: %v", r.params)
- }
- if _, ok := r.params["stale"]; !ok {
- t.Fatalf("bad: %v", r.params)
- }
- if _, ok := r.params["consistent"]; !ok {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("index") != "1000" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("wait") != "100000ms" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("token") != "12345" {
- t.Fatalf("bad: %v", r.params)
- }
-}
-
-func TestSetWriteOptions(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("GET", "/v1/kv/foo")
- q := &WriteOptions{
- Datacenter: "foo",
- Token: "23456",
- }
- r.setWriteOptions(q)
-
- if r.params.Get("dc") != "foo" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("token") != "23456" {
- t.Fatalf("bad: %v", r.params)
- }
-}
-
-func TestRequestToHTTP(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("DELETE", "/v1/kv/foo")
- q := &QueryOptions{
- Datacenter: "foo",
- }
- r.setQueryOptions(q)
- req, err := r.toHTTP()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if req.Method != "DELETE" {
- t.Fatalf("bad: %v", req)
- }
- if req.URL.RequestURI() != "/v1/kv/foo?dc=foo" {
- t.Fatalf("bad: %v", req)
- }
-}
-
-func TestParseQueryMeta(t *testing.T) {
- t.Parallel()
- resp := &http.Response{
- Header: make(map[string][]string),
- }
- resp.Header.Set("X-Consul-Index", "12345")
- resp.Header.Set("X-Consul-LastContact", "80")
- resp.Header.Set("X-Consul-KnownLeader", "true")
-
- qm := &QueryMeta{}
- if err := parseQueryMeta(resp, qm); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex != 12345 {
- t.Fatalf("Bad: %v", qm)
- }
- if qm.LastContact != 80*time.Millisecond {
- t.Fatalf("Bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("Bad: %v", qm)
- }
-}
-
-func TestAPI_UnixSocket(t *testing.T) {
- t.Parallel()
- if runtime.GOOS == "windows" {
- t.SkipNow()
- }
-
- tempDir, err := ioutil.TempDir("", "consul")
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- defer os.RemoveAll(tempDir)
- socket := filepath.Join(tempDir, "test.sock")
-
- c, s := makeClientWithConfig(t, func(c *Config) {
- c.Address = "unix://" + socket
- }, func(c *testutil.TestServerConfig) {
- c.Addresses = &testutil.TestAddressConfig{
- HTTP: "unix://" + socket,
- }
- })
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- if info["Config"]["NodeName"] == "" {
- t.Fatalf("bad: %v", info)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go
deleted file mode 100644
index bb8be25b0..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go
+++ /dev/null
@@ -1,279 +0,0 @@
-package api
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestCatalog_Datacenters(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- datacenters, err := catalog.Datacenters()
- if err != nil {
- return false, err
- }
-
- if len(datacenters) == 0 {
- return false, fmt.Errorf("Bad: %v", datacenters)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Nodes(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- nodes, meta, err := catalog.Nodes(nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(nodes) == 0 {
- return false, fmt.Errorf("Bad: %v", nodes)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Services(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- services, meta, err := catalog.Services(nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(services) == 0 {
- return false, fmt.Errorf("Bad: %v", services)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Service(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- services, meta, err := catalog.Service("consul", "", nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(services) == 0 {
- return false, fmt.Errorf("Bad: %v", services)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
- name, _ := c.Agent().NodeName()
-
- testutil.WaitForResult(func() (bool, error) {
- info, meta, err := catalog.Node(name, nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
- if len(info.Services) == 0 {
- return false, fmt.Errorf("Bad: %v", info)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Registration(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- service := &AgentService{
- ID: "redis1",
- Service: "redis",
- Tags: []string{"master", "v1"},
- Port: 8000,
- }
-
- check := &AgentCheck{
- Node: "foobar",
- CheckID: "service:redis1",
- Name: "Redis health check",
- Notes: "Script based health check",
- Status: "passing",
- ServiceID: "redis1",
- }
-
- reg := &CatalogRegistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- Service: service,
- Check: check,
- }
-
- testutil.WaitForResult(func() (bool, error) {
- if _, err := catalog.Register(reg, nil); err != nil {
- return false, err
- }
-
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if _, ok := node.Services["redis1"]; !ok {
- return false, fmt.Errorf("missing service: redis1")
- }
-
- health, _, err := c.Health().Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if health[0].CheckID != "service:redis1" {
- return false, fmt.Errorf("missing checkid service:redis1")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test catalog deregistration of the previously registered service
- dereg := &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- ServiceID: "redis1",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if _, ok := node.Services["redis1"]; ok {
- return false, fmt.Errorf("ServiceID:redis1 is not deregistered")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test deregistration of the previously registered check
- dereg = &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- CheckID: "service:redis1",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- health, _, err := c.Health().Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if len(health) != 0 {
- return false, fmt.Errorf("CheckID:service:redis1 is not deregistered")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test node deregistration of the previously registered node
- dereg = &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if node != nil {
- return false, fmt.Errorf("node is not deregistered: %v", node)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go
deleted file mode 100644
index 1ca92e233..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package api
-
-import (
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestEvent_FireList(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- event := c.Event()
-
- params := &UserEvent{Name: "foo"}
- id, meta, err := event.Fire(params, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- var events []*UserEvent
- var qm *QueryMeta
- testutil.WaitForResult(func() (bool, error) {
- events, qm, err = event.List("", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- return len(events) > 0, err
- }, func(err error) {
- t.Fatalf("err: %#v", err)
- })
-
- if events[len(events)-1].ID != id {
- t.Fatalf("bad: %#v", events)
- }
-
- if qm.LastIndex != event.IDToIndex(id) {
- t.Fatalf("Bad: %#v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go
deleted file mode 100644
index d80a4693a..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package api
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestHealth_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- health := c.Health()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- name := info["Config"]["NodeName"].(string)
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.Node(name, nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_Checks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- health := c.Health()
-
- // Make a service with a check
- reg := &AgentServiceRegistration{
- Name: "foo",
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
- defer agent.ServiceDeregister("foo")
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.Checks("foo", nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_Service(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- health := c.Health()
-
- testutil.WaitForResult(func() (bool, error) {
- // consul service should always exist...
- checks, meta, err := health.Service("consul", "", true, nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_State(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- health := c.Health()
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.State("any", nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go
deleted file mode 100644
index 346d13681..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go
+++ /dev/null
@@ -1,439 +0,0 @@
-package api
-
-import (
- "bytes"
- "path"
- "testing"
- "time"
-)
-
-func TestClientPutGetDelete(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- key := testKey()
- pair, _, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
-
- // Put the key
- value := []byte("test")
- p := &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if pair.Flags != 42 {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete
- if _, err := kv.Delete(key, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Get should fail
- pair, _, err = kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
-}
-
-func TestClient_List_DeleteRecurse(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Generate some test keys
- prefix := testKey()
- var keys []string
- for i := 0; i < 100; i++ {
- keys = append(keys, path.Join(prefix, testKey()))
- }
-
- // Set values
- value := []byte("test")
- for _, key := range keys {
- p := &KVPair{Key: key, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }
-
- // List the values
- pairs, meta, err := kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != len(keys) {
- t.Fatalf("got %d keys", len(pairs))
- }
- for _, pair := range pairs {
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete all
- if _, err := kv.DeleteTree(prefix, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // List the values
- pairs, _, err = kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 0 {
- t.Fatalf("got %d keys", len(pairs))
- }
-}
-
-func TestClient_DeleteCAS(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Put the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value}
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("CAS failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // CAS update with bad index
- p.ModifyIndex = 1
- if work, _, err := kv.DeleteCAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if work {
- t.Fatalf("unexpected CAS")
- }
-
- // CAS update with valid index
- p.ModifyIndex = meta.LastIndex
- if work, _, err := kv.DeleteCAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("unexpected CAS failure")
- }
-}
-
-func TestClient_CAS(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Put the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value}
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("CAS failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // CAS update with bad index
- newVal := []byte("foo")
- p.Value = newVal
- p.ModifyIndex = 1
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if work {
- t.Fatalf("unexpected CAS")
- }
-
- // CAS update with valid index
- p.ModifyIndex = meta.LastIndex
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("unexpected CAS failure")
- }
-}
-
-func TestClient_WatchGet(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- key := testKey()
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Put the key
- value := []byte("test")
- go func() {
- kv := c.KV()
-
- time.Sleep(100 * time.Millisecond)
- p := &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }()
-
- // Get should work
- options := &QueryOptions{WaitIndex: meta.LastIndex}
- pair, meta2, err := kv.Get(key, options)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if pair.Flags != 42 {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta2.LastIndex <= meta.LastIndex {
- t.Fatalf("unexpected value: %#v", meta2)
- }
-}
-
-func TestClient_WatchList(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- prefix := testKey()
- key := path.Join(prefix, testKey())
- pairs, meta, err := kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 0 {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Put the key
- value := []byte("test")
- go func() {
- kv := c.KV()
-
- time.Sleep(100 * time.Millisecond)
- p := &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }()
-
- // Get should work
- options := &QueryOptions{WaitIndex: meta.LastIndex}
- pairs, meta2, err := kv.List(prefix, options)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 1 {
- t.Fatalf("expected value: %#v", pairs)
- }
- if !bytes.Equal(pairs[0].Value, value) {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if pairs[0].Flags != 42 {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if meta2.LastIndex <= meta.LastIndex {
- t.Fatalf("unexpected value: %#v", meta2)
- }
-
-}
-
-func TestClient_Keys_DeleteRecurse(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Generate some test keys
- prefix := testKey()
- var keys []string
- for i := 0; i < 100; i++ {
- keys = append(keys, path.Join(prefix, testKey()))
- }
-
- // Set values
- value := []byte("test")
- for _, key := range keys {
- p := &KVPair{Key: key, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }
-
- // List the values
- out, meta, err := kv.Keys(prefix, "", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(out) != len(keys) {
- t.Fatalf("got %d keys", len(out))
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete all
- if _, err := kv.DeleteTree(prefix, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // List the values
- out, _, err = kv.Keys(prefix, "", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(out) != 0 {
- t.Fatalf("got %d keys", len(out))
- }
-}
-
-func TestClient_AcquireRelease(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
- kv := c.KV()
-
- // Make a session
- id, _, err := session.CreateNoChecks(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- // Acquire the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value, Session: id}
- if work, _, err := kv.Acquire(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("Lock failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if pair.LockIndex != 1 {
- t.Fatalf("Expected lock: %v", pair)
- }
- if pair.Session != id {
- t.Fatalf("Expected lock: %v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Release
- if work, _, err := kv.Release(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("Release fail")
- }
-
- // Get should work
- pair, meta, err = kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if pair.LockIndex != 1 {
- t.Fatalf("Expected lock: %v", pair)
- }
- if pair.Session != "" {
- t.Fatalf("Expected unlock: %v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go
deleted file mode 100644
index 0a8fa5172..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go
+++ /dev/null
@@ -1,363 +0,0 @@
-package api
-
-import (
- "log"
- "sync"
- "testing"
- "time"
-)
-
-func TestLock_LockUnlock(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Initial unlock should fail
- err = lock.Unlock()
- if err != ErrLockNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Double lock should fail
- _, err = lock.Lock(nil)
- if err != ErrLockHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be leader
- select {
- case <-leaderCh:
- t.Fatalf("should be leader")
- default:
- }
-
- // Initial unlock should work
- err = lock.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double unlock should fail
- err = lock.Unlock()
- if err != ErrLockNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_ForceInvalidate(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- go func() {
- // Nuke the session, simulator an operator invalidation
- // or a health check failure
- session := c.Session()
- session.Destroy(lock.lockSession, nil)
- }()
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_DeleteKey(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- go func() {
- // Nuke the key, simulate an operator intervention
- kv := c.KV()
- kv.Delete("test/lock", nil)
- }()
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_Contend(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- wg := &sync.WaitGroup{}
- acquired := make([]bool, 3)
- for idx := range acquired {
- wg.Add(1)
- go func(idx int) {
- defer wg.Done()
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work eventually, will contend
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
- log.Printf("Contender %d acquired", idx)
-
- // Set acquired and then leave
- acquired[idx] = true
- }(idx)
- }
-
- // Wait for termination
- doneCh := make(chan struct{})
- go func() {
- wg.Wait()
- close(doneCh)
- }()
-
- // Wait for everybody to get a turn
- select {
- case <-doneCh:
- case <-time.After(3 * DefaultLockRetryTime):
- t.Fatalf("timeout")
- }
-
- for idx, did := range acquired {
- if !did {
- t.Fatalf("contender %d never acquired", idx)
- }
- }
-}
-
-func TestLock_Destroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Destroy should fail
- if err := lock.Destroy(); err != ErrLockHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be able to release
- err = lock.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Acquire with a different lock
- l2, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err = l2.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Destroy should still fail
- if err := lock.Destroy(); err != ErrLockInUse {
- t.Fatalf("err: %v", err)
- }
-
- // Should relese
- err = l2.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- err = lock.Destroy()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double destroy should work
- err = l2.Destroy()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestLock_Conflict(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/lock/", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not hold")
- }
- defer sema.Release()
-
- lock, err := c.LockKey("test/lock/.lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with semaphore
- _, err = lock.Lock(nil)
- if err != ErrLockConflict {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with semaphore
- err = lock.Destroy()
- if err != ErrLockConflict {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestLock_ReclaimLock(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session, _, err := c.Session().Create(&SessionEntry{}, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- lock, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- l2, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- reclaimed := make(chan (<-chan struct{}), 1)
- go func() {
- l2Ch, err := l2.Lock(nil)
- if err != nil {
- t.Fatalf("not locked: %v", err)
- }
- reclaimed <- l2Ch
- }()
-
- // Should reclaim the lock
- var leader2Ch <-chan struct{}
-
- select {
- case leader2Ch = <-reclaimed:
- case <-time.After(time.Second):
- t.Fatalf("should have locked")
- }
-
- // unlock should work
- err = l2.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- //Both locks should see the unlock
- select {
- case <-leader2Ch:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go
deleted file mode 100644
index 5e5e53588..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package api
-
-import (
- "log"
- "sync"
- "testing"
- "time"
-)
-
-func TestSemaphore_AcquireRelease(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Initial release should fail
- err = sema.Release()
- if err != ErrSemaphoreNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not hold")
- }
-
- // Double lock should fail
- _, err = sema.Acquire(nil)
- if err != ErrSemaphoreHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be held
- select {
- case <-lockCh:
- t.Fatalf("should be held")
- default:
- }
-
- // Initial release should work
- err = sema.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double unlock should fail
- err = sema.Release()
- if err != ErrSemaphoreNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should lose resource
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be held")
- }
-}
-
-func TestSemaphore_ForceInvalidate(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not acquired")
- }
- defer sema.Release()
-
- go func() {
- // Nuke the session, simulator an operator invalidation
- // or a health check failure
- session := c.Session()
- session.Destroy(sema.lockSession, nil)
- }()
-
- // Should loose slot
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be locked")
- }
-}
-
-func TestSemaphore_DeleteKey(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not locked")
- }
- defer sema.Release()
-
- go func() {
- // Nuke the key, simulate an operator intervention
- kv := c.KV()
- kv.DeleteTree("test/semaphore", nil)
- }()
-
- // Should loose leadership
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be locked")
- }
-}
-
-func TestSemaphore_Contend(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- wg := &sync.WaitGroup{}
- acquired := make([]bool, 4)
- for idx := range acquired {
- wg.Add(1)
- go func(idx int) {
- defer wg.Done()
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work eventually, will contend
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not locked")
- }
- defer sema.Release()
- log.Printf("Contender %d acquired", idx)
-
- // Set acquired and then leave
- acquired[idx] = true
- }(idx)
- }
-
- // Wait for termination
- doneCh := make(chan struct{})
- go func() {
- wg.Wait()
- close(doneCh)
- }()
-
- // Wait for everybody to get a turn
- select {
- case <-doneCh:
- case <-time.After(3 * DefaultLockRetryTime):
- t.Fatalf("timeout")
- }
-
- for idx, did := range acquired {
- if !did {
- t.Fatalf("contender %d never acquired", idx)
- }
- }
-}
-
-func TestSemaphore_BadLimit(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 0)
- if err == nil {
- t.Fatalf("should error")
- }
-
- sema, err = c.SemaphorePrefix("test/semaphore", 1)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sema2, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema2.Acquire(nil)
- if err.Error() != "semaphore limit conflict (lock: 1, local: 2)" {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestSemaphore_Destroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sema2, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema2.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should fail, still held
- if err := sema.Destroy(); err != ErrSemaphoreHeld {
- t.Fatalf("err: %v", err)
- }
-
- err = sema.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should fail, still in use
- if err := sema.Destroy(); err != ErrSemaphoreInUse {
- t.Fatalf("err: %v", err)
- }
-
- err = sema2.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- if err := sema.Destroy(); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- if err := sema2.Destroy(); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestSemaphore_Conflict(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/sema/.lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- sema, err := c.SemaphorePrefix("test/sema/", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with lock
- _, err = sema.Acquire(nil)
- if err != ErrSemaphoreConflict {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with lock
- err = sema.Destroy()
- if err != ErrSemaphoreConflict {
- t.Fatalf("err: %v", err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go
deleted file mode 100644
index c503c21a0..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package api
-
-import (
- "testing"
-)
-
-func TestSession_CreateDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, meta, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- meta, err = session.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-}
-
-func TestSession_CreateRenewDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- se := &SessionEntry{
- TTL: "10s",
- }
-
- id, meta, err := session.Create(se, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- renew, meta, err := session.Renew(id, nil)
-
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if renew == nil {
- t.Fatalf("should get session")
- }
-
- if renew.ID != id {
- t.Fatalf("should have matching id")
- }
-
- if renew.TTL != "10s" {
- t.Fatalf("should get session with TTL")
- }
-}
-
-func TestSession_Info(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- info, qm, err := session.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-
- if info == nil {
- t.Fatalf("should get session")
- }
- if info.CreateIndex == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.ID != id {
- t.Fatalf("bad: %v", info)
- }
- if info.Name != "" {
- t.Fatalf("bad: %v", info)
- }
- if info.Node == "" {
- t.Fatalf("bad: %v", info)
- }
- if len(info.Checks) == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.LockDelay == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.Behavior != "release" {
- t.Fatalf("bad: %v", info)
- }
- if info.TTL != "" {
- t.Fatalf("bad: %v", info)
- }
-}
-
-func TestSession_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- info, qm, err := session.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sessions, qm, err := session.Node(info.Node, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(sessions) != 1 {
- t.Fatalf("bad: %v", sessions)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
-
-func TestSession_List(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- sessions, qm, err := session.List(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(sessions) != 1 {
- t.Fatalf("bad: %v", sessions)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go
deleted file mode 100644
index 62dc1550f..000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package api
-
-import (
- "testing"
-)
-
-func TestStatusLeader(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- status := c.Status()
-
- leader, err := status.Leader()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leader == "" {
- t.Fatalf("Expected leader")
- }
-}
-
-func TestStatusPeers(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- status := c.Status()
-
- peers, err := status.Peers()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(peers) == 0 {
- t.Fatalf("Expected peers ")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/jainvipin/bitset/bitset_test.go b/Godeps/_workspace/src/github.com/jainvipin/bitset/bitset_test.go
deleted file mode 100644
index eb7466da2..000000000
--- a/Godeps/_workspace/src/github.com/jainvipin/bitset/bitset_test.go
+++ /dev/null
@@ -1,792 +0,0 @@
-// Copyright 2014 Will Fitzgerald. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This file tests bit sets
-
-package bitset
-
-import (
- "encoding/json"
- "math"
- "math/rand"
- "testing"
-)
-
-func TestEmptyBitSet(t *testing.T) {
- defer func() {
- if r := recover(); r != nil {
- t.Error("A zero-length bitset should be fine")
- }
- }()
- b := New(0)
- if b.Len() != 0 {
- t.Errorf("Empty set should have capacity 0, not %d", b.Len())
- }
-}
-
-func TestZeroValueBitSet(t *testing.T) {
- defer func() {
- if r := recover(); r != nil {
- t.Error("A zero-length bitset should be fine")
- }
- }()
- var b BitSet
- if b.Len() != 0 {
- t.Errorf("Empty set should have capacity 0, not %d", b.Len())
- }
-}
-
-func TestBitSetNew(t *testing.T) {
- v := New(16)
- if v.Test(0) != false {
- t.Errorf("Unable to make a bit set and read its 0th value.")
- }
-}
-
-func TestBitSetHuge(t *testing.T) {
- v := New(uint(math.MaxUint32))
- if v.Test(0) != false {
- t.Errorf("Unable to make a huge bit set and read its 0th value.")
- }
-}
-
-func TestLen(t *testing.T) {
- v := New(1000)
- if v.Len() != 1000 {
- t.Errorf("Len should be 1000, but is %d.", v.Len())
- }
-}
-
-func TestBitSetIsClear(t *testing.T) {
- v := New(1000)
- for i := uint(0); i < 1000; i++ {
- if v.Test(i) != false {
- t.Errorf("Bit %d is set, and it shouldn't be.", i)
- }
- }
-}
-
-func TestExendOnBoundary(t *testing.T) {
- v := New(32)
- defer func() {
- if r := recover(); r != nil {
- t.Error("Border out of index error should not have caused a panic")
- }
- }()
- v.Set(32)
-}
-
-func TestExpand(t *testing.T) {
- v := New(0)
- defer func() {
- if r := recover(); r != nil {
- t.Error("Expansion should not have caused a panic")
- }
- }()
- for i := uint(0); i < 1000; i++ {
- v.Set(i)
- }
-}
-
-func TestBitSetAndGet(t *testing.T) {
- v := New(1000)
- v.Set(100)
- if v.Test(100) != true {
- t.Errorf("Bit %d is clear, and it shouldn't be.", 100)
- }
-}
-
-func TestNextClear(t *testing.T) {
- v := New(1000)
- v.Set(0).Set(1)
- next, found := v.NextClear(0)
- if !found || next != 2 {
- t.Errorf("Found next clear bit as %d, it should have been 2", next)
- }
-
- v = New(1000)
- for i := uint(0); i < 66; i++ {
- v.Set(i)
- }
- next, found = v.NextClear(0)
- if !found || next != 66 {
- t.Errorf("Found next clear bit as %d, it should have been 66", next)
- }
-
- v = New(1000)
- for i := uint(0); i < 64; i++ {
- v.Set(i)
- }
- v.Clear(45)
- v.Clear(52)
- next, found = v.NextClear(10)
- if !found || next != 45 {
- t.Errorf("Found next clear bit as %d, it should have been 45", next)
- }
-
- v = New(1000)
- for i := uint(0); i < 128; i++ {
- v.Set(i)
- }
- v.Clear(73)
- v.Clear(99)
- next, found = v.NextClear(10)
- if !found || next != 73 {
- t.Errorf("Found next clear bit as %d, it should have been 73", next)
- }
-}
-
-func TestIterate(t *testing.T) {
- v := New(10000)
- v.Set(0)
- v.Set(1)
- v.Set(2)
- data := make([]uint, 3)
- c := 0
- for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) {
- data[c] = i
- c++
- }
- if data[0] != 0 {
- t.Errorf("bug 0")
- }
- if data[1] != 1 {
- t.Errorf("bug 1")
- }
- if data[2] != 2 {
- t.Errorf("bug 2")
- }
- v.Set(10)
- v.Set(2000)
- data = make([]uint, 5)
- c = 0
- for i, e := v.NextSet(0); e; i, e = v.NextSet(i + 1) {
- data[c] = i
- c++
- }
- if data[0] != 0 {
- t.Errorf("bug 0")
- }
- if data[1] != 1 {
- t.Errorf("bug 1")
- }
- if data[2] != 2 {
- t.Errorf("bug 2")
- }
- if data[3] != 10 {
- t.Errorf("bug 3")
- }
- if data[4] != 2000 {
- t.Errorf("bug 4")
- }
-
-}
-
-func TestSetTo(t *testing.T) {
- v := New(1000)
- v.SetTo(100, true)
- if v.Test(100) != true {
- t.Errorf("Bit %d is clear, and it shouldn't be.", 100)
- }
- v.SetTo(100, false)
- if v.Test(100) != false {
- t.Errorf("Bit %d is set, and it shouldn't be.", 100)
- }
-}
-
-func TestChain(t *testing.T) {
- if New(1000).Set(100).Set(99).Clear(99).Test(100) != true {
- t.Errorf("Bit %d is clear, and it shouldn't be.", 100)
- }
-}
-
-func TestOutOfBoundsLong(t *testing.T) {
- v := New(64)
- defer func() {
- if r := recover(); r != nil {
- t.Error("Long distance out of index error should not have caused a panic")
- }
- }()
- v.Set(1000)
-}
-
-func TestOutOfBoundsClose(t *testing.T) {
- v := New(65)
- defer func() {
- if r := recover(); r != nil {
- t.Error("Local out of index error should not have caused a panic")
- }
- }()
- v.Set(66)
-}
-
-func TestCount(t *testing.T) {
- tot := uint(64*4 + 11) // just some multi unit64 number
- v := New(tot)
- checkLast := true
- for i := uint(0); i < tot; i++ {
- sz := uint(v.Count())
- if sz != i {
- t.Errorf("Count reported as %d, but it should be %d", sz, i)
- checkLast = false
- break
- }
- v.Set(i)
- }
- if checkLast {
- sz := uint(v.Count())
- if sz != tot {
- t.Errorf("After all bits set, size reported as %d, but it should be %d", sz, tot)
- }
- }
-}
-
-// test setting every 3rd bit, just in case something odd is happening
-func TestCount2(t *testing.T) {
- tot := uint(64*4 + 11) // just some multi unit64 number
- v := New(tot)
- for i := uint(0); i < tot; i += 3 {
- sz := uint(v.Count())
- if sz != i/3 {
- t.Errorf("Count reported as %d, but it should be %d", sz, i)
- break
- }
- v.Set(i)
- }
-}
-
-// nil tests
-func TestNullTest(t *testing.T) {
- var v *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Checking bit of null reference should have caused a panic")
- }
- }()
- v.Test(66)
-}
-
-func TestNullSet(t *testing.T) {
- var v *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Setting bit of null reference should have caused a panic")
- }
- }()
- v.Set(66)
-}
-
-func TestNullClear(t *testing.T) {
- var v *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Clearning bit of null reference should have caused a panic")
- }
- }()
- v.Clear(66)
-}
-
-func TestNullCount(t *testing.T) {
- var v *BitSet = nil
- defer func() {
- if r := recover(); r != nil {
- t.Error("Counting null reference should not have caused a panic")
- }
- }()
- cnt := v.Count()
- if cnt != 0 {
- t.Errorf("Count reported as %d, but it should be 0", cnt)
- }
-}
-
-func TestPanicDifferenceBNil(t *testing.T) {
- var b *BitSet = nil
- var compare = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil First should should have caused a panic")
- }
- }()
- b.Difference(compare)
-}
-
-func TestPanicDifferenceCompareNil(t *testing.T) {
- var compare *BitSet = nil
- var b = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil Second should should have caused a panic")
- }
- }()
- b.Difference(compare)
-}
-
-func TestPanicUnionBNil(t *testing.T) {
- var b *BitSet = nil
- var compare = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil First should should have caused a panic")
- }
- }()
- b.Union(compare)
-}
-
-func TestPanicUnionCompareNil(t *testing.T) {
- var compare *BitSet = nil
- var b = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil Second should should have caused a panic")
- }
- }()
- b.Union(compare)
-}
-
-func TestPanicIntersectionBNil(t *testing.T) {
- var b *BitSet = nil
- var compare = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil First should should have caused a panic")
- }
- }()
- b.Intersection(compare)
-}
-
-func TestPanicIntersectionCompareNil(t *testing.T) {
- var compare *BitSet = nil
- var b = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil Second should should have caused a panic")
- }
- }()
- b.Intersection(compare)
-}
-
-func TestPanicSymmetricDifferenceBNil(t *testing.T) {
- var b *BitSet = nil
- var compare = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil First should should have caused a panic")
- }
- }()
- b.SymmetricDifference(compare)
-}
-
-func TestPanicSymmetricDifferenceCompareNil(t *testing.T) {
- var compare *BitSet = nil
- var b = New(10)
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil Second should should have caused a panic")
- }
- }()
- b.SymmetricDifference(compare)
-}
-
-func TestPanicComplementBNil(t *testing.T) {
- var b *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil should should have caused a panic")
- }
- }()
- b.Complement()
-}
-
-func TestPanicAnytBNil(t *testing.T) {
- var b *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil should should have caused a panic")
- }
- }()
- b.Any()
-}
-
-func TestPanicNonetBNil(t *testing.T) {
- var b *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil should should have caused a panic")
- }
- }()
- b.None()
-}
-
-func TestPanicAlltBNil(t *testing.T) {
- var b *BitSet = nil
- defer func() {
- if r := recover(); r == nil {
- t.Error("Nil should should have caused a panic")
- }
- }()
- b.All()
-}
-
-func TestEqual(t *testing.T) {
- a := New(100)
- b := New(99)
- c := New(100)
- if a.Equal(b) {
- t.Error("Sets of different sizes should be not be equal")
- }
- if !a.Equal(c) {
- t.Error("Two empty sets of the same size should be equal")
- }
- a.Set(99)
- c.Set(0)
- if a.Equal(c) {
- t.Error("Two sets with differences should not be equal")
- }
- c.Set(99)
- a.Set(0)
- if !a.Equal(c) {
- t.Error("Two sets with the same bits set should be equal")
- }
-}
-
-func TestUnion(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- if a.UnionCardinality(b) != 200 {
- t.Errorf("Union should have 200 bits set, but had %d", a.UnionCardinality(b))
- }
- if a.UnionCardinality(b) != b.UnionCardinality(a) {
- t.Errorf("Union should be symmetric")
- }
-
- c := a.Union(b)
- d := b.Union(a)
- if c.Count() != 200 {
- t.Errorf("Union should have 200 bits set, but had %d", c.Count())
- }
- if !c.Equal(d) {
- t.Errorf("Union should be symmetric")
- }
-}
-
-func TestInPlaceUnion(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- c := a.Clone()
- c.InPlaceUnion(b)
- d := b.Clone()
- d.InPlaceUnion(a)
- if c.Count() != 200 {
- t.Errorf("Union should have 200 bits set, but had %d", c.Count())
- }
- if d.Count() != 200 {
- t.Errorf("Union should have 200 bits set, but had %d", d.Count())
- }
- if !c.Equal(d) {
- t.Errorf("Union should be symmetric")
- }
-}
-
-func TestIntersection(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1).Set(i)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- if a.IntersectionCardinality(b) != 50 {
- t.Errorf("Intersection should have 50 bits set, but had %d", a.IntersectionCardinality(b))
- }
- if a.IntersectionCardinality(b) != b.IntersectionCardinality(a) {
- t.Errorf("Intersection should be symmetric")
- }
- c := a.Intersection(b)
- d := b.Intersection(a)
- if c.Count() != 50 {
- t.Errorf("Intersection should have 50 bits set, but had %d", c.Count())
- }
- if !c.Equal(d) {
- t.Errorf("Intersection should be symmetric")
- }
-}
-
-func TestInplaceIntersection(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1).Set(i)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- c := a.Clone()
- c.InPlaceIntersection(b)
- d := b.Clone()
- d.InPlaceIntersection(a)
- if c.Count() != 50 {
- t.Errorf("Intersection should have 50 bits set, but had %d", c.Count())
- }
- if d.Count() != 50 {
- t.Errorf("Intersection should have 50 bits set, but had %d", d.Count())
- }
- if !c.Equal(d) {
- t.Errorf("Intersection should be symmetric")
- }
-}
-
-func TestDifference(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- if a.DifferenceCardinality(b) != 50 {
- t.Errorf("a-b Difference should have 50 bits set, but had %d", a.DifferenceCardinality(b))
- }
- if b.DifferenceCardinality(a) != 150 {
- t.Errorf("b-a Difference should have 150 bits set, but had %d", b.DifferenceCardinality(a))
- }
-
- c := a.Difference(b)
- d := b.Difference(a)
- if c.Count() != 50 {
- t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count())
- }
- if d.Count() != 150 {
- t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count())
- }
- if c.Equal(d) {
- t.Errorf("Difference, here, should not be symmetric")
- }
-}
-
-func TestInPlaceDifference(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i)
- b.Set(i - 1)
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- c := a.Clone()
- c.InPlaceDifference(b)
- d := b.Clone()
- d.InPlaceDifference(a)
- if c.Count() != 50 {
- t.Errorf("a-b Difference should have 50 bits set, but had %d", c.Count())
- }
- if d.Count() != 150 {
- t.Errorf("b-a Difference should have 150 bits set, but had %d", d.Count())
- }
- if c.Equal(d) {
- t.Errorf("Difference, here, should not be symmetric")
- }
-}
-
-func TestSymmetricDifference(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i) // 01010101010 ... 0000000
- b.Set(i - 1).Set(i) // 11111111111111111000000
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- if a.SymmetricDifferenceCardinality(b) != 150 {
- t.Errorf("a^b Difference should have 150 bits set, but had %d", a.SymmetricDifferenceCardinality(b))
- }
- if b.SymmetricDifferenceCardinality(a) != 150 {
- t.Errorf("b^a Difference should have 150 bits set, but had %d", b.SymmetricDifferenceCardinality(a))
- }
-
- c := a.SymmetricDifference(b)
- d := b.SymmetricDifference(a)
- if c.Count() != 150 {
- t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count())
- }
- if d.Count() != 150 {
- t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count())
- }
- if !c.Equal(d) {
- t.Errorf("SymmetricDifference should be symmetric")
- }
-}
-
-func TestInPlaceSymmetricDifference(t *testing.T) {
- a := New(100)
- b := New(200)
- for i := uint(1); i < 100; i += 2 {
- a.Set(i) // 01010101010 ... 0000000
- b.Set(i - 1).Set(i) // 11111111111111111000000
- }
- for i := uint(100); i < 200; i++ {
- b.Set(i)
- }
- c := a.Clone()
- c.InPlaceSymmetricDifference(b)
- d := b.Clone()
- d.InPlaceSymmetricDifference(a)
- if c.Count() != 150 {
- t.Errorf("a^b Difference should have 150 bits set, but had %d", c.Count())
- }
- if d.Count() != 150 {
- t.Errorf("b^a Difference should have 150 bits set, but had %d", d.Count())
- }
- if !c.Equal(d) {
- t.Errorf("SymmetricDifference should be symmetric")
- }
-}
-
-func TestComplement(t *testing.T) {
- a := New(50)
- b := a.Complement()
- if b.Count() != 50 {
- t.Errorf("Complement failed, size should be 50, but was %d", b.Count())
- }
- a = New(50)
- a.Set(10).Set(20).Set(42)
- b = a.Complement()
- if b.Count() != 47 {
- t.Errorf("Complement failed, size should be 47, but was %d", b.Count())
- }
-}
-
-func TestDumpAsBits(t *testing.T) {
- a := New(10).Set(10)
- astr := "0000000000000000000000000000000000000000000000000000010000000000."
- if a.DumpAsBits() != astr {
- t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", astr, a.DumpAsBits())
- }
- var b BitSet // zero value (b.set == nil)
- bstr := "."
- if b.DumpAsBits() != bstr {
- t.Errorf("DumpAsBits failed, output should be \"%s\" but was \"%s\"", bstr, b.DumpAsBits())
- }
-}
-
-func TestMarshalUnmarshalJSON(t *testing.T) {
- a := New(1010).Set(10).Set(1001)
- data, err := json.Marshal(a)
- if err != nil {
- t.Errorf(err.Error())
- return
- }
-
- b := new(BitSet)
- err = json.Unmarshal(data, b)
- if err != nil {
- t.Errorf(err.Error())
- return
- }
-
- // Bitsets must be equal after marshalling and unmarshalling
- if !a.Equal(b) {
- t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits())
- return
- }
-}
-
-// BENCHMARKS
-
-func BenchmarkSet(b *testing.B) {
- b.StopTimer()
- r := rand.New(rand.NewSource(0))
- sz := 100000
- s := New(uint(sz))
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- s.Set(uint(r.Int31n(int32(sz))))
- }
-}
-
-func BenchmarkGetTest(b *testing.B) {
- b.StopTimer()
- r := rand.New(rand.NewSource(0))
- sz := 100000
- s := New(uint(sz))
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- s.Test(uint(r.Int31n(int32(sz))))
- }
-}
-
-func BenchmarkSetExpand(b *testing.B) {
- b.StopTimer()
- sz := uint(100000)
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- var s BitSet
- s.Set(sz)
- }
-}
-
-// go test -bench=Count
-func BenchmarkCount(b *testing.B) {
- b.StopTimer()
- s := New(100000)
- for i := 0; i < 100000; i += 100 {
- s.Set(uint(i))
- }
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- s.Count()
- }
-}
-
-// go test -bench=Iterate
-func BenchmarkIterate(b *testing.B) {
- b.StopTimer()
- s := New(10000)
- for i := 0; i < 10000; i += 3 {
- s.Set(uint(i))
- }
- b.StartTimer()
- for j := 0; j < b.N; j++ {
- c := uint(0)
- for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) {
- c++
- }
- }
-}
-
-// go test -bench=SparseIterate
-func BenchmarkSparseIterate(b *testing.B) {
- b.StopTimer()
- s := New(100000)
- for i := 0; i < 100000; i += 30 {
- s.Set(uint(i))
- }
- b.StartTimer()
- for j := 0; j < b.N; j++ {
- c := uint(0)
- for i, e := s.NextSet(0); e; i, e = s.NextSet(i + 1) {
- c++
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/events.go b/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/events.go
deleted file mode 100644
index 2d6de40c7..000000000
--- a/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/events.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package main
-
-import (
- "github.com/samalba/dockerclient"
- "log"
- "os"
- "os/signal"
- "syscall"
-)
-
-func eventCallback(e *dockerclient.Event, ec chan error, args ...interface{}) {
- log.Println(e)
-}
-
-var (
- client *dockerclient.DockerClient
-)
-
-func waitForInterrupt() {
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
- for _ = range sigChan {
- client.StopAllMonitorEvents()
- os.Exit(0)
- }
-}
-
-func main() {
- docker, err := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), nil)
- if err != nil {
- log.Fatal(err)
- }
-
- client = docker
-
- client.StartMonitorEvents(eventCallback, nil)
-
- waitForInterrupt()
-}
diff --git a/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/stats/stats.go b/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/stats/stats.go
deleted file mode 100644
index 81ee2fb45..000000000
--- a/Godeps/_workspace/src/github.com/samalba/dockerclient/examples/stats/stats.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package main
-
-import (
- "github.com/samalba/dockerclient"
- "log"
- "os"
- "os/signal"
- "syscall"
-)
-
-func statCallback(id string, stat *dockerclient.Stats, ec chan error, args ...interface{}) {
- log.Println(stat)
-}
-
-func waitForInterrupt() {
- sigChan := make(chan os.Signal, 1)
- signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
- for _ = range sigChan {
- os.Exit(0)
- }
-}
-
-func main() {
- docker, err := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), nil)
- if err != nil {
- log.Fatal(err)
- }
-
- containerConfig := &dockerclient.ContainerConfig{Image: "busybox", Cmd: []string{"sh"}}
- containerId, err := docker.CreateContainer(containerConfig, "", nil)
- if err != nil {
- log.Fatal(err)
- }
-
- // Start the container
- err = docker.StartContainer(containerId, nil)
- if err != nil {
- log.Fatal(err)
- }
- docker.StartMonitorStats(containerId, statCallback, nil)
-
- waitForInterrupt()
-}
diff --git a/Godeps/_workspace/src/github.com/samalba/dockerclient/mockclient/mock.go b/Godeps/_workspace/src/github.com/samalba/dockerclient/mockclient/mock.go
deleted file mode 100644
index 12c50eed6..000000000
--- a/Godeps/_workspace/src/github.com/samalba/dockerclient/mockclient/mock.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package mockclient
-
-import (
- "io"
-
- "github.com/samalba/dockerclient"
- "github.com/stretchr/testify/mock"
-)
-
-type MockClient struct {
- mock.Mock
-}
-
-func NewMockClient() *MockClient {
- return &MockClient{}
-}
-
-func (client *MockClient) Info() (*dockerclient.Info, error) {
- args := client.Mock.Called()
- return args.Get(0).(*dockerclient.Info), args.Error(1)
-}
-
-func (client *MockClient) ListContainers(all bool, size bool, filters string) ([]dockerclient.Container, error) {
- args := client.Mock.Called(all, size, filters)
- return args.Get(0).([]dockerclient.Container), args.Error(1)
-}
-
-func (client *MockClient) InspectContainer(id string) (*dockerclient.ContainerInfo, error) {
- args := client.Mock.Called(id)
- return args.Get(0).(*dockerclient.ContainerInfo), args.Error(1)
-}
-
-func (client *MockClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
- args := client.Mock.Called(id)
- return args.Get(0).(*dockerclient.ImageInfo), args.Error(1)
-}
-
-func (client *MockClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
- args := client.Mock.Called(config, name, authConfig)
- return args.String(0), args.Error(1)
-}
-
-func (client *MockClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) {
- args := client.Mock.Called(id, options)
- return args.Get(0).(io.ReadCloser), args.Error(1)
-}
-
-func (client *MockClient) ContainerChanges(id string) ([]*dockerclient.ContainerChanges, error) {
- args := client.Mock.Called(id)
- return args.Get(0).([]*dockerclient.ContainerChanges), args.Error(1)
-}
-
-func (client *MockClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
- args := client.Mock.Called(id, options)
- return args.Get(0).(io.ReadCloser), args.Error(1)
-}
-
-func (client *MockClient) StartContainer(id string, config *dockerclient.HostConfig) error {
- args := client.Mock.Called(id, config)
- return args.Error(0)
-}
-
-func (client *MockClient) StopContainer(id string, timeout int) error {
- args := client.Mock.Called(id, timeout)
- return args.Error(0)
-}
-
-func (client *MockClient) RestartContainer(id string, timeout int) error {
- args := client.Mock.Called(id, timeout)
- return args.Error(0)
-}
-
-func (client *MockClient) KillContainer(id, signal string) error {
- args := client.Mock.Called(id, signal)
- return args.Error(0)
-}
-
-func (client *MockClient) Wait(id string) <-chan dockerclient.WaitResult {
- args := client.Mock.Called(id)
- return args.Get(0).(<-chan dockerclient.WaitResult)
-}
-
-func (client *MockClient) MonitorEvents(options *dockerclient.MonitorEventsOptions, stopChan <-chan struct{}) (<-chan dockerclient.EventOrError, error) {
- args := client.Mock.Called(options, stopChan)
- return args.Get(0).(<-chan dockerclient.EventOrError), args.Error(1)
-}
-
-func (client *MockClient) StartMonitorEvents(cb dockerclient.Callback, ec chan error, args ...interface{}) {
- client.Mock.Called(cb, ec, args)
-}
-
-func (client *MockClient) StopAllMonitorEvents() {
- client.Mock.Called()
-}
-
-func (client *MockClient) TagImage(nameOrID string, repo string, tag string, force bool) error {
- args := client.Mock.Called(nameOrID, repo, tag, force)
- return args.Error(0)
-}
-
-func (client *MockClient) StartMonitorStats(id string, cb dockerclient.StatCallback, ec chan error, args ...interface{}) {
- client.Mock.Called(id, cb, ec, args)
-}
-
-func (client *MockClient) StopAllMonitorStats() {
- client.Mock.Called()
-}
-
-func (client *MockClient) Version() (*dockerclient.Version, error) {
- args := client.Mock.Called()
- return args.Get(0).(*dockerclient.Version), args.Error(1)
-}
-
-func (client *MockClient) PullImage(name string, auth *dockerclient.AuthConfig) error {
- args := client.Mock.Called(name, auth)
- return args.Error(0)
-}
-
-func (client *MockClient) PushImage(name string, tag string, auth *dockerclient.AuthConfig) error {
- args := client.Mock.Called(name, tag, auth)
- return args.Error(0)
-}
-
-func (client *MockClient) LoadImage(reader io.Reader) error {
- args := client.Mock.Called(reader)
- return args.Error(0)
-}
-
-func (client *MockClient) RemoveContainer(id string, force, volumes bool) error {
- args := client.Mock.Called(id, force, volumes)
- return args.Error(0)
-}
-
-func (client *MockClient) ListImages(all bool) ([]*dockerclient.Image, error) {
- args := client.Mock.Called(all)
- return args.Get(0).([]*dockerclient.Image), args.Error(1)
-}
-
-func (client *MockClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
- args := client.Mock.Called(name, force)
- return args.Get(0).([]*dockerclient.ImageDelete), args.Error(1)
-}
-
-func (client *MockClient) SearchImages(query, registry string, authConfig *dockerclient.AuthConfig) ([]dockerclient.ImageSearch, error) {
- args := client.Mock.Called(query, registry, authConfig)
- return args.Get(0).([]dockerclient.ImageSearch), args.Error(1)
-}
-
-func (client *MockClient) PauseContainer(name string) error {
- args := client.Mock.Called(name)
- return args.Error(0)
-}
-
-func (client *MockClient) UnpauseContainer(name string) error {
- args := client.Mock.Called(name)
- return args.Error(0)
-}
-
-func (client *MockClient) ExecCreate(config *dockerclient.ExecConfig) (string, error) {
- args := client.Mock.Called(config)
- return args.String(0), args.Error(1)
-}
-
-func (client *MockClient) ExecStart(id string, config *dockerclient.ExecConfig) error {
- args := client.Mock.Called(id, config)
- return args.Error(0)
-}
-
-func (client *MockClient) ExecResize(id string, width, height int) error {
- args := client.Mock.Called(id, width, height)
- return args.Error(0)
-}
-
-func (client *MockClient) RenameContainer(oldName string, newName string) error {
- args := client.Mock.Called(oldName, newName)
- return args.Error(0)
-}
-
-func (client *MockClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) {
- args := client.Mock.Called(source, repository, tag, tar)
- return args.Get(0).(io.ReadCloser), args.Error(1)
-}
-
-func (client *MockClient) BuildImage(image *dockerclient.BuildImage) (io.ReadCloser, error) {
- args := client.Mock.Called(image)
- return args.Get(0).(io.ReadCloser), args.Error(1)
-}
-
-func (client *MockClient) ListVolumes() ([]*dockerclient.Volume, error) {
- args := client.Mock.Called()
- return args.Get(0).([]*dockerclient.Volume), args.Error(1)
-}
-
-func (client *MockClient) RemoveVolume(name string) error {
- args := client.Mock.Called(name)
- return args.Error(0)
-}
-
-func (client *MockClient) CreateVolume(request *dockerclient.VolumeCreateRequest) (*dockerclient.Volume, error) {
- args := client.Mock.Called(request)
- return args.Get(0).(*dockerclient.Volume), args.Error(1)
-}
-
-func (client *MockClient) ListNetworks(filters string) ([]*dockerclient.NetworkResource, error) {
- args := client.Mock.Called(filters)
- return args.Get(0).([]*dockerclient.NetworkResource), args.Error(1)
-}
-
-func (client *MockClient) InspectNetwork(id string) (*dockerclient.NetworkResource, error) {
- args := client.Mock.Called(id)
- return args.Get(0).(*dockerclient.NetworkResource), args.Error(1)
-}
-
-func (client *MockClient) CreateNetwork(config *dockerclient.NetworkCreate) (*dockerclient.NetworkCreateResponse, error) {
- args := client.Mock.Called(config)
- return args.Get(0).(*dockerclient.NetworkCreateResponse), args.Error(1)
-}
-
-func (client *MockClient) ConnectNetwork(id, container string) error {
- args := client.Mock.Called(id, container)
- return args.Error(0)
-}
-
-func (client *MockClient) DisconnectNetwork(id, container string, force bool) error {
- args := client.Mock.Called(id, container, force)
- return args.Error(0)
-}
-
-func (client *MockClient) RemoveNetwork(id string) error {
- args := client.Mock.Called(id)
- return args.Error(0)
-}
diff --git a/Godeps/_workspace/src/github.com/samalba/dockerclient/nopclient/nop.go b/Godeps/_workspace/src/github.com/samalba/dockerclient/nopclient/nop.go
deleted file mode 100644
index c89730cf0..000000000
--- a/Godeps/_workspace/src/github.com/samalba/dockerclient/nopclient/nop.go
+++ /dev/null
@@ -1,195 +0,0 @@
-package nopclient
-
-import (
- "errors"
- "io"
-
- "github.com/samalba/dockerclient"
-)
-
-var (
- ErrNoEngine = errors.New("Engine no longer exists")
-)
-
-type NopClient struct {
-}
-
-func NewNopClient() *NopClient {
- return &NopClient{}
-}
-
-func (client *NopClient) Info() (*dockerclient.Info, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) ListContainers(all bool, size bool, filters string) ([]dockerclient.Container, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) InspectContainer(id string) (*dockerclient.ContainerInfo, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) InspectImage(id string) (*dockerclient.ImageInfo, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) CreateContainer(config *dockerclient.ContainerConfig, name string, authConfig *dockerclient.AuthConfig) (string, error) {
- return "", ErrNoEngine
-}
-
-func (client *NopClient) ContainerLogs(id string, options *dockerclient.LogOptions) (io.ReadCloser, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) ContainerChanges(id string) ([]*dockerclient.ContainerChanges, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) AttachContainer(id string, options *dockerclient.AttachOptions) (io.ReadCloser, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) StartContainer(id string, config *dockerclient.HostConfig) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) StopContainer(id string, timeout int) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) RestartContainer(id string, timeout int) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) KillContainer(id, signal string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) Wait(id string) <-chan dockerclient.WaitResult {
- return nil
-}
-
-func (client *NopClient) MonitorEvents(options *dockerclient.MonitorEventsOptions, stopChan <-chan struct{}) (<-chan dockerclient.EventOrError, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) StartMonitorEvents(cb dockerclient.Callback, ec chan error, args ...interface{}) {
- return
-}
-
-func (client *NopClient) StopAllMonitorEvents() {
- return
-}
-
-func (client *NopClient) TagImage(nameOrID string, repo string, tag string, force bool) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) StartMonitorStats(id string, cb dockerclient.StatCallback, ec chan error, args ...interface{}) {
- return
-}
-
-func (client *NopClient) StopAllMonitorStats() {
- return
-}
-
-func (client *NopClient) Version() (*dockerclient.Version, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) PullImage(name string, auth *dockerclient.AuthConfig) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) PushImage(name, tag string, auth *dockerclient.AuthConfig) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) LoadImage(reader io.Reader) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) RemoveContainer(id string, force, volumes bool) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) ListImages(all bool) ([]*dockerclient.Image, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) RemoveImage(name string, force bool) ([]*dockerclient.ImageDelete, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) SearchImages(query, registry string, authConfig *dockerclient.AuthConfig) ([]dockerclient.ImageSearch, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) PauseContainer(name string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) UnpauseContainer(name string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) ExecCreate(config *dockerclient.ExecConfig) (string, error) {
- return "", ErrNoEngine
-}
-
-func (client *NopClient) ExecStart(id string, config *dockerclient.ExecConfig) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) ExecResize(id string, width, height int) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) RenameContainer(oldName string, newName string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) ImportImage(source string, repository string, tag string, tar io.Reader) (io.ReadCloser, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) BuildImage(image *dockerclient.BuildImage) (io.ReadCloser, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) ListVolumes() ([]*dockerclient.Volume, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) RemoveVolume(name string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) CreateVolume(request *dockerclient.VolumeCreateRequest) (*dockerclient.Volume, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) ListNetworks(filters string) ([]*dockerclient.NetworkResource, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) InspectNetwork(id string) (*dockerclient.NetworkResource, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) CreateNetwork(config *dockerclient.NetworkCreate) (*dockerclient.NetworkCreateResponse, error) {
- return nil, ErrNoEngine
-}
-
-func (client *NopClient) ConnectNetwork(id, container string) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) DisconnectNetwork(id, container string, force bool) error {
- return ErrNoEngine
-}
-
-func (client *NopClient) RemoveNetwork(id string) error {
- return ErrNoEngine
-}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/LICENCE.txt b/Godeps/_workspace/src/github.com/stretchr/testify/LICENCE.txt
new file mode 100644
index 000000000..a009ba467
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/stretchr/testify/LICENCE.txt
@@ -0,0 +1,9 @@
+Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
+
+Please consider promoting this project if you find it useful.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
deleted file mode 100644
index dff6f2d58..000000000
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go
+++ /dev/null
@@ -1,986 +0,0 @@
-package assert
-
-import (
- "errors"
- "io"
- "math"
- "reflect"
- "regexp"
- "testing"
- "time"
-)
-
-var (
- i interface{}
- zeros = []interface{}{
- false,
- byte(0),
- complex64(0),
- complex128(0),
- float32(0),
- float64(0),
- int(0),
- int8(0),
- int16(0),
- int32(0),
- int64(0),
- rune(0),
- uint(0),
- uint8(0),
- uint16(0),
- uint32(0),
- uint64(0),
- uintptr(0),
- "",
- [0]interface{}{},
- []interface{}(nil),
- struct{ x int }{},
- (*interface{})(nil),
- (func())(nil),
- nil,
- interface{}(nil),
- map[interface{}]interface{}(nil),
- (chan interface{})(nil),
- (<-chan interface{})(nil),
- (chan<- interface{})(nil),
- }
- nonZeros = []interface{}{
- true,
- byte(1),
- complex64(1),
- complex128(1),
- float32(1),
- float64(1),
- int(1),
- int8(1),
- int16(1),
- int32(1),
- int64(1),
- rune(1),
- uint(1),
- uint8(1),
- uint16(1),
- uint32(1),
- uint64(1),
- uintptr(1),
- "s",
- [1]interface{}{1},
- []interface{}{},
- struct{ x int }{1},
- (*interface{})(&i),
- (func())(func() {}),
- interface{}(1),
- map[interface{}]interface{}{},
- (chan interface{})(make(chan interface{})),
- (<-chan interface{})(make(chan interface{})),
- (chan<- interface{})(make(chan interface{})),
- }
-)
-
-// AssertionTesterInterface defines an interface to be used for testing assertion methods
-type AssertionTesterInterface interface {
- TestMethod()
-}
-
-// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
-type AssertionTesterConformingObject struct {
-}
-
-func (a *AssertionTesterConformingObject) TestMethod() {
-}
-
-// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
-type AssertionTesterNonConformingObject struct {
-}
-
-func TestObjectsAreEqual(t *testing.T) {
-
- if !ObjectsAreEqual("Hello World", "Hello World") {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(123, 123) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(123.5, 123.5) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
- t.Error("objectsAreEqual should return true")
- }
- if !ObjectsAreEqual(nil, nil) {
- t.Error("objectsAreEqual should return true")
- }
- if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual('x', "x") {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual("x", 'x') {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(0, 0.1) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(0.1, 0) {
- t.Error("objectsAreEqual should return false")
- }
- if ObjectsAreEqual(uint32(10), int32(10)) {
- t.Error("objectsAreEqual should return false")
- }
- if !ObjectsAreEqualValues(uint32(10), int32(10)) {
- t.Error("ObjectsAreEqualValues should return true")
- }
-
-}
-
-func TestImplements(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
- t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
- }
- if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
- t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
- }
-
-}
-
-func TestIsType(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
- t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
- }
- if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
- t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
- }
-
-}
-
-func TestEqual(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Equal(mockT, "Hello World", "Hello World") {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, 123, 123) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, 123.5, 123.5) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, nil, nil) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, int32(123), int32(123)) {
- t.Error("Equal should return true")
- }
- if !Equal(mockT, uint64(123), uint64(123)) {
- t.Error("Equal should return true")
- }
-
-}
-
-func TestNotNil(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !NotNil(mockT, new(AssertionTesterConformingObject)) {
- t.Error("NotNil should return true: object is not nil")
- }
- if NotNil(mockT, nil) {
- t.Error("NotNil should return false: object is nil")
- }
- if NotNil(mockT, (*struct{})(nil)) {
- t.Error("NotNil should return false: object is (*struct{})(nil)")
- }
-
-}
-
-func TestNil(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Nil(mockT, nil) {
- t.Error("Nil should return true: object is nil")
- }
- if !Nil(mockT, (*struct{})(nil)) {
- t.Error("Nil should return true: object is (*struct{})(nil)")
- }
- if Nil(mockT, new(AssertionTesterConformingObject)) {
- t.Error("Nil should return false: object is not nil")
- }
-
-}
-
-func TestTrue(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !True(mockT, true) {
- t.Error("True should return true")
- }
- if True(mockT, false) {
- t.Error("True should return false")
- }
-
-}
-
-func TestFalse(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !False(mockT, false) {
- t.Error("False should return true")
- }
- if False(mockT, true) {
- t.Error("False should return false")
- }
-
-}
-
-func TestExactly(t *testing.T) {
-
- mockT := new(testing.T)
-
- a := float32(1)
- b := float64(1)
- c := float32(1)
- d := float32(2)
-
- if Exactly(mockT, a, b) {
- t.Error("Exactly should return false")
- }
- if Exactly(mockT, a, d) {
- t.Error("Exactly should return false")
- }
- if !Exactly(mockT, a, c) {
- t.Error("Exactly should return true")
- }
-
- if Exactly(mockT, nil, a) {
- t.Error("Exactly should return false")
- }
- if Exactly(mockT, a, nil) {
- t.Error("Exactly should return false")
- }
-
-}
-
-func TestNotEqual(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !NotEqual(mockT, "Hello World", "Hello World!") {
- t.Error("NotEqual should return true")
- }
- if !NotEqual(mockT, 123, 1234) {
- t.Error("NotEqual should return true")
- }
- if !NotEqual(mockT, 123.5, 123.55) {
- t.Error("NotEqual should return true")
- }
- if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) {
- t.Error("NotEqual should return true")
- }
- if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) {
- t.Error("NotEqual should return true")
- }
- funcA := func() int { return 23 }
- funcB := func() int { return 42 }
- if !NotEqual(mockT, funcA, funcB) {
- t.Error("NotEqual should return true")
- }
-
- if NotEqual(mockT, "Hello World", "Hello World") {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, 123, 123) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, 123.5, 123.5) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) {
- t.Error("NotEqual should return false")
- }
- if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
- t.Error("NotEqual should return false")
- }
-}
-
-type A struct {
- Name, Value string
-}
-
-func TestContains(t *testing.T) {
-
- mockT := new(testing.T)
- list := []string{"Foo", "Bar"}
- complexList := []*A{
- {"b", "c"},
- {"d", "e"},
- {"g", "h"},
- {"j", "k"},
- }
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- if !Contains(mockT, "Hello World", "Hello") {
- t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
- }
- if Contains(mockT, "Hello World", "Salut") {
- t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
- }
-
- if !Contains(mockT, list, "Bar") {
- t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"")
- }
- if Contains(mockT, list, "Salut") {
- t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
- }
- if !Contains(mockT, complexList, &A{"g", "h"}) {
- t.Error("Contains should return true: complexList contains {\"g\", \"h\"}")
- }
- if Contains(mockT, complexList, &A{"g", "e"}) {
- t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
- }
- if Contains(mockT, complexList, &A{"g", "e"}) {
- t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
- }
- if !Contains(mockT, simpleMap, "Foo") {
- t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
- }
- if Contains(mockT, simpleMap, "Bar") {
- t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
- }
-}
-
-func TestNotContains(t *testing.T) {
-
- mockT := new(testing.T)
- list := []string{"Foo", "Bar"}
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- if !NotContains(mockT, "Hello World", "Hello!") {
- t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
- }
- if NotContains(mockT, "Hello World", "Hello") {
- t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
- }
-
- if !NotContains(mockT, list, "Foo!") {
- t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
- }
- if NotContains(mockT, list, "Foo") {
- t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
- }
- if NotContains(mockT, simpleMap, "Foo") {
- t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
- }
- if !NotContains(mockT, simpleMap, "Bar") {
- t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
- }
-}
-
-func Test_includeElement(t *testing.T) {
-
- list1 := []string{"Foo", "Bar"}
- list2 := []int{1, 2}
- simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
-
- ok, found := includeElement("Hello World", "World")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Foo")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Bar")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list2, 1)
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list2, 2)
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(list1, "Foo!")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(list2, 3)
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(list2, "1")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(simpleMap, "Foo")
- True(t, ok)
- True(t, found)
-
- ok, found = includeElement(simpleMap, "Bar")
- True(t, ok)
- False(t, found)
-
- ok, found = includeElement(1433, "1")
- False(t, ok)
- False(t, found)
-}
-
-func TestCondition(t *testing.T) {
- mockT := new(testing.T)
-
- if !Condition(mockT, func() bool { return true }, "Truth") {
- t.Error("Condition should return true")
- }
-
- if Condition(mockT, func() bool { return false }, "Lie") {
- t.Error("Condition should return false")
- }
-
-}
-
-func TestDidPanic(t *testing.T) {
-
- if funcDidPanic, _ := didPanic(func() {
- panic("Panic!")
- }); !funcDidPanic {
- t.Error("didPanic should return true")
- }
-
- if funcDidPanic, _ := didPanic(func() {
- }); funcDidPanic {
- t.Error("didPanic should return false")
- }
-
-}
-
-func TestPanics(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !Panics(mockT, func() {
- panic("Panic!")
- }) {
- t.Error("Panics should return true")
- }
-
- if Panics(mockT, func() {
- }) {
- t.Error("Panics should return false")
- }
-
-}
-
-func TestNotPanics(t *testing.T) {
-
- mockT := new(testing.T)
-
- if !NotPanics(mockT, func() {
- }) {
- t.Error("NotPanics should return true")
- }
-
- if NotPanics(mockT, func() {
- panic("Panic!")
- }) {
- t.Error("NotPanics should return false")
- }
-
-}
-
-func TestNoError(t *testing.T) {
-
- mockT := new(testing.T)
-
- // start with a nil error
- var err error
-
- True(t, NoError(mockT, err), "NoError should return True for nil arg")
-
- // now set an error
- err = errors.New("some error")
-
- False(t, NoError(mockT, err), "NoError with error should return False")
-
-}
-
-func TestError(t *testing.T) {
-
- mockT := new(testing.T)
-
- // start with a nil error
- var err error
-
- False(t, Error(mockT, err), "Error should return False for nil arg")
-
- // now set an error
- err = errors.New("some error")
-
- True(t, Error(mockT, err), "Error with error should return True")
-
-}
-
-func TestEqualError(t *testing.T) {
- mockT := new(testing.T)
-
- // start with a nil error
- var err error
- False(t, EqualError(mockT, err, ""),
- "EqualError should return false for nil arg")
-
- // now set an error
- err = errors.New("some error")
- False(t, EqualError(mockT, err, "Not some error"),
- "EqualError should return false for different error string")
- True(t, EqualError(mockT, err, "some error"),
- "EqualError should return true")
-}
-
-func Test_isEmpty(t *testing.T) {
-
- chWithValue := make(chan struct{}, 1)
- chWithValue <- struct{}{}
-
- True(t, isEmpty(""))
- True(t, isEmpty(nil))
- True(t, isEmpty([]string{}))
- True(t, isEmpty(0))
- True(t, isEmpty(int32(0)))
- True(t, isEmpty(int64(0)))
- True(t, isEmpty(false))
- True(t, isEmpty(map[string]string{}))
- True(t, isEmpty(new(time.Time)))
- True(t, isEmpty(make(chan struct{})))
- False(t, isEmpty("something"))
- False(t, isEmpty(errors.New("something")))
- False(t, isEmpty([]string{"something"}))
- False(t, isEmpty(1))
- False(t, isEmpty(true))
- False(t, isEmpty(map[string]string{"Hello": "World"}))
- False(t, isEmpty(chWithValue))
-
-}
-
-func TestEmpty(t *testing.T) {
-
- mockT := new(testing.T)
- chWithValue := make(chan struct{}, 1)
- chWithValue <- struct{}{}
-
- True(t, Empty(mockT, ""), "Empty string is empty")
- True(t, Empty(mockT, nil), "Nil is empty")
- True(t, Empty(mockT, []string{}), "Empty string array is empty")
- True(t, Empty(mockT, 0), "Zero int value is empty")
- True(t, Empty(mockT, false), "False value is empty")
- True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
-
- False(t, Empty(mockT, "something"), "Non Empty string is not empty")
- False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
- False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
- False(t, Empty(mockT, 1), "Non-zero int value is not empty")
- False(t, Empty(mockT, true), "True value is not empty")
- False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
-}
-
-func TestNotEmpty(t *testing.T) {
-
- mockT := new(testing.T)
- chWithValue := make(chan struct{}, 1)
- chWithValue <- struct{}{}
-
- False(t, NotEmpty(mockT, ""), "Empty string is empty")
- False(t, NotEmpty(mockT, nil), "Nil is empty")
- False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
- False(t, NotEmpty(mockT, 0), "Zero int value is empty")
- False(t, NotEmpty(mockT, false), "False value is empty")
- False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
-
- True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
- True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
- True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
- True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
- True(t, NotEmpty(mockT, true), "True value is not empty")
- True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
-}
-
-func Test_getLen(t *testing.T) {
- falseCases := []interface{}{
- nil,
- 0,
- true,
- false,
- 'A',
- struct{}{},
- }
- for _, v := range falseCases {
- ok, l := getLen(v)
- False(t, ok, "Expected getLen fail to get length of %#v", v)
- Equal(t, 0, l, "getLen should return 0 for %#v", v)
- }
-
- ch := make(chan int, 5)
- ch <- 1
- ch <- 2
- ch <- 3
- trueCases := []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 3},
- {[...]int{1, 2, 3}, 3},
- {"ABC", 3},
- {map[int]int{1: 2, 2: 4, 3: 6}, 3},
- {ch, 3},
-
- {[]int{}, 0},
- {map[int]int{}, 0},
- {make(chan int), 0},
-
- {[]int(nil), 0},
- {map[int]int(nil), 0},
- {(chan int)(nil), 0},
- }
-
- for _, c := range trueCases {
- ok, l := getLen(c.v)
- True(t, ok, "Expected getLen success to get length of %#v", c.v)
- Equal(t, c.l, l)
- }
-}
-
-func TestLen(t *testing.T) {
- mockT := new(testing.T)
-
- False(t, Len(mockT, nil, 0), "nil does not have length")
- False(t, Len(mockT, 0, 0), "int does not have length")
- False(t, Len(mockT, true, 0), "true does not have length")
- False(t, Len(mockT, false, 0), "false does not have length")
- False(t, Len(mockT, 'A', 0), "Rune does not have length")
- False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
-
- ch := make(chan int, 5)
- ch <- 1
- ch <- 2
- ch <- 3
-
- cases := []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 3},
- {[...]int{1, 2, 3}, 3},
- {"ABC", 3},
- {map[int]int{1: 2, 2: 4, 3: 6}, 3},
- {ch, 3},
-
- {[]int{}, 0},
- {map[int]int{}, 0},
- {make(chan int), 0},
-
- {[]int(nil), 0},
- {map[int]int(nil), 0},
- {(chan int)(nil), 0},
- }
-
- for _, c := range cases {
- True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
- }
-
- cases = []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 4},
- {[...]int{1, 2, 3}, 2},
- {"ABC", 2},
- {map[int]int{1: 2, 2: 4, 3: 6}, 4},
- {ch, 2},
-
- {[]int{}, 1},
- {map[int]int{}, 1},
- {make(chan int), 1},
-
- {[]int(nil), 1},
- {map[int]int(nil), 1},
- {(chan int)(nil), 1},
- }
-
- for _, c := range cases {
- False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
- }
-}
-
-func TestWithinDuration(t *testing.T) {
-
- mockT := new(testing.T)
- a := time.Now()
- b := a.Add(10 * time.Second)
-
- True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
- True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
-
- False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
-
- False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
-
- False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
- False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
-}
-
-func TestInDelta(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
- True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
- True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
- False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
- False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
- False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
- False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
- False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
-
- cases := []struct {
- a, b interface{}
- delta float64
- }{
- {uint8(2), uint8(1), 1},
- {uint16(2), uint16(1), 1},
- {uint32(2), uint32(1), 1},
- {uint64(2), uint64(1), 1},
-
- {int(2), int(1), 1},
- {int8(2), int8(1), 1},
- {int16(2), int16(1), 1},
- {int32(2), int32(1), 1},
- {int64(2), int64(1), 1},
-
- {float32(2), float32(1), 1},
- {float64(2), float64(1), 1},
- }
-
- for _, tc := range cases {
- True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
- }
-}
-
-func TestInDeltaSlice(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InDeltaSlice(mockT,
- []float64{1.001, 0.999},
- []float64{1, 1},
- 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1")
-
- True(t, InDeltaSlice(mockT,
- []float64{1, 2},
- []float64{0, 3},
- 1), "{1, 2} is element-wise close to {0, 3} in delta=1")
-
- False(t, InDeltaSlice(mockT,
- []float64{1, 2},
- []float64{0, 3},
- 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1")
-
- False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
-}
-
-func TestInEpsilon(t *testing.T) {
- mockT := new(testing.T)
-
- cases := []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), uint16(2), .001},
- {2.1, 2.2, 0.1},
- {2.2, 2.1, 0.1},
- {-2.1, -2.2, 0.1},
- {-2.2, -2.1, 0.1},
- {uint64(100), uint8(101), 0.01},
- {0.1, -0.1, 2},
- }
-
- for _, tc := range cases {
- True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
- }
-
- cases = []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), int16(-2), .001},
- {uint64(100), uint8(102), 0.01},
- {2.1, 2.2, 0.001},
- {2.2, 2.1, 0.001},
- {2.1, -2.2, 1},
- {2.1, "bla-bla", 0},
- {0.1, -0.1, 1.99},
- }
-
- for _, tc := range cases {
- False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
- }
-
-}
-
-func TestInEpsilonSlice(t *testing.T) {
- mockT := new(testing.T)
-
- True(t, InEpsilonSlice(mockT,
- []float64{2.2, 2.0},
- []float64{2.1, 2.1},
- 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06")
-
- False(t, InEpsilonSlice(mockT,
- []float64{2.2, 2.0},
- []float64{2.1, 2.1},
- 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04")
-
- False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
-}
-
-func TestRegexp(t *testing.T) {
- mockT := new(testing.T)
-
- cases := []struct {
- rx, str string
- }{
- {"^start", "start of the line"},
- {"end$", "in the end"},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
- }
-
- for _, tc := range cases {
- True(t, Regexp(mockT, tc.rx, tc.str))
- True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- False(t, NotRegexp(mockT, tc.rx, tc.str))
- False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- }
-
- cases = []struct {
- rx, str string
- }{
- {"^asdfastart", "Not the start of the line"},
- {"end$", "in the end."},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
- }
-
- for _, tc := range cases {
- False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
- False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- True(t, NotRegexp(mockT, tc.rx, tc.str))
- True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
- }
-}
-
-func testAutogeneratedFunction() {
- defer func() {
- if err := recover(); err == nil {
- panic("did not panic")
- }
- CallerInfo()
- }()
- t := struct {
- io.Closer
- }{}
- var c io.Closer
- c = t
- c.Close()
-}
-
-func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
- NotPanics(t, func() {
- testAutogeneratedFunction()
- })
-}
-
-func TestZero(t *testing.T) {
- mockT := new(testing.T)
-
- for _, test := range zeros {
- True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-
- for _, test := range nonZeros {
- False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-}
-
-func TestNotZero(t *testing.T) {
- mockT := new(testing.T)
-
- for _, test := range zeros {
- False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-
- for _, test := range nonZeros {
- True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
- }
-}
-
-func TestJSONEq_EqualSONString(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
-}
-
-func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
- "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
-}
-
-func TestJSONEq_Array(t *testing.T) {
- mockT := new(testing.T)
- True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
-}
-
-func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
-}
-
-func TestJSONEq_HashesNotEquivalent(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_ActualIsNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
-}
-
-func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
-}
-
-func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
-}
-
-func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
- mockT := new(testing.T)
- False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
-}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
deleted file mode 100644
index 22e1df1d9..000000000
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go
+++ /dev/null
@@ -1,611 +0,0 @@
-package assert
-
-import (
- "errors"
- "regexp"
- "testing"
- "time"
-)
-
-func TestImplementsWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
- t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
- }
- if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
- t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
- }
-}
-
-func TestIsTypeWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
- t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
- }
- if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
- t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
- }
-
-}
-
-func TestEqualWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.Equal("Hello World", "Hello World") {
- t.Error("Equal should return true")
- }
- if !assert.Equal(123, 123) {
- t.Error("Equal should return true")
- }
- if !assert.Equal(123.5, 123.5) {
- t.Error("Equal should return true")
- }
- if !assert.Equal([]byte("Hello World"), []byte("Hello World")) {
- t.Error("Equal should return true")
- }
- if !assert.Equal(nil, nil) {
- t.Error("Equal should return true")
- }
-}
-
-func TestEqualValuesWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.EqualValues(uint32(10), int32(10)) {
- t.Error("EqualValues should return true")
- }
-}
-
-func TestNotNilWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.NotNil(new(AssertionTesterConformingObject)) {
- t.Error("NotNil should return true: object is not nil")
- }
- if assert.NotNil(nil) {
- t.Error("NotNil should return false: object is nil")
- }
-
-}
-
-func TestNilWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.Nil(nil) {
- t.Error("Nil should return true: object is nil")
- }
- if assert.Nil(new(AssertionTesterConformingObject)) {
- t.Error("Nil should return false: object is not nil")
- }
-
-}
-
-func TestTrueWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.True(true) {
- t.Error("True should return true")
- }
- if assert.True(false) {
- t.Error("True should return false")
- }
-
-}
-
-func TestFalseWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- if !assert.False(false) {
- t.Error("False should return true")
- }
- if assert.False(true) {
- t.Error("False should return false")
- }
-
-}
-
-func TestExactlyWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- a := float32(1)
- b := float64(1)
- c := float32(1)
- d := float32(2)
-
- if assert.Exactly(a, b) {
- t.Error("Exactly should return false")
- }
- if assert.Exactly(a, d) {
- t.Error("Exactly should return false")
- }
- if !assert.Exactly(a, c) {
- t.Error("Exactly should return true")
- }
-
- if assert.Exactly(nil, a) {
- t.Error("Exactly should return false")
- }
- if assert.Exactly(a, nil) {
- t.Error("Exactly should return false")
- }
-
-}
-
-func TestNotEqualWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
-
- if !assert.NotEqual("Hello World", "Hello World!") {
- t.Error("NotEqual should return true")
- }
- if !assert.NotEqual(123, 1234) {
- t.Error("NotEqual should return true")
- }
- if !assert.NotEqual(123.5, 123.55) {
- t.Error("NotEqual should return true")
- }
- if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) {
- t.Error("NotEqual should return true")
- }
- if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) {
- t.Error("NotEqual should return true")
- }
-}
-
-func TestContainsWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
- list := []string{"Foo", "Bar"}
-
- if !assert.Contains("Hello World", "Hello") {
- t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
- }
- if assert.Contains("Hello World", "Salut") {
- t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
- }
-
- if !assert.Contains(list, "Foo") {
- t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
- }
- if assert.Contains(list, "Salut") {
- t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
- }
-
-}
-
-func TestNotContainsWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
- list := []string{"Foo", "Bar"}
-
- if !assert.NotContains("Hello World", "Hello!") {
- t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
- }
- if assert.NotContains("Hello World", "Hello") {
- t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
- }
-
- if !assert.NotContains(list, "Foo!") {
- t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
- }
- if assert.NotContains(list, "Foo") {
- t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
- }
-
-}
-
-func TestConditionWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
-
- if !assert.Condition(func() bool { return true }, "Truth") {
- t.Error("Condition should return true")
- }
-
- if assert.Condition(func() bool { return false }, "Lie") {
- t.Error("Condition should return false")
- }
-
-}
-
-func TestDidPanicWrapper(t *testing.T) {
-
- if funcDidPanic, _ := didPanic(func() {
- panic("Panic!")
- }); !funcDidPanic {
- t.Error("didPanic should return true")
- }
-
- if funcDidPanic, _ := didPanic(func() {
- }); funcDidPanic {
- t.Error("didPanic should return false")
- }
-
-}
-
-func TestPanicsWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
-
- if !assert.Panics(func() {
- panic("Panic!")
- }) {
- t.Error("Panics should return true")
- }
-
- if assert.Panics(func() {
- }) {
- t.Error("Panics should return false")
- }
-
-}
-
-func TestNotPanicsWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
-
- if !assert.NotPanics(func() {
- }) {
- t.Error("NotPanics should return true")
- }
-
- if assert.NotPanics(func() {
- panic("Panic!")
- }) {
- t.Error("NotPanics should return false")
- }
-
-}
-
-func TestNoErrorWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- // start with a nil error
- var err error
-
- assert.True(mockAssert.NoError(err), "NoError should return True for nil arg")
-
- // now set an error
- err = errors.New("Some error")
-
- assert.False(mockAssert.NoError(err), "NoError with error should return False")
-
-}
-
-func TestErrorWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- // start with a nil error
- var err error
-
- assert.False(mockAssert.Error(err), "Error should return False for nil arg")
-
- // now set an error
- err = errors.New("Some error")
-
- assert.True(mockAssert.Error(err), "Error with error should return True")
-
-}
-
-func TestEqualErrorWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- // start with a nil error
- var err error
- assert.False(mockAssert.EqualError(err, ""),
- "EqualError should return false for nil arg")
-
- // now set an error
- err = errors.New("some error")
- assert.False(mockAssert.EqualError(err, "Not some error"),
- "EqualError should return false for different error string")
- assert.True(mockAssert.EqualError(err, "some error"),
- "EqualError should return true")
-}
-
-func TestEmptyWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.True(mockAssert.Empty(""), "Empty string is empty")
- assert.True(mockAssert.Empty(nil), "Nil is empty")
- assert.True(mockAssert.Empty([]string{}), "Empty string array is empty")
- assert.True(mockAssert.Empty(0), "Zero int value is empty")
- assert.True(mockAssert.Empty(false), "False value is empty")
-
- assert.False(mockAssert.Empty("something"), "Non Empty string is not empty")
- assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty")
- assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty")
- assert.False(mockAssert.Empty(1), "Non-zero int value is not empty")
- assert.False(mockAssert.Empty(true), "True value is not empty")
-
-}
-
-func TestNotEmptyWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.False(mockAssert.NotEmpty(""), "Empty string is empty")
- assert.False(mockAssert.NotEmpty(nil), "Nil is empty")
- assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty")
- assert.False(mockAssert.NotEmpty(0), "Zero int value is empty")
- assert.False(mockAssert.NotEmpty(false), "False value is empty")
-
- assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty")
- assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty")
- assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty")
- assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty")
- assert.True(mockAssert.NotEmpty(true), "True value is not empty")
-
-}
-
-func TestLenWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.False(mockAssert.Len(nil, 0), "nil does not have length")
- assert.False(mockAssert.Len(0, 0), "int does not have length")
- assert.False(mockAssert.Len(true, 0), "true does not have length")
- assert.False(mockAssert.Len(false, 0), "false does not have length")
- assert.False(mockAssert.Len('A', 0), "Rune does not have length")
- assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length")
-
- ch := make(chan int, 5)
- ch <- 1
- ch <- 2
- ch <- 3
-
- cases := []struct {
- v interface{}
- l int
- }{
- {[]int{1, 2, 3}, 3},
- {[...]int{1, 2, 3}, 3},
- {"ABC", 3},
- {map[int]int{1: 2, 2: 4, 3: 6}, 3},
- {ch, 3},
-
- {[]int{}, 0},
- {map[int]int{}, 0},
- {make(chan int), 0},
-
- {[]int(nil), 0},
- {map[int]int(nil), 0},
- {(chan int)(nil), 0},
- }
-
- for _, c := range cases {
- assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l)
- }
-}
-
-func TestWithinDurationWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
- a := time.Now()
- b := a.Add(10 * time.Second)
-
- assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
- assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
-
- assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
- assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
-
- assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
- assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
-
- assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
- assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
-}
-
-func TestInDeltaWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
- True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
- True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1")
- False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
- False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
- False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail")
-
- cases := []struct {
- a, b interface{}
- delta float64
- }{
- {uint8(2), uint8(1), 1},
- {uint16(2), uint16(1), 1},
- {uint32(2), uint32(1), 1},
- {uint64(2), uint64(1), 1},
-
- {int(2), int(1), 1},
- {int8(2), int8(1), 1},
- {int16(2), int16(1), 1},
- {int32(2), int32(1), 1},
- {int64(2), int64(1), 1},
-
- {float32(2), float32(1), 1},
- {float64(2), float64(1), 1},
- }
-
- for _, tc := range cases {
- True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
- }
-}
-
-func TestInEpsilonWrapper(t *testing.T) {
- assert := New(new(testing.T))
-
- cases := []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), uint16(2), .001},
- {2.1, 2.2, 0.1},
- {2.2, 2.1, 0.1},
- {-2.1, -2.2, 0.1},
- {-2.2, -2.1, 0.1},
- {uint64(100), uint8(101), 0.01},
- {0.1, -0.1, 2},
- }
-
- for _, tc := range cases {
- True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
- }
-
- cases = []struct {
- a, b interface{}
- epsilon float64
- }{
- {uint8(2), int16(-2), .001},
- {uint64(100), uint8(102), 0.01},
- {2.1, 2.2, 0.001},
- {2.2, 2.1, 0.001},
- {2.1, -2.2, 1},
- {2.1, "bla-bla", 0},
- {0.1, -0.1, 1.99},
- }
-
- for _, tc := range cases {
- False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
- }
-}
-
-func TestRegexpWrapper(t *testing.T) {
-
- assert := New(new(testing.T))
-
- cases := []struct {
- rx, str string
- }{
- {"^start", "start of the line"},
- {"end$", "in the end"},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
- }
-
- for _, tc := range cases {
- True(t, assert.Regexp(tc.rx, tc.str))
- True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str))
- False(t, assert.NotRegexp(tc.rx, tc.str))
- False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str))
- }
-
- cases = []struct {
- rx, str string
- }{
- {"^asdfastart", "Not the start of the line"},
- {"end$", "in the end."},
- {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
- }
-
- for _, tc := range cases {
- False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
- False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str))
- True(t, assert.NotRegexp(tc.rx, tc.str))
- True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str))
- }
-}
-
-func TestZeroWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- for _, test := range zeros {
- assert.True(mockAssert.Zero(test), "Zero should return true for %v", test)
- }
-
- for _, test := range nonZeros {
- assert.False(mockAssert.Zero(test), "Zero should return false for %v", test)
- }
-}
-
-func TestNotZeroWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- for _, test := range zeros {
- assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test)
- }
-
- for _, test := range nonZeros {
- assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test)
- }
-}
-
-func TestJSONEqWrapper_EqualSONString(t *testing.T) {
- assert := New(new(testing.T))
- if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) {
- t.Error("JSONEq should return true")
- }
-
-}
-
-func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) {
- assert := New(new(testing.T))
- if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) {
- t.Error("JSONEq should return true")
- }
-
-}
-
-func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) {
- assert := New(new(testing.T))
- if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
- "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") {
- t.Error("JSONEq should return true")
- }
-}
-
-func TestJSONEqWrapper_Array(t *testing.T) {
- assert := New(new(testing.T))
- if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) {
- t.Error("JSONEq should return true")
- }
-
-}
-
-func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) {
- t.Error("JSONEq should return false")
- }
-}
-
-func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) {
- t.Error("JSONEq should return false")
- }
-}
-
-func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") {
- t.Error("JSONEq should return false")
- }
-}
-
-func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) {
- t.Error("JSONEq should return false")
- }
-}
-
-func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq("Not JSON", "Not JSON") {
- t.Error("JSONEq should return false")
- }
-}
-
-func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) {
- assert := New(new(testing.T))
- if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) {
- t.Error("JSONEq should return false")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go
deleted file mode 100644
index 684c2d5d1..000000000
--- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package assert
-
-import (
- "fmt"
- "net/http"
- "net/url"
- "testing"
-)
-
-func httpOK(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusOK)
-}
-
-func httpRedirect(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusTemporaryRedirect)
-}
-
-func httpError(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusInternalServerError)
-}
-
-func TestHTTPStatuses(t *testing.T) {
- assert := New(t)
- mockT := new(testing.T)
-
- assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true)
- assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false)
- assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false)
-
- assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false)
- assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true)
- assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false)
-
- assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false)
- assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false)
- assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true)
-}
-
-func TestHTTPStatusesWrapper(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true)
- assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false)
-
- assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true)
- assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false)
-
- assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false)
- assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true)
-}
-
-func httpHelloName(w http.ResponseWriter, r *http.Request) {
- name := r.FormValue("name")
- w.Write([]byte(fmt.Sprintf("Hello, %s!", name)))
-}
-
-func TestHttpBody(t *testing.T) {
- assert := New(t)
- mockT := new(testing.T)
-
- assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
- assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-}
-
-func TestHttpBodyWrappers(t *testing.T) {
- assert := New(t)
- mockAssert := New(new(testing.T))
-
- assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
- assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"))
- assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World"))
- assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world"))
-
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/.travis.yml b/Godeps/_workspace/src/github.com/vishvananda/netlink/.travis.yml
index 1970069d5..73a0374c4 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/.travis.yml
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/.travis.yml
@@ -1,3 +1,8 @@
language: go
+before_script:
+ # make sure we keep path in tact when we sudo
+ - sudo sed -i -e 's/^Defaults\tsecure_path.*$//' /etc/sudoers
+ # modprobe ip_gre or else the first gre device can't be deleted
+ - sudo modprobe ip_gre
install:
- - go get github.com/vishvananda/netns
+ - go get github.com/vishvananda/netns
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/Makefile b/Godeps/_workspace/src/github.com/vishvananda/netlink/Makefile
index b3250185f..75f342983 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/Makefile
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/Makefile
@@ -11,7 +11,7 @@ goroot = $(addprefix ../../../,$(1))
unroot = $(subst ../../../,,$(1))
fmt = $(addprefix fmt-,$(1))
-all: fmt
+all: test
$(call goroot,$(DEPS)):
go get $(call unroot,$@)
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/addr.go
index 9bbaf508e..079fff3b3 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/addr.go
@@ -11,11 +11,13 @@ import (
type Addr struct {
*net.IPNet
Label string
+ Flags int
+ Scope int
}
// String returns $ip/$netmask $label
func (a Addr) String() string {
- return fmt.Sprintf("%s %s", a.IPNet, a.Label)
+ return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label))
}
// ParseAddr parses the string representation of an address in the
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_linux.go
index 19aac0fb9..ace92fa43 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_linux.go
@@ -2,6 +2,7 @@ package netlink
import (
"fmt"
+ "log"
"net"
"strings"
"syscall"
@@ -9,6 +10,9 @@ import (
"github.com/vishvananda/netlink/nl"
)
+// IFA_FLAGS is a u32 attribute.
+const IFA_FLAGS = 0x8
+
// AddrAdd will add an IP address to a link device.
// Equivalent to: `ip addr add $addr dev $link`
func AddrAdd(link Link, addr *Addr) error {
@@ -35,6 +39,7 @@ func addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error {
msg := nl.NewIfAddrmsg(family)
msg.Index = uint32(base.Index)
+ msg.Scope = uint8(addr.Scope)
prefixlen, _ := addr.Mask.Size()
msg.Prefixlen = uint8(prefixlen)
req.AddData(msg)
@@ -52,6 +57,13 @@ func addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error {
addressData := nl.NewRtAttr(syscall.IFA_ADDRESS, addrData)
req.AddData(addressData)
+ if addr.Flags != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(addr.Flags))
+ flagsData := nl.NewRtAttr(IFA_FLAGS, b)
+ req.AddData(flagsData)
+ }
+
if addr.Label != "" {
labelData := nl.NewRtAttr(syscall.IFA_LABEL, nl.ZeroTerminated(addr.Label))
req.AddData(labelData)
@@ -74,55 +86,125 @@ func AddrList(link Link, family int) ([]Addr, error) {
return nil, err
}
- index := 0
+ indexFilter := 0
if link != nil {
base := link.Attrs()
ensureIndex(base)
- index = base.Index
+ indexFilter = base.Index
}
var res []Addr
for _, m := range msgs {
- msg := nl.DeserializeIfAddrmsg(m)
+ addr, msgFamily, ifindex, err := parseAddr(m)
+ if err != nil {
+ return res, err
+ }
- if link != nil && msg.Index != uint32(index) {
+ if link != nil && ifindex != indexFilter {
// Ignore messages from other interfaces
continue
}
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
+ if family != FAMILY_ALL && msgFamily != family {
+ continue
}
- var local, dst *net.IPNet
- var addr Addr
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.IFA_ADDRESS:
- dst = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
- }
- case syscall.IFA_LOCAL:
- local = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
- }
- case syscall.IFA_LABEL:
- addr.Label = string(attr.Value[:len(attr.Value)-1])
+ res = append(res, addr)
+ }
+
+ return res, nil
+}
+
+func parseAddr(m []byte) (addr Addr, family, index int, err error) {
+ msg := nl.DeserializeIfAddrmsg(m)
+
+ family = -1
+ index = -1
+
+ attrs, err1 := nl.ParseRouteAttr(m[msg.Len():])
+ if err1 != nil {
+ err = err1
+ return
+ }
+
+ family = int(msg.Family)
+ index = int(msg.Index)
+
+ var local, dst *net.IPNet
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.IFA_ADDRESS:
+ dst = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
}
+ case syscall.IFA_LOCAL:
+ local = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
+ }
+ case syscall.IFA_LABEL:
+ addr.Label = string(attr.Value[:len(attr.Value)-1])
+ case IFA_FLAGS:
+ addr.Flags = int(native.Uint32(attr.Value[0:4]))
}
+ }
- // IFA_LOCAL should be there but if not, fall back to IFA_ADDRESS
- if local != nil {
- addr.IPNet = local
- } else {
- addr.IPNet = dst
- }
+ // IFA_LOCAL should be there but if not, fall back to IFA_ADDRESS
+ if local != nil {
+ addr.IPNet = local
+ } else {
+ addr.IPNet = dst
+ }
+ addr.Scope = int(msg.Scope)
- res = append(res, addr)
+ return
+}
+
+type AddrUpdate struct {
+ LinkAddress net.IPNet
+ LinkIndex int
+ NewAddr bool // true=added false=deleted
+}
+
+// AddrSubscribe takes a chan down which notifications will be sent
+// when addresses change. Close the 'done' chan to stop subscription.
+func AddrSubscribe(ch chan<- AddrUpdate, done <-chan struct{}) error {
+ s, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_IFADDR, syscall.RTNLGRP_IPV6_IFADDR)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
}
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ log.Printf("netlink.AddrSubscribe: Receive() error: %v", err)
+ return
+ }
+ for _, m := range msgs {
+ msgType := m.Header.Type
+ if msgType != syscall.RTM_NEWADDR && msgType != syscall.RTM_DELADDR {
+ log.Printf("netlink.AddrSubscribe: bad message type: %d", msgType)
+ continue
+ }
- return res, nil
+ addr, _, ifindex, err := parseAddr(m.Data)
+ if err != nil {
+ log.Printf("netlink.AddrSubscribe: could not parse address: %v", err)
+ continue
+ }
+
+ ch <- AddrUpdate{LinkAddress: *addr.IPNet, LinkIndex: ifindex, NewAddr: msgType == syscall.RTM_NEWADDR}
+ }
+ }
+ }()
+
+ return nil
}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_test.go
deleted file mode 100644
index 45e22c052..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/addr_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package netlink
-
-import (
- "testing"
-)
-
-func TestAddrAddDel(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- link, err := LinkByName("lo")
- if err != nil {
- t.Fatal(err)
- }
-
- addr, err := ParseAddr("127.1.1.1/24 local")
- if err != nil {
- t.Fatal(err)
- }
-
- if err = AddrAdd(link, addr); err != nil {
- t.Fatal(err)
- }
-
- addrs, err := AddrList(link, FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(addrs) != 1 || !addr.Equal(addrs[0]) || addrs[0].Label != addr.Label {
- t.Fatal("Address not added properly")
- }
-
- if err = AddrDel(link, addr); err != nil {
- t.Fatal(err)
- }
- addrs, err = AddrList(link, FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(addrs) != 0 {
- t.Fatal("Address not removed properly")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/bpf_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/bpf_linux.go
new file mode 100644
index 000000000..acd949013
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/bpf_linux.go
@@ -0,0 +1,60 @@
+package netlink
+
+/*
+#include
+#include
+#include
+#include
+#include
+#include
+
+static int load_simple_bpf(int prog_type) {
+#ifdef __NR_bpf
+ // { return 1; }
+ __u64 __attribute__((aligned(8))) insns[] = {
+ 0x00000001000000b7ull,
+ 0x0000000000000095ull,
+ };
+ __u8 __attribute__((aligned(8))) license[] = "ASL2";
+ // Copied from a header file since libc is notoriously slow to update.
+ // The call will succeed or fail and that will be our indication on
+ // whether or not it is supported.
+ struct {
+ __u32 prog_type;
+ __u32 insn_cnt;
+ __u64 insns;
+ __u64 license;
+ __u32 log_level;
+ __u32 log_size;
+ __u64 log_buf;
+ __u32 kern_version;
+ } __attribute__((aligned(8))) attr = {
+ .prog_type = prog_type,
+ .insn_cnt = 2,
+ .insns = (uintptr_t)&insns,
+ .license = (uintptr_t)&license,
+ };
+ return syscall(__NR_bpf, 5, &attr, sizeof(attr));
+#else
+ errno = EINVAL;
+ return -1;
+#endif
+}
+*/
+import "C"
+
+type BpfProgType C.int
+
+const (
+ BPF_PROG_TYPE_UNSPEC BpfProgType = iota
+ BPF_PROG_TYPE_SOCKET_FILTER
+ BPF_PROG_TYPE_KPROBE
+ BPF_PROG_TYPE_SCHED_CLS
+ BPF_PROG_TYPE_SCHED_ACT
+)
+
+// loadSimpleBpf loads a trivial bpf program for testing purposes
+func loadSimpleBpf(progType BpfProgType) (int, error) {
+ fd, err := C.load_simple_bpf(C.int(progType))
+ return int(fd), err
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/class.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/class.go
new file mode 100644
index 000000000..457730410
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/class.go
@@ -0,0 +1,111 @@
+package netlink
+
+import (
+ "fmt"
+)
+
+type Class interface {
+ Attrs() *ClassAttrs
+ Type() string
+}
+
+// ClassAttrs represents a netlink class. A filter is associated with a link,
+// has a handle and a parent. The root filter of a device should have a
+// parent == HANDLE_ROOT.
+type ClassAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Leaf uint32
+}
+
+func (q ClassAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Leaf: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Leaf)
+}
+
+type HtbClassAttrs struct {
+ // TODO handle all attributes
+ Rate uint64
+ Ceil uint64
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func (q HtbClassAttrs) String() string {
+ return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
+}
+
+// HtbClass represents an Htb class
+type HtbClass struct {
+ ClassAttrs
+ Rate uint64
+ Ceil uint64
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func NewHtbClass(attrs ClassAttrs, cattrs HtbClassAttrs) *HtbClass {
+ mtu := 1600
+ rate := cattrs.Rate / 8
+ ceil := cattrs.Ceil / 8
+ buffer := cattrs.Buffer
+ cbuffer := cattrs.Cbuffer
+
+ if ceil == 0 {
+ ceil = rate
+ }
+
+ if buffer == 0 {
+ buffer = uint32(float64(rate)/Hz() + float64(mtu))
+ }
+ buffer = uint32(Xmittime(rate, buffer))
+
+ if cbuffer == 0 {
+ cbuffer = uint32(float64(ceil)/Hz() + float64(mtu))
+ }
+ cbuffer = uint32(Xmittime(ceil, cbuffer))
+
+ return &HtbClass{
+ ClassAttrs: attrs,
+ Rate: rate,
+ Ceil: ceil,
+ Buffer: buffer,
+ Cbuffer: cbuffer,
+ Quantum: 10,
+ Level: 0,
+ Prio: 0,
+ }
+}
+
+func (q HtbClass) String() string {
+ return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
+}
+
+func (q *HtbClass) Attrs() *ClassAttrs {
+ return &q.ClassAttrs
+}
+
+func (q *HtbClass) Type() string {
+ return "htb"
+}
+
+// GenericClass classes represent types that are not currently understood
+// by this netlink library.
+type GenericClass struct {
+ ClassAttrs
+ ClassType string
+}
+
+func (class *GenericClass) Attrs() *ClassAttrs {
+ return &class.ClassAttrs
+}
+
+func (class *GenericClass) Type() string {
+ return class.ClassType
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/class_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/class_linux.go
new file mode 100644
index 000000000..fe81796de
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/class_linux.go
@@ -0,0 +1,186 @@
+package netlink
+
+import (
+ "errors"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// ClassDel will delete a class from the system.
+// Equivalent to: `tc class del $class`
+func ClassDel(class Class) error {
+ return classModify(syscall.RTM_DELTCLASS, 0, class)
+}
+
+// ClassChange will change a class in place
+// Equivalent to: `tc class change $class`
+// The parent and handle MUST NOT be changed.
+
+func ClassChange(class Class) error {
+ return classModify(syscall.RTM_NEWTCLASS, 0, class)
+}
+
+// ClassReplace will replace a class to the system.
+// quivalent to: `tc class replace $class`
+// The handle MAY be changed.
+// If a class already exist with this parent/handle pair, the class is changed.
+// If a class does not already exist with this parent/handle, a new class is created.
+func ClassReplace(class Class) error {
+ return classModify(syscall.RTM_NEWTCLASS, syscall.NLM_F_CREATE, class)
+}
+
+// ClassAdd will add a class to the system.
+// Equivalent to: `tc class add $class`
+func ClassAdd(class Class) error {
+ return classModify(
+ syscall.RTM_NEWTCLASS,
+ syscall.NLM_F_CREATE|syscall.NLM_F_EXCL,
+ class,
+ )
+}
+
+func classModify(cmd, flags int, class Class) error {
+ req := nl.NewNetlinkRequest(cmd, flags|syscall.NLM_F_ACK)
+ base := class.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ }
+ req.AddData(msg)
+
+ if cmd != syscall.RTM_DELTCLASS {
+ if err := classPayload(req, class); err != nil {
+ return err
+ }
+ }
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func classPayload(req *nl.NetlinkRequest, class Class) error {
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(class.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if htb, ok := class.(*HtbClass); ok {
+ opt := nl.TcHtbCopt{}
+ opt.Buffer = htb.Buffer
+ opt.Cbuffer = htb.Cbuffer
+ opt.Quantum = htb.Quantum
+ opt.Level = htb.Level
+ opt.Prio = htb.Prio
+ // TODO: Handle Debug properly. For now default to 0
+ /* Calculate {R,C}Tab and set Rate and Ceil */
+ cellLog := -1
+ ccellLog := -1
+ linklayer := nl.LINKLAYER_ETHERNET
+ mtu := 1600
+ var rtab [256]uint32
+ var ctab [256]uint32
+ tcrate := nl.TcRateSpec{Rate: uint32(htb.Rate)}
+ if CalcRtable(&tcrate, rtab, cellLog, uint32(mtu), linklayer) < 0 {
+ return errors.New("HTB: failed to calculate rate table")
+ }
+ opt.Rate = tcrate
+ tcceil := nl.TcRateSpec{Rate: uint32(htb.Ceil)}
+ if CalcRtable(&tcceil, ctab, ccellLog, uint32(mtu), linklayer) < 0 {
+ return errors.New("HTB: failed to calculate ceil rate table")
+ }
+ opt.Ceil = tcceil
+ nl.NewRtAttrChild(options, nl.TCA_HTB_PARMS, opt.Serialize())
+ nl.NewRtAttrChild(options, nl.TCA_HTB_RTAB, SerializeRtab(rtab))
+ nl.NewRtAttrChild(options, nl.TCA_HTB_CTAB, SerializeRtab(ctab))
+ }
+ req.AddData(options)
+ return nil
+}
+
+// ClassList gets a list of classes in the system.
+// Equivalent to: `tc class show`.
+// Generally returns nothing if link and parent are not specified.
+func ClassList(link Link, parent uint32) ([]Class, error) {
+ req := nl.NewNetlinkRequest(syscall.RTM_GETTCLASS, syscall.NLM_F_DUMP)
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Parent: parent,
+ }
+ if link != nil {
+ base := link.Attrs()
+ ensureIndex(base)
+ msg.Ifindex = int32(base.Index)
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTCLASS)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Class
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ base := ClassAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ }
+
+ var class Class
+ classType := ""
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ classType = string(attr.Value[:len(attr.Value)-1])
+ switch classType {
+ case "htb":
+ class = &HtbClass{}
+ default:
+ class = &GenericClass{ClassType: classType}
+ }
+ case nl.TCA_OPTIONS:
+ switch classType {
+ case "htb":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ _, err = parseHtbClassData(class, data)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+ }
+ *class.Attrs() = base
+ res = append(res, class)
+ }
+
+ return res, nil
+}
+
+func parseHtbClassData(class Class, data []syscall.NetlinkRouteAttr) (bool, error) {
+ htb := class.(*HtbClass)
+ detailed := false
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_HTB_PARMS:
+ opt := nl.DeserializeTcHtbCopt(datum.Value)
+ htb.Rate = uint64(opt.Rate.Rate)
+ htb.Ceil = uint64(opt.Ceil.Rate)
+ htb.Buffer = opt.Buffer
+ htb.Cbuffer = opt.Cbuffer
+ htb.Quantum = opt.Quantum
+ htb.Level = opt.Level
+ htb.Prio = opt.Prio
+ }
+ }
+ return detailed, nil
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/filter.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/filter.go
new file mode 100644
index 000000000..8d62ca55e
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/filter.go
@@ -0,0 +1,190 @@
+package netlink
+
+import (
+ "errors"
+ "fmt"
+ "github.com/vishvananda/netlink/nl"
+)
+
+type Filter interface {
+ Attrs() *FilterAttrs
+ Type() string
+}
+
+// FilterAttrs represents a netlink filter. A filter is associated with a link,
+// has a handle and a parent. The root filter of a device should have a
+// parent == HANDLE_ROOT.
+type FilterAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Priority uint16 // lower is higher priority
+ Protocol uint16 // syscall.ETH_P_*
+}
+
+func (q FilterAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol)
+}
+
+// Action represents an action in any supported filter.
+type Action interface {
+ Type() string
+}
+
+type BpfAction struct {
+ nl.TcActBpf
+ Fd int
+ Name string
+}
+
+func (action *BpfAction) Type() string {
+ return "bpf"
+}
+
+type MirredAction struct {
+ nl.TcMirred
+}
+
+func (action *MirredAction) Type() string {
+ return "mirred"
+}
+
+func NewMirredAction(redirIndex int) *MirredAction {
+ return &MirredAction{
+ TcMirred: nl.TcMirred{
+ TcGen: nl.TcGen{Action: nl.TC_ACT_STOLEN},
+ Eaction: nl.TCA_EGRESS_REDIR,
+ Ifindex: uint32(redirIndex),
+ },
+ }
+}
+
+// U32 filters on many packet related properties
+type U32 struct {
+ FilterAttrs
+ ClassId uint32
+ RedirIndex int
+ Actions []Action
+}
+
+func (filter *U32) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *U32) Type() string {
+ return "u32"
+}
+
+type FilterFwAttrs struct {
+ ClassId uint32
+ InDev string
+ Mask uint32
+ Index uint32
+ Buffer uint32
+ Mtu uint32
+ Mpu uint16
+ Rate uint32
+ AvRate uint32
+ PeakRate uint32
+ Action int
+ Overhead uint16
+ LinkLayer int
+}
+
+// Fw filter filters on firewall marks
+type Fw struct {
+ FilterAttrs
+ ClassId uint32
+ Police nl.TcPolice
+ InDev string
+ // TODO Action
+ Mask uint32
+ AvRate uint32
+ Rtab [256]uint32
+ Ptab [256]uint32
+}
+
+func NewFw(attrs FilterAttrs, fattrs FilterFwAttrs) (*Fw, error) {
+ var rtab [256]uint32
+ var ptab [256]uint32
+ rcellLog := -1
+ pcellLog := -1
+ avrate := fattrs.AvRate / 8
+ police := nl.TcPolice{}
+ police.Rate.Rate = fattrs.Rate / 8
+ police.PeakRate.Rate = fattrs.PeakRate / 8
+ buffer := fattrs.Buffer
+ linklayer := nl.LINKLAYER_ETHERNET
+
+ if fattrs.LinkLayer != nl.LINKLAYER_UNSPEC {
+ linklayer = fattrs.LinkLayer
+ }
+
+ police.Action = int32(fattrs.Action)
+ if police.Rate.Rate != 0 {
+ police.Rate.Mpu = fattrs.Mpu
+ police.Rate.Overhead = fattrs.Overhead
+ if CalcRtable(&police.Rate, rtab, rcellLog, fattrs.Mtu, linklayer) < 0 {
+ return nil, errors.New("TBF: failed to calculate rate table")
+ }
+ police.Burst = uint32(Xmittime(uint64(police.Rate.Rate), uint32(buffer)))
+ }
+ police.Mtu = fattrs.Mtu
+ if police.PeakRate.Rate != 0 {
+ police.PeakRate.Mpu = fattrs.Mpu
+ police.PeakRate.Overhead = fattrs.Overhead
+ if CalcRtable(&police.PeakRate, ptab, pcellLog, fattrs.Mtu, linklayer) < 0 {
+ return nil, errors.New("POLICE: failed to calculate peak rate table")
+ }
+ }
+
+ return &Fw{
+ FilterAttrs: attrs,
+ ClassId: fattrs.ClassId,
+ InDev: fattrs.InDev,
+ Mask: fattrs.Mask,
+ Police: police,
+ AvRate: avrate,
+ Rtab: rtab,
+ Ptab: ptab,
+ }, nil
+}
+
+func (filter *Fw) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *Fw) Type() string {
+ return "fw"
+}
+
+type BpfFilter struct {
+ FilterAttrs
+ ClassId uint32
+ Fd int
+ Name string
+ DirectAction bool
+}
+
+func (filter *BpfFilter) Type() string {
+ return "bpf"
+}
+
+func (filter *BpfFilter) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+// GenericFilter filters represent types that are not currently understood
+// by this netlink library.
+type GenericFilter struct {
+ FilterAttrs
+ FilterType string
+}
+
+func (filter *GenericFilter) Attrs() *FilterAttrs {
+ return &filter.FilterAttrs
+}
+
+func (filter *GenericFilter) Type() string {
+ return filter.FilterType
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/filter_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/filter_linux.go
new file mode 100644
index 000000000..f0f5859f7
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/filter_linux.go
@@ -0,0 +1,424 @@
+package netlink
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// FilterDel will delete a filter from the system.
+// Equivalent to: `tc filter del $filter`
+func FilterDel(filter Filter) error {
+ req := nl.NewNetlinkRequest(syscall.RTM_DELTFILTER, syscall.NLM_F_ACK)
+ base := filter.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
+ }
+ req.AddData(msg)
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// FilterAdd will add a filter to the system.
+// Equivalent to: `tc filter add $filter`
+func FilterAdd(filter Filter) error {
+ native = nl.NativeEndian()
+ req := nl.NewNetlinkRequest(syscall.RTM_NEWTFILTER, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ base := filter.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
+ }
+ req.AddData(msg)
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(filter.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if u32, ok := filter.(*U32); ok {
+ // match all
+ sel := nl.TcU32Sel{
+ Nkeys: 1,
+ Flags: nl.TC_U32_TERMINAL,
+ }
+ sel.Keys = append(sel.Keys, nl.TcU32Key{})
+ nl.NewRtAttrChild(options, nl.TCA_U32_SEL, sel.Serialize())
+ if u32.ClassId != 0 {
+ nl.NewRtAttrChild(options, nl.TCA_U32_CLASSID, nl.Uint32Attr(u32.ClassId))
+ }
+ actionsAttr := nl.NewRtAttrChild(options, nl.TCA_U32_ACT, nil)
+ // backwards compatibility
+ if u32.RedirIndex != 0 {
+ u32.Actions = append([]Action{NewMirredAction(u32.RedirIndex)}, u32.Actions...)
+ }
+ if err := encodeActions(actionsAttr, u32.Actions); err != nil {
+ return err
+ }
+ } else if fw, ok := filter.(*Fw); ok {
+ if fw.Mask != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, fw.Mask)
+ nl.NewRtAttrChild(options, nl.TCA_FW_MASK, b)
+ }
+ if fw.InDev != "" {
+ nl.NewRtAttrChild(options, nl.TCA_FW_INDEV, nl.ZeroTerminated(fw.InDev))
+ }
+ if (fw.Police != nl.TcPolice{}) {
+
+ police := nl.NewRtAttrChild(options, nl.TCA_FW_POLICE, nil)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_TBF, fw.Police.Serialize())
+ if (fw.Police.Rate != nl.TcRateSpec{}) {
+ payload := SerializeRtab(fw.Rtab)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_RATE, payload)
+ }
+ if (fw.Police.PeakRate != nl.TcRateSpec{}) {
+ payload := SerializeRtab(fw.Ptab)
+ nl.NewRtAttrChild(police, nl.TCA_POLICE_PEAKRATE, payload)
+ }
+ }
+ if fw.ClassId != 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, fw.ClassId)
+ nl.NewRtAttrChild(options, nl.TCA_FW_CLASSID, b)
+ }
+ } else if bpf, ok := filter.(*BpfFilter); ok {
+ var bpfFlags uint32
+ if bpf.ClassId != 0 {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_CLASSID, nl.Uint32Attr(bpf.ClassId))
+ }
+ if bpf.Fd >= 0 {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_FD, nl.Uint32Attr((uint32(bpf.Fd))))
+ }
+ if bpf.Name != "" {
+ nl.NewRtAttrChild(options, nl.TCA_BPF_NAME, nl.ZeroTerminated(bpf.Name))
+ }
+ if bpf.DirectAction {
+ bpfFlags |= nl.TCA_BPF_FLAG_ACT_DIRECT
+ }
+ nl.NewRtAttrChild(options, nl.TCA_BPF_FLAGS, nl.Uint32Attr(bpfFlags))
+ }
+
+ req.AddData(options)
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// FilterList gets a list of filters in the system.
+// Equivalent to: `tc filter show`.
+// Generally retunrs nothing if link and parent are not specified.
+func FilterList(link Link, parent uint32) ([]Filter, error) {
+ req := nl.NewNetlinkRequest(syscall.RTM_GETTFILTER, syscall.NLM_F_DUMP)
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Parent: parent,
+ }
+ if link != nil {
+ base := link.Attrs()
+ ensureIndex(base)
+ msg.Ifindex = int32(base.Index)
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTFILTER)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Filter
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ base := FilterAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ }
+ base.Priority, base.Protocol = MajorMinor(msg.Info)
+ base.Protocol = nl.Swap16(base.Protocol)
+
+ var filter Filter
+ filterType := ""
+ detailed := false
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ filterType = string(attr.Value[:len(attr.Value)-1])
+ switch filterType {
+ case "u32":
+ filter = &U32{}
+ case "fw":
+ filter = &Fw{}
+ case "bpf":
+ filter = &BpfFilter{}
+ default:
+ filter = &GenericFilter{FilterType: filterType}
+ }
+ case nl.TCA_OPTIONS:
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ switch filterType {
+ case "u32":
+ detailed, err = parseU32Data(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ case "fw":
+ detailed, err = parseFwData(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ case "bpf":
+ detailed, err = parseBpfData(filter, data)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+ }
+ // only return the detailed version of the filter
+ if detailed {
+ *filter.Attrs() = base
+ res = append(res, filter)
+ }
+ }
+
+ return res, nil
+}
+
+func encodeActions(attr *nl.RtAttr, actions []Action) error {
+ tabIndex := int(nl.TCA_ACT_TAB)
+
+ for _, action := range actions {
+ switch action := action.(type) {
+ default:
+ return fmt.Errorf("unknown action type %s", action.Type())
+ case *MirredAction:
+ table := nl.NewRtAttrChild(attr, tabIndex, nil)
+ tabIndex++
+ nl.NewRtAttrChild(table, nl.TCA_ACT_KIND, nl.ZeroTerminated("mirred"))
+ aopts := nl.NewRtAttrChild(table, nl.TCA_ACT_OPTIONS, nil)
+ nl.NewRtAttrChild(aopts, nl.TCA_MIRRED_PARMS, action.Serialize())
+ case *BpfAction:
+ table := nl.NewRtAttrChild(attr, tabIndex, nil)
+ tabIndex++
+ nl.NewRtAttrChild(table, nl.TCA_ACT_KIND, nl.ZeroTerminated("bpf"))
+ aopts := nl.NewRtAttrChild(table, nl.TCA_ACT_OPTIONS, nil)
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_PARMS, action.Serialize())
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_FD, nl.Uint32Attr(uint32(action.Fd)))
+ nl.NewRtAttrChild(aopts, nl.TCA_ACT_BPF_NAME, nl.ZeroTerminated(action.Name))
+ }
+ }
+ return nil
+}
+
+func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) {
+ var actions []Action
+ for _, table := range tables {
+ var action Action
+ var actionType string
+ aattrs, err := nl.ParseRouteAttr(table.Value)
+ if err != nil {
+ return nil, err
+ }
+ nextattr:
+ for _, aattr := range aattrs {
+ switch aattr.Attr.Type {
+ case nl.TCA_KIND:
+ actionType = string(aattr.Value[:len(aattr.Value)-1])
+ // only parse if the action is mirred or bpf
+ switch actionType {
+ case "mirred":
+ action = &MirredAction{}
+ case "bpf":
+ action = &BpfAction{}
+ default:
+ break nextattr
+ }
+ case nl.TCA_OPTIONS:
+ adata, err := nl.ParseRouteAttr(aattr.Value)
+ if err != nil {
+ return nil, err
+ }
+ for _, adatum := range adata {
+ switch actionType {
+ case "mirred":
+ switch adatum.Attr.Type {
+ case nl.TCA_MIRRED_PARMS:
+ action.(*MirredAction).TcMirred = *nl.DeserializeTcMirred(adatum.Value)
+ }
+ case "bpf":
+ switch adatum.Attr.Type {
+ case nl.TCA_ACT_BPF_PARMS:
+ action.(*BpfAction).TcActBpf = *nl.DeserializeTcActBpf(adatum.Value)
+ case nl.TCA_ACT_BPF_FD:
+ action.(*BpfAction).Fd = int(native.Uint32(adatum.Value[0:4]))
+ case nl.TCA_ACT_BPF_NAME:
+ action.(*BpfAction).Name = string(adatum.Value[:len(adatum.Value)-1])
+ }
+ }
+ }
+ }
+ }
+ actions = append(actions, action)
+ }
+ return actions, nil
+}
+
+func parseU32Data(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ u32 := filter.(*U32)
+ detailed := false
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_U32_SEL:
+ detailed = true
+ sel := nl.DeserializeTcU32Sel(datum.Value)
+ // only parse if we have a very basic redirect
+ if sel.Flags&nl.TC_U32_TERMINAL == 0 || sel.Nkeys != 1 {
+ return detailed, nil
+ }
+ case nl.TCA_U32_ACT:
+ tables, err := nl.ParseRouteAttr(datum.Value)
+ if err != nil {
+ return detailed, err
+ }
+ u32.Actions, err = parseActions(tables)
+ if err != nil {
+ return detailed, err
+ }
+ for _, action := range u32.Actions {
+ if action, ok := action.(*MirredAction); ok {
+ u32.RedirIndex = int(action.Ifindex)
+ }
+ }
+ }
+ }
+ return detailed, nil
+}
+
+func parseFwData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ fw := filter.(*Fw)
+ detailed := true
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_FW_MASK:
+ fw.Mask = native.Uint32(datum.Value[0:4])
+ case nl.TCA_FW_CLASSID:
+ fw.ClassId = native.Uint32(datum.Value[0:4])
+ case nl.TCA_FW_INDEV:
+ fw.InDev = string(datum.Value[:len(datum.Value)-1])
+ case nl.TCA_FW_POLICE:
+ adata, _ := nl.ParseRouteAttr(datum.Value)
+ for _, aattr := range adata {
+ switch aattr.Attr.Type {
+ case nl.TCA_POLICE_TBF:
+ fw.Police = *nl.DeserializeTcPolice(aattr.Value)
+ case nl.TCA_POLICE_RATE:
+ fw.Rtab = DeserializeRtab(aattr.Value)
+ case nl.TCA_POLICE_PEAKRATE:
+ fw.Ptab = DeserializeRtab(aattr.Value)
+ }
+ }
+ }
+ }
+ return detailed, nil
+}
+
+func parseBpfData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
+ native = nl.NativeEndian()
+ bpf := filter.(*BpfFilter)
+ detailed := true
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_BPF_FD:
+ bpf.Fd = int(native.Uint32(datum.Value[0:4]))
+ case nl.TCA_BPF_NAME:
+ bpf.Name = string(datum.Value[:len(datum.Value)-1])
+ case nl.TCA_BPF_CLASSID:
+ bpf.ClassId = native.Uint32(datum.Value[0:4])
+ case nl.TCA_BPF_FLAGS:
+ flags := native.Uint32(datum.Value[0:4])
+ if (flags & nl.TCA_BPF_FLAG_ACT_DIRECT) != 0 {
+ bpf.DirectAction = true
+ }
+ }
+ }
+ return detailed, nil
+}
+
+func AlignToAtm(size uint) uint {
+ var linksize, cells int
+ cells = int(size / nl.ATM_CELL_PAYLOAD)
+ if (size % nl.ATM_CELL_PAYLOAD) > 0 {
+ cells++
+ }
+ linksize = cells * nl.ATM_CELL_SIZE
+ return uint(linksize)
+}
+
+func AdjustSize(sz uint, mpu uint, linklayer int) uint {
+ if sz < mpu {
+ sz = mpu
+ }
+ switch linklayer {
+ case nl.LINKLAYER_ATM:
+ return AlignToAtm(sz)
+ default:
+ return sz
+ }
+}
+
+func CalcRtable(rate *nl.TcRateSpec, rtab [256]uint32, cellLog int, mtu uint32, linklayer int) int {
+ bps := rate.Rate
+ mpu := rate.Mpu
+ var sz uint
+ if mtu == 0 {
+ mtu = 2047
+ }
+ if cellLog < 0 {
+ cellLog = 0
+ for (mtu >> uint(cellLog)) > 255 {
+ cellLog++
+ }
+ }
+ for i := 0; i < 256; i++ {
+ sz = AdjustSize(uint((i+1)< 0 {
@@ -273,6 +352,87 @@ func addVxlanAttrs(vxlan *Vxlan, linkInfo *nl.RtAttr) {
}
}
+func addBondAttrs(bond *Bond, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+ if bond.Mode >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MODE, nl.Uint8Attr(uint8(bond.Mode)))
+ }
+ if bond.ActiveSlave >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ACTIVE_SLAVE, nl.Uint32Attr(uint32(bond.ActiveSlave)))
+ }
+ if bond.Miimon >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MIIMON, nl.Uint32Attr(uint32(bond.Miimon)))
+ }
+ if bond.UpDelay >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_UPDELAY, nl.Uint32Attr(uint32(bond.UpDelay)))
+ }
+ if bond.DownDelay >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_DOWNDELAY, nl.Uint32Attr(uint32(bond.DownDelay)))
+ }
+ if bond.UseCarrier >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_USE_CARRIER, nl.Uint8Attr(uint8(bond.UseCarrier)))
+ }
+ if bond.ArpInterval >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_INTERVAL, nl.Uint32Attr(uint32(bond.ArpInterval)))
+ }
+ if bond.ArpIpTargets != nil {
+ msg := nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_IP_TARGET, nil)
+ for i := range bond.ArpIpTargets {
+ ip := bond.ArpIpTargets[i].To4()
+ if ip != nil {
+ nl.NewRtAttrChild(msg, i, []byte(ip))
+ continue
+ }
+ ip = bond.ArpIpTargets[i].To16()
+ if ip != nil {
+ nl.NewRtAttrChild(msg, i, []byte(ip))
+ }
+ }
+ }
+ if bond.ArpValidate >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_VALIDATE, nl.Uint32Attr(uint32(bond.ArpValidate)))
+ }
+ if bond.ArpAllTargets >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ARP_ALL_TARGETS, nl.Uint32Attr(uint32(bond.ArpAllTargets)))
+ }
+ if bond.Primary >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PRIMARY, nl.Uint32Attr(uint32(bond.Primary)))
+ }
+ if bond.PrimaryReselect >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PRIMARY_RESELECT, nl.Uint8Attr(uint8(bond.PrimaryReselect)))
+ }
+ if bond.FailOverMac >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_FAIL_OVER_MAC, nl.Uint8Attr(uint8(bond.FailOverMac)))
+ }
+ if bond.XmitHashPolicy >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_XMIT_HASH_POLICY, nl.Uint8Attr(uint8(bond.XmitHashPolicy)))
+ }
+ if bond.ResendIgmp >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_RESEND_IGMP, nl.Uint32Attr(uint32(bond.ResendIgmp)))
+ }
+ if bond.NumPeerNotif >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_NUM_PEER_NOTIF, nl.Uint8Attr(uint8(bond.NumPeerNotif)))
+ }
+ if bond.AllSlavesActive >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_ALL_SLAVES_ACTIVE, nl.Uint8Attr(uint8(bond.AllSlavesActive)))
+ }
+ if bond.MinLinks >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_MIN_LINKS, nl.Uint32Attr(uint32(bond.MinLinks)))
+ }
+ if bond.LpInterval >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_LP_INTERVAL, nl.Uint32Attr(uint32(bond.LpInterval)))
+ }
+ if bond.PackersPerSlave >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_PACKETS_PER_SLAVE, nl.Uint32Attr(uint32(bond.PackersPerSlave)))
+ }
+ if bond.LacpRate >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_LACP_RATE, nl.Uint8Attr(uint8(bond.LacpRate)))
+ }
+ if bond.AdSelect >= 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_BOND_AD_SELECT, nl.Uint8Attr(uint8(bond.AdSelect)))
+ }
+}
+
// LinkAdd adds a new link device. The type and features of the device
// are taken fromt the parameters in the link object.
// Equivalent to: `ip link add $link`
@@ -285,9 +445,68 @@ func LinkAdd(link Link) error {
return fmt.Errorf("LinkAttrs.Name cannot be empty!")
}
+ if tuntap, ok := link.(*Tuntap); ok {
+ // TODO: support user
+ // TODO: support group
+ // TODO: support non- one_queue
+ // TODO: support pi | vnet_hdr | multi_queue
+ // TODO: support non- exclusive
+ // TODO: support non- persistent
+ if tuntap.Mode < syscall.IFF_TUN || tuntap.Mode > syscall.IFF_TAP {
+ return fmt.Errorf("Tuntap.Mode %v unknown!", tuntap.Mode)
+ }
+ file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ var req ifReq
+ req.Flags |= syscall.IFF_ONE_QUEUE
+ req.Flags |= syscall.IFF_TUN_EXCL
+ copy(req.Name[:15], base.Name)
+ req.Flags |= uint16(tuntap.Mode)
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETIFF), uintptr(unsafe.Pointer(&req)))
+ if errno != 0 {
+ return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed, errno %v", errno)
+ }
+ _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETPERSIST), 1)
+ if errno != 0 {
+ return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno)
+ }
+ ensureIndex(base)
+
+ // can't set master during create, so set it afterwards
+ if base.MasterIndex != 0 {
+ // TODO: verify MasterIndex is actually a bridge?
+ return LinkSetMasterByIndex(link, base.MasterIndex)
+ }
+ return nil
+ }
+
req := nl.NewNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ // TODO: make it shorter
+ if base.Flags&net.FlagUp != 0 {
+ msg.Change = syscall.IFF_UP
+ msg.Flags = syscall.IFF_UP
+ }
+ if base.Flags&net.FlagBroadcast != 0 {
+ msg.Change |= syscall.IFF_BROADCAST
+ msg.Flags |= syscall.IFF_BROADCAST
+ }
+ if base.Flags&net.FlagLoopback != 0 {
+ msg.Change |= syscall.IFF_LOOPBACK
+ msg.Flags |= syscall.IFF_LOOPBACK
+ }
+ if base.Flags&net.FlagPointToPoint != 0 {
+ msg.Change |= syscall.IFF_POINTOPOINT
+ msg.Flags |= syscall.IFF_POINTOPOINT
+ }
+ if base.Flags&net.FlagMulticast != 0 {
+ msg.Change |= syscall.IFF_MULTICAST
+ msg.Flags |= syscall.IFF_MULTICAST
+ }
req.AddData(msg)
if base.ParentIndex != 0 {
@@ -348,6 +567,8 @@ func LinkAdd(link Link) error {
} else if vxlan, ok := link.(*Vxlan); ok {
addVxlanAttrs(vxlan, linkInfo)
+ } else if bond, ok := link.(*Bond); ok {
+ addBondAttrs(bond, linkInfo)
} else if ipv, ok := link.(*IPVlan); ok {
data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
nl.NewRtAttrChild(data, nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(ipv.Mode)))
@@ -356,6 +577,8 @@ func LinkAdd(link Link) error {
data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
nl.NewRtAttrChild(data, nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[macv.Mode]))
}
+ } else if gretap, ok := link.(*Gretap); ok {
+ addGretapAttrs(gretap, linkInfo)
}
req.AddData(linkInfo)
@@ -407,6 +630,20 @@ func linkByNameDump(name string) (Link, error) {
return nil, fmt.Errorf("Link %s not found", name)
}
+func linkByAliasDump(alias string) (Link, error) {
+ links, err := LinkList()
+ if err != nil {
+ return nil, err
+ }
+
+ for _, link := range links {
+ if link.Attrs().Alias == alias {
+ return link, nil
+ }
+ }
+ return nil, fmt.Errorf("Link alias %s not found", alias)
+}
+
// LinkByName finds a link by name and returns a pointer to the object.
func LinkByName(name string) (Link, error) {
if lookupByDump {
@@ -432,6 +669,32 @@ func LinkByName(name string) (Link, error) {
return link, err
}
+// LinkByAlias finds a link by its alias and returns a pointer to the object.
+// If there are multiple links with the alias it returns the first one
+func LinkByAlias(alias string) (Link, error) {
+ if lookupByDump {
+ return linkByAliasDump(alias)
+ }
+
+ req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
+
+ msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
+ req.AddData(msg)
+
+ nameData := nl.NewRtAttr(syscall.IFLA_IFALIAS, nl.ZeroTerminated(alias))
+ req.AddData(nameData)
+
+ link, err := execGetLink(req)
+ if err == syscall.EINVAL {
+ // older kernels don't support looking up via IFLA_IFALIAS
+ // so fall back to dumping all links
+ lookupByDump = true
+ return linkByAliasDump(alias)
+ }
+
+ return link, err
+}
+
// LinkByIndex finds a link by index and returns a pointer to the object.
func LinkByIndex(index int) (Link, error) {
req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
@@ -493,6 +756,8 @@ func linkDeserialize(m []byte) (Link, error) {
switch linkType {
case "dummy":
link = &Dummy{}
+ case "ifb":
+ link = &Ifb{}
case "bridge":
link = &Bridge{}
case "vlan":
@@ -501,12 +766,18 @@ func linkDeserialize(m []byte) (Link, error) {
link = &Veth{}
case "vxlan":
link = &Vxlan{}
+ case "bond":
+ link = &Bond{}
case "ipvlan":
link = &IPVlan{}
case "macvlan":
link = &Macvlan{}
+ case "macvtap":
+ link = &Macvtap{}
+ case "gretap":
+ link = &Gretap{}
default:
- link = &Generic{LinkType: linkType}
+ link = &GenericLink{LinkType: linkType}
}
case nl.IFLA_INFO_DATA:
data, err := nl.ParseRouteAttr(info.Value)
@@ -518,10 +789,16 @@ func linkDeserialize(m []byte) (Link, error) {
parseVlanData(link, data)
case "vxlan":
parseVxlanData(link, data)
+ case "bond":
+ parseBondData(link, data)
case "ipvlan":
parseIPVlanData(link, data)
case "macvlan":
parseMacvlanData(link, data)
+ case "macvtap":
+ parseMacvtapData(link, data)
+ case "gretap":
+ parseGretapData(link, data)
}
}
}
@@ -545,6 +822,8 @@ func linkDeserialize(m []byte) (Link, error) {
base.MasterIndex = int(native.Uint32(attr.Value[0:4]))
case syscall.IFLA_TXQLEN:
base.TxQLen = int(native.Uint32(attr.Value[0:4]))
+ case syscall.IFLA_IFALIAS:
+ base.Alias = string(attr.Value[:len(attr.Value)-1])
}
}
// Links that don't have IFLA_INFO_KIND are hardware devices
@@ -583,6 +862,47 @@ func LinkList() ([]Link, error) {
return res, nil
}
+// LinkUpdate is used to pass information back from LinkSubscribe()
+type LinkUpdate struct {
+ nl.IfInfomsg
+ Header syscall.NlMsghdr
+ Link
+}
+
+// LinkSubscribe takes a chan down which notifications will be sent
+// when links change. Close the 'done' chan to stop subscription.
+func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error {
+ s, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_LINK)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+ }
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return
+ }
+ for _, m := range msgs {
+ ifmsg := nl.DeserializeIfInfomsg(m.Data)
+ link, err := linkDeserialize(m.Data)
+ if err != nil {
+ return
+ }
+ ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: m.Header, Link: link}
+ }
+ }
+ }()
+
+ return nil
+}
+
func LinkSetHairpin(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE)
}
@@ -666,6 +986,8 @@ func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) {
vxlan.L2miss = int8(datum.Value[0]) != 0
case nl.IFLA_VXLAN_L3MISS:
vxlan.L3miss = int8(datum.Value[0]) != 0
+ case nl.IFLA_VXLAN_UDP_CSUM:
+ vxlan.UDPCSum = int8(datum.Value[0]) != 0
case nl.IFLA_VXLAN_GBP:
vxlan.GBP = int8(datum.Value[0]) != 0
case nl.IFLA_VXLAN_AGEING:
@@ -686,6 +1008,60 @@ func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
+func parseBondData(link Link, data []syscall.NetlinkRouteAttr) {
+ bond := NewLinkBond(NewLinkAttrs())
+ for i := range data {
+ switch data[i].Attr.Type {
+ case nl.IFLA_BOND_MODE:
+ bond.Mode = BondMode(data[i].Value[0])
+ case nl.IFLA_BOND_ACTIVE_SLAVE:
+ bond.ActiveSlave = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_MIIMON:
+ bond.Miimon = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_UPDELAY:
+ bond.UpDelay = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_DOWNDELAY:
+ bond.DownDelay = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_USE_CARRIER:
+ bond.UseCarrier = int(data[i].Value[0])
+ case nl.IFLA_BOND_ARP_INTERVAL:
+ bond.ArpInterval = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_ARP_IP_TARGET:
+ // TODO: implement
+ case nl.IFLA_BOND_ARP_VALIDATE:
+ bond.ArpValidate = BondArpValidate(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_ARP_ALL_TARGETS:
+ bond.ArpAllTargets = BondArpAllTargets(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PRIMARY:
+ bond.Primary = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PRIMARY_RESELECT:
+ bond.PrimaryReselect = BondPrimaryReselect(data[i].Value[0])
+ case nl.IFLA_BOND_FAIL_OVER_MAC:
+ bond.FailOverMac = BondFailOverMac(data[i].Value[0])
+ case nl.IFLA_BOND_XMIT_HASH_POLICY:
+ bond.XmitHashPolicy = BondXmitHashPolicy(data[i].Value[0])
+ case nl.IFLA_BOND_RESEND_IGMP:
+ bond.ResendIgmp = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_NUM_PEER_NOTIF:
+ bond.NumPeerNotif = int(data[i].Value[0])
+ case nl.IFLA_BOND_ALL_SLAVES_ACTIVE:
+ bond.AllSlavesActive = int(data[i].Value[0])
+ case nl.IFLA_BOND_MIN_LINKS:
+ bond.MinLinks = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_LP_INTERVAL:
+ bond.LpInterval = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_PACKETS_PER_SLAVE:
+ bond.PackersPerSlave = int(native.Uint32(data[i].Value[0:4]))
+ case nl.IFLA_BOND_AD_LACP_RATE:
+ bond.LacpRate = BondLacpRate(data[i].Value[0])
+ case nl.IFLA_BOND_AD_SELECT:
+ bond.AdSelect = BondAdSelect(data[i].Value[0])
+ case nl.IFLA_BOND_AD_INFO:
+ // TODO: implement
+ }
+ }
+}
+
func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
ipv := link.(*IPVlan)
for _, datum := range data {
@@ -696,6 +1072,11 @@ func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
+func parseMacvtapData(link Link, data []syscall.NetlinkRouteAttr) {
+ macv := link.(*Macvtap)
+ parseMacvlanData(&macv.Macvlan, data)
+}
+
func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) {
macv := link.(*Macvlan)
for _, datum := range data {
@@ -737,3 +1118,96 @@ func linkFlags(rawFlags uint32) net.Flags {
}
return f
}
+
+func htonl(val uint32) []byte {
+ bytes := make([]byte, 4)
+ binary.BigEndian.PutUint32(bytes, val)
+ return bytes
+}
+
+func htons(val uint16) []byte {
+ bytes := make([]byte, 2)
+ binary.BigEndian.PutUint16(bytes, val)
+ return bytes
+}
+
+func ntohl(buf []byte) uint32 {
+ return binary.BigEndian.Uint32(buf)
+}
+
+func ntohs(buf []byte) uint16 {
+ return binary.BigEndian.Uint16(buf)
+}
+
+func addGretapAttrs(gretap *Gretap, linkInfo *nl.RtAttr) {
+ data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
+
+ ip := gretap.Local.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_LOCAL, []byte(ip))
+ }
+ ip = gretap.Remote.To4()
+ if ip != nil {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_REMOTE, []byte(ip))
+ }
+
+ if gretap.IKey != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_IKEY, htonl(gretap.IKey))
+ gretap.IFlags |= uint16(nl.GRE_KEY)
+ }
+
+ if gretap.OKey != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_OKEY, htonl(gretap.OKey))
+ gretap.OFlags |= uint16(nl.GRE_KEY)
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_IFLAGS, htons(gretap.IFlags))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_OFLAGS, htons(gretap.OFlags))
+
+ if gretap.Link != 0 {
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_LINK, nl.Uint32Attr(gretap.Link))
+ }
+
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gretap.PMtuDisc))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_TTL, nl.Uint8Attr(gretap.Ttl))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_TOS, nl.Uint8Attr(gretap.Tos))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gretap.EncapType))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gretap.EncapFlags))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_SPORT, htons(gretap.EncapSport))
+ nl.NewRtAttrChild(data, nl.IFLA_GRE_ENCAP_DPORT, htons(gretap.EncapDport))
+}
+
+func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) {
+ gre := link.(*Gretap)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.IFLA_GRE_OKEY:
+ gre.IKey = ntohl(datum.Value[0:4])
+ case nl.IFLA_GRE_IKEY:
+ gre.OKey = ntohl(datum.Value[0:4])
+ case nl.IFLA_GRE_LOCAL:
+ gre.Local = net.IP(datum.Value[0:4])
+ case nl.IFLA_GRE_REMOTE:
+ gre.Remote = net.IP(datum.Value[0:4])
+ case nl.IFLA_GRE_ENCAP_SPORT:
+ gre.EncapSport = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_ENCAP_DPORT:
+ gre.EncapDport = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_IFLAGS:
+ gre.IFlags = ntohs(datum.Value[0:2])
+ case nl.IFLA_GRE_OFLAGS:
+ gre.OFlags = ntohs(datum.Value[0:2])
+
+ case nl.IFLA_GRE_TTL:
+ gre.Ttl = uint8(datum.Value[0])
+ case nl.IFLA_GRE_TOS:
+ gre.Tos = uint8(datum.Value[0])
+ case nl.IFLA_GRE_PMTUDISC:
+ gre.PMtuDisc = uint8(datum.Value[0])
+ case nl.IFLA_GRE_ENCAP_TYPE:
+ gre.EncapType = native.Uint16(datum.Value[0:2])
+ case nl.IFLA_GRE_ENCAP_FLAGS:
+ gre.EncapFlags = native.Uint16(datum.Value[0:2])
+ }
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/link_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/link_test.go
deleted file mode 100644
index 9e44f0d0c..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/link_test.go
+++ /dev/null
@@ -1,643 +0,0 @@
-package netlink
-
-import (
- "bytes"
- "net"
- "testing"
-
- "github.com/vishvananda/netns"
-)
-
-const (
- testTxQLen int = 100
- defaultTxQLen int = 1000
-)
-
-func testLinkAddDel(t *testing.T, link Link) {
- links, err := LinkList()
- if err != nil {
- t.Fatal(err)
- }
- num := len(links)
-
- if err := LinkAdd(link); err != nil {
- t.Fatal(err)
- }
-
- base := link.Attrs()
-
- result, err := LinkByName(base.Name)
- if err != nil {
- t.Fatal(err)
- }
-
- rBase := result.Attrs()
-
- if vlan, ok := link.(*Vlan); ok {
- other, ok := result.(*Vlan)
- if !ok {
- t.Fatal("Result of create is not a vlan")
- }
- if vlan.VlanId != other.VlanId {
- t.Fatal("Link.VlanId id doesn't match")
- }
- }
-
- if rBase.ParentIndex == 0 && base.ParentIndex != 0 {
- t.Fatal("Created link doesn't have a Parent but it should")
- } else if rBase.ParentIndex != 0 && base.ParentIndex == 0 {
- t.Fatal("Created link has a Parent but it shouldn't")
- } else if rBase.ParentIndex != 0 && base.ParentIndex != 0 {
- if rBase.ParentIndex != base.ParentIndex {
- t.Fatal("Link.ParentIndex doesn't match")
- }
- }
-
- if veth, ok := result.(*Veth); ok {
- if rBase.TxQLen != base.TxQLen {
- t.Fatalf("qlen is %d, should be %d", rBase.TxQLen, base.TxQLen)
- }
- if rBase.MTU != base.MTU {
- t.Fatalf("MTU is %d, should be %d", rBase.MTU, base.MTU)
- }
-
- if veth.PeerName != "" {
- var peer *Veth
- other, err := LinkByName(veth.PeerName)
- if err != nil {
- t.Fatalf("Peer %s not created", veth.PeerName)
- }
- if peer, ok = other.(*Veth); !ok {
- t.Fatalf("Peer %s is incorrect type", veth.PeerName)
- }
- if peer.TxQLen != testTxQLen {
- t.Fatalf("TxQLen of peer is %d, should be %d", peer.TxQLen, testTxQLen)
- }
- }
- }
-
- if vxlan, ok := link.(*Vxlan); ok {
- other, ok := result.(*Vxlan)
- if !ok {
- t.Fatal("Result of create is not a vxlan")
- }
- compareVxlan(t, vxlan, other)
- }
-
- if ipv, ok := link.(*IPVlan); ok {
- other, ok := result.(*IPVlan)
- if !ok {
- t.Fatal("Result of create is not a ipvlan")
- }
- if ipv.Mode != other.Mode {
- t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, ipv.Mode)
- }
- }
-
- if macv, ok := link.(*Macvlan); ok {
- other, ok := result.(*Macvlan)
- if !ok {
- t.Fatal("Result of create is not a macvlan")
- }
- if macv.Mode != other.Mode {
- t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, macv.Mode)
- }
- }
-
- if err = LinkDel(link); err != nil {
- t.Fatal(err)
- }
-
- links, err = LinkList()
- if err != nil {
- t.Fatal(err)
- }
-
- if len(links) != num {
- t.Fatal("Link not removed properly")
- }
-}
-
-func compareVxlan(t *testing.T, expected, actual *Vxlan) {
-
- if actual.VxlanId != expected.VxlanId {
- t.Fatal("Vxlan.VxlanId doesn't match")
- }
- if expected.SrcAddr != nil && !actual.SrcAddr.Equal(expected.SrcAddr) {
- t.Fatal("Vxlan.SrcAddr doesn't match")
- }
- if expected.Group != nil && !actual.Group.Equal(expected.Group) {
- t.Fatal("Vxlan.Group doesn't match")
- }
- if expected.TTL != -1 && actual.TTL != expected.TTL {
- t.Fatal("Vxlan.TTL doesn't match")
- }
- if expected.TOS != -1 && actual.TOS != expected.TOS {
- t.Fatal("Vxlan.TOS doesn't match")
- }
- if actual.Learning != expected.Learning {
- t.Fatal("Vxlan.Learning doesn't match")
- }
- if actual.Proxy != expected.Proxy {
- t.Fatal("Vxlan.Proxy doesn't match")
- }
- if actual.RSC != expected.RSC {
- t.Fatal("Vxlan.RSC doesn't match")
- }
- if actual.L2miss != expected.L2miss {
- t.Fatal("Vxlan.L2miss doesn't match")
- }
- if actual.L3miss != expected.L3miss {
- t.Fatal("Vxlan.L3miss doesn't match")
- }
- if actual.GBP != expected.GBP {
- t.Fatal("Vxlan.GBP doesn't match")
- }
- if expected.NoAge {
- if !actual.NoAge {
- t.Fatal("Vxlan.NoAge doesn't match")
- }
- } else if expected.Age > 0 && actual.Age != expected.Age {
- t.Fatal("Vxlan.Age doesn't match")
- }
- if expected.Limit > 0 && actual.Limit != expected.Limit {
- t.Fatal("Vxlan.Limit doesn't match")
- }
- if expected.Port > 0 && actual.Port != expected.Port {
- t.Fatal("Vxlan.Port doesn't match")
- }
- if expected.PortLow > 0 || expected.PortHigh > 0 {
- if actual.PortLow != expected.PortLow {
- t.Fatal("Vxlan.PortLow doesn't match")
- }
- if actual.PortHigh != expected.PortHigh {
- t.Fatal("Vxlan.PortHigh doesn't match")
- }
- }
-}
-
-func TestLinkAddDelDummy(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- testLinkAddDel(t, &Dummy{LinkAttrs{Name: "foo"}})
-}
-
-func TestLinkAddDelBridge(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- testLinkAddDel(t, &Bridge{LinkAttrs{Name: "foo", MTU: 1400}})
-}
-
-func TestLinkAddDelVlan(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- parent := &Dummy{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(parent); err != nil {
- t.Fatal(err)
- }
-
- testLinkAddDel(t, &Vlan{LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index}, 900})
-
- if err := LinkDel(parent); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLinkAddDelMacvlan(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- parent := &Dummy{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(parent); err != nil {
- t.Fatal(err)
- }
-
- testLinkAddDel(t, &Macvlan{
- LinkAttrs: LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index},
- Mode: MACVLAN_MODE_PRIVATE,
- })
-
- if err := LinkDel(parent); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLinkAddDelVeth(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- testLinkAddDel(t, &Veth{LinkAttrs{Name: "foo", TxQLen: testTxQLen, MTU: 1400}, "bar"})
-}
-
-func TestLinkAddVethWithDefaultTxQLen(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- la := NewLinkAttrs()
- la.Name = "foo"
-
- veth := &Veth{LinkAttrs: la, PeerName: "bar"}
- if err := LinkAdd(veth); err != nil {
- t.Fatal(err)
- }
- link, err := LinkByName("foo")
- if err != nil {
- t.Fatal(err)
- }
- if veth, ok := link.(*Veth); !ok {
- t.Fatalf("unexpected link type: %T", link)
- } else {
- if veth.TxQLen != defaultTxQLen {
- t.Fatalf("TxQLen is %d, should be %d", veth.TxQLen, defaultTxQLen)
- }
- }
- peer, err := LinkByName("bar")
- if err != nil {
- t.Fatal(err)
- }
- if veth, ok := peer.(*Veth); !ok {
- t.Fatalf("unexpected link type: %T", link)
- } else {
- if veth.TxQLen != defaultTxQLen {
- t.Fatalf("TxQLen is %d, should be %d", veth.TxQLen, defaultTxQLen)
- }
- }
-}
-
-func TestLinkAddVethWithZeroTxQLen(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- la := NewLinkAttrs()
- la.Name = "foo"
- la.TxQLen = 0
-
- veth := &Veth{LinkAttrs: la, PeerName: "bar"}
- if err := LinkAdd(veth); err != nil {
- t.Fatal(err)
- }
- link, err := LinkByName("foo")
- if err != nil {
- t.Fatal(err)
- }
- if veth, ok := link.(*Veth); !ok {
- t.Fatalf("unexpected link type: %T", link)
- } else {
- if veth.TxQLen != 0 {
- t.Fatalf("TxQLen is %d, should be %d", veth.TxQLen, 0)
- }
- }
- peer, err := LinkByName("bar")
- if err != nil {
- t.Fatal(err)
- }
- if veth, ok := peer.(*Veth); !ok {
- t.Fatalf("unexpected link type: %T", link)
- } else {
- if veth.TxQLen != 0 {
- t.Fatalf("TxQLen is %d, should be %d", veth.TxQLen, 0)
- }
- }
-}
-
-func TestLinkAddDummyWithTxQLen(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- la := NewLinkAttrs()
- la.Name = "foo"
- la.TxQLen = 1500
-
- dummy := &Dummy{LinkAttrs: la}
- if err := LinkAdd(dummy); err != nil {
- t.Fatal(err)
- }
- link, err := LinkByName("foo")
- if err != nil {
- t.Fatal(err)
- }
- if dummy, ok := link.(*Dummy); !ok {
- t.Fatalf("unexpected link type: %T", link)
- } else {
- if dummy.TxQLen != 1500 {
- t.Fatalf("TxQLen is %d, should be %d", dummy.TxQLen, 1500)
- }
- }
-}
-
-func TestLinkAddDelBridgeMaster(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- master := &Bridge{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(master); err != nil {
- t.Fatal(err)
- }
- testLinkAddDel(t, &Dummy{LinkAttrs{Name: "bar", MasterIndex: master.Attrs().Index}})
-
- if err := LinkDel(master); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLinkSetUnsetResetMaster(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- master := &Bridge{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(master); err != nil {
- t.Fatal(err)
- }
-
- newmaster := &Bridge{LinkAttrs{Name: "bar"}}
- if err := LinkAdd(newmaster); err != nil {
- t.Fatal(err)
- }
-
- slave := &Dummy{LinkAttrs{Name: "baz"}}
- if err := LinkAdd(slave); err != nil {
- t.Fatal(err)
- }
-
- if err := LinkSetMaster(slave, master); err != nil {
- t.Fatal(err)
- }
-
- link, err := LinkByName("baz")
- if err != nil {
- t.Fatal(err)
- }
-
- if link.Attrs().MasterIndex != master.Attrs().Index {
- t.Fatal("Master not set properly")
- }
-
- if err := LinkSetMaster(slave, newmaster); err != nil {
- t.Fatal(err)
- }
-
- link, err = LinkByName("baz")
- if err != nil {
- t.Fatal(err)
- }
-
- if link.Attrs().MasterIndex != newmaster.Attrs().Index {
- t.Fatal("Master not reset properly")
- }
-
- if err := LinkSetMaster(slave, nil); err != nil {
- t.Fatal(err)
- }
-
- link, err = LinkByName("baz")
- if err != nil {
- t.Fatal(err)
- }
-
- if link.Attrs().MasterIndex != 0 {
- t.Fatal("Master not unset properly")
- }
- if err := LinkDel(slave); err != nil {
- t.Fatal(err)
- }
-
- if err := LinkDel(newmaster); err != nil {
- t.Fatal(err)
- }
-
- if err := LinkDel(master); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLinkSetNs(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- basens, err := netns.Get()
- if err != nil {
- t.Fatal("Failed to get basens")
- }
- defer basens.Close()
-
- newns, err := netns.New()
- if err != nil {
- t.Fatal("Failed to create newns")
- }
- defer newns.Close()
-
- link := &Veth{LinkAttrs{Name: "foo"}, "bar"}
- if err := LinkAdd(link); err != nil {
- t.Fatal(err)
- }
-
- peer, err := LinkByName("bar")
- if err != nil {
- t.Fatal(err)
- }
-
- LinkSetNsFd(peer, int(basens))
- if err != nil {
- t.Fatal("Failed to set newns for link")
- }
-
- _, err = LinkByName("bar")
- if err == nil {
- t.Fatal("Link bar is still in newns")
- }
-
- err = netns.Set(basens)
- if err != nil {
- t.Fatal("Failed to set basens")
- }
-
- peer, err = LinkByName("bar")
- if err != nil {
- t.Fatal("Link is not in basens")
- }
-
- if err := LinkDel(peer); err != nil {
- t.Fatal(err)
- }
-
- err = netns.Set(newns)
- if err != nil {
- t.Fatal("Failed to set newns")
- }
-
- _, err = LinkByName("foo")
- if err == nil {
- t.Fatal("Other half of veth pair not deleted")
- }
-
-}
-
-func TestLinkAddDelVxlan(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- parent := &Dummy{
- LinkAttrs{Name: "foo"},
- }
- if err := LinkAdd(parent); err != nil {
- t.Fatal(err)
- }
-
- vxlan := Vxlan{
- LinkAttrs: LinkAttrs{
- Name: "bar",
- },
- VxlanId: 10,
- VtepDevIndex: parent.Index,
- Learning: true,
- L2miss: true,
- L3miss: true,
- }
-
- testLinkAddDel(t, &vxlan)
- if err := LinkDel(parent); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLinkAddDelIPVlanL2(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- parent := &Dummy{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(parent); err != nil {
- t.Fatal(err)
- }
-
- ipv := IPVlan{
- LinkAttrs: LinkAttrs{
- Name: "bar",
- ParentIndex: parent.Index,
- },
- Mode: IPVLAN_MODE_L2,
- }
-
- testLinkAddDel(t, &ipv)
-}
-
-func TestLinkAddDelIPVlanL3(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- parent := &Dummy{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(parent); err != nil {
- t.Fatal(err)
- }
-
- ipv := IPVlan{
- LinkAttrs: LinkAttrs{
- Name: "bar",
- ParentIndex: parent.Index,
- },
- Mode: IPVLAN_MODE_L3,
- }
-
- testLinkAddDel(t, &ipv)
-}
-
-func TestLinkAddDelIPVlanNoParent(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- ipv := IPVlan{
- LinkAttrs: LinkAttrs{
- Name: "bar",
- },
- Mode: IPVLAN_MODE_L3,
- }
- err := LinkAdd(&ipv)
- if err == nil {
- t.Fatal("Add should fail if ipvlan creating without ParentIndex")
- }
- if err.Error() != "Can't create ipvlan link without ParentIndex" {
- t.Fatalf("Error should be about missing ParentIndex, got %q", err)
- }
-}
-
-func TestLinkByIndex(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- dummy := &Dummy{LinkAttrs{Name: "dummy"}}
- if err := LinkAdd(dummy); err != nil {
- t.Fatal(err)
- }
-
- found, err := LinkByIndex(dummy.Index)
- if err != nil {
- t.Fatal(err)
- }
-
- if found.Attrs().Index != dummy.Attrs().Index {
- t.Fatalf("Indices don't match: %v != %v", found.Attrs().Index, dummy.Attrs().Index)
- }
-
- LinkDel(dummy)
-
- // test not found
- _, err = LinkByIndex(dummy.Attrs().Index)
- if err == nil {
- t.Fatalf("LinkByIndex(%v) found deleted link", err)
- }
-}
-
-func TestLinkSet(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- iface := &Dummy{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(iface); err != nil {
- t.Fatal(err)
- }
-
- link, err := LinkByName("foo")
- if err != nil {
- t.Fatal(err)
- }
-
- err = LinkSetName(link, "bar")
- if err != nil {
- t.Fatalf("Could not change interface name: %v", err)
- }
-
- link, err = LinkByName("bar")
- if err != nil {
- t.Fatalf("Interface name not changed: %v", err)
- }
-
- err = LinkSetMTU(link, 1400)
- if err != nil {
- t.Fatalf("Could not set MTU: %v", err)
- }
-
- link, err = LinkByName("bar")
- if err != nil {
- t.Fatal(err)
- }
-
- if link.Attrs().MTU != 1400 {
- t.Fatal("MTU not changed!")
- }
-
- addr, err := net.ParseMAC("00:12:34:56:78:AB")
- if err != nil {
- t.Fatal(err)
- }
-
- err = LinkSetHardwareAddr(link, addr)
- if err != nil {
- t.Fatal(err)
- }
-
- link, err = LinkByName("bar")
- if err != nil {
- t.Fatal(err)
- }
-
- if !bytes.Equal(link.Attrs().HardwareAddr, addr) {
- t.Fatalf("hardware address not changed!")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/link_tuntap_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/link_tuntap_linux.go
new file mode 100644
index 000000000..310bd33d8
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/link_tuntap_linux.go
@@ -0,0 +1,14 @@
+package netlink
+
+// ideally golang.org/x/sys/unix would define IfReq but it only has
+// IFNAMSIZ, hence this minimalistic implementation
+const (
+ SizeOfIfReq = 40
+ IFNAMSIZ = 16
+)
+
+type ifReq struct {
+ Name [IFNAMSIZ]byte
+ Flags uint16
+ pad [SizeOfIfReq - IFNAMSIZ - 2]byte
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_linux.go
index 620a0ee70..2af693bab 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_linux.go
@@ -70,10 +70,10 @@ func NeighAdd(neigh *Neigh) error {
return neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL)
}
-// NeighAdd will add or replace an IP to MAC mapping to the ARP table
+// NeighSet will add or replace an IP to MAC mapping to the ARP table
// Equivalent to: `ip neigh replace....`
func NeighSet(neigh *Neigh) error {
- return neighAdd(neigh, syscall.NLM_F_CREATE)
+ return neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE)
}
// NeighAppend will append an entry to FDB
@@ -133,6 +133,7 @@ func NeighList(linkIndex, family int) ([]Neigh, error) {
req := nl.NewNetlinkRequest(syscall.RTM_GETNEIGH, syscall.NLM_F_DUMP)
msg := Ndmsg{
Family: uint8(family),
+ Index: uint32(linkIndex),
}
req.AddData(&msg)
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_test.go
deleted file mode 100644
index 50da59c5c..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/neigh_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package netlink
-
-import (
- "net"
- "testing"
-)
-
-type arpEntry struct {
- ip net.IP
- mac net.HardwareAddr
-}
-
-func parseMAC(s string) net.HardwareAddr {
- m, err := net.ParseMAC(s)
- if err != nil {
- panic(err)
- }
- return m
-}
-
-func dumpContains(dump []Neigh, e arpEntry) bool {
- for _, n := range dump {
- if n.IP.Equal(e.ip) && (n.State&NUD_INCOMPLETE) == 0 {
- return true
- }
- }
- return false
-}
-
-func TestNeighAddDel(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- dummy := Dummy{LinkAttrs{Name: "neigh0"}}
- if err := LinkAdd(&dummy); err != nil {
- t.Fatal(err)
- }
-
- ensureIndex(dummy.Attrs())
-
- arpTable := []arpEntry{
- {net.ParseIP("10.99.0.1"), parseMAC("aa:bb:cc:dd:00:01")},
- {net.ParseIP("10.99.0.2"), parseMAC("aa:bb:cc:dd:00:02")},
- {net.ParseIP("10.99.0.3"), parseMAC("aa:bb:cc:dd:00:03")},
- {net.ParseIP("10.99.0.4"), parseMAC("aa:bb:cc:dd:00:04")},
- {net.ParseIP("10.99.0.5"), parseMAC("aa:bb:cc:dd:00:05")},
- }
-
- // Add the arpTable
- for _, entry := range arpTable {
- err := NeighAdd(&Neigh{
- LinkIndex: dummy.Index,
- State: NUD_REACHABLE,
- IP: entry.ip,
- HardwareAddr: entry.mac,
- })
-
- if err != nil {
- t.Errorf("Failed to NeighAdd: %v", err)
- }
- }
-
- // Dump and see that all added entries are there
- dump, err := NeighList(dummy.Index, 0)
- if err != nil {
- t.Errorf("Failed to NeighList: %v", err)
- }
-
- for _, entry := range arpTable {
- if !dumpContains(dump, entry) {
- t.Errorf("Dump does not contain: %v", entry)
- }
- }
-
- // Delete the arpTable
- for _, entry := range arpTable {
- err := NeighDel(&Neigh{
- LinkIndex: dummy.Index,
- IP: entry.ip,
- HardwareAddr: entry.mac,
- })
-
- if err != nil {
- t.Errorf("Failed to NeighDel: %v", err)
- }
- }
-
- // TODO: seems not working because of cache
- //// Dump and see that none of deleted entries are there
- //dump, err = NeighList(dummy.Index, 0)
- //if err != nil {
- //t.Errorf("Failed to NeighList: %v", err)
- //}
-
- //for _, entry := range arpTable {
- //if dumpContains(dump, entry) {
- //t.Errorf("Dump contains: %v", entry)
- //}
- //}
-
- if err := LinkDel(&dummy); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink.go
index 41ebdb11f..deafb6cfa 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink.go
@@ -14,8 +14,8 @@ import (
"github.com/vishvananda/netlink/nl"
)
+// Family type definitions
const (
- // Family type definitions
FAMILY_ALL = nl.FAMILY_ALL
FAMILY_V4 = nl.FAMILY_V4
FAMILY_V6 = nl.FAMILY_V6
@@ -33,7 +33,10 @@ func ParseIPNet(s string) (*net.IPNet, error) {
return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
}
-// NewIPNet generates an IPNet from an ip address using a netmask of 32.
+// NewIPNet generates an IPNet from an ip address using a netmask of 32 or 128.
func NewIPNet(ip net.IP) *net.IPNet {
- return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
+ if ip.To4() != nil {
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
+ }
+ return &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)}
}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink_test.go
deleted file mode 100644
index 3292b750a..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/netlink_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package netlink
-
-import (
- "log"
- "os"
- "runtime"
- "testing"
-
- "github.com/vishvananda/netns"
-)
-
-type tearDownNetlinkTest func()
-
-func setUpNetlinkTest(t *testing.T) tearDownNetlinkTest {
- if os.Getuid() != 0 {
- msg := "Skipped test because it requires root privileges."
- log.Printf(msg)
- t.Skip(msg)
- }
-
- // new temporary namespace so we don't pollute the host
- // lock thread since the namespace is thread local
- runtime.LockOSThread()
- var err error
- ns, err := netns.New()
- if err != nil {
- t.Fatal("Failed to create newns", ns)
- }
-
- return func() {
- ns.Close()
- runtime.UnlockOSThread()
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/addr_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/addr_linux_test.go
deleted file mode 100644
index 98c3b211f..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/addr_linux_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "syscall"
- "testing"
-)
-
-func (msg *IfAddrmsg) write(b []byte) {
- native := NativeEndian()
- b[0] = msg.Family
- b[1] = msg.Prefixlen
- b[2] = msg.Flags
- b[3] = msg.Scope
- native.PutUint32(b[4:8], msg.Index)
-}
-
-func (msg *IfAddrmsg) serializeSafe() []byte {
- len := syscall.SizeofIfAddrmsg
- b := make([]byte, len)
- msg.write(b)
- return b
-}
-
-func deserializeIfAddrmsgSafe(b []byte) *IfAddrmsg {
- var msg = IfAddrmsg{}
- binary.Read(bytes.NewReader(b[0:syscall.SizeofIfAddrmsg]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestIfAddrmsgDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, syscall.SizeofIfAddrmsg)
- rand.Read(orig)
- safemsg := deserializeIfAddrmsgSafe(orig)
- msg := DeserializeIfAddrmsg(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/link_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/link_linux.go
index 1f9ab088f..b7f50646d 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/link_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/link_linux.go
@@ -1,7 +1,13 @@
package nl
+import (
+ "unsafe"
+)
+
const (
DEFAULT_CHANGE = 0xFFFFFFFF
+ // doesn't exist in syscall
+ IFLA_VFINFO_LIST = 0x16
)
const (
@@ -102,3 +108,289 @@ const (
MACVLAN_MODE_PASSTHRU = 8
MACVLAN_MODE_SOURCE = 16
)
+
+const (
+ IFLA_BOND_UNSPEC = iota
+ IFLA_BOND_MODE
+ IFLA_BOND_ACTIVE_SLAVE
+ IFLA_BOND_MIIMON
+ IFLA_BOND_UPDELAY
+ IFLA_BOND_DOWNDELAY
+ IFLA_BOND_USE_CARRIER
+ IFLA_BOND_ARP_INTERVAL
+ IFLA_BOND_ARP_IP_TARGET
+ IFLA_BOND_ARP_VALIDATE
+ IFLA_BOND_ARP_ALL_TARGETS
+ IFLA_BOND_PRIMARY
+ IFLA_BOND_PRIMARY_RESELECT
+ IFLA_BOND_FAIL_OVER_MAC
+ IFLA_BOND_XMIT_HASH_POLICY
+ IFLA_BOND_RESEND_IGMP
+ IFLA_BOND_NUM_PEER_NOTIF
+ IFLA_BOND_ALL_SLAVES_ACTIVE
+ IFLA_BOND_MIN_LINKS
+ IFLA_BOND_LP_INTERVAL
+ IFLA_BOND_PACKETS_PER_SLAVE
+ IFLA_BOND_AD_LACP_RATE
+ IFLA_BOND_AD_SELECT
+ IFLA_BOND_AD_INFO
+)
+
+const (
+ IFLA_BOND_AD_INFO_UNSPEC = iota
+ IFLA_BOND_AD_INFO_AGGREGATOR
+ IFLA_BOND_AD_INFO_NUM_PORTS
+ IFLA_BOND_AD_INFO_ACTOR_KEY
+ IFLA_BOND_AD_INFO_PARTNER_KEY
+ IFLA_BOND_AD_INFO_PARTNER_MAC
+)
+
+const (
+ IFLA_BOND_SLAVE_UNSPEC = iota
+ IFLA_BOND_SLAVE_STATE
+ IFLA_BOND_SLAVE_MII_STATUS
+ IFLA_BOND_SLAVE_LINK_FAILURE_COUNT
+ IFLA_BOND_SLAVE_PERM_HWADDR
+ IFLA_BOND_SLAVE_QUEUE_ID
+ IFLA_BOND_SLAVE_AD_AGGREGATOR_ID
+)
+
+const (
+ IFLA_GRE_UNSPEC = iota
+ IFLA_GRE_LINK
+ IFLA_GRE_IFLAGS
+ IFLA_GRE_OFLAGS
+ IFLA_GRE_IKEY
+ IFLA_GRE_OKEY
+ IFLA_GRE_LOCAL
+ IFLA_GRE_REMOTE
+ IFLA_GRE_TTL
+ IFLA_GRE_TOS
+ IFLA_GRE_PMTUDISC
+ IFLA_GRE_ENCAP_LIMIT
+ IFLA_GRE_FLOWINFO
+ IFLA_GRE_FLAGS
+ IFLA_GRE_ENCAP_TYPE
+ IFLA_GRE_ENCAP_FLAGS
+ IFLA_GRE_ENCAP_SPORT
+ IFLA_GRE_ENCAP_DPORT
+ IFLA_GRE_COLLECT_METADATA
+ IFLA_GRE_MAX = IFLA_GRE_COLLECT_METADATA
+)
+
+const (
+ GRE_CSUM = 0x8000
+ GRE_ROUTING = 0x4000
+ GRE_KEY = 0x2000
+ GRE_SEQ = 0x1000
+ GRE_STRICT = 0x0800
+ GRE_REC = 0x0700
+ GRE_FLAGS = 0x00F8
+ GRE_VERSION = 0x0007
+)
+
+const (
+ IFLA_VF_INFO_UNSPEC = iota
+ IFLA_VF_INFO
+ IFLA_VF_INFO_MAX = IFLA_VF_INFO
+)
+
+const (
+ IFLA_VF_UNSPEC = iota
+ IFLA_VF_MAC /* Hardware queue specific attributes */
+ IFLA_VF_VLAN
+ IFLA_VF_TX_RATE /* Max TX Bandwidth Allocation */
+ IFLA_VF_SPOOFCHK /* Spoof Checking on/off switch */
+ IFLA_VF_LINK_STATE /* link state enable/disable/auto switch */
+ IFLA_VF_RATE /* Min and Max TX Bandwidth Allocation */
+ IFLA_VF_RSS_QUERY_EN /* RSS Redirection Table and Hash Key query
+ * on/off switch
+ */
+ IFLA_VF_STATS /* network device statistics */
+ IFLA_VF_MAX = IFLA_VF_STATS
+)
+
+const (
+ IFLA_VF_LINK_STATE_AUTO = iota /* link state of the uplink */
+ IFLA_VF_LINK_STATE_ENABLE /* link always up */
+ IFLA_VF_LINK_STATE_DISABLE /* link always down */
+ IFLA_VF_LINK_STATE_MAX = IFLA_VF_LINK_STATE_DISABLE
+)
+
+const (
+ IFLA_VF_STATS_RX_PACKETS = iota
+ IFLA_VF_STATS_TX_PACKETS
+ IFLA_VF_STATS_RX_BYTES
+ IFLA_VF_STATS_TX_BYTES
+ IFLA_VF_STATS_BROADCAST
+ IFLA_VF_STATS_MULTICAST
+ IFLA_VF_STATS_MAX = IFLA_VF_STATS_MULTICAST
+)
+
+const (
+ SizeofVfMac = 0x24
+ SizeofVfVlan = 0x0c
+ SizeofVfTxRate = 0x08
+ SizeofVfRate = 0x0c
+ SizeofVfSpoofchk = 0x08
+ SizeofVfLinkState = 0x08
+ SizeofVfRssQueryEn = 0x08
+)
+
+// struct ifla_vf_mac {
+// __u32 vf;
+// __u8 mac[32]; /* MAX_ADDR_LEN */
+// };
+
+type VfMac struct {
+ Vf uint32
+ Mac [32]byte
+}
+
+func (msg *VfMac) Len() int {
+ return SizeofVfMac
+}
+
+func DeserializeVfMac(b []byte) *VfMac {
+ return (*VfMac)(unsafe.Pointer(&b[0:SizeofVfMac][0]))
+}
+
+func (msg *VfMac) Serialize() []byte {
+ return (*(*[SizeofVfMac]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_vlan {
+// __u32 vf;
+// __u32 vlan; /* 0 - 4095, 0 disables VLAN filter */
+// __u32 qos;
+// };
+
+type VfVlan struct {
+ Vf uint32
+ Vlan uint32
+ Qos uint32
+}
+
+func (msg *VfVlan) Len() int {
+ return SizeofVfVlan
+}
+
+func DeserializeVfVlan(b []byte) *VfVlan {
+ return (*VfVlan)(unsafe.Pointer(&b[0:SizeofVfVlan][0]))
+}
+
+func (msg *VfVlan) Serialize() []byte {
+ return (*(*[SizeofVfVlan]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_tx_rate {
+// __u32 vf;
+// __u32 rate; /* Max TX bandwidth in Mbps, 0 disables throttling */
+// };
+
+type VfTxRate struct {
+ Vf uint32
+ Rate uint32
+}
+
+func (msg *VfTxRate) Len() int {
+ return SizeofVfTxRate
+}
+
+func DeserializeVfTxRate(b []byte) *VfTxRate {
+ return (*VfTxRate)(unsafe.Pointer(&b[0:SizeofVfTxRate][0]))
+}
+
+func (msg *VfTxRate) Serialize() []byte {
+ return (*(*[SizeofVfTxRate]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_rate {
+// __u32 vf;
+// __u32 min_tx_rate; /* Min Bandwidth in Mbps */
+// __u32 max_tx_rate; /* Max Bandwidth in Mbps */
+// };
+
+type VfRate struct {
+ Vf uint32
+ MinTxRate uint32
+ MaxTxRate uint32
+}
+
+func (msg *VfRate) Len() int {
+ return SizeofVfRate
+}
+
+func DeserializeVfRate(b []byte) *VfRate {
+ return (*VfRate)(unsafe.Pointer(&b[0:SizeofVfRate][0]))
+}
+
+func (msg *VfRate) Serialize() []byte {
+ return (*(*[SizeofVfRate]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_spoofchk {
+// __u32 vf;
+// __u32 setting;
+// };
+
+type VfSpoofchk struct {
+ Vf uint32
+ Setting uint32
+}
+
+func (msg *VfSpoofchk) Len() int {
+ return SizeofVfSpoofchk
+}
+
+func DeserializeVfSpoofchk(b []byte) *VfSpoofchk {
+ return (*VfSpoofchk)(unsafe.Pointer(&b[0:SizeofVfSpoofchk][0]))
+}
+
+func (msg *VfSpoofchk) Serialize() []byte {
+ return (*(*[SizeofVfSpoofchk]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_link_state {
+// __u32 vf;
+// __u32 link_state;
+// };
+
+type VfLinkState struct {
+ Vf uint32
+ LinkState uint32
+}
+
+func (msg *VfLinkState) Len() int {
+ return SizeofVfLinkState
+}
+
+func DeserializeVfLinkState(b []byte) *VfLinkState {
+ return (*VfLinkState)(unsafe.Pointer(&b[0:SizeofVfLinkState][0]))
+}
+
+func (msg *VfLinkState) Serialize() []byte {
+ return (*(*[SizeofVfLinkState]byte)(unsafe.Pointer(msg)))[:]
+}
+
+// struct ifla_vf_rss_query_en {
+// __u32 vf;
+// __u32 setting;
+// };
+
+type VfRssQueryEn struct {
+ Vf uint32
+ Setting uint32
+}
+
+func (msg *VfRssQueryEn) Len() int {
+ return SizeofVfRssQueryEn
+}
+
+func DeserializeVfRssQueryEn(b []byte) *VfRssQueryEn {
+ return (*VfRssQueryEn)(unsafe.Pointer(&b[0:SizeofVfRssQueryEn][0]))
+}
+
+func (msg *VfRssQueryEn) Serialize() []byte {
+ return (*(*[SizeofVfRssQueryEn]byte)(unsafe.Pointer(msg)))[:]
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux.go
index 3cb137d01..e3afb5c23 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux.go
@@ -142,17 +142,19 @@ func (a *RtAttr) Len() int {
}
// Serialize the RtAttr into a byte array
-// This can't ust unsafe.cast because it must iterate through children.
+// This can't just unsafe.cast because it must iterate through children.
func (a *RtAttr) Serialize() []byte {
native := NativeEndian()
length := a.Len()
buf := make([]byte, rtaAlignOf(length))
+ next := 4
if a.Data != nil {
- copy(buf[4:], a.Data)
- } else {
- next := 4
+ copy(buf[next:], a.Data)
+ next += rtaAlignOf(len(a.Data))
+ }
+ if len(a.children) > 0 {
for _, child := range a.children {
childBuf := child.Serialize()
copy(buf[next:], childBuf)
@@ -323,6 +325,10 @@ func (s *NetlinkSocket) Close() {
syscall.Close(s.fd)
}
+func (s *NetlinkSocket) GetFd() int {
+ return s.fd
+}
+
func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
if err := syscall.Sendto(s.fd, request.Serialize(), 0, &s.lsa); err != nil {
return err
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux_test.go
deleted file mode 100644
index 4672684c7..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/nl_linux_test.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "reflect"
- "syscall"
- "testing"
-)
-
-type testSerializer interface {
- serializeSafe() []byte
- Serialize() []byte
-}
-
-func testDeserializeSerialize(t *testing.T, orig []byte, safemsg testSerializer, msg testSerializer) {
- if !reflect.DeepEqual(safemsg, msg) {
- t.Fatal("Deserialization failed.\n", safemsg, "\n", msg)
- }
- safe := msg.serializeSafe()
- if !bytes.Equal(safe, orig) {
- t.Fatal("Safe serialization failed.\n", safe, "\n", orig)
- }
- b := msg.Serialize()
- if !bytes.Equal(b, safe) {
- t.Fatal("Serialization failed.\n", b, "\n", safe)
- }
-}
-
-func (msg *IfInfomsg) write(b []byte) {
- native := NativeEndian()
- b[0] = msg.Family
- b[1] = msg.X__ifi_pad
- native.PutUint16(b[2:4], msg.Type)
- native.PutUint32(b[4:8], uint32(msg.Index))
- native.PutUint32(b[8:12], msg.Flags)
- native.PutUint32(b[12:16], msg.Change)
-}
-
-func (msg *IfInfomsg) serializeSafe() []byte {
- length := syscall.SizeofIfInfomsg
- b := make([]byte, length)
- msg.write(b)
- return b
-}
-
-func deserializeIfInfomsgSafe(b []byte) *IfInfomsg {
- var msg = IfInfomsg{}
- binary.Read(bytes.NewReader(b[0:syscall.SizeofIfInfomsg]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestIfInfomsgDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, syscall.SizeofIfInfomsg)
- rand.Read(orig)
- safemsg := deserializeIfInfomsgSafe(orig)
- msg := DeserializeIfInfomsg(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/route_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/route_linux_test.go
deleted file mode 100644
index ba9c410ee..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/route_linux_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "syscall"
- "testing"
-)
-
-func (msg *RtMsg) write(b []byte) {
- native := NativeEndian()
- b[0] = msg.Family
- b[1] = msg.Dst_len
- b[2] = msg.Src_len
- b[3] = msg.Tos
- b[4] = msg.Table
- b[5] = msg.Protocol
- b[6] = msg.Scope
- b[7] = msg.Type
- native.PutUint32(b[8:12], msg.Flags)
-}
-
-func (msg *RtMsg) serializeSafe() []byte {
- len := syscall.SizeofRtMsg
- b := make([]byte, len)
- msg.write(b)
- return b
-}
-
-func deserializeRtMsgSafe(b []byte) *RtMsg {
- var msg = RtMsg{}
- binary.Read(bytes.NewReader(b[0:syscall.SizeofRtMsg]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestRtMsgDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, syscall.SizeofRtMsg)
- rand.Read(orig)
- safemsg := deserializeRtMsgSafe(orig)
- msg := DeserializeRtMsg(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/syscall.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/syscall.go
new file mode 100644
index 000000000..47aa6322d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/syscall.go
@@ -0,0 +1,37 @@
+package nl
+
+// syscall package lack of rule atributes type.
+// Thus there are defined below
+const (
+ FRA_UNSPEC = iota
+ FRA_DST /* destination address */
+ FRA_SRC /* source address */
+ FRA_IIFNAME /* interface name */
+ FRA_GOTO /* target to jump to (FR_ACT_GOTO) */
+ FRA_UNUSED2
+ FRA_PRIORITY /* priority/preference */
+ FRA_UNUSED3
+ FRA_UNUSED4
+ FRA_UNUSED5
+ FRA_FWMARK /* mark */
+ FRA_FLOW /* flow/class id */
+ FRA_TUN_ID
+ FRA_SUPPRESS_IFGROUP
+ FRA_SUPPRESS_PREFIXLEN
+ FRA_TABLE /* Extended table id */
+ FRA_FWMASK /* mask for netfilter mark */
+ FRA_OIFNAME
+)
+
+// ip rule netlink request types
+const (
+ FR_ACT_UNSPEC = iota
+ FR_ACT_TO_TBL /* Pass to fixed table */
+ FR_ACT_GOTO /* Jump to another rule */
+ FR_ACT_NOP /* No operation */
+ FR_ACT_RES3
+ FR_ACT_RES4
+ FR_ACT_BLACKHOLE /* Drop without notification */
+ FR_ACT_UNREACHABLE /* Drop with ENETUNREACH */
+ FR_ACT_PROHIBIT /* Drop with EACCES */
+)
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/tc_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/tc_linux.go
new file mode 100644
index 000000000..c6d85e951
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/tc_linux.go
@@ -0,0 +1,686 @@
+package nl
+
+import (
+ "unsafe"
+)
+
+// LinkLayer
+const (
+ LINKLAYER_UNSPEC = iota
+ LINKLAYER_ETHERNET
+ LINKLAYER_ATM
+)
+
+// ATM
+const (
+ ATM_CELL_PAYLOAD = 48
+ ATM_CELL_SIZE = 53
+)
+
+const TC_LINKLAYER_MASK = 0x0F
+
+// Police
+const (
+ TCA_POLICE_UNSPEC = iota
+ TCA_POLICE_TBF
+ TCA_POLICE_RATE
+ TCA_POLICE_PEAKRATE
+ TCA_POLICE_AVRATE
+ TCA_POLICE_RESULT
+ TCA_POLICE_MAX = TCA_POLICE_RESULT
+)
+
+// Message types
+const (
+ TCA_UNSPEC = iota
+ TCA_KIND
+ TCA_OPTIONS
+ TCA_STATS
+ TCA_XSTATS
+ TCA_RATE
+ TCA_FCNT
+ TCA_STATS2
+ TCA_STAB
+ TCA_MAX = TCA_STAB
+)
+
+const (
+ TCA_ACT_TAB = 1
+ TCAA_MAX = 1
+)
+
+const (
+ TCA_ACT_UNSPEC = iota
+ TCA_ACT_KIND
+ TCA_ACT_OPTIONS
+ TCA_ACT_INDEX
+ TCA_ACT_STATS
+ TCA_ACT_MAX
+)
+
+const (
+ TCA_PRIO_UNSPEC = iota
+ TCA_PRIO_MQ
+ TCA_PRIO_MAX = TCA_PRIO_MQ
+)
+
+const (
+ SizeofTcMsg = 0x14
+ SizeofTcActionMsg = 0x04
+ SizeofTcPrioMap = 0x14
+ SizeofTcRateSpec = 0x0c
+ SizeofTcNetemQopt = 0x18
+ SizeofTcNetemCorr = 0x0c
+ SizeofTcNetemReorder = 0x08
+ SizeofTcNetemCorrupt = 0x08
+ SizeofTcTbfQopt = 2*SizeofTcRateSpec + 0x0c
+ SizeofTcHtbCopt = 2*SizeofTcRateSpec + 0x14
+ SizeofTcHtbGlob = 0x14
+ SizeofTcU32Key = 0x10
+ SizeofTcU32Sel = 0x10 // without keys
+ SizeofTcActBpf = 0x14
+ SizeofTcMirred = 0x1c
+ SizeofTcPolice = 2*SizeofTcRateSpec + 0x20
+)
+
+// struct tcmsg {
+// unsigned char tcm_family;
+// unsigned char tcm__pad1;
+// unsigned short tcm__pad2;
+// int tcm_ifindex;
+// __u32 tcm_handle;
+// __u32 tcm_parent;
+// __u32 tcm_info;
+// };
+
+type TcMsg struct {
+ Family uint8
+ Pad [3]byte
+ Ifindex int32
+ Handle uint32
+ Parent uint32
+ Info uint32
+}
+
+func (msg *TcMsg) Len() int {
+ return SizeofTcMsg
+}
+
+func DeserializeTcMsg(b []byte) *TcMsg {
+ return (*TcMsg)(unsafe.Pointer(&b[0:SizeofTcMsg][0]))
+}
+
+func (x *TcMsg) Serialize() []byte {
+ return (*(*[SizeofTcMsg]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tcamsg {
+// unsigned char tca_family;
+// unsigned char tca__pad1;
+// unsigned short tca__pad2;
+// };
+
+type TcActionMsg struct {
+ Family uint8
+ Pad [3]byte
+}
+
+func (msg *TcActionMsg) Len() int {
+ return SizeofTcActionMsg
+}
+
+func DeserializeTcActionMsg(b []byte) *TcActionMsg {
+ return (*TcActionMsg)(unsafe.Pointer(&b[0:SizeofTcActionMsg][0]))
+}
+
+func (x *TcActionMsg) Serialize() []byte {
+ return (*(*[SizeofTcActionMsg]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TC_PRIO_MAX = 15
+)
+
+// struct tc_prio_qopt {
+// int bands; /* Number of bands */
+// __u8 priomap[TC_PRIO_MAX+1]; /* Map: logical priority -> PRIO band */
+// };
+
+type TcPrioMap struct {
+ Bands int32
+ Priomap [TC_PRIO_MAX + 1]uint8
+}
+
+func (msg *TcPrioMap) Len() int {
+ return SizeofTcPrioMap
+}
+
+func DeserializeTcPrioMap(b []byte) *TcPrioMap {
+ return (*TcPrioMap)(unsafe.Pointer(&b[0:SizeofTcPrioMap][0]))
+}
+
+func (x *TcPrioMap) Serialize() []byte {
+ return (*(*[SizeofTcPrioMap]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_TBF_UNSPEC = iota
+ TCA_TBF_PARMS
+ TCA_TBF_RTAB
+ TCA_TBF_PTAB
+ TCA_TBF_RATE64
+ TCA_TBF_PRATE64
+ TCA_TBF_BURST
+ TCA_TBF_PBURST
+ TCA_TBF_MAX = TCA_TBF_PBURST
+)
+
+// struct tc_ratespec {
+// unsigned char cell_log;
+// __u8 linklayer; /* lower 4 bits */
+// unsigned short overhead;
+// short cell_align;
+// unsigned short mpu;
+// __u32 rate;
+// };
+
+type TcRateSpec struct {
+ CellLog uint8
+ Linklayer uint8
+ Overhead uint16
+ CellAlign int16
+ Mpu uint16
+ Rate uint32
+}
+
+func (msg *TcRateSpec) Len() int {
+ return SizeofTcRateSpec
+}
+
+func DeserializeTcRateSpec(b []byte) *TcRateSpec {
+ return (*TcRateSpec)(unsafe.Pointer(&b[0:SizeofTcRateSpec][0]))
+}
+
+func (x *TcRateSpec) Serialize() []byte {
+ return (*(*[SizeofTcRateSpec]byte)(unsafe.Pointer(x)))[:]
+}
+
+/**
+* NETEM
+ */
+
+const (
+ TCA_NETEM_UNSPEC = iota
+ TCA_NETEM_CORR
+ TCA_NETEM_DELAY_DIST
+ TCA_NETEM_REORDER
+ TCA_NETEM_CORRUPT
+ TCA_NETEM_LOSS
+ TCA_NETEM_RATE
+ TCA_NETEM_ECN
+ TCA_NETEM_RATE64
+ TCA_NETEM_MAX = TCA_NETEM_RATE64
+)
+
+// struct tc_netem_qopt {
+// __u32 latency; /* added delay (us) */
+// __u32 limit; /* fifo limit (packets) */
+// __u32 loss; /* random packet loss (0=none ~0=100%) */
+// __u32 gap; /* re-ordering gap (0 for none) */
+// __u32 duplicate; /* random packet dup (0=none ~0=100%) */
+// __u32 jitter; /* random jitter in latency (us) */
+// };
+
+type TcNetemQopt struct {
+ Latency uint32
+ Limit uint32
+ Loss uint32
+ Gap uint32
+ Duplicate uint32
+ Jitter uint32
+}
+
+func (msg *TcNetemQopt) Len() int {
+ return SizeofTcNetemQopt
+}
+
+func DeserializeTcNetemQopt(b []byte) *TcNetemQopt {
+ return (*TcNetemQopt)(unsafe.Pointer(&b[0:SizeofTcNetemQopt][0]))
+}
+
+func (x *TcNetemQopt) Serialize() []byte {
+ return (*(*[SizeofTcNetemQopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_corr {
+// __u32 delay_corr; /* delay correlation */
+// __u32 loss_corr; /* packet loss correlation */
+// __u32 dup_corr; /* duplicate correlation */
+// };
+
+type TcNetemCorr struct {
+ DelayCorr uint32
+ LossCorr uint32
+ DupCorr uint32
+}
+
+func (msg *TcNetemCorr) Len() int {
+ return SizeofTcNetemCorr
+}
+
+func DeserializeTcNetemCorr(b []byte) *TcNetemCorr {
+ return (*TcNetemCorr)(unsafe.Pointer(&b[0:SizeofTcNetemCorr][0]))
+}
+
+func (x *TcNetemCorr) Serialize() []byte {
+ return (*(*[SizeofTcNetemCorr]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_reorder {
+// __u32 probability;
+// __u32 correlation;
+// };
+
+type TcNetemReorder struct {
+ Probability uint32
+ Correlation uint32
+}
+
+func (msg *TcNetemReorder) Len() int {
+ return SizeofTcNetemReorder
+}
+
+func DeserializeTcNetemReorder(b []byte) *TcNetemReorder {
+ return (*TcNetemReorder)(unsafe.Pointer(&b[0:SizeofTcNetemReorder][0]))
+}
+
+func (x *TcNetemReorder) Serialize() []byte {
+ return (*(*[SizeofTcNetemReorder]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_netem_corrupt {
+// __u32 probability;
+// __u32 correlation;
+// };
+
+type TcNetemCorrupt struct {
+ Probability uint32
+ Correlation uint32
+}
+
+func (msg *TcNetemCorrupt) Len() int {
+ return SizeofTcNetemCorrupt
+}
+
+func DeserializeTcNetemCorrupt(b []byte) *TcNetemCorrupt {
+ return (*TcNetemCorrupt)(unsafe.Pointer(&b[0:SizeofTcNetemCorrupt][0]))
+}
+
+func (x *TcNetemCorrupt) Serialize() []byte {
+ return (*(*[SizeofTcNetemCorrupt]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_tbf_qopt {
+// struct tc_ratespec rate;
+// struct tc_ratespec peakrate;
+// __u32 limit;
+// __u32 buffer;
+// __u32 mtu;
+// };
+
+type TcTbfQopt struct {
+ Rate TcRateSpec
+ Peakrate TcRateSpec
+ Limit uint32
+ Buffer uint32
+ Mtu uint32
+}
+
+func (msg *TcTbfQopt) Len() int {
+ return SizeofTcTbfQopt
+}
+
+func DeserializeTcTbfQopt(b []byte) *TcTbfQopt {
+ return (*TcTbfQopt)(unsafe.Pointer(&b[0:SizeofTcTbfQopt][0]))
+}
+
+func (x *TcTbfQopt) Serialize() []byte {
+ return (*(*[SizeofTcTbfQopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_HTB_UNSPEC = iota
+ TCA_HTB_PARMS
+ TCA_HTB_INIT
+ TCA_HTB_CTAB
+ TCA_HTB_RTAB
+ TCA_HTB_DIRECT_QLEN
+ TCA_HTB_RATE64
+ TCA_HTB_CEIL64
+ TCA_HTB_MAX = TCA_HTB_CEIL64
+)
+
+//struct tc_htb_opt {
+// struct tc_ratespec rate;
+// struct tc_ratespec ceil;
+// __u32 buffer;
+// __u32 cbuffer;
+// __u32 quantum;
+// __u32 level; /* out only */
+// __u32 prio;
+//};
+
+type TcHtbCopt struct {
+ Rate TcRateSpec
+ Ceil TcRateSpec
+ Buffer uint32
+ Cbuffer uint32
+ Quantum uint32
+ Level uint32
+ Prio uint32
+}
+
+func (msg *TcHtbCopt) Len() int {
+ return SizeofTcHtbCopt
+}
+
+func DeserializeTcHtbCopt(b []byte) *TcHtbCopt {
+ return (*TcHtbCopt)(unsafe.Pointer(&b[0:SizeofTcHtbCopt][0]))
+}
+
+func (x *TcHtbCopt) Serialize() []byte {
+ return (*(*[SizeofTcHtbCopt]byte)(unsafe.Pointer(x)))[:]
+}
+
+type TcHtbGlob struct {
+ Version uint32
+ Rate2Quantum uint32
+ Defcls uint32
+ Debug uint32
+ DirectPkts uint32
+}
+
+func (msg *TcHtbGlob) Len() int {
+ return SizeofTcHtbGlob
+}
+
+func DeserializeTcHtbGlob(b []byte) *TcHtbGlob {
+ return (*TcHtbGlob)(unsafe.Pointer(&b[0:SizeofTcHtbGlob][0]))
+}
+
+func (x *TcHtbGlob) Serialize() []byte {
+ return (*(*[SizeofTcHtbGlob]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_U32_UNSPEC = iota
+ TCA_U32_CLASSID
+ TCA_U32_HASH
+ TCA_U32_LINK
+ TCA_U32_DIVISOR
+ TCA_U32_SEL
+ TCA_U32_POLICE
+ TCA_U32_ACT
+ TCA_U32_INDEV
+ TCA_U32_PCNT
+ TCA_U32_MARK
+ TCA_U32_MAX = TCA_U32_MARK
+)
+
+// struct tc_u32_key {
+// __be32 mask;
+// __be32 val;
+// int off;
+// int offmask;
+// };
+
+type TcU32Key struct {
+ Mask uint32 // big endian
+ Val uint32 // big endian
+ Off int32
+ OffMask int32
+}
+
+func (msg *TcU32Key) Len() int {
+ return SizeofTcU32Key
+}
+
+func DeserializeTcU32Key(b []byte) *TcU32Key {
+ return (*TcU32Key)(unsafe.Pointer(&b[0:SizeofTcU32Key][0]))
+}
+
+func (x *TcU32Key) Serialize() []byte {
+ return (*(*[SizeofTcU32Key]byte)(unsafe.Pointer(x)))[:]
+}
+
+// struct tc_u32_sel {
+// unsigned char flags;
+// unsigned char offshift;
+// unsigned char nkeys;
+//
+// __be16 offmask;
+// __u16 off;
+// short offoff;
+//
+// short hoff;
+// __be32 hmask;
+// struct tc_u32_key keys[0];
+// };
+
+const (
+ TC_U32_TERMINAL = 1 << iota
+ TC_U32_OFFSET = 1 << iota
+ TC_U32_VAROFFSET = 1 << iota
+ TC_U32_EAT = 1 << iota
+)
+
+type TcU32Sel struct {
+ Flags uint8
+ Offshift uint8
+ Nkeys uint8
+ Pad uint8
+ Offmask uint16 // big endian
+ Off uint16
+ Offoff int16
+ Hoff int16
+ Hmask uint32 // big endian
+ Keys []TcU32Key
+}
+
+func (msg *TcU32Sel) Len() int {
+ return SizeofTcU32Sel + int(msg.Nkeys)*SizeofTcU32Key
+}
+
+func DeserializeTcU32Sel(b []byte) *TcU32Sel {
+ x := &TcU32Sel{}
+ copy((*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:], b)
+ next := SizeofTcU32Sel
+ var i uint8
+ for i = 0; i < x.Nkeys; i++ {
+ x.Keys = append(x.Keys, *DeserializeTcU32Key(b[next:]))
+ next += SizeofTcU32Key
+ }
+ return x
+}
+
+func (x *TcU32Sel) Serialize() []byte {
+ // This can't just unsafe.cast because it must iterate through keys.
+ buf := make([]byte, x.Len())
+ copy(buf, (*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:])
+ next := SizeofTcU32Sel
+ for _, key := range x.Keys {
+ keyBuf := key.Serialize()
+ copy(buf[next:], keyBuf)
+ next += SizeofTcU32Key
+ }
+ return buf
+}
+
+const (
+ TCA_ACT_MIRRED = 8
+)
+
+const (
+ TCA_MIRRED_UNSPEC = iota
+ TCA_MIRRED_TM
+ TCA_MIRRED_PARMS
+ TCA_MIRRED_MAX = TCA_MIRRED_PARMS
+)
+
+const (
+ TCA_EGRESS_REDIR = 1 /* packet redirect to EGRESS*/
+ TCA_EGRESS_MIRROR = 2 /* mirror packet to EGRESS */
+ TCA_INGRESS_REDIR = 3 /* packet redirect to INGRESS*/
+ TCA_INGRESS_MIRROR = 4 /* mirror packet to INGRESS */
+)
+
+const (
+ TC_ACT_UNSPEC = int32(-1)
+ TC_ACT_OK = 0
+ TC_ACT_RECLASSIFY = 1
+ TC_ACT_SHOT = 2
+ TC_ACT_PIPE = 3
+ TC_ACT_STOLEN = 4
+ TC_ACT_QUEUED = 5
+ TC_ACT_REPEAT = 6
+ TC_ACT_REDIRECT = 7
+ TC_ACT_JUMP = 0x10000000
+)
+
+type TcGen struct {
+ Index uint32
+ Capab uint32
+ Action int32
+ Refcnt int32
+ Bindcnt int32
+}
+
+type TcActBpf struct {
+ TcGen
+}
+
+func (msg *TcActBpf) Len() int {
+ return SizeofTcActBpf
+}
+
+func DeserializeTcActBpf(b []byte) *TcActBpf {
+ return (*TcActBpf)(unsafe.Pointer(&b[0:SizeofTcActBpf][0]))
+}
+
+func (x *TcActBpf) Serialize() []byte {
+ return (*(*[SizeofTcActBpf]byte)(unsafe.Pointer(x)))[:]
+}
+
+// #define tc_gen \
+// __u32 index; \
+// __u32 capab; \
+// int action; \
+// int refcnt; \
+// int bindcnt
+// struct tc_mirred {
+// tc_gen;
+// int eaction; /* one of IN/EGRESS_MIRROR/REDIR */
+// __u32 ifindex; /* ifindex of egress port */
+// };
+
+type TcMirred struct {
+ TcGen
+ Eaction int32
+ Ifindex uint32
+}
+
+func (msg *TcMirred) Len() int {
+ return SizeofTcMirred
+}
+
+func DeserializeTcMirred(b []byte) *TcMirred {
+ return (*TcMirred)(unsafe.Pointer(&b[0:SizeofTcMirred][0]))
+}
+
+func (x *TcMirred) Serialize() []byte {
+ return (*(*[SizeofTcMirred]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TC_POLICE_UNSPEC = TC_ACT_UNSPEC
+ TC_POLICE_OK = TC_ACT_OK
+ TC_POLICE_RECLASSIFY = TC_ACT_RECLASSIFY
+ TC_POLICE_SHOT = TC_ACT_SHOT
+ TC_POLICE_PIPE = TC_ACT_PIPE
+)
+
+// struct tc_police {
+// __u32 index;
+// int action;
+// __u32 limit;
+// __u32 burst;
+// __u32 mtu;
+// struct tc_ratespec rate;
+// struct tc_ratespec peakrate;
+// int refcnt;
+// int bindcnt;
+// __u32 capab;
+// };
+
+type TcPolice struct {
+ Index uint32
+ Action int32
+ Limit uint32
+ Burst uint32
+ Mtu uint32
+ Rate TcRateSpec
+ PeakRate TcRateSpec
+ Refcnt int32
+ Bindcnt int32
+ Capab uint32
+}
+
+func (msg *TcPolice) Len() int {
+ return SizeofTcPolice
+}
+
+func DeserializeTcPolice(b []byte) *TcPolice {
+ return (*TcPolice)(unsafe.Pointer(&b[0:SizeofTcPolice][0]))
+}
+
+func (x *TcPolice) Serialize() []byte {
+ return (*(*[SizeofTcPolice]byte)(unsafe.Pointer(x)))[:]
+}
+
+const (
+ TCA_FW_UNSPEC = iota
+ TCA_FW_CLASSID
+ TCA_FW_POLICE
+ TCA_FW_INDEV
+ TCA_FW_ACT
+ TCA_FW_MASK
+ TCA_FW_MAX = TCA_FW_MASK
+)
+
+const (
+ TCA_BPF_FLAG_ACT_DIRECT uint32 = 1 << iota
+)
+
+const (
+ TCA_BPF_UNSPEC = iota
+ TCA_BPF_ACT
+ TCA_BPF_POLICE
+ TCA_BPF_CLASSID
+ TCA_BPF_OPS_LEN
+ TCA_BPF_OPS
+ TCA_BPF_FD
+ TCA_BPF_NAME
+ TCA_BPF_FLAGS
+ TCA_BPF_MAX = TCA_BPF_FLAGS
+)
+
+const (
+ TCA_ACT_BPF_UNSPEC = iota
+ TCA_ACT_BPF_TM
+ TCA_ACT_BPF_PARMS
+ TCA_ACT_BPF_OPS_LEN
+ TCA_ACT_BPF_OPS
+ TCA_ACT_BPF_FD
+ TCA_ACT_BPF_NAME
+ TCA_ACT_BPF_MAX = TCA_ACT_BPF_NAME
+)
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_linux_test.go
deleted file mode 100644
index 04404d751..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_linux_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "testing"
-)
-
-func (msg *XfrmAddress) write(b []byte) {
- copy(b[0:SizeofXfrmAddress], msg[:])
-}
-
-func (msg *XfrmAddress) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmAddress)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmAddressSafe(b []byte) *XfrmAddress {
- var msg = XfrmAddress{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmAddress]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmAddressDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmAddress)
- rand.Read(orig)
- safemsg := deserializeXfrmAddressSafe(orig)
- msg := DeserializeXfrmAddress(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmSelector) write(b []byte) {
- const AddrEnd = SizeofXfrmAddress * 2
- native := NativeEndian()
- msg.Daddr.write(b[0:SizeofXfrmAddress])
- msg.Saddr.write(b[SizeofXfrmAddress:AddrEnd])
- native.PutUint16(b[AddrEnd:AddrEnd+2], msg.Dport)
- native.PutUint16(b[AddrEnd+2:AddrEnd+4], msg.DportMask)
- native.PutUint16(b[AddrEnd+4:AddrEnd+6], msg.Sport)
- native.PutUint16(b[AddrEnd+6:AddrEnd+8], msg.SportMask)
- native.PutUint16(b[AddrEnd+8:AddrEnd+10], msg.Family)
- b[AddrEnd+10] = msg.PrefixlenD
- b[AddrEnd+11] = msg.PrefixlenS
- b[AddrEnd+12] = msg.Proto
- copy(b[AddrEnd+13:AddrEnd+16], msg.Pad[:])
- native.PutUint32(b[AddrEnd+16:AddrEnd+20], uint32(msg.Ifindex))
- native.PutUint32(b[AddrEnd+20:AddrEnd+24], msg.User)
-}
-
-func (msg *XfrmSelector) serializeSafe() []byte {
- length := SizeofXfrmSelector
- b := make([]byte, length)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmSelectorSafe(b []byte) *XfrmSelector {
- var msg = XfrmSelector{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmSelector]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmSelectorDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmSelector)
- rand.Read(orig)
- safemsg := deserializeXfrmSelectorSafe(orig)
- msg := DeserializeXfrmSelector(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmLifetimeCfg) write(b []byte) {
- native := NativeEndian()
- native.PutUint64(b[0:8], msg.SoftByteLimit)
- native.PutUint64(b[8:16], msg.HardByteLimit)
- native.PutUint64(b[16:24], msg.SoftPacketLimit)
- native.PutUint64(b[24:32], msg.HardPacketLimit)
- native.PutUint64(b[32:40], msg.SoftAddExpiresSeconds)
- native.PutUint64(b[40:48], msg.HardAddExpiresSeconds)
- native.PutUint64(b[48:56], msg.SoftUseExpiresSeconds)
- native.PutUint64(b[56:64], msg.HardUseExpiresSeconds)
-}
-
-func (msg *XfrmLifetimeCfg) serializeSafe() []byte {
- length := SizeofXfrmLifetimeCfg
- b := make([]byte, length)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmLifetimeCfgSafe(b []byte) *XfrmLifetimeCfg {
- var msg = XfrmLifetimeCfg{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmLifetimeCfg]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmLifetimeCfgDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmLifetimeCfg)
- rand.Read(orig)
- safemsg := deserializeXfrmLifetimeCfgSafe(orig)
- msg := DeserializeXfrmLifetimeCfg(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmLifetimeCur) write(b []byte) {
- native := NativeEndian()
- native.PutUint64(b[0:8], msg.Bytes)
- native.PutUint64(b[8:16], msg.Packets)
- native.PutUint64(b[16:24], msg.AddTime)
- native.PutUint64(b[24:32], msg.UseTime)
-}
-
-func (msg *XfrmLifetimeCur) serializeSafe() []byte {
- length := SizeofXfrmLifetimeCur
- b := make([]byte, length)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmLifetimeCurSafe(b []byte) *XfrmLifetimeCur {
- var msg = XfrmLifetimeCur{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmLifetimeCur]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmLifetimeCurDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmLifetimeCur)
- rand.Read(orig)
- safemsg := deserializeXfrmLifetimeCurSafe(orig)
- msg := DeserializeXfrmLifetimeCur(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmId) write(b []byte) {
- native := NativeEndian()
- msg.Daddr.write(b[0:SizeofXfrmAddress])
- native.PutUint32(b[SizeofXfrmAddress:SizeofXfrmAddress+4], msg.Spi)
- b[SizeofXfrmAddress+4] = msg.Proto
- copy(b[SizeofXfrmAddress+5:SizeofXfrmAddress+8], msg.Pad[:])
-}
-
-func (msg *XfrmId) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmId)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmIdSafe(b []byte) *XfrmId {
- var msg = XfrmId{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmId]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmIdDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmId)
- rand.Read(orig)
- safemsg := deserializeXfrmIdSafe(orig)
- msg := DeserializeXfrmId(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_policy_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_policy_linux_test.go
deleted file mode 100644
index 08a604b9c..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_policy_linux_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "testing"
-)
-
-func (msg *XfrmUserpolicyId) write(b []byte) {
- native := NativeEndian()
- msg.Sel.write(b[0:SizeofXfrmSelector])
- native.PutUint32(b[SizeofXfrmSelector:SizeofXfrmSelector+4], msg.Index)
- b[SizeofXfrmSelector+4] = msg.Dir
- copy(b[SizeofXfrmSelector+5:SizeofXfrmSelector+8], msg.Pad[:])
-}
-
-func (msg *XfrmUserpolicyId) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmUserpolicyId)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmUserpolicyIdSafe(b []byte) *XfrmUserpolicyId {
- var msg = XfrmUserpolicyId{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmUserpolicyId]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmUserpolicyIdDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmUserpolicyId)
- rand.Read(orig)
- safemsg := deserializeXfrmUserpolicyIdSafe(orig)
- msg := DeserializeXfrmUserpolicyId(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmUserpolicyInfo) write(b []byte) {
- const CfgEnd = SizeofXfrmSelector + SizeofXfrmLifetimeCfg
- const CurEnd = CfgEnd + SizeofXfrmLifetimeCur
- native := NativeEndian()
- msg.Sel.write(b[0:SizeofXfrmSelector])
- msg.Lft.write(b[SizeofXfrmSelector:CfgEnd])
- msg.Curlft.write(b[CfgEnd:CurEnd])
- native.PutUint32(b[CurEnd:CurEnd+4], msg.Priority)
- native.PutUint32(b[CurEnd+4:CurEnd+8], msg.Index)
- b[CurEnd+8] = msg.Dir
- b[CurEnd+9] = msg.Action
- b[CurEnd+10] = msg.Flags
- b[CurEnd+11] = msg.Share
- copy(b[CurEnd+12:CurEnd+16], msg.Pad[:])
-}
-
-func (msg *XfrmUserpolicyInfo) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmUserpolicyInfo)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmUserpolicyInfoSafe(b []byte) *XfrmUserpolicyInfo {
- var msg = XfrmUserpolicyInfo{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmUserpolicyInfo]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmUserpolicyInfoDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmUserpolicyInfo)
- rand.Read(orig)
- safemsg := deserializeXfrmUserpolicyInfoSafe(orig)
- msg := DeserializeXfrmUserpolicyInfo(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmUserTmpl) write(b []byte) {
- const AddrEnd = SizeofXfrmId + 4 + SizeofXfrmAddress
- native := NativeEndian()
- msg.XfrmId.write(b[0:SizeofXfrmId])
- native.PutUint16(b[SizeofXfrmId:SizeofXfrmId+2], msg.Family)
- copy(b[SizeofXfrmId+2:SizeofXfrmId+4], msg.Pad1[:])
- msg.Saddr.write(b[SizeofXfrmId+4 : AddrEnd])
- native.PutUint32(b[AddrEnd:AddrEnd+4], msg.Reqid)
- b[AddrEnd+4] = msg.Mode
- b[AddrEnd+5] = msg.Share
- b[AddrEnd+6] = msg.Optional
- b[AddrEnd+7] = msg.Pad2
- native.PutUint32(b[AddrEnd+8:AddrEnd+12], msg.Aalgos)
- native.PutUint32(b[AddrEnd+12:AddrEnd+16], msg.Ealgos)
- native.PutUint32(b[AddrEnd+16:AddrEnd+20], msg.Calgos)
-}
-
-func (msg *XfrmUserTmpl) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmUserTmpl)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmUserTmplSafe(b []byte) *XfrmUserTmpl {
- var msg = XfrmUserTmpl{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmUserTmpl]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmUserTmplDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmUserTmpl)
- rand.Read(orig)
- safemsg := deserializeXfrmUserTmplSafe(orig)
- msg := DeserializeXfrmUserTmpl(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_state_linux_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_state_linux_test.go
deleted file mode 100644
index d5281e9a6..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/nl/xfrm_state_linux_test.go
+++ /dev/null
@@ -1,207 +0,0 @@
-package nl
-
-import (
- "bytes"
- "crypto/rand"
- "encoding/binary"
- "testing"
-)
-
-func (msg *XfrmUsersaId) write(b []byte) {
- native := NativeEndian()
- msg.Daddr.write(b[0:SizeofXfrmAddress])
- native.PutUint32(b[SizeofXfrmAddress:SizeofXfrmAddress+4], msg.Spi)
- native.PutUint16(b[SizeofXfrmAddress+4:SizeofXfrmAddress+6], msg.Family)
- b[SizeofXfrmAddress+6] = msg.Proto
- b[SizeofXfrmAddress+7] = msg.Pad
-}
-
-func (msg *XfrmUsersaId) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmUsersaId)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmUsersaIdSafe(b []byte) *XfrmUsersaId {
- var msg = XfrmUsersaId{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmUsersaId]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmUsersaIdDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmUsersaId)
- rand.Read(orig)
- safemsg := deserializeXfrmUsersaIdSafe(orig)
- msg := DeserializeXfrmUsersaId(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmStats) write(b []byte) {
- native := NativeEndian()
- native.PutUint32(b[0:4], msg.ReplayWindow)
- native.PutUint32(b[4:8], msg.Replay)
- native.PutUint32(b[8:12], msg.IntegrityFailed)
-}
-
-func (msg *XfrmStats) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmStats)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmStatsSafe(b []byte) *XfrmStats {
- var msg = XfrmStats{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmStats]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmStatsDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmStats)
- rand.Read(orig)
- safemsg := deserializeXfrmStatsSafe(orig)
- msg := DeserializeXfrmStats(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmUsersaInfo) write(b []byte) {
- const IdEnd = SizeofXfrmSelector + SizeofXfrmId
- const AddressEnd = IdEnd + SizeofXfrmAddress
- const CfgEnd = AddressEnd + SizeofXfrmLifetimeCfg
- const CurEnd = CfgEnd + SizeofXfrmLifetimeCur
- const StatsEnd = CurEnd + SizeofXfrmStats
- native := NativeEndian()
- msg.Sel.write(b[0:SizeofXfrmSelector])
- msg.Id.write(b[SizeofXfrmSelector:IdEnd])
- msg.Saddr.write(b[IdEnd:AddressEnd])
- msg.Lft.write(b[AddressEnd:CfgEnd])
- msg.Curlft.write(b[CfgEnd:CurEnd])
- msg.Stats.write(b[CurEnd:StatsEnd])
- native.PutUint32(b[StatsEnd:StatsEnd+4], msg.Seq)
- native.PutUint32(b[StatsEnd+4:StatsEnd+8], msg.Reqid)
- native.PutUint16(b[StatsEnd+8:StatsEnd+10], msg.Family)
- b[StatsEnd+10] = msg.Mode
- b[StatsEnd+11] = msg.ReplayWindow
- b[StatsEnd+12] = msg.Flags
- copy(b[StatsEnd+13:StatsEnd+20], msg.Pad[:])
-}
-
-func (msg *XfrmUsersaInfo) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmUsersaInfo)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmUsersaInfoSafe(b []byte) *XfrmUsersaInfo {
- var msg = XfrmUsersaInfo{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmUsersaInfo]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmUsersaInfoDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmUsersaInfo)
- rand.Read(orig)
- safemsg := deserializeXfrmUsersaInfoSafe(orig)
- msg := DeserializeXfrmUsersaInfo(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmAlgo) write(b []byte) {
- native := NativeEndian()
- copy(b[0:64], msg.AlgName[:])
- native.PutUint32(b[64:68], msg.AlgKeyLen)
- copy(b[68:msg.Len()], msg.AlgKey[:])
-}
-
-func (msg *XfrmAlgo) serializeSafe() []byte {
- b := make([]byte, msg.Len())
- msg.write(b)
- return b
-}
-
-func deserializeXfrmAlgoSafe(b []byte) *XfrmAlgo {
- var msg = XfrmAlgo{}
- copy(msg.AlgName[:], b[0:64])
- binary.Read(bytes.NewReader(b[64:68]), NativeEndian(), &msg.AlgKeyLen)
- msg.AlgKey = b[68:msg.Len()]
- return &msg
-}
-
-func TestXfrmAlgoDeserializeSerialize(t *testing.T) {
- // use a 32 byte key len
- var orig = make([]byte, SizeofXfrmAlgo+32)
- rand.Read(orig)
- // set the key len to 256 bits
- orig[64] = 0
- orig[65] = 1
- orig[66] = 0
- orig[67] = 0
- safemsg := deserializeXfrmAlgoSafe(orig)
- msg := DeserializeXfrmAlgo(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmAlgoAuth) write(b []byte) {
- native := NativeEndian()
- copy(b[0:64], msg.AlgName[:])
- native.PutUint32(b[64:68], msg.AlgKeyLen)
- native.PutUint32(b[68:72], msg.AlgTruncLen)
- copy(b[72:msg.Len()], msg.AlgKey[:])
-}
-
-func (msg *XfrmAlgoAuth) serializeSafe() []byte {
- b := make([]byte, msg.Len())
- msg.write(b)
- return b
-}
-
-func deserializeXfrmAlgoAuthSafe(b []byte) *XfrmAlgoAuth {
- var msg = XfrmAlgoAuth{}
- copy(msg.AlgName[:], b[0:64])
- binary.Read(bytes.NewReader(b[64:68]), NativeEndian(), &msg.AlgKeyLen)
- binary.Read(bytes.NewReader(b[68:72]), NativeEndian(), &msg.AlgTruncLen)
- msg.AlgKey = b[72:msg.Len()]
- return &msg
-}
-
-func TestXfrmAlgoAuthDeserializeSerialize(t *testing.T) {
- // use a 32 byte key len
- var orig = make([]byte, SizeofXfrmAlgoAuth+32)
- rand.Read(orig)
- // set the key len to 256 bits
- orig[64] = 0
- orig[65] = 1
- orig[66] = 0
- orig[67] = 0
- safemsg := deserializeXfrmAlgoAuthSafe(orig)
- msg := DeserializeXfrmAlgoAuth(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
-
-func (msg *XfrmEncapTmpl) write(b []byte) {
- native := NativeEndian()
- native.PutUint16(b[0:2], msg.EncapType)
- native.PutUint16(b[2:4], msg.EncapSport)
- native.PutUint16(b[4:6], msg.EncapDport)
- copy(b[6:8], msg.Pad[:])
- msg.EncapOa.write(b[8:SizeofXfrmAddress])
-}
-
-func (msg *XfrmEncapTmpl) serializeSafe() []byte {
- b := make([]byte, SizeofXfrmEncapTmpl)
- msg.write(b)
- return b
-}
-
-func deserializeXfrmEncapTmplSafe(b []byte) *XfrmEncapTmpl {
- var msg = XfrmEncapTmpl{}
- binary.Read(bytes.NewReader(b[0:SizeofXfrmEncapTmpl]), NativeEndian(), &msg)
- return &msg
-}
-
-func TestXfrmEncapTmplDeserializeSerialize(t *testing.T) {
- var orig = make([]byte, SizeofXfrmEncapTmpl)
- rand.Read(orig)
- safemsg := deserializeXfrmEncapTmplSafe(orig)
- msg := DeserializeXfrmEncapTmpl(orig)
- testDeserializeSerialize(t, orig, safemsg, msg)
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo_test.go
deleted file mode 100644
index f94c42b1c..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/protinfo_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package netlink
-
-import "testing"
-
-func TestProtinfo(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
- master := &Bridge{LinkAttrs{Name: "foo"}}
- if err := LinkAdd(master); err != nil {
- t.Fatal(err)
- }
- iface1 := &Dummy{LinkAttrs{Name: "bar1", MasterIndex: master.Index}}
- iface2 := &Dummy{LinkAttrs{Name: "bar2", MasterIndex: master.Index}}
- iface3 := &Dummy{LinkAttrs{Name: "bar3"}}
-
- if err := LinkAdd(iface1); err != nil {
- t.Fatal(err)
- }
- if err := LinkAdd(iface2); err != nil {
- t.Fatal(err)
- }
- if err := LinkAdd(iface3); err != nil {
- t.Fatal(err)
- }
-
- oldpi1, err := LinkGetProtinfo(iface1)
- if err != nil {
- t.Fatal(err)
- }
- oldpi2, err := LinkGetProtinfo(iface2)
- if err != nil {
- t.Fatal(err)
- }
-
- if err := LinkSetHairpin(iface1, true); err != nil {
- t.Fatal(err)
- }
-
- if err := LinkSetRootBlock(iface1, true); err != nil {
- t.Fatal(err)
- }
-
- pi1, err := LinkGetProtinfo(iface1)
- if err != nil {
- t.Fatal(err)
- }
- if !pi1.Hairpin {
- t.Fatalf("Hairpin mode is not enabled for %s, but should", iface1.Name)
- }
- if !pi1.RootBlock {
- t.Fatalf("RootBlock is not enabled for %s, but should", iface1.Name)
- }
- if pi1.Guard != oldpi1.Guard {
- t.Fatalf("Guard field was changed for %s but shouldn't", iface1.Name)
- }
- if pi1.FastLeave != oldpi1.FastLeave {
- t.Fatalf("FastLeave field was changed for %s but shouldn't", iface1.Name)
- }
- if pi1.Learning != oldpi1.Learning {
- t.Fatalf("Learning field was changed for %s but shouldn't", iface1.Name)
- }
- if pi1.Flood != oldpi1.Flood {
- t.Fatalf("Flood field was changed for %s but shouldn't", iface1.Name)
- }
-
- if err := LinkSetGuard(iface2, true); err != nil {
- t.Fatal(err)
- }
- if err := LinkSetLearning(iface2, false); err != nil {
- t.Fatal(err)
- }
- pi2, err := LinkGetProtinfo(iface2)
- if err != nil {
- t.Fatal(err)
- }
- if pi2.Hairpin {
- t.Fatalf("Hairpin mode is enabled for %s, but shouldn't", iface2.Name)
- }
- if !pi2.Guard {
- t.Fatalf("Guard is not enabled for %s, but should", iface2.Name)
- }
- if pi2.Learning {
- t.Fatalf("Learning is enabled for %s, but shouldn't", iface2.Name)
- }
- if pi2.RootBlock != oldpi2.RootBlock {
- t.Fatalf("RootBlock field was changed for %s but shouldn't", iface2.Name)
- }
- if pi2.FastLeave != oldpi2.FastLeave {
- t.Fatalf("FastLeave field was changed for %s but shouldn't", iface2.Name)
- }
- if pi2.Flood != oldpi2.Flood {
- t.Fatalf("Flood field was changed for %s but shouldn't", iface2.Name)
- }
-
- if err := LinkSetHairpin(iface3, true); err == nil || err.Error() != "operation not supported" {
- t.Fatalf("Set protinfo attrs for link without master is not supported, but err: %s", err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc.go
new file mode 100644
index 000000000..3fb2bbae2
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc.go
@@ -0,0 +1,295 @@
+package netlink
+
+import (
+ "fmt"
+ "math"
+)
+
+const (
+ HANDLE_NONE = 0
+ HANDLE_INGRESS = 0xFFFFFFF1
+ HANDLE_CLSACT = HANDLE_INGRESS
+ HANDLE_ROOT = 0xFFFFFFFF
+ PRIORITY_MAP_LEN = 16
+)
+const (
+ HANDLE_MIN_INGRESS = 0xFFFFFFF2
+ HANDLE_MIN_EGRESS = 0xFFFFFFF3
+)
+
+type Qdisc interface {
+ Attrs() *QdiscAttrs
+ Type() string
+}
+
+// QdiscAttrs represents a netlink qdisc. A qdisc is associated with a link,
+// has a handle, a parent and a refcnt. The root qdisc of a device should
+// have parent == HANDLE_ROOT.
+type QdiscAttrs struct {
+ LinkIndex int
+ Handle uint32
+ Parent uint32
+ Refcnt uint32 // read only
+}
+
+func (q QdiscAttrs) String() string {
+ return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Refcnt: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Refcnt)
+}
+
+func MakeHandle(major, minor uint16) uint32 {
+ return (uint32(major) << 16) | uint32(minor)
+}
+
+func MajorMinor(handle uint32) (uint16, uint16) {
+ return uint16((handle & 0xFFFF0000) >> 16), uint16(handle & 0x0000FFFFF)
+}
+
+func HandleStr(handle uint32) string {
+ switch handle {
+ case HANDLE_NONE:
+ return "none"
+ case HANDLE_INGRESS:
+ return "ingress"
+ case HANDLE_ROOT:
+ return "root"
+ default:
+ major, minor := MajorMinor(handle)
+ return fmt.Sprintf("%x:%x", major, minor)
+ }
+}
+
+func Percentage2u32(percentage float32) uint32 {
+ // FIXME this is most likely not the best way to convert from % to uint32
+ if percentage == 100 {
+ return math.MaxUint32
+ }
+ return uint32(math.MaxUint32 * (percentage / 100))
+}
+
+// PfifoFast is the default qdisc created by the kernel if one has not
+// been defined for the interface
+type PfifoFast struct {
+ QdiscAttrs
+ Bands uint8
+ PriorityMap [PRIORITY_MAP_LEN]uint8
+}
+
+func (qdisc *PfifoFast) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *PfifoFast) Type() string {
+ return "pfifo_fast"
+}
+
+// Prio is a basic qdisc that works just like PfifoFast
+type Prio struct {
+ QdiscAttrs
+ Bands uint8
+ PriorityMap [PRIORITY_MAP_LEN]uint8
+}
+
+func NewPrio(attrs QdiscAttrs) *Prio {
+ return &Prio{
+ QdiscAttrs: attrs,
+ Bands: 3,
+ PriorityMap: [PRIORITY_MAP_LEN]uint8{1, 2, 2, 2, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1},
+ }
+}
+
+func (qdisc *Prio) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Prio) Type() string {
+ return "prio"
+}
+
+// Htb is a classful qdisc that rate limits based on tokens
+type Htb struct {
+ QdiscAttrs
+ Version uint32
+ Rate2Quantum uint32
+ Defcls uint32
+ Debug uint32
+ DirectPkts uint32
+}
+
+func NewHtb(attrs QdiscAttrs) *Htb {
+ return &Htb{
+ QdiscAttrs: attrs,
+ Version: 3,
+ Defcls: 0,
+ Rate2Quantum: 10,
+ Debug: 0,
+ DirectPkts: 0,
+ }
+}
+
+func (qdisc *Htb) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Htb) Type() string {
+ return "htb"
+}
+
+// Netem is a classless qdisc that rate limits based on tokens
+
+type NetemQdiscAttrs struct {
+ Latency uint32 // in us
+ DelayCorr float32 // in %
+ Limit uint32
+ Loss float32 // in %
+ LossCorr float32 // in %
+ Gap uint32
+ Duplicate float32 // in %
+ DuplicateCorr float32 // in %
+ Jitter uint32 // in us
+ ReorderProb float32 // in %
+ ReorderCorr float32 // in %
+ CorruptProb float32 // in %
+ CorruptCorr float32 // in %
+}
+
+func (q NetemQdiscAttrs) String() string {
+ return fmt.Sprintf(
+ "{Latency: %d, Limit: %d, Loss: %f, Gap: %d, Duplicate: %f, Jitter: %d}",
+ q.Latency, q.Limit, q.Loss, q.Gap, q.Duplicate, q.Jitter,
+ )
+}
+
+type Netem struct {
+ QdiscAttrs
+ Latency uint32
+ DelayCorr uint32
+ Limit uint32
+ Loss uint32
+ LossCorr uint32
+ Gap uint32
+ Duplicate uint32
+ DuplicateCorr uint32
+ Jitter uint32
+ ReorderProb uint32
+ ReorderCorr uint32
+ CorruptProb uint32
+ CorruptCorr uint32
+}
+
+func NewNetem(attrs QdiscAttrs, nattrs NetemQdiscAttrs) *Netem {
+ var limit uint32 = 1000
+ var lossCorr, delayCorr, duplicateCorr uint32
+ var reorderProb, reorderCorr uint32
+ var corruptProb, corruptCorr uint32
+
+ latency := nattrs.Latency
+ loss := Percentage2u32(nattrs.Loss)
+ gap := nattrs.Gap
+ duplicate := Percentage2u32(nattrs.Duplicate)
+ jitter := nattrs.Jitter
+
+ // Correlation
+ if latency > 0 && jitter > 0 {
+ delayCorr = Percentage2u32(nattrs.DelayCorr)
+ }
+ if loss > 0 {
+ lossCorr = Percentage2u32(nattrs.LossCorr)
+ }
+ if duplicate > 0 {
+ duplicateCorr = Percentage2u32(nattrs.DuplicateCorr)
+ }
+ // FIXME should validate values(like loss/duplicate are percentages...)
+ latency = time2Tick(latency)
+
+ if nattrs.Limit != 0 {
+ limit = nattrs.Limit
+ }
+ // Jitter is only value if latency is > 0
+ if latency > 0 {
+ jitter = time2Tick(jitter)
+ }
+
+ reorderProb = Percentage2u32(nattrs.ReorderProb)
+ reorderCorr = Percentage2u32(nattrs.ReorderCorr)
+
+ if reorderProb > 0 {
+ // ERROR if lantency == 0
+ if gap == 0 {
+ gap = 1
+ }
+ }
+
+ corruptProb = Percentage2u32(nattrs.CorruptProb)
+ corruptCorr = Percentage2u32(nattrs.CorruptCorr)
+
+ return &Netem{
+ QdiscAttrs: attrs,
+ Latency: latency,
+ DelayCorr: delayCorr,
+ Limit: limit,
+ Loss: loss,
+ LossCorr: lossCorr,
+ Gap: gap,
+ Duplicate: duplicate,
+ DuplicateCorr: duplicateCorr,
+ Jitter: jitter,
+ ReorderProb: reorderProb,
+ ReorderCorr: reorderCorr,
+ CorruptProb: corruptProb,
+ CorruptCorr: corruptCorr,
+ }
+}
+
+func (qdisc *Netem) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Netem) Type() string {
+ return "netem"
+}
+
+// Tbf is a classless qdisc that rate limits based on tokens
+type Tbf struct {
+ QdiscAttrs
+ // TODO: handle 64bit rate properly
+ Rate uint64
+ Limit uint32
+ Buffer uint32
+ // TODO: handle other settings
+}
+
+func (qdisc *Tbf) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Tbf) Type() string {
+ return "tbf"
+}
+
+// Ingress is a qdisc for adding ingress filters
+type Ingress struct {
+ QdiscAttrs
+}
+
+func (qdisc *Ingress) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *Ingress) Type() string {
+ return "ingress"
+}
+
+// GenericQdisc qdiscs represent types that are not currently understood
+// by this netlink library.
+type GenericQdisc struct {
+ QdiscAttrs
+ QdiscType string
+}
+
+func (qdisc *GenericQdisc) Attrs() *QdiscAttrs {
+ return &qdisc.QdiscAttrs
+}
+
+func (qdisc *GenericQdisc) Type() string {
+ return qdisc.QdiscType
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc_linux.go
new file mode 100644
index 000000000..7b68a2f8d
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/qdisc_linux.go
@@ -0,0 +1,415 @@
+package netlink
+
+import (
+ "fmt"
+ "io/ioutil"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// QdiscDel will delete a qdisc from the system.
+// Equivalent to: `tc qdisc del $qdisc`
+func QdiscDel(qdisc Qdisc) error {
+ return qdiscModify(syscall.RTM_DELQDISC, 0, qdisc)
+}
+
+// QdiscChange will change a qdisc in place
+// Equivalent to: `tc qdisc change $qdisc`
+// The parent and handle MUST NOT be changed.
+func QdiscChange(qdisc Qdisc) error {
+ return qdiscModify(syscall.RTM_NEWQDISC, 0, qdisc)
+}
+
+// QdiscReplace will replace a qdisc to the system.
+// Equivalent to: `tc qdisc replace $qdisc`
+// The handle MUST change.
+func QdiscReplace(qdisc Qdisc) error {
+ return qdiscModify(
+ syscall.RTM_NEWQDISC,
+ syscall.NLM_F_CREATE|syscall.NLM_F_REPLACE,
+ qdisc)
+}
+
+// QdiscAdd will add a qdisc to the system.
+// Equivalent to: `tc qdisc add $qdisc`
+func QdiscAdd(qdisc Qdisc) error {
+ return qdiscModify(
+ syscall.RTM_NEWQDISC,
+ syscall.NLM_F_CREATE|syscall.NLM_F_EXCL,
+ qdisc)
+}
+
+func qdiscModify(cmd, flags int, qdisc Qdisc) error {
+ req := nl.NewNetlinkRequest(cmd, flags|syscall.NLM_F_ACK)
+ base := qdisc.Attrs()
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: int32(base.LinkIndex),
+ Handle: base.Handle,
+ Parent: base.Parent,
+ }
+ req.AddData(msg)
+
+ // When deleting don't bother building the rest of the netlink payload
+ if cmd != syscall.RTM_DELQDISC {
+ if err := qdiscPayload(req, qdisc); err != nil {
+ return err
+ }
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+func qdiscPayload(req *nl.NetlinkRequest, qdisc Qdisc) error {
+
+ req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(qdisc.Type())))
+
+ options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
+ if prio, ok := qdisc.(*Prio); ok {
+ tcmap := nl.TcPrioMap{
+ Bands: int32(prio.Bands),
+ Priomap: prio.PriorityMap,
+ }
+ options = nl.NewRtAttr(nl.TCA_OPTIONS, tcmap.Serialize())
+ } else if tbf, ok := qdisc.(*Tbf); ok {
+ opt := nl.TcTbfQopt{}
+ // TODO: handle rate > uint32
+ opt.Rate.Rate = uint32(tbf.Rate)
+ opt.Limit = tbf.Limit
+ opt.Buffer = tbf.Buffer
+ nl.NewRtAttrChild(options, nl.TCA_TBF_PARMS, opt.Serialize())
+ } else if htb, ok := qdisc.(*Htb); ok {
+ opt := nl.TcHtbGlob{}
+ opt.Version = htb.Version
+ opt.Rate2Quantum = htb.Rate2Quantum
+ opt.Defcls = htb.Defcls
+ // TODO: Handle Debug properly. For now default to 0
+ opt.Debug = htb.Debug
+ opt.DirectPkts = htb.DirectPkts
+ nl.NewRtAttrChild(options, nl.TCA_HTB_INIT, opt.Serialize())
+ // nl.NewRtAttrChild(options, nl.TCA_HTB_DIRECT_QLEN, opt.Serialize())
+ } else if netem, ok := qdisc.(*Netem); ok {
+ opt := nl.TcNetemQopt{}
+ opt.Latency = netem.Latency
+ opt.Limit = netem.Limit
+ opt.Loss = netem.Loss
+ opt.Gap = netem.Gap
+ opt.Duplicate = netem.Duplicate
+ opt.Jitter = netem.Jitter
+ options = nl.NewRtAttr(nl.TCA_OPTIONS, opt.Serialize())
+ // Correlation
+ corr := nl.TcNetemCorr{}
+ corr.DelayCorr = netem.DelayCorr
+ corr.LossCorr = netem.LossCorr
+ corr.DupCorr = netem.DuplicateCorr
+
+ if corr.DelayCorr > 0 || corr.LossCorr > 0 || corr.DupCorr > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_CORR, corr.Serialize())
+ }
+ // Corruption
+ corruption := nl.TcNetemCorrupt{}
+ corruption.Probability = netem.CorruptProb
+ corruption.Correlation = netem.CorruptCorr
+ if corruption.Probability > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_CORRUPT, corruption.Serialize())
+ }
+ // Reorder
+ reorder := nl.TcNetemReorder{}
+ reorder.Probability = netem.ReorderProb
+ reorder.Correlation = netem.ReorderCorr
+ if reorder.Probability > 0 {
+ nl.NewRtAttrChild(options, nl.TCA_NETEM_REORDER, reorder.Serialize())
+ }
+ } else if _, ok := qdisc.(*Ingress); ok {
+ // ingress filters must use the proper handle
+ if qdisc.Attrs().Parent != HANDLE_INGRESS {
+ return fmt.Errorf("Ingress filters must set Parent to HANDLE_INGRESS")
+ }
+ }
+
+ req.AddData(options)
+ return nil
+}
+
+// QdiscList gets a list of qdiscs in the system.
+// Equivalent to: `tc qdisc show`.
+// The list can be filtered by link.
+func QdiscList(link Link) ([]Qdisc, error) {
+ req := nl.NewNetlinkRequest(syscall.RTM_GETQDISC, syscall.NLM_F_DUMP)
+ index := int32(0)
+ if link != nil {
+ base := link.Attrs()
+ ensureIndex(base)
+ index = int32(base.Index)
+ }
+ msg := &nl.TcMsg{
+ Family: nl.FAMILY_ALL,
+ Ifindex: index,
+ }
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWQDISC)
+ if err != nil {
+ return nil, err
+ }
+
+ var res []Qdisc
+ for _, m := range msgs {
+ msg := nl.DeserializeTcMsg(m)
+
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ // skip qdiscs from other interfaces
+ if link != nil && msg.Ifindex != index {
+ continue
+ }
+
+ base := QdiscAttrs{
+ LinkIndex: int(msg.Ifindex),
+ Handle: msg.Handle,
+ Parent: msg.Parent,
+ Refcnt: msg.Info,
+ }
+ var qdisc Qdisc
+ qdiscType := ""
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case nl.TCA_KIND:
+ qdiscType = string(attr.Value[:len(attr.Value)-1])
+ switch qdiscType {
+ case "pfifo_fast":
+ qdisc = &PfifoFast{}
+ case "prio":
+ qdisc = &Prio{}
+ case "tbf":
+ qdisc = &Tbf{}
+ case "ingress":
+ qdisc = &Ingress{}
+ case "htb":
+ qdisc = &Htb{}
+ case "netem":
+ qdisc = &Netem{}
+ default:
+ qdisc = &GenericQdisc{QdiscType: qdiscType}
+ }
+ case nl.TCA_OPTIONS:
+ switch qdiscType {
+ case "pfifo_fast":
+ // pfifo returns TcPrioMap directly without wrapping it in rtattr
+ if err := parsePfifoFastData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+ case "prio":
+ // prio returns TcPrioMap directly without wrapping it in rtattr
+ if err := parsePrioData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+ case "tbf":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ if err := parseTbfData(qdisc, data); err != nil {
+ return nil, err
+ }
+ case "htb":
+ data, err := nl.ParseRouteAttr(attr.Value)
+ if err != nil {
+ return nil, err
+ }
+ if err := parseHtbData(qdisc, data); err != nil {
+ return nil, err
+ }
+ case "netem":
+ if err := parseNetemData(qdisc, attr.Value); err != nil {
+ return nil, err
+ }
+
+ // no options for ingress
+ }
+ }
+ }
+ *qdisc.Attrs() = base
+ res = append(res, qdisc)
+ }
+
+ return res, nil
+}
+
+func parsePfifoFastData(qdisc Qdisc, value []byte) error {
+ pfifo := qdisc.(*PfifoFast)
+ tcmap := nl.DeserializeTcPrioMap(value)
+ pfifo.PriorityMap = tcmap.Priomap
+ pfifo.Bands = uint8(tcmap.Bands)
+ return nil
+}
+
+func parsePrioData(qdisc Qdisc, value []byte) error {
+ prio := qdisc.(*Prio)
+ tcmap := nl.DeserializeTcPrioMap(value)
+ prio.PriorityMap = tcmap.Priomap
+ prio.Bands = uint8(tcmap.Bands)
+ return nil
+}
+
+func parseHtbData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
+ native = nl.NativeEndian()
+ htb := qdisc.(*Htb)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_HTB_INIT:
+ opt := nl.DeserializeTcHtbGlob(datum.Value)
+ htb.Version = opt.Version
+ htb.Rate2Quantum = opt.Rate2Quantum
+ htb.Defcls = opt.Defcls
+ htb.Debug = opt.Debug
+ htb.DirectPkts = opt.DirectPkts
+ case nl.TCA_HTB_DIRECT_QLEN:
+ // TODO
+ //htb.DirectQlen = native.uint32(datum.Value)
+ }
+ }
+ return nil
+}
+
+func parseNetemData(qdisc Qdisc, value []byte) error {
+ netem := qdisc.(*Netem)
+ opt := nl.DeserializeTcNetemQopt(value)
+ netem.Latency = opt.Latency
+ netem.Limit = opt.Limit
+ netem.Loss = opt.Loss
+ netem.Gap = opt.Gap
+ netem.Duplicate = opt.Duplicate
+ netem.Jitter = opt.Jitter
+ data, err := nl.ParseRouteAttr(value[nl.SizeofTcNetemQopt:])
+ if err != nil {
+ return err
+ }
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_NETEM_CORR:
+ opt := nl.DeserializeTcNetemCorr(datum.Value)
+ netem.DelayCorr = opt.DelayCorr
+ netem.LossCorr = opt.LossCorr
+ netem.DuplicateCorr = opt.DupCorr
+ case nl.TCA_NETEM_CORRUPT:
+ opt := nl.DeserializeTcNetemCorrupt(datum.Value)
+ netem.CorruptProb = opt.Probability
+ netem.CorruptCorr = opt.Correlation
+ case nl.TCA_NETEM_REORDER:
+ opt := nl.DeserializeTcNetemReorder(datum.Value)
+ netem.ReorderProb = opt.Probability
+ netem.ReorderCorr = opt.Correlation
+ }
+ }
+ return nil
+}
+
+func parseTbfData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
+ native = nl.NativeEndian()
+ tbf := qdisc.(*Tbf)
+ for _, datum := range data {
+ switch datum.Attr.Type {
+ case nl.TCA_TBF_PARMS:
+ opt := nl.DeserializeTcTbfQopt(datum.Value)
+ tbf.Rate = uint64(opt.Rate.Rate)
+ tbf.Limit = opt.Limit
+ tbf.Buffer = opt.Buffer
+ case nl.TCA_TBF_RATE64:
+ tbf.Rate = native.Uint64(datum.Value[0:4])
+ }
+ }
+ return nil
+}
+
+const (
+ TIME_UNITS_PER_SEC = 1000000
+)
+
+var (
+ tickInUsec float64
+ clockFactor float64
+ hz float64
+)
+
+func initClock() {
+ data, err := ioutil.ReadFile("/proc/net/psched")
+ if err != nil {
+ return
+ }
+ parts := strings.Split(strings.TrimSpace(string(data)), " ")
+ if len(parts) < 3 {
+ return
+ }
+ var vals [3]uint64
+ for i := range vals {
+ val, err := strconv.ParseUint(parts[i], 16, 32)
+ if err != nil {
+ return
+ }
+ vals[i] = val
+ }
+ // compatibility
+ if vals[2] == 1000000000 {
+ vals[0] = vals[1]
+ }
+ clockFactor = float64(vals[2]) / TIME_UNITS_PER_SEC
+ tickInUsec = float64(vals[0]) / float64(vals[1]) * clockFactor
+ hz = float64(vals[0])
+}
+
+func TickInUsec() float64 {
+ if tickInUsec == 0.0 {
+ initClock()
+ }
+ return tickInUsec
+}
+
+func ClockFactor() float64 {
+ if clockFactor == 0.0 {
+ initClock()
+ }
+ return clockFactor
+}
+
+func Hz() float64 {
+ if hz == 0.0 {
+ initClock()
+ }
+ return hz
+}
+
+func time2Tick(time uint32) uint32 {
+ return uint32(float64(time) * TickInUsec())
+}
+
+func tick2Time(tick uint32) uint32 {
+ return uint32(float64(tick) / TickInUsec())
+}
+
+func time2Ktime(time uint32) uint32 {
+ return uint32(float64(time) * ClockFactor())
+}
+
+func ktime2Time(ktime uint32) uint32 {
+ return uint32(float64(ktime) / ClockFactor())
+}
+
+func burst(rate uint64, buffer uint32) uint32 {
+ return uint32(float64(rate) * float64(tick2Time(buffer)) / TIME_UNITS_PER_SEC)
+}
+
+func latency(rate uint64, limit, buffer uint32) float64 {
+ return TIME_UNITS_PER_SEC*(float64(limit)/float64(rate)) - float64(tick2Time(buffer))
+}
+
+func Xmittime(rate uint64, size uint32) float64 {
+ return TickInUsec() * TIME_UNITS_PER_SEC * (float64(size) / float64(rate))
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/route.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/route.go
index 6218546f8..da780919c 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/route.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/route.go
@@ -17,19 +17,64 @@ const (
SCOPE_NOWHERE Scope = syscall.RT_SCOPE_NOWHERE
)
-// Route represents a netlink route. A route is associated with a link,
-// has a destination network, an optional source ip, and optional
-// gateway. Advanced route parameters and non-main routing tables are
-// currently not supported.
+type NextHopFlag int
+
+const (
+ FLAG_ONLINK NextHopFlag = syscall.RTNH_F_ONLINK
+ FLAG_PERVASIVE NextHopFlag = syscall.RTNH_F_PERVASIVE
+)
+
+// Route represents a netlink route.
type Route struct {
- LinkIndex int
- Scope Scope
- Dst *net.IPNet
- Src net.IP
- Gw net.IP
+ LinkIndex int
+ ILinkIndex int
+ Scope Scope
+ Dst *net.IPNet
+ Src net.IP
+ Gw net.IP
+ Protocol int
+ Priority int
+ Table int
+ Type int
+ Tos int
+ Flags int
}
func (r Route) String() string {
- return fmt.Sprintf("{Ifindex: %d Dst: %s Src: %s Gw: %s}", r.LinkIndex, r.Dst,
- r.Src, r.Gw)
+ return fmt.Sprintf("{Ifindex: %d Dst: %s Src: %s Gw: %s Flags: %s}", r.LinkIndex, r.Dst,
+ r.Src, r.Gw, r.ListFlags())
+}
+
+func (r *Route) SetFlag(flag NextHopFlag) {
+ r.Flags |= int(flag)
+}
+
+func (r *Route) ClearFlag(flag NextHopFlag) {
+ r.Flags &^= int(flag)
+}
+
+type flagString struct {
+ f NextHopFlag
+ s string
+}
+
+var testFlags = []flagString{
+ {f: FLAG_ONLINK, s: "onlink"},
+ {f: FLAG_PERVASIVE, s: "pervasive"},
+}
+
+func (r *Route) ListFlags() []string {
+ var flags []string
+ for _, tf := range testFlags {
+ if r.Flags&int(tf.f) != 0 {
+ flags = append(flags, tf.s)
+ }
+ }
+ return flags
+}
+
+// RouteUpdate is sent when a route changes - type is RTM_NEWROUTE or RTM_DELROUTE
+type RouteUpdate struct {
+ Type uint16
+ Route
}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/route_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/route_linux.go
index 38908951f..e7b8beb15 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/route_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/route_linux.go
@@ -10,6 +10,19 @@ import (
// RtAttr is shared so it is in netlink_linux.go
+const (
+ RT_FILTER_PROTOCOL uint64 = 1 << (1 + iota)
+ RT_FILTER_SCOPE
+ RT_FILTER_TYPE
+ RT_FILTER_TOS
+ RT_FILTER_IIF
+ RT_FILTER_OIF
+ RT_FILTER_DST
+ RT_FILTER_SRC
+ RT_FILTER_GW
+ RT_FILTER_TABLE
+)
+
// RouteAdd will add a route to the system.
// Equivalent to: `ip route add $route`
func RouteAdd(route *Route) error {
@@ -17,7 +30,7 @@ func RouteAdd(route *Route) error {
return routeHandle(route, req, nl.NewRtMsg())
}
-// RouteAdd will delete a route from the system.
+// RouteDel will delete a route from the system.
// Equivalent to: `ip route del $route`
func RouteDel(route *Route) error {
req := nl.NewNetlinkRequest(syscall.RTM_DELROUTE, syscall.NLM_F_ACK)
@@ -29,7 +42,6 @@ func routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error {
return fmt.Errorf("one of Dst.IP, Src, or Gw must not be nil")
}
- msg.Scope = uint8(route.Scope)
family := -1
var rtAttrs []*nl.RtAttr
@@ -78,8 +90,35 @@ func routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error {
rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_GATEWAY, gwData))
}
- msg.Family = uint8(family)
+ if route.Table > 0 {
+ if route.Table >= 256 {
+ msg.Table = syscall.RT_TABLE_UNSPEC
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(route.Table))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_TABLE, b))
+ } else {
+ msg.Table = uint8(route.Table)
+ }
+ }
+ if route.Priority > 0 {
+ b := make([]byte, 4)
+ native.PutUint32(b, uint32(route.Priority))
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PRIORITY, b))
+ }
+ if route.Tos > 0 {
+ msg.Tos = uint8(route.Tos)
+ }
+ if route.Protocol > 0 {
+ msg.Protocol = uint8(route.Protocol)
+ }
+ if route.Type > 0 {
+ msg.Type = uint8(route.Type)
+ }
+
+ msg.Flags = uint32(route.Flags)
+ msg.Scope = uint8(route.Scope)
+ msg.Family = uint8(family)
req.AddData(msg)
for _, attr := range rtAttrs {
req.AddData(attr)
@@ -101,69 +140,121 @@ func routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error {
// Equivalent to: `ip route show`.
// The list can be filtered by link and ip family.
func RouteList(link Link, family int) ([]Route, error) {
+ var routeFilter *Route
+ if link != nil {
+ routeFilter = &Route{
+ LinkIndex: link.Attrs().Index,
+ }
+ }
+ return RouteListFiltered(family, routeFilter, RT_FILTER_OIF)
+}
+
+// RouteListFiltered gets a list of routes in the system filtered with specified rules.
+// All rules must be defined in RouteFilter struct
+func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) {
req := nl.NewNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP)
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
+ infmsg := nl.NewIfInfomsg(family)
+ req.AddData(infmsg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
if err != nil {
return nil, err
}
- index := 0
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- index = base.Index
- }
-
- native := nl.NativeEndian()
var res []Route
for _, m := range msgs {
msg := nl.DeserializeRtMsg(m)
-
if msg.Flags&syscall.RTM_F_CLONED != 0 {
// Ignore cloned routes
continue
}
-
if msg.Table != syscall.RT_TABLE_MAIN {
- // Ignore non-main tables
- continue
+ if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 {
+ // Ignore non-main tables
+ continue
+ }
}
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ route, err := deserializeRoute(m)
if err != nil {
return nil, err
}
-
- route := Route{Scope: Scope(msg.Scope)}
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.RTA_GATEWAY:
- route.Gw = net.IP(attr.Value)
- case syscall.RTA_PREFSRC:
- route.Src = net.IP(attr.Value)
- case syscall.RTA_DST:
- route.Dst = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
+ if filter != nil {
+ switch {
+ case filterMask&RT_FILTER_TABLE != 0 && route.Table != filter.Table:
+ continue
+ case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol:
+ continue
+ case filterMask&RT_FILTER_SCOPE != 0 && route.Scope != filter.Scope:
+ continue
+ case filterMask&RT_FILTER_TYPE != 0 && route.Type != filter.Type:
+ continue
+ case filterMask&RT_FILTER_TOS != 0 && route.Tos != filter.Tos:
+ continue
+ case filterMask&RT_FILTER_OIF != 0 && route.LinkIndex != filter.LinkIndex:
+ continue
+ case filterMask&RT_FILTER_IIF != 0 && route.ILinkIndex != filter.ILinkIndex:
+ continue
+ case filterMask&RT_FILTER_GW != 0 && !route.Gw.Equal(filter.Gw):
+ continue
+ case filterMask&RT_FILTER_SRC != 0 && !route.Src.Equal(filter.Src):
+ continue
+ case filterMask&RT_FILTER_DST != 0 && filter.Dst != nil:
+ if route.Dst == nil {
+ continue
}
- case syscall.RTA_OIF:
- routeIndex := int(native.Uint32(attr.Value[0:4]))
- if link != nil && routeIndex != index {
- // Ignore routes from other interfaces
+ aMaskLen, aMaskBits := route.Dst.Mask.Size()
+ bMaskLen, bMaskBits := filter.Dst.Mask.Size()
+ if !(route.Dst.IP.Equal(filter.Dst.IP) && aMaskLen == bMaskLen && aMaskBits == bMaskBits) {
continue
}
- route.LinkIndex = routeIndex
}
}
res = append(res, route)
}
-
return res, nil
}
+// deserializeRoute decodes a binary netlink message into a Route struct
+func deserializeRoute(m []byte) (Route, error) {
+ msg := nl.DeserializeRtMsg(m)
+ attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ if err != nil {
+ return Route{}, err
+ }
+ route := Route{
+ Scope: Scope(msg.Scope),
+ Protocol: int(msg.Protocol),
+ Table: int(msg.Table),
+ Type: int(msg.Type),
+ Tos: int(msg.Tos),
+ Flags: int(msg.Flags),
+ }
+
+ native := nl.NativeEndian()
+ for _, attr := range attrs {
+ switch attr.Attr.Type {
+ case syscall.RTA_GATEWAY:
+ route.Gw = net.IP(attr.Value)
+ case syscall.RTA_PREFSRC:
+ route.Src = net.IP(attr.Value)
+ case syscall.RTA_DST:
+ route.Dst = &net.IPNet{
+ IP: attr.Value,
+ Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
+ }
+ case syscall.RTA_OIF:
+ route.LinkIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_IIF:
+ route.ILinkIndex = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_PRIORITY:
+ route.Priority = int(native.Uint32(attr.Value[0:4]))
+ case syscall.RTA_TABLE:
+ route.Table = int(native.Uint32(attr.Value[0:4]))
+ }
+ }
+ return route, nil
+}
+
// RouteGet gets a route to a specific destination from the host system.
// Equivalent to: 'ip route get'.
func RouteGet(destination net.IP) ([]Route, error) {
@@ -191,34 +282,47 @@ func RouteGet(destination net.IP) ([]Route, error) {
return nil, err
}
- native := nl.NativeEndian()
var res []Route
for _, m := range msgs {
- msg := nl.DeserializeRtMsg(m)
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
+ route, err := deserializeRoute(m)
if err != nil {
return nil, err
}
+ res = append(res, route)
+ }
+ return res, nil
+
+}
- route := Route{}
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.RTA_GATEWAY:
- route.Gw = net.IP(attr.Value)
- case syscall.RTA_PREFSRC:
- route.Src = net.IP(attr.Value)
- case syscall.RTA_DST:
- route.Dst = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
+// RouteSubscribe takes a chan down which notifications will be sent
+// when routes are added or deleted. Close the 'done' chan to stop subscription.
+func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error {
+ s, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_ROUTE, syscall.RTNLGRP_IPV6_ROUTE)
+ if err != nil {
+ return err
+ }
+ if done != nil {
+ go func() {
+ <-done
+ s.Close()
+ }()
+ }
+ go func() {
+ defer close(ch)
+ for {
+ msgs, err := s.Receive()
+ if err != nil {
+ return
+ }
+ for _, m := range msgs {
+ route, err := deserializeRoute(m.Data)
+ if err != nil {
+ return
}
- case syscall.RTA_OIF:
- routeIndex := int(native.Uint32(attr.Value[0:4]))
- route.LinkIndex = routeIndex
+ ch <- RouteUpdate{Type: m.Header.Type, Route: route}
}
}
- res = append(res, route)
- }
- return res, nil
+ }()
+ return nil
}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/route_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/route_test.go
deleted file mode 100644
index f02bef8c8..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/route_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package netlink
-
-import (
- "net"
- "testing"
-)
-
-func TestRouteAddDel(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- // get loopback interface
- link, err := LinkByName("lo")
- if err != nil {
- t.Fatal(err)
- }
-
- // bring the interface up
- if err = LinkSetUp(link); err != nil {
- t.Fatal(err)
- }
-
- // add a gateway route
- _, dst, err := net.ParseCIDR("192.168.0.0/24")
-
- ip := net.ParseIP("127.1.1.1")
- route := Route{LinkIndex: link.Attrs().Index, Dst: dst, Src: ip}
- err = RouteAdd(&route)
- if err != nil {
- t.Fatal(err)
- }
- routes, err := RouteList(link, FAMILY_V4)
- if err != nil {
- t.Fatal(err)
- }
- if len(routes) != 1 {
- t.Fatal("Link not added properly")
- }
-
- dstIP := net.ParseIP("192.168.0.42")
- routeToDstIP, err := RouteGet(dstIP)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(routeToDstIP) == 0 {
- t.Fatal("Default route not present")
- }
-
- err = RouteDel(&route)
- if err != nil {
- t.Fatal(err)
- }
-
- routes, err = RouteList(link, FAMILY_V4)
- if err != nil {
- t.Fatal(err)
- }
- if len(routes) != 0 {
- t.Fatal("Route not removed properly")
- }
-
-}
-
-func TestRouteAddIncomplete(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- // get loopback interface
- link, err := LinkByName("lo")
- if err != nil {
- t.Fatal(err)
- }
-
- // bring the interface up
- if err = LinkSetUp(link); err != nil {
- t.Fatal(err)
- }
-
- route := Route{LinkIndex: link.Attrs().Index}
- if err := RouteAdd(&route); err == nil {
- t.Fatal("Adding incomplete route should fail")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/rule.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/rule.go
new file mode 100644
index 000000000..bd699a7e1
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/rule.go
@@ -0,0 +1,43 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// Rule represents a netlink rule.
+type Rule struct {
+ *nl.RtMsg
+ Priority int
+ Table int
+ Mark int
+ Mask int
+ TunID uint
+ Goto int
+ Src *net.IPNet
+ Dst *net.IPNet
+ Flow int
+ IifName string
+ OifName string
+ SuppressIfgroup int
+ SuppressPrefixlen int
+}
+
+func (r Rule) String() string {
+ return fmt.Sprintf("ip rule %d: from %s table %d", r.Priority, r.Src, r.Table)
+}
+
+// NewRule return empty rules.
+func NewRule() *Rule {
+ return &Rule{
+ SuppressIfgroup: -1,
+ SuppressPrefixlen: -1,
+ Priority: -1,
+ Mark: -1,
+ Mask: -1,
+ Goto: -1,
+ Flow: -1,
+ }
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/rule_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/rule_linux.go
new file mode 100644
index 000000000..ba84be00e
--- /dev/null
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/rule_linux.go
@@ -0,0 +1,198 @@
+package netlink
+
+import (
+ "fmt"
+ "net"
+ "syscall"
+
+ "github.com/vishvananda/netlink/nl"
+)
+
+// RuleAdd adds a rule to the system.
+// Equivalent to: ip rule add
+func RuleAdd(rule *Rule) error {
+ req := nl.NewNetlinkRequest(syscall.RTM_NEWRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ return ruleHandle(rule, req)
+}
+
+// RuleDel deletes a rule from the system.
+// Equivalent to: ip rule del
+func RuleDel(rule *Rule) error {
+ req := nl.NewNetlinkRequest(syscall.RTM_DELRULE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
+ return ruleHandle(rule, req)
+}
+
+func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error {
+ msg := nl.NewRtMsg()
+ msg.Family = syscall.AF_INET
+ var dstFamily uint8
+
+ var rtAttrs []*nl.RtAttr
+ if rule.Dst != nil && rule.Dst.IP != nil {
+ dstLen, _ := rule.Dst.Mask.Size()
+ msg.Dst_len = uint8(dstLen)
+ msg.Family = uint8(nl.GetIPFamily(rule.Dst.IP))
+ dstFamily = msg.Family
+ var dstData []byte
+ if msg.Family == syscall.AF_INET {
+ dstData = rule.Dst.IP.To4()
+ } else {
+ dstData = rule.Dst.IP.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData))
+ }
+
+ if rule.Src != nil && rule.Src.IP != nil {
+ msg.Family = uint8(nl.GetIPFamily(rule.Src.IP))
+ if dstFamily != 0 && dstFamily != msg.Family {
+ return fmt.Errorf("source and destination ip are not the same IP family")
+ }
+ srcLen, _ := rule.Src.Mask.Size()
+ msg.Src_len = uint8(srcLen)
+ var srcData []byte
+ if msg.Family == syscall.AF_INET {
+ srcData = rule.Src.IP.To4()
+ } else {
+ srcData = rule.Src.IP.To16()
+ }
+ rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_SRC, srcData))
+ }
+
+ if rule.Table >= 0 {
+ msg.Table = uint8(rule.Table)
+ if rule.Table >= 256 {
+ msg.Table = syscall.RT_TABLE_UNSPEC
+ }
+ }
+
+ req.AddData(msg)
+ for i := range rtAttrs {
+ req.AddData(rtAttrs[i])
+ }
+
+ var (
+ b = make([]byte, 4)
+ native = nl.NativeEndian()
+ )
+
+ if rule.Priority >= 0 {
+ native.PutUint32(b, uint32(rule.Priority))
+ req.AddData(nl.NewRtAttr(nl.FRA_PRIORITY, b))
+ }
+ if rule.Mark >= 0 {
+ native.PutUint32(b, uint32(rule.Mark))
+ req.AddData(nl.NewRtAttr(nl.FRA_FWMARK, b))
+ }
+ if rule.Mask >= 0 {
+ native.PutUint32(b, uint32(rule.Mask))
+ req.AddData(nl.NewRtAttr(nl.FRA_FWMASK, b))
+ }
+ if rule.Flow >= 0 {
+ native.PutUint32(b, uint32(rule.Flow))
+ req.AddData(nl.NewRtAttr(nl.FRA_FLOW, b))
+ }
+ if rule.TunID > 0 {
+ native.PutUint32(b, uint32(rule.TunID))
+ req.AddData(nl.NewRtAttr(nl.FRA_TUN_ID, b))
+ }
+ if rule.Table >= 256 {
+ native.PutUint32(b, uint32(rule.Table))
+ req.AddData(nl.NewRtAttr(nl.FRA_TABLE, b))
+ }
+ if msg.Table > 0 {
+ if rule.SuppressPrefixlen >= 0 {
+ native.PutUint32(b, uint32(rule.SuppressPrefixlen))
+ req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_PREFIXLEN, b))
+ }
+ if rule.SuppressIfgroup >= 0 {
+ native.PutUint32(b, uint32(rule.SuppressIfgroup))
+ req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_IFGROUP, b))
+ }
+ }
+ if rule.IifName != "" {
+ req.AddData(nl.NewRtAttr(nl.FRA_IIFNAME, []byte(rule.IifName)))
+ }
+ if rule.OifName != "" {
+ req.AddData(nl.NewRtAttr(nl.FRA_OIFNAME, []byte(rule.OifName)))
+ }
+ if rule.Goto >= 0 {
+ msg.Type = nl.FR_ACT_NOP
+ native.PutUint32(b, uint32(rule.Goto))
+ req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b))
+ }
+
+ _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
+ return err
+}
+
+// RuleList lists rules in the system.
+// Equivalent to: ip rule list
+func RuleList(family int) ([]Rule, error) {
+ req := nl.NewNetlinkRequest(syscall.RTM_GETRULE, syscall.NLM_F_DUMP|syscall.NLM_F_REQUEST)
+ msg := nl.NewIfInfomsg(family)
+ req.AddData(msg)
+
+ msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWRULE)
+ if err != nil {
+ return nil, err
+ }
+
+ native := nl.NativeEndian()
+ var res = make([]Rule, 0)
+ for i := range msgs {
+ msg := nl.DeserializeRtMsg(msgs[i])
+ attrs, err := nl.ParseRouteAttr(msgs[i][msg.Len():])
+ if err != nil {
+ return nil, err
+ }
+
+ rule := NewRule()
+ rule.RtMsg = msg
+
+ for j := range attrs {
+ switch attrs[j].Attr.Type {
+ case syscall.RTA_TABLE:
+ rule.Table = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_SRC:
+ rule.Src = &net.IPNet{
+ IP: attrs[j].Value,
+ Mask: net.CIDRMask(int(msg.Src_len), 8*len(attrs[j].Value)),
+ }
+ case nl.FRA_DST:
+ rule.Dst = &net.IPNet{
+ IP: attrs[j].Value,
+ Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attrs[j].Value)),
+ }
+ case nl.FRA_FWMARK:
+ rule.Mark = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_FWMASK:
+ rule.Mask = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_TUN_ID:
+ rule.TunID = uint(native.Uint64(attrs[j].Value[0:4]))
+ case nl.FRA_IIFNAME:
+ rule.IifName = string(attrs[j].Value[:len(attrs[j].Value)-1])
+ case nl.FRA_OIFNAME:
+ rule.OifName = string(attrs[j].Value[:len(attrs[j].Value)-1])
+ case nl.FRA_SUPPRESS_PREFIXLEN:
+ i := native.Uint32(attrs[j].Value[0:4])
+ if i != 0xffffffff {
+ rule.SuppressPrefixlen = int(i)
+ }
+ case nl.FRA_SUPPRESS_IFGROUP:
+ i := native.Uint32(attrs[j].Value[0:4])
+ if i != 0xffffffff {
+ rule.SuppressIfgroup = int(i)
+ }
+ case nl.FRA_FLOW:
+ rule.Flow = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_GOTO:
+ rule.Goto = int(native.Uint32(attrs[j].Value[0:4]))
+ case nl.FRA_PRIORITY:
+ rule.Priority = int(native.Uint32(attrs[j].Value[0:4]))
+ }
+ }
+ res = append(res, *rule)
+ }
+
+ return res, nil
+}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy_test.go
deleted file mode 100644
index 06d178d1f..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_policy_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package netlink
-
-import (
- "net"
- "testing"
-)
-
-func TestXfrmPolicyAddDel(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- src, _ := ParseIPNet("127.1.1.1/32")
- dst, _ := ParseIPNet("127.1.1.2/32")
- policy := XfrmPolicy{
- Src: src,
- Dst: dst,
- Dir: XFRM_DIR_OUT,
- }
- tmpl := XfrmPolicyTmpl{
- Src: net.ParseIP("127.0.0.1"),
- Dst: net.ParseIP("127.0.0.2"),
- Proto: XFRM_PROTO_ESP,
- Mode: XFRM_MODE_TUNNEL,
- }
- policy.Tmpls = append(policy.Tmpls, tmpl)
- if err := XfrmPolicyAdd(&policy); err != nil {
- t.Fatal(err)
- }
- policies, err := XfrmPolicyList(FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(policies) != 1 {
- t.Fatal("Policy not added properly")
- }
-
- if err = XfrmPolicyDel(&policy); err != nil {
- t.Fatal(err)
- }
-
- policies, err = XfrmPolicyList(FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
- if len(policies) != 0 {
- t.Fatal("Policy not removed properly")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state.go
index 5b8f2df70..bdc25fe14 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state.go
@@ -29,7 +29,7 @@ func (e EncapType) String() string {
return "unknown"
}
-// XfrmEncap represents the encapsulation to use for the ipsec encryption.
+// XfrmStateEncap represents the encapsulation to use for the ipsec encryption.
type XfrmStateEncap struct {
Type EncapType
SrcPort int
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_linux.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_linux.go
index 5f44ec852..fc8604b9d 100644
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_linux.go
+++ b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_linux.go
@@ -110,9 +110,6 @@ func XfrmStateDel(state *XfrmState) error {
func XfrmStateList(family int) ([]XfrmState, error) {
req := nl.NewNetlinkRequest(nl.XFRM_MSG_GETSA, syscall.NLM_F_DUMP)
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
-
msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
if err != nil {
return nil, err
diff --git a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_test.go b/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_test.go
deleted file mode 100644
index df57ef8b7..000000000
--- a/Godeps/_workspace/src/github.com/vishvananda/netlink/xfrm_state_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package netlink
-
-import (
- "net"
- "testing"
-)
-
-func TestXfrmStateAddDel(t *testing.T) {
- tearDown := setUpNetlinkTest(t)
- defer tearDown()
-
- state := XfrmState{
- Src: net.ParseIP("127.0.0.1"),
- Dst: net.ParseIP("127.0.0.2"),
- Proto: XFRM_PROTO_ESP,
- Mode: XFRM_MODE_TUNNEL,
- Spi: 1,
- Auth: &XfrmStateAlgo{
- Name: "hmac(sha256)",
- Key: []byte("abcdefghijklmnopqrstuvwzyzABCDEF"),
- },
- Crypt: &XfrmStateAlgo{
- Name: "cbc(aes)",
- Key: []byte("abcdefghijklmnopqrstuvwzyzABCDEF"),
- },
- }
- if err := XfrmStateAdd(&state); err != nil {
- t.Fatal(err)
- }
- policies, err := XfrmStateList(FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(policies) != 1 {
- t.Fatal("State not added properly")
- }
-
- if err = XfrmStateDel(&state); err != nil {
- t.Fatal(err)
- }
-
- policies, err = XfrmStateList(FAMILY_ALL)
- if err != nil {
- t.Fatal(err)
- }
- if len(policies) != 0 {
- t.Fatal("State not removed properly")
- }
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client.go
deleted file mode 100644
index c98cb16b2..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client.go
+++ /dev/null
@@ -1,563 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
- Package agent implements a client to an ssh-agent daemon.
-
-References:
- [PROTOCOL.agent]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent?rev=HEAD
-*/
-package agent
-
-import (
- "bytes"
- "crypto/dsa"
- "crypto/ecdsa"
- "crypto/elliptic"
- "crypto/rsa"
- "encoding/base64"
- "encoding/binary"
- "errors"
- "fmt"
- "io"
- "math/big"
- "sync"
-
- "golang.org/x/crypto/ssh"
-)
-
-// Agent represents the capabilities of an ssh-agent.
-type Agent interface {
- // List returns the identities known to the agent.
- List() ([]*Key, error)
-
- // Sign has the agent sign the data using a protocol 2 key as defined
- // in [PROTOCOL.agent] section 2.6.2.
- Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error)
-
- // Insert adds a private key to the agent. If a certificate
- // is given, that certificate is added as public key.
- Add(s interface{}, cert *ssh.Certificate, comment string) error
-
- // Remove removes all identities with the given public key.
- Remove(key ssh.PublicKey) error
-
- // RemoveAll removes all identities.
- RemoveAll() error
-
- // Lock locks the agent. Sign and Remove will fail, and List will empty an empty list.
- Lock(passphrase []byte) error
-
- // Unlock undoes the effect of Lock
- Unlock(passphrase []byte) error
-
- // Signers returns signers for all the known keys.
- Signers() ([]ssh.Signer, error)
-}
-
-// See [PROTOCOL.agent], section 3.
-const (
- agentRequestV1Identities = 1
-
- // 3.2 Requests from client to agent for protocol 2 key operations
- agentAddIdentity = 17
- agentRemoveIdentity = 18
- agentRemoveAllIdentities = 19
- agentAddIdConstrained = 25
-
- // 3.3 Key-type independent requests from client to agent
- agentAddSmartcardKey = 20
- agentRemoveSmartcardKey = 21
- agentLock = 22
- agentUnlock = 23
- agentAddSmartcardKeyConstrained = 26
-
- // 3.7 Key constraint identifiers
- agentConstrainLifetime = 1
- agentConstrainConfirm = 2
-)
-
-// maxAgentResponseBytes is the maximum agent reply size that is accepted. This
-// is a sanity check, not a limit in the spec.
-const maxAgentResponseBytes = 16 << 20
-
-// Agent messages:
-// These structures mirror the wire format of the corresponding ssh agent
-// messages found in [PROTOCOL.agent].
-
-// 3.4 Generic replies from agent to client
-const agentFailure = 5
-
-type failureAgentMsg struct{}
-
-const agentSuccess = 6
-
-type successAgentMsg struct{}
-
-// See [PROTOCOL.agent], section 2.5.2.
-const agentRequestIdentities = 11
-
-type requestIdentitiesAgentMsg struct{}
-
-// See [PROTOCOL.agent], section 2.5.2.
-const agentIdentitiesAnswer = 12
-
-type identitiesAnswerAgentMsg struct {
- NumKeys uint32 `sshtype:"12"`
- Keys []byte `ssh:"rest"`
-}
-
-// See [PROTOCOL.agent], section 2.6.2.
-const agentSignRequest = 13
-
-type signRequestAgentMsg struct {
- KeyBlob []byte `sshtype:"13"`
- Data []byte
- Flags uint32
-}
-
-// See [PROTOCOL.agent], section 2.6.2.
-
-// 3.6 Replies from agent to client for protocol 2 key operations
-const agentSignResponse = 14
-
-type signResponseAgentMsg struct {
- SigBlob []byte `sshtype:"14"`
-}
-
-type publicKey struct {
- Format string
- Rest []byte `ssh:"rest"`
-}
-
-// Key represents a protocol 2 public key as defined in
-// [PROTOCOL.agent], section 2.5.2.
-type Key struct {
- Format string
- Blob []byte
- Comment string
-}
-
-func clientErr(err error) error {
- return fmt.Errorf("agent: client error: %v", err)
-}
-
-// String returns the storage form of an agent key with the format, base64
-// encoded serialized key, and the comment if it is not empty.
-func (k *Key) String() string {
- s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob)
-
- if k.Comment != "" {
- s += " " + k.Comment
- }
-
- return s
-}
-
-// Type returns the public key type.
-func (k *Key) Type() string {
- return k.Format
-}
-
-// Marshal returns key blob to satisfy the ssh.PublicKey interface.
-func (k *Key) Marshal() []byte {
- return k.Blob
-}
-
-// Verify satisfies the ssh.PublicKey interface, but is not
-// implemented for agent keys.
-func (k *Key) Verify(data []byte, sig *ssh.Signature) error {
- return errors.New("agent: agent key does not know how to verify")
-}
-
-type wireKey struct {
- Format string
- Rest []byte `ssh:"rest"`
-}
-
-func parseKey(in []byte) (out *Key, rest []byte, err error) {
- var record struct {
- Blob []byte
- Comment string
- Rest []byte `ssh:"rest"`
- }
-
- if err := ssh.Unmarshal(in, &record); err != nil {
- return nil, nil, err
- }
-
- var wk wireKey
- if err := ssh.Unmarshal(record.Blob, &wk); err != nil {
- return nil, nil, err
- }
-
- return &Key{
- Format: wk.Format,
- Blob: record.Blob,
- Comment: record.Comment,
- }, record.Rest, nil
-}
-
-// client is a client for an ssh-agent process.
-type client struct {
- // conn is typically a *net.UnixConn
- conn io.ReadWriter
- // mu is used to prevent concurrent access to the agent
- mu sync.Mutex
-}
-
-// NewClient returns an Agent that talks to an ssh-agent process over
-// the given connection.
-func NewClient(rw io.ReadWriter) Agent {
- return &client{conn: rw}
-}
-
-// call sends an RPC to the agent. On success, the reply is
-// unmarshaled into reply and replyType is set to the first byte of
-// the reply, which contains the type of the message.
-func (c *client) call(req []byte) (reply interface{}, err error) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- msg := make([]byte, 4+len(req))
- binary.BigEndian.PutUint32(msg, uint32(len(req)))
- copy(msg[4:], req)
- if _, err = c.conn.Write(msg); err != nil {
- return nil, clientErr(err)
- }
-
- var respSizeBuf [4]byte
- if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil {
- return nil, clientErr(err)
- }
- respSize := binary.BigEndian.Uint32(respSizeBuf[:])
- if respSize > maxAgentResponseBytes {
- return nil, clientErr(err)
- }
-
- buf := make([]byte, respSize)
- if _, err = io.ReadFull(c.conn, buf); err != nil {
- return nil, clientErr(err)
- }
- reply, err = unmarshal(buf)
- if err != nil {
- return nil, clientErr(err)
- }
- return reply, err
-}
-
-func (c *client) simpleCall(req []byte) error {
- resp, err := c.call(req)
- if err != nil {
- return err
- }
- if _, ok := resp.(*successAgentMsg); ok {
- return nil
- }
- return errors.New("agent: failure")
-}
-
-func (c *client) RemoveAll() error {
- return c.simpleCall([]byte{agentRemoveAllIdentities})
-}
-
-func (c *client) Remove(key ssh.PublicKey) error {
- req := ssh.Marshal(&agentRemoveIdentityMsg{
- KeyBlob: key.Marshal(),
- })
- return c.simpleCall(req)
-}
-
-func (c *client) Lock(passphrase []byte) error {
- req := ssh.Marshal(&agentLockMsg{
- Passphrase: passphrase,
- })
- return c.simpleCall(req)
-}
-
-func (c *client) Unlock(passphrase []byte) error {
- req := ssh.Marshal(&agentUnlockMsg{
- Passphrase: passphrase,
- })
- return c.simpleCall(req)
-}
-
-// List returns the identities known to the agent.
-func (c *client) List() ([]*Key, error) {
- // see [PROTOCOL.agent] section 2.5.2.
- req := []byte{agentRequestIdentities}
-
- msg, err := c.call(req)
- if err != nil {
- return nil, err
- }
-
- switch msg := msg.(type) {
- case *identitiesAnswerAgentMsg:
- if msg.NumKeys > maxAgentResponseBytes/8 {
- return nil, errors.New("agent: too many keys in agent reply")
- }
- keys := make([]*Key, msg.NumKeys)
- data := msg.Keys
- for i := uint32(0); i < msg.NumKeys; i++ {
- var key *Key
- var err error
- if key, data, err = parseKey(data); err != nil {
- return nil, err
- }
- keys[i] = key
- }
- return keys, nil
- case *failureAgentMsg:
- return nil, errors.New("agent: failed to list keys")
- }
- panic("unreachable")
-}
-
-// Sign has the agent sign the data using a protocol 2 key as defined
-// in [PROTOCOL.agent] section 2.6.2.
-func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
- req := ssh.Marshal(signRequestAgentMsg{
- KeyBlob: key.Marshal(),
- Data: data,
- })
-
- msg, err := c.call(req)
- if err != nil {
- return nil, err
- }
-
- switch msg := msg.(type) {
- case *signResponseAgentMsg:
- var sig ssh.Signature
- if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil {
- return nil, err
- }
-
- return &sig, nil
- case *failureAgentMsg:
- return nil, errors.New("agent: failed to sign challenge")
- }
- panic("unreachable")
-}
-
-// unmarshal parses an agent message in packet, returning the parsed
-// form and the message type of packet.
-func unmarshal(packet []byte) (interface{}, error) {
- if len(packet) < 1 {
- return nil, errors.New("agent: empty packet")
- }
- var msg interface{}
- switch packet[0] {
- case agentFailure:
- return new(failureAgentMsg), nil
- case agentSuccess:
- return new(successAgentMsg), nil
- case agentIdentitiesAnswer:
- msg = new(identitiesAnswerAgentMsg)
- case agentSignResponse:
- msg = new(signResponseAgentMsg)
- default:
- return nil, fmt.Errorf("agent: unknown type tag %d", packet[0])
- }
- if err := ssh.Unmarshal(packet, msg); err != nil {
- return nil, err
- }
- return msg, nil
-}
-
-type rsaKeyMsg struct {
- Type string `sshtype:"17"`
- N *big.Int
- E *big.Int
- D *big.Int
- Iqmp *big.Int // IQMP = Inverse Q Mod P
- P *big.Int
- Q *big.Int
- Comments string
-}
-
-type dsaKeyMsg struct {
- Type string `sshtype:"17"`
- P *big.Int
- Q *big.Int
- G *big.Int
- Y *big.Int
- X *big.Int
- Comments string
-}
-
-type ecdsaKeyMsg struct {
- Type string `sshtype:"17"`
- Curve string
- KeyBytes []byte
- D *big.Int
- Comments string
-}
-
-// Insert adds a private key to the agent.
-func (c *client) insertKey(s interface{}, comment string) error {
- var req []byte
- switch k := s.(type) {
- case *rsa.PrivateKey:
- if len(k.Primes) != 2 {
- return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
- }
- k.Precompute()
- req = ssh.Marshal(rsaKeyMsg{
- Type: ssh.KeyAlgoRSA,
- N: k.N,
- E: big.NewInt(int64(k.E)),
- D: k.D,
- Iqmp: k.Precomputed.Qinv,
- P: k.Primes[0],
- Q: k.Primes[1],
- Comments: comment,
- })
- case *dsa.PrivateKey:
- req = ssh.Marshal(dsaKeyMsg{
- Type: ssh.KeyAlgoDSA,
- P: k.P,
- Q: k.Q,
- G: k.G,
- Y: k.Y,
- X: k.X,
- Comments: comment,
- })
- case *ecdsa.PrivateKey:
- nistID := fmt.Sprintf("nistp%d", k.Params().BitSize)
- req = ssh.Marshal(ecdsaKeyMsg{
- Type: "ecdsa-sha2-" + nistID,
- Curve: nistID,
- KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y),
- D: k.D,
- Comments: comment,
- })
- default:
- return fmt.Errorf("agent: unsupported key type %T", s)
- }
- resp, err := c.call(req)
- if err != nil {
- return err
- }
- if _, ok := resp.(*successAgentMsg); ok {
- return nil
- }
- return errors.New("agent: failure")
-}
-
-type rsaCertMsg struct {
- Type string `sshtype:"17"`
- CertBytes []byte
- D *big.Int
- Iqmp *big.Int // IQMP = Inverse Q Mod P
- P *big.Int
- Q *big.Int
- Comments string
-}
-
-type dsaCertMsg struct {
- Type string `sshtype:"17"`
- CertBytes []byte
- X *big.Int
- Comments string
-}
-
-type ecdsaCertMsg struct {
- Type string `sshtype:"17"`
- CertBytes []byte
- D *big.Int
- Comments string
-}
-
-// Insert adds a private key to the agent. If a certificate is given,
-// that certificate is added instead as public key.
-func (c *client) Add(s interface{}, cert *ssh.Certificate, comment string) error {
- if cert == nil {
- return c.insertKey(s, comment)
- } else {
- return c.insertCert(s, cert, comment)
- }
-}
-
-func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string) error {
- var req []byte
- switch k := s.(type) {
- case *rsa.PrivateKey:
- if len(k.Primes) != 2 {
- return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
- }
- k.Precompute()
- req = ssh.Marshal(rsaCertMsg{
- Type: cert.Type(),
- CertBytes: cert.Marshal(),
- D: k.D,
- Iqmp: k.Precomputed.Qinv,
- P: k.Primes[0],
- Q: k.Primes[1],
- Comments: comment,
- })
- case *dsa.PrivateKey:
- req = ssh.Marshal(dsaCertMsg{
- Type: cert.Type(),
- CertBytes: cert.Marshal(),
- X: k.X,
- Comments: comment,
- })
- case *ecdsa.PrivateKey:
- req = ssh.Marshal(ecdsaCertMsg{
- Type: cert.Type(),
- CertBytes: cert.Marshal(),
- D: k.D,
- Comments: comment,
- })
- default:
- return fmt.Errorf("agent: unsupported key type %T", s)
- }
-
- signer, err := ssh.NewSignerFromKey(s)
- if err != nil {
- return err
- }
- if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
- return errors.New("agent: signer and cert have different public key")
- }
-
- resp, err := c.call(req)
- if err != nil {
- return err
- }
- if _, ok := resp.(*successAgentMsg); ok {
- return nil
- }
- return errors.New("agent: failure")
-}
-
-// Signers provides a callback for client authentication.
-func (c *client) Signers() ([]ssh.Signer, error) {
- keys, err := c.List()
- if err != nil {
- return nil, err
- }
-
- var result []ssh.Signer
- for _, k := range keys {
- result = append(result, &agentKeyringSigner{c, k})
- }
- return result, nil
-}
-
-type agentKeyringSigner struct {
- agent *client
- pub ssh.PublicKey
-}
-
-func (s *agentKeyringSigner) PublicKey() ssh.PublicKey {
- return s.pub
-}
-
-func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
- // The agent has its own entropy source, so the rand argument is ignored.
- return s.agent.Sign(s.pub, data)
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/forward.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/forward.go
deleted file mode 100644
index fd24ba900..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/forward.go
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package agent
-
-import (
- "errors"
- "io"
- "net"
- "sync"
-
- "golang.org/x/crypto/ssh"
-)
-
-// RequestAgentForwarding sets up agent forwarding for the session.
-// ForwardToAgent or ForwardToRemote should be called to route
-// the authentication requests.
-func RequestAgentForwarding(session *ssh.Session) error {
- ok, err := session.SendRequest("auth-agent-req@openssh.com", true, nil)
- if err != nil {
- return err
- }
- if !ok {
- return errors.New("forwarding request denied")
- }
- return nil
-}
-
-// ForwardToAgent routes authentication requests to the given keyring.
-func ForwardToAgent(client *ssh.Client, keyring Agent) error {
- channels := client.HandleChannelOpen(channelType)
- if channels == nil {
- return errors.New("agent: already have handler for " + channelType)
- }
-
- go func() {
- for ch := range channels {
- channel, reqs, err := ch.Accept()
- if err != nil {
- continue
- }
- go ssh.DiscardRequests(reqs)
- go func() {
- ServeAgent(keyring, channel)
- channel.Close()
- }()
- }
- }()
- return nil
-}
-
-const channelType = "auth-agent@openssh.com"
-
-// ForwardToRemote routes authentication requests to the ssh-agent
-// process serving on the given unix socket.
-func ForwardToRemote(client *ssh.Client, addr string) error {
- channels := client.HandleChannelOpen(channelType)
- if channels == nil {
- return errors.New("agent: already have handler for " + channelType)
- }
- conn, err := net.Dial("unix", addr)
- if err != nil {
- return err
- }
- conn.Close()
-
- go func() {
- for ch := range channels {
- channel, reqs, err := ch.Accept()
- if err != nil {
- continue
- }
- go ssh.DiscardRequests(reqs)
- go forwardUnixSocket(channel, addr)
- }
- }()
- return nil
-}
-
-func forwardUnixSocket(channel ssh.Channel, addr string) {
- conn, err := net.Dial("unix", addr)
- if err != nil {
- return
- }
-
- var wg sync.WaitGroup
- wg.Add(2)
- go func() {
- io.Copy(conn, channel)
- conn.(*net.UnixConn).CloseWrite()
- wg.Done()
- }()
- go func() {
- io.Copy(channel, conn)
- channel.CloseWrite()
- wg.Done()
- }()
-
- wg.Wait()
- conn.Close()
- channel.Close()
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/keyring.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/keyring.go
deleted file mode 100644
index 8ac20090a..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/keyring.go
+++ /dev/null
@@ -1,183 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package agent
-
-import (
- "bytes"
- "crypto/rand"
- "crypto/subtle"
- "errors"
- "fmt"
- "sync"
-
- "golang.org/x/crypto/ssh"
-)
-
-type privKey struct {
- signer ssh.Signer
- comment string
-}
-
-type keyring struct {
- mu sync.Mutex
- keys []privKey
-
- locked bool
- passphrase []byte
-}
-
-var errLocked = errors.New("agent: locked")
-
-// NewKeyring returns an Agent that holds keys in memory. It is safe
-// for concurrent use by multiple goroutines.
-func NewKeyring() Agent {
- return &keyring{}
-}
-
-// RemoveAll removes all identities.
-func (r *keyring) RemoveAll() error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return errLocked
- }
-
- r.keys = nil
- return nil
-}
-
-// Remove removes all identities with the given public key.
-func (r *keyring) Remove(key ssh.PublicKey) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return errLocked
- }
-
- want := key.Marshal()
- found := false
- for i := 0; i < len(r.keys); {
- if bytes.Equal(r.keys[i].signer.PublicKey().Marshal(), want) {
- found = true
- r.keys[i] = r.keys[len(r.keys)-1]
- r.keys = r.keys[len(r.keys)-1:]
- continue
- } else {
- i++
- }
- }
-
- if !found {
- return errors.New("agent: key not found")
- }
- return nil
-}
-
-// Lock locks the agent. Sign and Remove will fail, and List will empty an empty list.
-func (r *keyring) Lock(passphrase []byte) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return errLocked
- }
-
- r.locked = true
- r.passphrase = passphrase
- return nil
-}
-
-// Unlock undoes the effect of Lock
-func (r *keyring) Unlock(passphrase []byte) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if !r.locked {
- return errors.New("agent: not locked")
- }
- if len(passphrase) != len(r.passphrase) || 1 != subtle.ConstantTimeCompare(passphrase, r.passphrase) {
- return fmt.Errorf("agent: incorrect passphrase")
- }
-
- r.locked = false
- r.passphrase = nil
- return nil
-}
-
-// List returns the identities known to the agent.
-func (r *keyring) List() ([]*Key, error) {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- // section 2.7: locked agents return empty.
- return nil, nil
- }
-
- var ids []*Key
- for _, k := range r.keys {
- pub := k.signer.PublicKey()
- ids = append(ids, &Key{
- Format: pub.Type(),
- Blob: pub.Marshal(),
- Comment: k.comment})
- }
- return ids, nil
-}
-
-// Insert adds a private key to the keyring. If a certificate
-// is given, that certificate is added as public key.
-func (r *keyring) Add(priv interface{}, cert *ssh.Certificate, comment string) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return errLocked
- }
- signer, err := ssh.NewSignerFromKey(priv)
-
- if err != nil {
- return err
- }
-
- if cert != nil {
- signer, err = ssh.NewCertSigner(cert, signer)
- if err != nil {
- return err
- }
- }
-
- r.keys = append(r.keys, privKey{signer, comment})
-
- return nil
-}
-
-// Sign returns a signature for the data.
-func (r *keyring) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return nil, errLocked
- }
-
- wanted := key.Marshal()
- for _, k := range r.keys {
- if bytes.Equal(k.signer.PublicKey().Marshal(), wanted) {
- return k.signer.Sign(rand.Reader, data)
- }
- }
- return nil, errors.New("not found")
-}
-
-// Signers returns signers for all the known keys.
-func (r *keyring) Signers() ([]ssh.Signer, error) {
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.locked {
- return nil, errLocked
- }
-
- s := make([]ssh.Signer, 0, len(r.keys))
- for _, k := range r.keys {
- s = append(s, k.signer)
- }
- return s, nil
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server.go
deleted file mode 100644
index be9df0eb0..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/server.go
+++ /dev/null
@@ -1,209 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package agent
-
-import (
- "crypto/rsa"
- "encoding/binary"
- "fmt"
- "io"
- "log"
- "math/big"
-
- "golang.org/x/crypto/ssh"
-)
-
-// Server wraps an Agent and uses it to implement the agent side of
-// the SSH-agent, wire protocol.
-type server struct {
- agent Agent
-}
-
-func (s *server) processRequestBytes(reqData []byte) []byte {
- rep, err := s.processRequest(reqData)
- if err != nil {
- if err != errLocked {
- // TODO(hanwen): provide better logging interface?
- log.Printf("agent %d: %v", reqData[0], err)
- }
- return []byte{agentFailure}
- }
-
- if err == nil && rep == nil {
- return []byte{agentSuccess}
- }
-
- return ssh.Marshal(rep)
-}
-
-func marshalKey(k *Key) []byte {
- var record struct {
- Blob []byte
- Comment string
- }
- record.Blob = k.Marshal()
- record.Comment = k.Comment
-
- return ssh.Marshal(&record)
-}
-
-type agentV1IdentityMsg struct {
- Numkeys uint32 `sshtype:"2"`
-}
-
-type agentRemoveIdentityMsg struct {
- KeyBlob []byte `sshtype:"18"`
-}
-
-type agentLockMsg struct {
- Passphrase []byte `sshtype:"22"`
-}
-
-type agentUnlockMsg struct {
- Passphrase []byte `sshtype:"23"`
-}
-
-func (s *server) processRequest(data []byte) (interface{}, error) {
- switch data[0] {
- case agentRequestV1Identities:
- return &agentV1IdentityMsg{0}, nil
- case agentRemoveIdentity:
- var req agentRemoveIdentityMsg
- if err := ssh.Unmarshal(data, &req); err != nil {
- return nil, err
- }
-
- var wk wireKey
- if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil {
- return nil, err
- }
-
- return nil, s.agent.Remove(&Key{Format: wk.Format, Blob: req.KeyBlob})
-
- case agentRemoveAllIdentities:
- return nil, s.agent.RemoveAll()
-
- case agentLock:
- var req agentLockMsg
- if err := ssh.Unmarshal(data, &req); err != nil {
- return nil, err
- }
-
- return nil, s.agent.Lock(req.Passphrase)
-
- case agentUnlock:
- var req agentLockMsg
- if err := ssh.Unmarshal(data, &req); err != nil {
- return nil, err
- }
- return nil, s.agent.Unlock(req.Passphrase)
-
- case agentSignRequest:
- var req signRequestAgentMsg
- if err := ssh.Unmarshal(data, &req); err != nil {
- return nil, err
- }
-
- var wk wireKey
- if err := ssh.Unmarshal(req.KeyBlob, &wk); err != nil {
- return nil, err
- }
-
- k := &Key{
- Format: wk.Format,
- Blob: req.KeyBlob,
- }
-
- sig, err := s.agent.Sign(k, req.Data) // TODO(hanwen): flags.
- if err != nil {
- return nil, err
- }
- return &signResponseAgentMsg{SigBlob: ssh.Marshal(sig)}, nil
- case agentRequestIdentities:
- keys, err := s.agent.List()
- if err != nil {
- return nil, err
- }
-
- rep := identitiesAnswerAgentMsg{
- NumKeys: uint32(len(keys)),
- }
- for _, k := range keys {
- rep.Keys = append(rep.Keys, marshalKey(k)...)
- }
- return rep, nil
- case agentAddIdentity:
- return nil, s.insertIdentity(data)
- }
-
- return nil, fmt.Errorf("unknown opcode %d", data[0])
-}
-
-func (s *server) insertIdentity(req []byte) error {
- var record struct {
- Type string `sshtype:"17"`
- Rest []byte `ssh:"rest"`
- }
- if err := ssh.Unmarshal(req, &record); err != nil {
- return err
- }
-
- switch record.Type {
- case ssh.KeyAlgoRSA:
- var k rsaKeyMsg
- if err := ssh.Unmarshal(req, &k); err != nil {
- return err
- }
-
- priv := rsa.PrivateKey{
- PublicKey: rsa.PublicKey{
- E: int(k.E.Int64()),
- N: k.N,
- },
- D: k.D,
- Primes: []*big.Int{k.P, k.Q},
- }
- priv.Precompute()
-
- return s.agent.Add(&priv, nil, k.Comments)
- }
- return fmt.Errorf("not implemented: %s", record.Type)
-}
-
-// ServeAgent serves the agent protocol on the given connection. It
-// returns when an I/O error occurs.
-func ServeAgent(agent Agent, c io.ReadWriter) error {
- s := &server{agent}
-
- var length [4]byte
- for {
- if _, err := io.ReadFull(c, length[:]); err != nil {
- return err
- }
- l := binary.BigEndian.Uint32(length[:])
- if l > maxAgentResponseBytes {
- // We also cap requests.
- return fmt.Errorf("agent: request too large: %d", l)
- }
-
- req := make([]byte, l)
- if _, err := io.ReadFull(c, req); err != nil {
- return err
- }
-
- repData := s.processRequestBytes(req)
- if len(repData) > maxAgentResponseBytes {
- return fmt.Errorf("agent: reply too large: %d bytes", len(repData))
- }
-
- binary.BigEndian.PutUint32(length[:], uint32(len(repData)))
- if _, err := c.Write(length[:]); err != nil {
- return err
- }
- if _, err := c.Write(repData); err != nil {
- return err
- }
- }
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal.go
deleted file mode 100644
index 741eeb13f..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/terminal.go
+++ /dev/null
@@ -1,892 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package terminal
-
-import (
- "bytes"
- "io"
- "sync"
- "unicode/utf8"
-)
-
-// EscapeCodes contains escape sequences that can be written to the terminal in
-// order to achieve different styles of text.
-type EscapeCodes struct {
- // Foreground colors
- Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
-
- // Reset all attributes
- Reset []byte
-}
-
-var vt100EscapeCodes = EscapeCodes{
- Black: []byte{keyEscape, '[', '3', '0', 'm'},
- Red: []byte{keyEscape, '[', '3', '1', 'm'},
- Green: []byte{keyEscape, '[', '3', '2', 'm'},
- Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
- Blue: []byte{keyEscape, '[', '3', '4', 'm'},
- Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
- Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
- White: []byte{keyEscape, '[', '3', '7', 'm'},
-
- Reset: []byte{keyEscape, '[', '0', 'm'},
-}
-
-// Terminal contains the state for running a VT100 terminal that is capable of
-// reading lines of input.
-type Terminal struct {
- // AutoCompleteCallback, if non-null, is called for each keypress with
- // the full input line and the current position of the cursor (in
- // bytes, as an index into |line|). If it returns ok=false, the key
- // press is processed normally. Otherwise it returns a replacement line
- // and the new cursor position.
- AutoCompleteCallback func(line string, pos int, key rune) (newLine string, newPos int, ok bool)
-
- // Escape contains a pointer to the escape codes for this terminal.
- // It's always a valid pointer, although the escape codes themselves
- // may be empty if the terminal doesn't support them.
- Escape *EscapeCodes
-
- // lock protects the terminal and the state in this object from
- // concurrent processing of a key press and a Write() call.
- lock sync.Mutex
-
- c io.ReadWriter
- prompt []rune
-
- // line is the current line being entered.
- line []rune
- // pos is the logical position of the cursor in line
- pos int
- // echo is true if local echo is enabled
- echo bool
- // pasteActive is true iff there is a bracketed paste operation in
- // progress.
- pasteActive bool
-
- // cursorX contains the current X value of the cursor where the left
- // edge is 0. cursorY contains the row number where the first row of
- // the current line is 0.
- cursorX, cursorY int
- // maxLine is the greatest value of cursorY so far.
- maxLine int
-
- termWidth, termHeight int
-
- // outBuf contains the terminal data to be sent.
- outBuf []byte
- // remainder contains the remainder of any partial key sequences after
- // a read. It aliases into inBuf.
- remainder []byte
- inBuf [256]byte
-
- // history contains previously entered commands so that they can be
- // accessed with the up and down keys.
- history stRingBuffer
- // historyIndex stores the currently accessed history entry, where zero
- // means the immediately previous entry.
- historyIndex int
- // When navigating up and down the history it's possible to return to
- // the incomplete, initial line. That value is stored in
- // historyPending.
- historyPending string
-}
-
-// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
-// a local terminal, that terminal must first have been put into raw mode.
-// prompt is a string that is written at the start of each input line (i.e.
-// "> ").
-func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
- return &Terminal{
- Escape: &vt100EscapeCodes,
- c: c,
- prompt: []rune(prompt),
- termWidth: 80,
- termHeight: 24,
- echo: true,
- historyIndex: -1,
- }
-}
-
-const (
- keyCtrlD = 4
- keyCtrlU = 21
- keyEnter = '\r'
- keyEscape = 27
- keyBackspace = 127
- keyUnknown = 0xd800 /* UTF-16 surrogate area */ + iota
- keyUp
- keyDown
- keyLeft
- keyRight
- keyAltLeft
- keyAltRight
- keyHome
- keyEnd
- keyDeleteWord
- keyDeleteLine
- keyClearScreen
- keyPasteStart
- keyPasteEnd
-)
-
-var pasteStart = []byte{keyEscape, '[', '2', '0', '0', '~'}
-var pasteEnd = []byte{keyEscape, '[', '2', '0', '1', '~'}
-
-// bytesToKey tries to parse a key sequence from b. If successful, it returns
-// the key and the remainder of the input. Otherwise it returns utf8.RuneError.
-func bytesToKey(b []byte, pasteActive bool) (rune, []byte) {
- if len(b) == 0 {
- return utf8.RuneError, nil
- }
-
- if !pasteActive {
- switch b[0] {
- case 1: // ^A
- return keyHome, b[1:]
- case 5: // ^E
- return keyEnd, b[1:]
- case 8: // ^H
- return keyBackspace, b[1:]
- case 11: // ^K
- return keyDeleteLine, b[1:]
- case 12: // ^L
- return keyClearScreen, b[1:]
- case 23: // ^W
- return keyDeleteWord, b[1:]
- }
- }
-
- if b[0] != keyEscape {
- if !utf8.FullRune(b) {
- return utf8.RuneError, b
- }
- r, l := utf8.DecodeRune(b)
- return r, b[l:]
- }
-
- if !pasteActive && len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
- switch b[2] {
- case 'A':
- return keyUp, b[3:]
- case 'B':
- return keyDown, b[3:]
- case 'C':
- return keyRight, b[3:]
- case 'D':
- return keyLeft, b[3:]
- case 'H':
- return keyHome, b[3:]
- case 'F':
- return keyEnd, b[3:]
- }
- }
-
- if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
- switch b[5] {
- case 'C':
- return keyAltRight, b[6:]
- case 'D':
- return keyAltLeft, b[6:]
- }
- }
-
- if !pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteStart) {
- return keyPasteStart, b[6:]
- }
-
- if pasteActive && len(b) >= 6 && bytes.Equal(b[:6], pasteEnd) {
- return keyPasteEnd, b[6:]
- }
-
- // If we get here then we have a key that we don't recognise, or a
- // partial sequence. It's not clear how one should find the end of a
- // sequence without knowing them all, but it seems that [a-zA-Z~] only
- // appears at the end of a sequence.
- for i, c := range b[0:] {
- if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '~' {
- return keyUnknown, b[i+1:]
- }
- }
-
- return utf8.RuneError, b
-}
-
-// queue appends data to the end of t.outBuf
-func (t *Terminal) queue(data []rune) {
- t.outBuf = append(t.outBuf, []byte(string(data))...)
-}
-
-var eraseUnderCursor = []rune{' ', keyEscape, '[', 'D'}
-var space = []rune{' '}
-
-func isPrintable(key rune) bool {
- isInSurrogateArea := key >= 0xd800 && key <= 0xdbff
- return key >= 32 && !isInSurrogateArea
-}
-
-// moveCursorToPos appends data to t.outBuf which will move the cursor to the
-// given, logical position in the text.
-func (t *Terminal) moveCursorToPos(pos int) {
- if !t.echo {
- return
- }
-
- x := visualLength(t.prompt) + pos
- y := x / t.termWidth
- x = x % t.termWidth
-
- up := 0
- if y < t.cursorY {
- up = t.cursorY - y
- }
-
- down := 0
- if y > t.cursorY {
- down = y - t.cursorY
- }
-
- left := 0
- if x < t.cursorX {
- left = t.cursorX - x
- }
-
- right := 0
- if x > t.cursorX {
- right = x - t.cursorX
- }
-
- t.cursorX = x
- t.cursorY = y
- t.move(up, down, left, right)
-}
-
-func (t *Terminal) move(up, down, left, right int) {
- movement := make([]rune, 3*(up+down+left+right))
- m := movement
- for i := 0; i < up; i++ {
- m[0] = keyEscape
- m[1] = '['
- m[2] = 'A'
- m = m[3:]
- }
- for i := 0; i < down; i++ {
- m[0] = keyEscape
- m[1] = '['
- m[2] = 'B'
- m = m[3:]
- }
- for i := 0; i < left; i++ {
- m[0] = keyEscape
- m[1] = '['
- m[2] = 'D'
- m = m[3:]
- }
- for i := 0; i < right; i++ {
- m[0] = keyEscape
- m[1] = '['
- m[2] = 'C'
- m = m[3:]
- }
-
- t.queue(movement)
-}
-
-func (t *Terminal) clearLineToRight() {
- op := []rune{keyEscape, '[', 'K'}
- t.queue(op)
-}
-
-const maxLineLength = 4096
-
-func (t *Terminal) setLine(newLine []rune, newPos int) {
- if t.echo {
- t.moveCursorToPos(0)
- t.writeLine(newLine)
- for i := len(newLine); i < len(t.line); i++ {
- t.writeLine(space)
- }
- t.moveCursorToPos(newPos)
- }
- t.line = newLine
- t.pos = newPos
-}
-
-func (t *Terminal) advanceCursor(places int) {
- t.cursorX += places
- t.cursorY += t.cursorX / t.termWidth
- if t.cursorY > t.maxLine {
- t.maxLine = t.cursorY
- }
- t.cursorX = t.cursorX % t.termWidth
-
- if places > 0 && t.cursorX == 0 {
- // Normally terminals will advance the current position
- // when writing a character. But that doesn't happen
- // for the last character in a line. However, when
- // writing a character (except a new line) that causes
- // a line wrap, the position will be advanced two
- // places.
- //
- // So, if we are stopping at the end of a line, we
- // need to write a newline so that our cursor can be
- // advanced to the next line.
- t.outBuf = append(t.outBuf, '\n')
- }
-}
-
-func (t *Terminal) eraseNPreviousChars(n int) {
- if n == 0 {
- return
- }
-
- if t.pos < n {
- n = t.pos
- }
- t.pos -= n
- t.moveCursorToPos(t.pos)
-
- copy(t.line[t.pos:], t.line[n+t.pos:])
- t.line = t.line[:len(t.line)-n]
- if t.echo {
- t.writeLine(t.line[t.pos:])
- for i := 0; i < n; i++ {
- t.queue(space)
- }
- t.advanceCursor(n)
- t.moveCursorToPos(t.pos)
- }
-}
-
-// countToLeftWord returns then number of characters from the cursor to the
-// start of the previous word.
-func (t *Terminal) countToLeftWord() int {
- if t.pos == 0 {
- return 0
- }
-
- pos := t.pos - 1
- for pos > 0 {
- if t.line[pos] != ' ' {
- break
- }
- pos--
- }
- for pos > 0 {
- if t.line[pos] == ' ' {
- pos++
- break
- }
- pos--
- }
-
- return t.pos - pos
-}
-
-// countToRightWord returns then number of characters from the cursor to the
-// start of the next word.
-func (t *Terminal) countToRightWord() int {
- pos := t.pos
- for pos < len(t.line) {
- if t.line[pos] == ' ' {
- break
- }
- pos++
- }
- for pos < len(t.line) {
- if t.line[pos] != ' ' {
- break
- }
- pos++
- }
- return pos - t.pos
-}
-
-// visualLength returns the number of visible glyphs in s.
-func visualLength(runes []rune) int {
- inEscapeSeq := false
- length := 0
-
- for _, r := range runes {
- switch {
- case inEscapeSeq:
- if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') {
- inEscapeSeq = false
- }
- case r == '\x1b':
- inEscapeSeq = true
- default:
- length++
- }
- }
-
- return length
-}
-
-// handleKey processes the given key and, optionally, returns a line of text
-// that the user has entered.
-func (t *Terminal) handleKey(key rune) (line string, ok bool) {
- if t.pasteActive && key != keyEnter {
- t.addKeyToLine(key)
- return
- }
-
- switch key {
- case keyBackspace:
- if t.pos == 0 {
- return
- }
- t.eraseNPreviousChars(1)
- case keyAltLeft:
- // move left by a word.
- t.pos -= t.countToLeftWord()
- t.moveCursorToPos(t.pos)
- case keyAltRight:
- // move right by a word.
- t.pos += t.countToRightWord()
- t.moveCursorToPos(t.pos)
- case keyLeft:
- if t.pos == 0 {
- return
- }
- t.pos--
- t.moveCursorToPos(t.pos)
- case keyRight:
- if t.pos == len(t.line) {
- return
- }
- t.pos++
- t.moveCursorToPos(t.pos)
- case keyHome:
- if t.pos == 0 {
- return
- }
- t.pos = 0
- t.moveCursorToPos(t.pos)
- case keyEnd:
- if t.pos == len(t.line) {
- return
- }
- t.pos = len(t.line)
- t.moveCursorToPos(t.pos)
- case keyUp:
- entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
- if !ok {
- return "", false
- }
- if t.historyIndex == -1 {
- t.historyPending = string(t.line)
- }
- t.historyIndex++
- runes := []rune(entry)
- t.setLine(runes, len(runes))
- case keyDown:
- switch t.historyIndex {
- case -1:
- return
- case 0:
- runes := []rune(t.historyPending)
- t.setLine(runes, len(runes))
- t.historyIndex--
- default:
- entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
- if ok {
- t.historyIndex--
- runes := []rune(entry)
- t.setLine(runes, len(runes))
- }
- }
- case keyEnter:
- t.moveCursorToPos(len(t.line))
- t.queue([]rune("\r\n"))
- line = string(t.line)
- ok = true
- t.line = t.line[:0]
- t.pos = 0
- t.cursorX = 0
- t.cursorY = 0
- t.maxLine = 0
- case keyDeleteWord:
- // Delete zero or more spaces and then one or more characters.
- t.eraseNPreviousChars(t.countToLeftWord())
- case keyDeleteLine:
- // Delete everything from the current cursor position to the
- // end of line.
- for i := t.pos; i < len(t.line); i++ {
- t.queue(space)
- t.advanceCursor(1)
- }
- t.line = t.line[:t.pos]
- t.moveCursorToPos(t.pos)
- case keyCtrlD:
- // Erase the character under the current position.
- // The EOF case when the line is empty is handled in
- // readLine().
- if t.pos < len(t.line) {
- t.pos++
- t.eraseNPreviousChars(1)
- }
- case keyCtrlU:
- t.eraseNPreviousChars(t.pos)
- case keyClearScreen:
- // Erases the screen and moves the cursor to the home position.
- t.queue([]rune("\x1b[2J\x1b[H"))
- t.queue(t.prompt)
- t.cursorX, t.cursorY = 0, 0
- t.advanceCursor(visualLength(t.prompt))
- t.setLine(t.line, t.pos)
- default:
- if t.AutoCompleteCallback != nil {
- prefix := string(t.line[:t.pos])
- suffix := string(t.line[t.pos:])
-
- t.lock.Unlock()
- newLine, newPos, completeOk := t.AutoCompleteCallback(prefix+suffix, len(prefix), key)
- t.lock.Lock()
-
- if completeOk {
- t.setLine([]rune(newLine), utf8.RuneCount([]byte(newLine)[:newPos]))
- return
- }
- }
- if !isPrintable(key) {
- return
- }
- if len(t.line) == maxLineLength {
- return
- }
- t.addKeyToLine(key)
- }
- return
-}
-
-// addKeyToLine inserts the given key at the current position in the current
-// line.
-func (t *Terminal) addKeyToLine(key rune) {
- if len(t.line) == cap(t.line) {
- newLine := make([]rune, len(t.line), 2*(1+len(t.line)))
- copy(newLine, t.line)
- t.line = newLine
- }
- t.line = t.line[:len(t.line)+1]
- copy(t.line[t.pos+1:], t.line[t.pos:])
- t.line[t.pos] = key
- if t.echo {
- t.writeLine(t.line[t.pos:])
- }
- t.pos++
- t.moveCursorToPos(t.pos)
-}
-
-func (t *Terminal) writeLine(line []rune) {
- for len(line) != 0 {
- remainingOnLine := t.termWidth - t.cursorX
- todo := len(line)
- if todo > remainingOnLine {
- todo = remainingOnLine
- }
- t.queue(line[:todo])
- t.advanceCursor(visualLength(line[:todo]))
- line = line[todo:]
- }
-}
-
-func (t *Terminal) Write(buf []byte) (n int, err error) {
- t.lock.Lock()
- defer t.lock.Unlock()
-
- if t.cursorX == 0 && t.cursorY == 0 {
- // This is the easy case: there's nothing on the screen that we
- // have to move out of the way.
- return t.c.Write(buf)
- }
-
- // We have a prompt and possibly user input on the screen. We
- // have to clear it first.
- t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
- t.cursorX = 0
- t.clearLineToRight()
-
- for t.cursorY > 0 {
- t.move(1 /* up */, 0, 0, 0)
- t.cursorY--
- t.clearLineToRight()
- }
-
- if _, err = t.c.Write(t.outBuf); err != nil {
- return
- }
- t.outBuf = t.outBuf[:0]
-
- if n, err = t.c.Write(buf); err != nil {
- return
- }
-
- t.writeLine(t.prompt)
- if t.echo {
- t.writeLine(t.line)
- }
-
- t.moveCursorToPos(t.pos)
-
- if _, err = t.c.Write(t.outBuf); err != nil {
- return
- }
- t.outBuf = t.outBuf[:0]
- return
-}
-
-// ReadPassword temporarily changes the prompt and reads a password, without
-// echo, from the terminal.
-func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
- t.lock.Lock()
- defer t.lock.Unlock()
-
- oldPrompt := t.prompt
- t.prompt = []rune(prompt)
- t.echo = false
-
- line, err = t.readLine()
-
- t.prompt = oldPrompt
- t.echo = true
-
- return
-}
-
-// ReadLine returns a line of input from the terminal.
-func (t *Terminal) ReadLine() (line string, err error) {
- t.lock.Lock()
- defer t.lock.Unlock()
-
- return t.readLine()
-}
-
-func (t *Terminal) readLine() (line string, err error) {
- // t.lock must be held at this point
-
- if t.cursorX == 0 && t.cursorY == 0 {
- t.writeLine(t.prompt)
- t.c.Write(t.outBuf)
- t.outBuf = t.outBuf[:0]
- }
-
- lineIsPasted := t.pasteActive
-
- for {
- rest := t.remainder
- lineOk := false
- for !lineOk {
- var key rune
- key, rest = bytesToKey(rest, t.pasteActive)
- if key == utf8.RuneError {
- break
- }
- if !t.pasteActive {
- if key == keyCtrlD {
- if len(t.line) == 0 {
- return "", io.EOF
- }
- }
- if key == keyPasteStart {
- t.pasteActive = true
- if len(t.line) == 0 {
- lineIsPasted = true
- }
- continue
- }
- } else if key == keyPasteEnd {
- t.pasteActive = false
- continue
- }
- if !t.pasteActive {
- lineIsPasted = false
- }
- line, lineOk = t.handleKey(key)
- }
- if len(rest) > 0 {
- n := copy(t.inBuf[:], rest)
- t.remainder = t.inBuf[:n]
- } else {
- t.remainder = nil
- }
- t.c.Write(t.outBuf)
- t.outBuf = t.outBuf[:0]
- if lineOk {
- if t.echo {
- t.historyIndex = -1
- t.history.Add(line)
- }
- if lineIsPasted {
- err = ErrPasteIndicator
- }
- return
- }
-
- // t.remainder is a slice at the beginning of t.inBuf
- // containing a partial key sequence
- readBuf := t.inBuf[len(t.remainder):]
- var n int
-
- t.lock.Unlock()
- n, err = t.c.Read(readBuf)
- t.lock.Lock()
-
- if err != nil {
- return
- }
-
- t.remainder = t.inBuf[:n+len(t.remainder)]
- }
-
- panic("unreachable") // for Go 1.0.
-}
-
-// SetPrompt sets the prompt to be used when reading subsequent lines.
-func (t *Terminal) SetPrompt(prompt string) {
- t.lock.Lock()
- defer t.lock.Unlock()
-
- t.prompt = []rune(prompt)
-}
-
-func (t *Terminal) clearAndRepaintLinePlusNPrevious(numPrevLines int) {
- // Move cursor to column zero at the start of the line.
- t.move(t.cursorY, 0, t.cursorX, 0)
- t.cursorX, t.cursorY = 0, 0
- t.clearLineToRight()
- for t.cursorY < numPrevLines {
- // Move down a line
- t.move(0, 1, 0, 0)
- t.cursorY++
- t.clearLineToRight()
- }
- // Move back to beginning.
- t.move(t.cursorY, 0, 0, 0)
- t.cursorX, t.cursorY = 0, 0
-
- t.queue(t.prompt)
- t.advanceCursor(visualLength(t.prompt))
- t.writeLine(t.line)
- t.moveCursorToPos(t.pos)
-}
-
-func (t *Terminal) SetSize(width, height int) error {
- t.lock.Lock()
- defer t.lock.Unlock()
-
- if width == 0 {
- width = 1
- }
-
- oldWidth := t.termWidth
- t.termWidth, t.termHeight = width, height
-
- switch {
- case width == oldWidth:
- // If the width didn't change then nothing else needs to be
- // done.
- return nil
- case len(t.line) == 0 && t.cursorX == 0 && t.cursorY == 0:
- // If there is nothing on current line and no prompt printed,
- // just do nothing
- return nil
- case width < oldWidth:
- // Some terminals (e.g. xterm) will truncate lines that were
- // too long when shinking. Others, (e.g. gnome-terminal) will
- // attempt to wrap them. For the former, repainting t.maxLine
- // works great, but that behaviour goes badly wrong in the case
- // of the latter because they have doubled every full line.
-
- // We assume that we are working on a terminal that wraps lines
- // and adjust the cursor position based on every previous line
- // wrapping and turning into two. This causes the prompt on
- // xterms to move upwards, which isn't great, but it avoids a
- // huge mess with gnome-terminal.
- if t.cursorX >= t.termWidth {
- t.cursorX = t.termWidth - 1
- }
- t.cursorY *= 2
- t.clearAndRepaintLinePlusNPrevious(t.maxLine * 2)
- case width > oldWidth:
- // If the terminal expands then our position calculations will
- // be wrong in the future because we think the cursor is
- // |t.pos| chars into the string, but there will be a gap at
- // the end of any wrapped line.
- //
- // But the position will actually be correct until we move, so
- // we can move back to the beginning and repaint everything.
- t.clearAndRepaintLinePlusNPrevious(t.maxLine)
- }
-
- _, err := t.c.Write(t.outBuf)
- t.outBuf = t.outBuf[:0]
- return err
-}
-
-type pasteIndicatorError struct{}
-
-func (pasteIndicatorError) Error() string {
- return "terminal: ErrPasteIndicator not correctly handled"
-}
-
-// ErrPasteIndicator may be returned from ReadLine as the error, in addition
-// to valid line data. It indicates that bracketed paste mode is enabled and
-// that the returned line consists only of pasted data. Programs may wish to
-// interpret pasted data more literally than typed data.
-var ErrPasteIndicator = pasteIndicatorError{}
-
-// SetBracketedPasteMode requests that the terminal bracket paste operations
-// with markers. Not all terminals support this but, if it is supported, then
-// enabling this mode will stop any autocomplete callback from running due to
-// pastes. Additionally, any lines that are completely pasted will be returned
-// from ReadLine with the error set to ErrPasteIndicator.
-func (t *Terminal) SetBracketedPasteMode(on bool) {
- if on {
- io.WriteString(t.c, "\x1b[?2004h")
- } else {
- io.WriteString(t.c, "\x1b[?2004l")
- }
-}
-
-// stRingBuffer is a ring buffer of strings.
-type stRingBuffer struct {
- // entries contains max elements.
- entries []string
- max int
- // head contains the index of the element most recently added to the ring.
- head int
- // size contains the number of elements in the ring.
- size int
-}
-
-func (s *stRingBuffer) Add(a string) {
- if s.entries == nil {
- const defaultNumEntries = 100
- s.entries = make([]string, defaultNumEntries)
- s.max = defaultNumEntries
- }
-
- s.head = (s.head + 1) % s.max
- s.entries[s.head] = a
- if s.size < s.max {
- s.size++
- }
-}
-
-// NthPreviousEntry returns the value passed to the nth previous call to Add.
-// If n is zero then the immediately prior value is returned, if one, then the
-// next most recent, and so on. If such an element doesn't exist then ok is
-// false.
-func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
- if n >= s.size {
- return "", false
- }
- index := s.head - n
- if index < 0 {
- index += s.max
- }
- return s.entries[index], true
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go
deleted file mode 100644
index 0763c9a97..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd
-
-// Package terminal provides support functions for dealing with terminals, as
-// commonly found on UNIX systems.
-//
-// Putting a terminal into raw mode is the most common requirement:
-//
-// oldState, err := terminal.MakeRaw(0)
-// if err != nil {
-// panic(err)
-// }
-// defer terminal.Restore(0, oldState)
-package terminal
-
-import (
- "io"
- "syscall"
- "unsafe"
-)
-
-// State contains the state of a terminal.
-type State struct {
- termios syscall.Termios
-}
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(fd int) bool {
- var termios syscall.Termios
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
- return err == 0
-}
-
-// MakeRaw put the terminal connected to the given file descriptor into raw
-// mode and returns the previous state of the terminal so that it can be
-// restored.
-func MakeRaw(fd int) (*State, error) {
- var oldState State
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
- return nil, err
- }
-
- newState := oldState.termios
- newState.Iflag &^= syscall.ISTRIP | syscall.INLCR | syscall.ICRNL | syscall.IGNCR | syscall.IXON | syscall.IXOFF
- newState.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.ISIG
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
- return nil, err
- }
-
- return &oldState, nil
-}
-
-// GetState returns the current state of a terminal which may be useful to
-// restore the terminal after a signal.
-func GetState(fd int) (*State, error) {
- var oldState State
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState.termios)), 0, 0, 0); err != 0 {
- return nil, err
- }
-
- return &oldState, nil
-}
-
-// Restore restores the terminal connected to the given file descriptor to a
-// previous state.
-func Restore(fd int, state *State) error {
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&state.termios)), 0, 0, 0)
- return err
-}
-
-// GetSize returns the dimensions of the given terminal.
-func GetSize(fd int) (width, height int, err error) {
- var dimensions [4]uint16
-
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&dimensions)), 0, 0, 0); err != 0 {
- return -1, -1, err
- }
- return int(dimensions[1]), int(dimensions[0]), nil
-}
-
-// ReadPassword reads a line of input from a terminal without local echo. This
-// is commonly used for inputting passwords and other sensitive data. The slice
-// returned does not include the \n.
-func ReadPassword(fd int) ([]byte, error) {
- var oldState syscall.Termios
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
- return nil, err
- }
-
- newState := oldState
- newState.Lflag &^= syscall.ECHO
- newState.Lflag |= syscall.ICANON | syscall.ISIG
- newState.Iflag |= syscall.ICRNL
- if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
- return nil, err
- }
-
- defer func() {
- syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0)
- }()
-
- var buf [16]byte
- var ret []byte
- for {
- n, err := syscall.Read(fd, buf[:])
- if err != nil {
- return nil, err
- }
- if n == 0 {
- if len(ret) == 0 {
- return nil, io.EOF
- }
- break
- }
- if buf[n-1] == '\n' {
- n--
- }
- ret = append(ret, buf[:n]...)
- if n < len(buf) {
- break
- }
- }
-
- return ret, nil
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_bsd.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_bsd.go
deleted file mode 100644
index 9c1ffd145..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_bsd.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd netbsd openbsd
-
-package terminal
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TIOCGETA
-const ioctlWriteTermios = syscall.TIOCSETA
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_linux.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_linux.go
deleted file mode 100644
index 5883b22d7..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_linux.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package terminal
-
-// These constants are declared here, rather than importing
-// them from the syscall package as some syscall packages, even
-// on linux, for example gccgo, do not declare them.
-const ioctlReadTermios = 0x5401 // syscall.TCGETS
-const ioctlWriteTermios = 0x5402 // syscall.TCSETS
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_windows.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_windows.go
deleted file mode 100644
index 2dd6c3d97..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util_windows.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build windows
-
-// Package terminal provides support functions for dealing with terminals, as
-// commonly found on UNIX systems.
-//
-// Putting a terminal into raw mode is the most common requirement:
-//
-// oldState, err := terminal.MakeRaw(0)
-// if err != nil {
-// panic(err)
-// }
-// defer terminal.Restore(0, oldState)
-package terminal
-
-import (
- "io"
- "syscall"
- "unsafe"
-)
-
-const (
- enableLineInput = 2
- enableEchoInput = 4
- enableProcessedInput = 1
- enableWindowInput = 8
- enableMouseInput = 16
- enableInsertMode = 32
- enableQuickEditMode = 64
- enableExtendedFlags = 128
- enableAutoPosition = 256
- enableProcessedOutput = 1
- enableWrapAtEolOutput = 2
-)
-
-var kernel32 = syscall.NewLazyDLL("kernel32.dll")
-
-var (
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
- procSetConsoleMode = kernel32.NewProc("SetConsoleMode")
- procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
-)
-
-type (
- short int16
- word uint16
-
- coord struct {
- x short
- y short
- }
- smallRect struct {
- left short
- top short
- right short
- bottom short
- }
- consoleScreenBufferInfo struct {
- size coord
- cursorPosition coord
- attributes word
- window smallRect
- maximumWindowSize coord
- }
-)
-
-type State struct {
- mode uint32
-}
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(fd int) bool {
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
-}
-
-// MakeRaw put the terminal connected to the given file descriptor into raw
-// mode and returns the previous state of the terminal so that it can be
-// restored.
-func MakeRaw(fd int) (*State, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- st &^= (enableEchoInput | enableProcessedInput | enableLineInput | enableProcessedOutput)
- _, _, e = syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(st), 0)
- if e != 0 {
- return nil, error(e)
- }
- return &State{st}, nil
-}
-
-// GetState returns the current state of a terminal which may be useful to
-// restore the terminal after a signal.
-func GetState(fd int) (*State, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- return &State{st}, nil
-}
-
-// Restore restores the terminal connected to the given file descriptor to a
-// previous state.
-func Restore(fd int, state *State) error {
- _, _, err := syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(state.mode), 0)
- return err
-}
-
-// GetSize returns the dimensions of the given terminal.
-func GetSize(fd int) (width, height int, err error) {
- var info consoleScreenBufferInfo
- _, _, e := syscall.Syscall(procGetConsoleScreenBufferInfo.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&info)), 0)
- if e != 0 {
- return 0, 0, error(e)
- }
- return int(info.size.x), int(info.size.y), nil
-}
-
-// ReadPassword reads a line of input from a terminal without local echo. This
-// is commonly used for inputting passwords and other sensitive data. The slice
-// returned does not include the \n.
-func ReadPassword(fd int) ([]byte, error) {
- var st uint32
- _, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- if e != 0 {
- return nil, error(e)
- }
- old := st
-
- st &^= (enableEchoInput)
- st |= (enableProcessedInput | enableLineInput | enableProcessedOutput)
- _, _, e = syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(st), 0)
- if e != 0 {
- return nil, error(e)
- }
-
- defer func() {
- syscall.Syscall(procSetConsoleMode.Addr(), 2, uintptr(fd), uintptr(old), 0)
- }()
-
- var buf [16]byte
- var ret []byte
- for {
- n, err := syscall.Read(syscall.Handle(fd), buf[:])
- if err != nil {
- return nil, err
- }
- if n == 0 {
- if len(ret) == 0 {
- return nil, io.EOF
- }
- break
- }
- if buf[n-1] == '\n' {
- n--
- }
- if n > 0 && buf[n-1] == '\r' {
- n--
- }
- ret = append(ret, buf[:n]...)
- if n < len(buf) {
- break
- }
- }
-
- return ret, nil
-}
diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/doc.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/doc.go
deleted file mode 100644
index 29ad65e96..000000000
--- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/doc.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// This package contains integration tests for the
-// golang.org/x/crypto/ssh package.
-package test
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/.gitignore b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/.gitignore
deleted file mode 100644
index 0de86ddbc..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-h2demo
-h2demo.linux
-client-id.dat
-client-secret.dat
-token.dat
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/Makefile b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/Makefile
deleted file mode 100644
index f5c31ef3e..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/Makefile
+++ /dev/null
@@ -1,8 +0,0 @@
-h2demo.linux: h2demo.go
- GOOS=linux go build --tags=h2demo -o h2demo.linux .
-
-FORCE:
-
-upload: FORCE
- go install golang.org/x/build/cmd/upload
- upload --verbose --osarch=linux-amd64 --tags=h2demo --file=go:golang.org/x/net/http2/h2demo --public http2-demo-server-tls/h2demo
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/README b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/README
deleted file mode 100644
index 212a96f38..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/README
+++ /dev/null
@@ -1,16 +0,0 @@
-
-Client:
- -- Firefox nightly with about:config network.http.spdy.enabled.http2draft set true
- -- Chrome: go to chrome://flags/#enable-spdy4, save and restart (button at bottom)
-
-Make CA:
-$ openssl genrsa -out rootCA.key 2048
-$ openssl req -x509 -new -nodes -key rootCA.key -days 1024 -out rootCA.pem
-... install that to Firefox
-
-Make cert:
-$ openssl genrsa -out server.key 2048
-$ openssl req -new -key server.key -out server.csr
-$ openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500
-
-
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/h2demo.go b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/h2demo.go
deleted file mode 100644
index 8d5e4fd1c..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/h2demo.go
+++ /dev/null
@@ -1,436 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build h2demo
-
-package main
-
-import (
- "bytes"
- "crypto/tls"
- "flag"
- "fmt"
- "hash/crc32"
- "image"
- "image/jpeg"
- "io"
- "io/ioutil"
- "log"
- "net"
- "net/http"
- "path"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "time"
-
- "camlistore.org/pkg/googlestorage"
- "camlistore.org/pkg/singleflight"
- "golang.org/x/net/http2"
-)
-
-var (
- prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")
-
- httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.")
- httpAddr = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.")
-
- hostHTTP = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.")
- hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.")
-)
-
-func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
- io.WriteString(w, `
-
-Go + HTTP/2
-Welcome to the Go language's HTTP/2 demo & interop server.
-Unfortunately, you're not using HTTP/2 right now. To do so:
-
- - Use Firefox Nightly or go to about:config and enable "network.http.spdy.enabled.http2draft"
- - Use Google Chrome Canary and/or go to chrome://flags/#enable-spdy4 to Enable SPDY/4 (Chrome's name for HTTP/2)
-
-See code & instructions for connecting at https://github.com/golang/net/tree/master/http2.
-
-`)
-}
-
-func home(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/" {
- http.NotFound(w, r)
- return
- }
- io.WriteString(w, `
-
-Go + HTTP/2
-
-Welcome to the Go language's HTTP/2 demo & interop server.
-
-Congratulations, you're using HTTP/2 right now.
-
-This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.
-
-
-The code is at golang.org/x/net/http2 and
-is used transparently by the Go standard library from Go 1.6 and later.
-
-
-Contact info: bradfitz@golang.org, or file a bug.
-
-Handlers for testing
-
- - GET /reqinfo to dump the request + headers received
- - GET /clockstream streams the current time every second
- - GET /gophertiles to see a page with a bunch of images
- - GET /file/gopher.png for a small file (does If-Modified-Since, Content-Range, etc)
- - GET /file/go.src.tar.gz for a larger file (~10 MB)
- - GET /redirect to redirect back to / (this page)
- - GET /goroutines to see all active goroutines in this server
- - PUT something to /crc32 to get a count of number of bytes and its CRC-32
-
-
-`)
-}
-
-func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/plain")
- fmt.Fprintf(w, "Method: %s\n", r.Method)
- fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
- fmt.Fprintf(w, "Host: %s\n", r.Host)
- fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
- fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
- fmt.Fprintf(w, "URL: %#v\n", r.URL)
- fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
- fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
- fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
- fmt.Fprintf(w, "\nHeaders:\n")
- r.Header.Write(w)
-}
-
-func crcHandler(w http.ResponseWriter, r *http.Request) {
- if r.Method != "PUT" {
- http.Error(w, "PUT required.", 400)
- return
- }
- crc := crc32.NewIEEE()
- n, err := io.Copy(crc, r.Body)
- if err == nil {
- w.Header().Set("Content-Type", "text/plain")
- fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
- }
-}
-
-var (
- fsGrp singleflight.Group
- fsMu sync.Mutex // guards fsCache
- fsCache = map[string]http.Handler{}
-)
-
-// fileServer returns a file-serving handler that proxies URL.
-// It lazily fetches URL on the first access and caches its contents forever.
-func fileServer(url string) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- hi, err := fsGrp.Do(url, func() (interface{}, error) {
- fsMu.Lock()
- if h, ok := fsCache[url]; ok {
- fsMu.Unlock()
- return h, nil
- }
- fsMu.Unlock()
-
- res, err := http.Get(url)
- if err != nil {
- return nil, err
- }
- defer res.Body.Close()
- slurp, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return nil, err
- }
-
- modTime := time.Now()
- var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
- })
- fsMu.Lock()
- fsCache[url] = h
- fsMu.Unlock()
- return h, nil
- })
- if err != nil {
- http.Error(w, err.Error(), 500)
- return
- }
- hi.(http.Handler).ServeHTTP(w, r)
- })
-}
-
-func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
- clientGone := w.(http.CloseNotifier).CloseNotify()
- w.Header().Set("Content-Type", "text/plain")
- ticker := time.NewTicker(1 * time.Second)
- defer ticker.Stop()
- fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
- io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))
-
- for {
- fmt.Fprintf(w, "%v\n", time.Now())
- w.(http.Flusher).Flush()
- select {
- case <-ticker.C:
- case <-clientGone:
- log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
- return
- }
- }
-}
-
-func registerHandlers() {
- tiles := newGopherTilesHandler()
-
- mux2 := http.NewServeMux()
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- if r.TLS == nil {
- if r.URL.Path == "/gophertiles" {
- tiles.ServeHTTP(w, r)
- return
- }
- http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound)
- return
- }
- if r.ProtoMajor == 1 {
- if r.URL.Path == "/reqinfo" {
- reqInfoHandler(w, r)
- return
- }
- homeOldHTTP(w, r)
- return
- }
- mux2.ServeHTTP(w, r)
- })
- mux2.HandleFunc("/", home)
- mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png"))
- mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz"))
- mux2.HandleFunc("/reqinfo", reqInfoHandler)
- mux2.HandleFunc("/crc32", crcHandler)
- mux2.HandleFunc("/clockstream", clockStreamHandler)
- mux2.Handle("/gophertiles", tiles)
- mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, "/", http.StatusFound)
- })
- stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`)
- mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- buf := make([]byte, 2<<20)
- w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil))
- })
-}
-
-func newGopherTilesHandler() http.Handler {
- const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg"
- res, err := http.Get(gopherURL)
- if err != nil {
- log.Fatal(err)
- }
- if res.StatusCode != 200 {
- log.Fatalf("Error fetching %s: %v", gopherURL, res.Status)
- }
- slurp, err := ioutil.ReadAll(res.Body)
- res.Body.Close()
- if err != nil {
- log.Fatal(err)
- }
- im, err := jpeg.Decode(bytes.NewReader(slurp))
- if err != nil {
- if len(slurp) > 1024 {
- slurp = slurp[:1024]
- }
- log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp)
- }
-
- type subImager interface {
- SubImage(image.Rectangle) image.Image
- }
- const tileSize = 32
- xt := im.Bounds().Max.X / tileSize
- yt := im.Bounds().Max.Y / tileSize
- var tile [][][]byte // y -> x -> jpeg bytes
- for yi := 0; yi < yt; yi++ {
- var row [][]byte
- for xi := 0; xi < xt; xi++ {
- si := im.(subImager).SubImage(image.Rectangle{
- Min: image.Point{xi * tileSize, yi * tileSize},
- Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize},
- })
- buf := new(bytes.Buffer)
- if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil {
- log.Fatal(err)
- }
- row = append(row, buf.Bytes())
- }
- tile = append(tile, row)
- }
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- ms, _ := strconv.Atoi(r.FormValue("latency"))
- const nanosPerMilli = 1e6
- if r.FormValue("x") != "" {
- x, _ := strconv.Atoi(r.FormValue("x"))
- y, _ := strconv.Atoi(r.FormValue("y"))
- if ms <= 1000 {
- time.Sleep(time.Duration(ms) * nanosPerMilli)
- }
- if x >= 0 && x < xt && y >= 0 && y < yt {
- http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x]))
- return
- }
- }
- io.WriteString(w, "")
- fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:", xt*yt)
- for _, ms := range []int{0, 30, 200, 1000} {
- d := time.Duration(ms) * nanosPerMilli
- fmt.Fprintf(w, "[HTTP/2, %v latency] [HTTP/1, %v latency]
\n",
- httpsHost(), ms, d,
- httpHost(), ms, d,
- )
- }
- io.WriteString(w, "
\n")
- cacheBust := time.Now().UnixNano()
- for y := 0; y < yt; y++ {
- for x := 0; x < xt; x++ {
- fmt.Fprintf(w, "",
- tileSize, tileSize, x, y, cacheBust, ms)
- }
- io.WriteString(w, "
\n")
- }
- io.WriteString(w, `
-
-
<< Back to Go HTTP/2 demo server`)
- })
-}
-
-func httpsHost() string {
- if *hostHTTPS != "" {
- return *hostHTTPS
- }
- if v := *httpsAddr; strings.HasPrefix(v, ":") {
- return "localhost" + v
- } else {
- return v
- }
-}
-
-func httpHost() string {
- if *hostHTTP != "" {
- return *hostHTTP
- }
- if v := *httpAddr; strings.HasPrefix(v, ":") {
- return "localhost" + v
- } else {
- return v
- }
-}
-
-func serveProdTLS() error {
- c, err := googlestorage.NewServiceClient()
- if err != nil {
- return err
- }
- slurp := func(key string) ([]byte, error) {
- const bucket = "http2-demo-server-tls"
- rc, _, err := c.GetObject(&googlestorage.Object{
- Bucket: bucket,
- Key: key,
- })
- if err != nil {
- return nil, fmt.Errorf("Error fetching GCS object %q in bucket %q: %v", key, bucket, err)
- }
- defer rc.Close()
- return ioutil.ReadAll(rc)
- }
- certPem, err := slurp("http2.golang.org.chained.pem")
- if err != nil {
- return err
- }
- keyPem, err := slurp("http2.golang.org.key")
- if err != nil {
- return err
- }
- cert, err := tls.X509KeyPair(certPem, keyPem)
- if err != nil {
- return err
- }
- srv := &http.Server{
- TLSConfig: &tls.Config{
- Certificates: []tls.Certificate{cert},
- },
- }
- http2.ConfigureServer(srv, &http2.Server{})
- ln, err := net.Listen("tcp", ":443")
- if err != nil {
- return err
- }
- return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
-}
-
-type tcpKeepAliveListener struct {
- *net.TCPListener
-}
-
-func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
- tc, err := ln.AcceptTCP()
- if err != nil {
- return
- }
- tc.SetKeepAlive(true)
- tc.SetKeepAlivePeriod(3 * time.Minute)
- return tc, nil
-}
-
-func serveProd() error {
- errc := make(chan error, 2)
- go func() { errc <- http.ListenAndServe(":80", nil) }()
- go func() { errc <- serveProdTLS() }()
- return <-errc
-}
-
-func main() {
- var srv http.Server
- flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
- flag.Parse()
- srv.Addr = *httpsAddr
-
- registerHandlers()
-
- if *prod {
- *hostHTTP = "http2.golang.org"
- *hostHTTPS = "http2.golang.org"
- log.Fatal(serveProd())
- }
-
- url := "https://" + httpsHost() + "/"
- log.Printf("Listening on " + url)
- http2.ConfigureServer(&srv, &http2.Server{})
-
- if *httpAddr != "" {
- go func() {
- log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)")
- log.Fatal(http.ListenAndServe(*httpAddr, nil))
- }()
- }
-
- go func() {
- log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
- }()
- select {}
-}
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/launch.go b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/launch.go
deleted file mode 100644
index 13b1cfd73..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/launch.go
+++ /dev/null
@@ -1,302 +0,0 @@
-// Copyright 2014 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-package main
-
-import (
- "bufio"
- "bytes"
- "encoding/json"
- "flag"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "net/http"
- "os"
- "strings"
- "time"
-
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/google"
- compute "google.golang.org/api/compute/v1"
-)
-
-var (
- proj = flag.String("project", "symbolic-datum-552", "name of Project")
- zone = flag.String("zone", "us-central1-a", "GCE zone")
- mach = flag.String("machinetype", "n1-standard-1", "Machine type")
- instName = flag.String("instance_name", "http2-demo", "Name of VM instance.")
- sshPub = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.")
- staticIP = flag.String("static_ip", "130.211.116.44", "Static IP to use. If empty, automatic.")
-
- writeObject = flag.String("write_object", "", "If non-empty, a VM isn't created and the flag value is Google Cloud Storage bucket/object to write. The contents from stdin.")
- publicObject = flag.Bool("write_object_is_public", false, "Whether the object created by --write_object should be public.")
-)
-
-func readFile(v string) string {
- slurp, err := ioutil.ReadFile(v)
- if err != nil {
- log.Fatalf("Error reading %s: %v", v, err)
- }
- return strings.TrimSpace(string(slurp))
-}
-
-var config = &oauth2.Config{
- // The client-id and secret should be for an "Installed Application" when using
- // the CLI. Later we'll use a web application with a callback.
- ClientID: readFile("client-id.dat"),
- ClientSecret: readFile("client-secret.dat"),
- Endpoint: google.Endpoint,
- Scopes: []string{
- compute.DevstorageFullControlScope,
- compute.ComputeScope,
- "https://www.googleapis.com/auth/sqlservice",
- "https://www.googleapis.com/auth/sqlservice.admin",
- },
- RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
-}
-
-const baseConfig = `#cloud-config
-coreos:
- units:
- - name: h2demo.service
- command: start
- content: |
- [Unit]
- Description=HTTP2 Demo
-
- [Service]
- ExecStartPre=/bin/bash -c 'mkdir -p /opt/bin && curl -s -o /opt/bin/h2demo http://storage.googleapis.com/http2-demo-server-tls/h2demo && chmod +x /opt/bin/h2demo'
- ExecStart=/opt/bin/h2demo --prod
- RestartSec=5s
- Restart=always
- Type=simple
-
- [Install]
- WantedBy=multi-user.target
-`
-
-func main() {
- flag.Parse()
- if *proj == "" {
- log.Fatalf("Missing --project flag")
- }
- prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj
- machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach
-
- const tokenFileName = "token.dat"
- tokenFile := tokenCacheFile(tokenFileName)
- tokenSource := oauth2.ReuseTokenSource(nil, tokenFile)
- token, err := tokenSource.Token()
- if err != nil {
- if *writeObject != "" {
- log.Fatalf("Can't use --write_object without a valid token.dat file already cached.")
- }
- log.Printf("Error getting token from %s: %v", tokenFileName, err)
- log.Printf("Get auth code from %v", config.AuthCodeURL("my-state"))
- fmt.Print("\nEnter auth code: ")
- sc := bufio.NewScanner(os.Stdin)
- sc.Scan()
- authCode := strings.TrimSpace(sc.Text())
- token, err = config.Exchange(oauth2.NoContext, authCode)
- if err != nil {
- log.Fatalf("Error exchanging auth code for a token: %v", err)
- }
- if err := tokenFile.WriteToken(token); err != nil {
- log.Fatalf("Error writing to %s: %v", tokenFileName, err)
- }
- tokenSource = oauth2.ReuseTokenSource(token, nil)
- }
-
- oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
-
- if *writeObject != "" {
- writeCloudStorageObject(oauthClient)
- return
- }
-
- computeService, _ := compute.New(oauthClient)
-
- natIP := *staticIP
- if natIP == "" {
- // Try to find it by name.
- aggAddrList, err := computeService.Addresses.AggregatedList(*proj).Do()
- if err != nil {
- log.Fatal(err)
- }
- // http://godoc.org/code.google.com/p/google-api-go-client/compute/v1#AddressAggregatedList
- IPLoop:
- for _, asl := range aggAddrList.Items {
- for _, addr := range asl.Addresses {
- if addr.Name == *instName+"-ip" && addr.Status == "RESERVED" {
- natIP = addr.Address
- break IPLoop
- }
- }
- }
- }
-
- cloudConfig := baseConfig
- if *sshPub != "" {
- key := strings.TrimSpace(readFile(*sshPub))
- cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", key)
- }
- if os.Getenv("USER") == "bradfitz" {
- cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwks9dwWKlRC+73gRbvYtVg0vdCwDSuIlyt4z6xa/YU/jTDynM4R4W10hm2tPjy8iR1k8XhDv4/qdxe6m07NjG/By1tkmGpm1mGwho4Pr5kbAAy/Qg+NLCSdAYnnE00FQEcFOC15GFVMOW2AzDGKisReohwH9eIzHPzdYQNPRWXE= bradfitz@papag.bradfitz.com")
- }
- const maxCloudConfig = 32 << 10 // per compute API docs
- if len(cloudConfig) > maxCloudConfig {
- log.Fatalf("cloud config length of %d bytes is over %d byte limit", len(cloudConfig), maxCloudConfig)
- }
-
- instance := &compute.Instance{
- Name: *instName,
- Description: "Go Builder",
- MachineType: machType,
- Disks: []*compute.AttachedDisk{instanceDisk(computeService)},
- Tags: &compute.Tags{
- Items: []string{"http-server", "https-server"},
- },
- Metadata: &compute.Metadata{
- Items: []*compute.MetadataItems{
- {
- Key: "user-data",
- Value: &cloudConfig,
- },
- },
- },
- NetworkInterfaces: []*compute.NetworkInterface{
- &compute.NetworkInterface{
- AccessConfigs: []*compute.AccessConfig{
- &compute.AccessConfig{
- Type: "ONE_TO_ONE_NAT",
- Name: "External NAT",
- NatIP: natIP,
- },
- },
- Network: prefix + "/global/networks/default",
- },
- },
- ServiceAccounts: []*compute.ServiceAccount{
- {
- Email: "default",
- Scopes: []string{
- compute.DevstorageFullControlScope,
- compute.ComputeScope,
- },
- },
- },
- }
-
- log.Printf("Creating instance...")
- op, err := computeService.Instances.Insert(*proj, *zone, instance).Do()
- if err != nil {
- log.Fatalf("Failed to create instance: %v", err)
- }
- opName := op.Name
- log.Printf("Created. Waiting on operation %v", opName)
-OpLoop:
- for {
- time.Sleep(2 * time.Second)
- op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do()
- if err != nil {
- log.Fatalf("Failed to get op %s: %v", opName, err)
- }
- switch op.Status {
- case "PENDING", "RUNNING":
- log.Printf("Waiting on operation %v", opName)
- continue
- case "DONE":
- if op.Error != nil {
- for _, operr := range op.Error.Errors {
- log.Printf("Error: %+v", operr)
- }
- log.Fatalf("Failed to start.")
- }
- log.Printf("Success. %+v", op)
- break OpLoop
- default:
- log.Fatalf("Unknown status %q: %+v", op.Status, op)
- }
- }
-
- inst, err := computeService.Instances.Get(*proj, *zone, *instName).Do()
- if err != nil {
- log.Fatalf("Error getting instance after creation: %v", err)
- }
- ij, _ := json.MarshalIndent(inst, "", " ")
- log.Printf("Instance: %s", ij)
-}
-
-func instanceDisk(svc *compute.Service) *compute.AttachedDisk {
- const imageURL = "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-444-5-0-v20141016"
- diskName := *instName + "-disk"
-
- return &compute.AttachedDisk{
- AutoDelete: true,
- Boot: true,
- Type: "PERSISTENT",
- InitializeParams: &compute.AttachedDiskInitializeParams{
- DiskName: diskName,
- SourceImage: imageURL,
- DiskSizeGb: 50,
- },
- }
-}
-
-func writeCloudStorageObject(httpClient *http.Client) {
- content := os.Stdin
- const maxSlurp = 1 << 20
- var buf bytes.Buffer
- n, err := io.CopyN(&buf, content, maxSlurp)
- if err != nil && err != io.EOF {
- log.Fatalf("Error reading from stdin: %v, %v", n, err)
- }
- contentType := http.DetectContentType(buf.Bytes())
-
- req, err := http.NewRequest("PUT", "https://storage.googleapis.com/"+*writeObject, io.MultiReader(&buf, content))
- if err != nil {
- log.Fatal(err)
- }
- req.Header.Set("x-goog-api-version", "2")
- if *publicObject {
- req.Header.Set("x-goog-acl", "public-read")
- }
- req.Header.Set("Content-Type", contentType)
- res, err := httpClient.Do(req)
- if err != nil {
- log.Fatal(err)
- }
- if res.StatusCode != 200 {
- res.Write(os.Stderr)
- log.Fatalf("Failed.")
- }
- log.Printf("Success.")
- os.Exit(0)
-}
-
-type tokenCacheFile string
-
-func (f tokenCacheFile) Token() (*oauth2.Token, error) {
- slurp, err := ioutil.ReadFile(string(f))
- if err != nil {
- return nil, err
- }
- t := new(oauth2.Token)
- if err := json.Unmarshal(slurp, t); err != nil {
- return nil, err
- }
- return t, nil
-}
-
-func (f tokenCacheFile) WriteToken(t *oauth2.Token) error {
- jt, err := json.Marshal(t)
- if err != nil {
- return err
- }
- return ioutil.WriteFile(string(f), jt, 0600)
-}
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.key b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.key
deleted file mode 100644
index a15a6abaf..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.key
+++ /dev/null
@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEowIBAAKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSSR8Od0+9Q
-62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoTZjkUygby
-XDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYkJfODVGnV
-mr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3mOoLb4yJ
-JQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYWcaiW8LWZ
-SUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABAoIBAFFHV7JMAqPWnMYA
-nezY6J81v9+XN+7xABNWM2Q8uv4WdksbigGLTXR3/680Z2hXqJ7LMeC5XJACFT/e
-/Gr0vmpgOCygnCPfjGehGKpavtfksXV3edikUlnCXsOP1C//c1bFL+sMYmFCVgTx
-qYdDK8yKzXNGrKYT6q5YG7IglyRNV1rsQa8lM/5taFYiD1Ck/3tQi3YIq8Lcuser
-hrxsMABcQ6mi+EIvG6Xr4mfJug0dGJMHG4RG1UGFQn6RXrQq2+q53fC8ZbVUSi0j
-NQ918aKFzktwv+DouKU0ME4I9toks03gM860bAL7zCbKGmwR3hfgX/TqzVCWpG9E
-LDVfvekCgYEA8fk9N53jbBRmULUGEf4qWypcLGiZnNU0OeXWpbPV9aa3H0VDytA7
-8fCN2dPAVDPqlthMDdVe983NCNwp2Yo8ZimDgowyIAKhdC25s1kejuaiH9OAPj3c
-0f8KbriYX4n8zNHxFwK6Ae3pQ6EqOLJVCUsziUaZX9nyKY5aZlyX6xcCgYEAwjws
-K62PjC64U5wYddNLp+kNdJ4edx+a7qBb3mEgPvSFT2RO3/xafJyG8kQB30Mfstjd
-bRxyUV6N0vtX1zA7VQtRUAvfGCecpMo+VQZzcHXKzoRTnQ7eZg4Lmj5fQ9tOAKAo
-QCVBoSW/DI4PZL26CAMDcAba4Pa22ooLapoRIQsCgYA6pIfkkbxLNkpxpt2YwLtt
-Kr/590O7UaR9n6k8sW/aQBRDXNsILR1KDl2ifAIxpf9lnXgZJiwE7HiTfCAcW7c1
-nzwDCI0hWuHcMTS/NYsFYPnLsstyyjVZI3FY0h4DkYKV9Q9z3zJLQ2hz/nwoD3gy
-b2pHC7giFcTts1VPV4Nt8wKBgHeFn4ihHJweg76vZz3Z78w7VNRWGFklUalVdDK7
-gaQ7w2y/ROn/146mo0OhJaXFIFRlrpvdzVrU3GDf2YXJYDlM5ZRkObwbZADjksev
-WInzcgDy3KDg7WnPasRXbTfMU4t/AkW2p1QKbi3DnSVYuokDkbH2Beo45vxDxhKr
-C69RAoGBAIyo3+OJenoZmoNzNJl2WPW5MeBUzSh8T/bgyjFTdqFHF5WiYRD/lfHj
-x9Glyw2nutuT4hlOqHvKhgTYdDMsF2oQ72fe3v8Q5FU7FuKndNPEAyvKNXZaShVA
-hnlhv5DjXKb0wFWnt5PCCiQLtzG0yyHaITrrEme7FikkIcTxaX/Y
------END RSA PRIVATE KEY-----
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.pem b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.pem
deleted file mode 100644
index 3a323e774..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.pem
+++ /dev/null
@@ -1,26 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIEWjCCA0KgAwIBAgIJALfRlWsI8YQHMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNV
-BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEUMBIG
-A1UEChMLQnJhZGZpdHppbmMxEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsGCSqGSIb3
-DQEJARYOYnJhZEBkYW5nYS5jb20wHhcNMTQwNzE1MjA0NjA1WhcNMTcwNTA0MjA0
-NjA1WjB7MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBG
-cmFuY2lzY28xFDASBgNVBAoTC0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhv
-c3QxHTAbBgkqhkiG9w0BCQEWDmJyYWRAZGFuZ2EuY29tMIIBIjANBgkqhkiG9w0B
-AQEFAAOCAQ8AMIIBCgKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSS
-R8Od0+9Q62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoT
-ZjkUygbyXDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYk
-JfODVGnVmr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3
-mOoLb4yJJQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYW
-caiW8LWZSUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABo4HgMIHdMB0G
-A1UdDgQWBBRcAROthS4P4U7vTfjByC569R7E6DCBrQYDVR0jBIGlMIGigBRcAROt
-hS4P4U7vTfjByC569R7E6KF/pH0wezELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNB
-MRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRQwEgYDVQQKEwtCcmFkZml0emluYzES
-MBAGA1UEAxMJbG9jYWxob3N0MR0wGwYJKoZIhvcNAQkBFg5icmFkQGRhbmdhLmNv
-bYIJALfRlWsI8YQHMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAG6h
-U9f9sNH0/6oBbGGy2EVU0UgITUQIrFWo9rFkrW5k/XkDjQm+3lzjT0iGR4IxE/Ao
-eU6sQhua7wrWeFEn47GL98lnCsJdD7oZNhFmQ95Tb/LnDUjs5Yj9brP0NWzXfYU4
-UK2ZnINJRcJpB8iRCaCxE8DdcUF0XqIEq6pA272snoLmiXLMvNl3kYEdm+je6voD
-58SNVEUsztzQyXmJEhCpwVI0A6QCjzXj+qvpmw3ZZHi8JwXei8ZZBLTSFBki8Z7n
-sH9BBH38/SzUmAN4QHSPy1gjqm00OAE8NaYDkh/bzE4d7mLGGMWp/WE3KPSu82HF
-kPe6XoSbiLm/kxk32T0=
------END CERTIFICATE-----
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.srl b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.srl
deleted file mode 100644
index 6db389188..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/rootCA.srl
+++ /dev/null
@@ -1 +0,0 @@
-E2CE26BF3285059C
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.crt b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.crt
deleted file mode 100644
index c59059bd6..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.crt
+++ /dev/null
@@ -1,20 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDPjCCAiYCCQDizia/MoUFnDANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJV
-UzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xFDASBgNVBAoT
-C0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhvc3QxHTAbBgkqhkiG9w0BCQEW
-DmJyYWRAZGFuZ2EuY29tMB4XDTE0MDcxNTIwNTAyN1oXDTE1MTEyNzIwNTAyN1ow
-RzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQHEwJTRjEeMBwGA1UE
-ChMVYnJhZGZpdHogaHR0cDIgc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
-MIIBCgKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDifx2l
-gZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1LmJ4c2
-dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nefb3HL
-A7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55mjws
-/vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/fz88
-F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABMA0GCSqGSIb3DQEBBQUAA4IB
-AQC0zL+n/YpRZOdulSu9tS8FxrstXqGWoxfe+vIUgqfMZ5+0MkjJ/vW0FqlLDl2R
-rn4XaR3e7FmWkwdDVbq/UB6lPmoAaFkCgh9/5oapMaclNVNnfF3fjCJfRr+qj/iD
-EmJStTIN0ZuUjAlpiACmfnpEU55PafT5Zx+i1yE4FGjw8bJpFoyD4Hnm54nGjX19
-KeCuvcYFUPnBm3lcL0FalF2AjqV02WTHYNQk7YF/oeO7NKBoEgvGvKG3x+xaOeBI
-dwvdq175ZsGul30h+QjrRlXhH/twcuaT3GSdoysDl9cCYE8f1Mk8PD6gan3uBCJU
-90p6/CbU71bGbfpM2PHot2fm
------END CERTIFICATE-----
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.key b/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.key
deleted file mode 100644
index f329c1421..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2demo/server.key
+++ /dev/null
@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEowIBAAKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDi
-fx2lgZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1Lm
-J4c2dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nef
-b3HLA7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55
-mjws/vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/
-fz88F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABAoIBADQ2spUwbY+bcz4p
-3M66ECrNQTBggP40gYl2XyHxGGOu2xhZ94f9ELf1hjRWU2DUKWco1rJcdZClV6q3
-qwmXvcM2Q/SMS8JW0ImkNVl/0/NqPxGatEnj8zY30d/L8hGFb0orzFu/XYA5gCP4
-NbN2WrXgk3ZLeqwcNxHHtSiJWGJ/fPyeDWAu/apy75u9Xf2GlzBZmV6HYD9EfK80
-LTlI60f5FO487CrJnboL7ovPJrIHn+k05xRQqwma4orpz932rTXnTjs9Lg6KtbQN
-a7PrqfAntIISgr11a66Mng3IYH1lYqJsWJJwX/xHT4WLEy0EH4/0+PfYemJekz2+
-Co62drECgYEA6O9zVJZXrLSDsIi54cfxA7nEZWm5CAtkYWeAHa4EJ+IlZ7gIf9sL
-W8oFcEfFGpvwVqWZ+AsQ70dsjXAv3zXaG0tmg9FtqWp7pzRSMPidifZcQwWkKeTO
-gJnFmnVyed8h6GfjTEu4gxo1/S5U0V+mYSha01z5NTnN6ltKx1Or3b0CgYEAxRgm
-S30nZxnyg/V7ys61AZhst1DG2tkZXEMcA7dYhabMoXPJAP/EfhlWwpWYYUs/u0gS
-Wwmf5IivX5TlYScgmkvb/NYz0u4ZmOXkLTnLPtdKKFXhjXJcHjUP67jYmOxNlJLp
-V4vLRnFxTpffAV+OszzRxsXX6fvruwZBANYJeXUCgYBVouLFsFgfWGYp2rpr9XP4
-KK25kvrBqF6JKOIDB1zjxNJ3pUMKrl8oqccCFoCyXa4oTM2kUX0yWxHfleUjrMq4
-yimwQKiOZmV7fVLSSjSw6e/VfBd0h3gb82ygcplZkN0IclkwTY5SNKqwn/3y07V5
-drqdhkrgdJXtmQ6O5YYECQKBgATERcDToQ1USlI4sKrB/wyv1AlG8dg/IebiVJ4e
-ZAyvcQmClFzq0qS+FiQUnB/WQw9TeeYrwGs1hxBHuJh16srwhLyDrbMvQP06qh8R
-48F8UXXSRec22dV9MQphaROhu2qZdv1AC0WD3tqov6L33aqmEOi+xi8JgbT/PLk5
-c/c1AoGBAI1A/02ryksW6/wc7/6SP2M2rTy4m1sD/GnrTc67EHnRcVBdKO6qH2RY
-nqC8YcveC2ZghgPTDsA3VGuzuBXpwY6wTyV99q6jxQJ6/xcrD9/NUG6Uwv/xfCxl
-IJLeBYEqQundSSny3VtaAUK8Ul1nxpTvVRNwtcyWTo8RHAAyNPWd
------END RSA PRIVATE KEY-----
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2i/README.md b/Godeps/_workspace/src/golang.org/x/net/http2/h2i/README.md
deleted file mode 100644
index fb5c5efb0..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2i/README.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# h2i
-
-**h2i** is an interactive HTTP/2 ("h2") console debugger. Miss the good ol'
-days of telnetting to your HTTP/1.n servers? We're bringing you
-back.
-
-Features:
-- send raw HTTP/2 frames
- - PING
- - SETTINGS
- - HEADERS
- - etc
-- type in HTTP/1.n and have it auto-HPACK/frame-ify it for HTTP/2
-- pretty print all received HTTP/2 frames from the peer (including HPACK decoding)
-- tab completion of commands, options
-
-Not yet features, but soon:
-- unnecessary CONTINUATION frames on short boundaries, to test peer implementations
-- request bodies (DATA frames)
-- send invalid frames for testing server implementations (supported by underlying Framer)
-
-Later:
-- act like a server
-
-## Installation
-
-```
-$ go get golang.org/x/net/http2/h2i
-$ h2i
-```
-
-## Demo
-
-```
-$ h2i
-Usage: h2i
-
- -insecure
- Whether to skip TLS cert validation
- -nextproto string
- Comma-separated list of NPN/ALPN protocol names to negotiate. (default "h2,h2-14")
-
-$ h2i google.com
-Connecting to google.com:443 ...
-Connected to 74.125.224.41:443
-Negotiated protocol "h2-14"
-[FrameHeader SETTINGS len=18]
- [MAX_CONCURRENT_STREAMS = 100]
- [INITIAL_WINDOW_SIZE = 1048576]
- [MAX_FRAME_SIZE = 16384]
-[FrameHeader WINDOW_UPDATE len=4]
- Window-Increment = 983041
-
-h2i> PING h2iSayHI
-[FrameHeader PING flags=ACK len=8]
- Data = "h2iSayHI"
-h2i> headers
-(as HTTP/1.1)> GET / HTTP/1.1
-(as HTTP/1.1)> Host: ip.appspot.com
-(as HTTP/1.1)> User-Agent: h2i/brad-n-blake
-(as HTTP/1.1)>
-Opening Stream-ID 1:
- :authority = ip.appspot.com
- :method = GET
- :path = /
- :scheme = https
- user-agent = h2i/brad-n-blake
-[FrameHeader HEADERS flags=END_HEADERS stream=1 len=77]
- :status = "200"
- alternate-protocol = "443:quic,p=1"
- content-length = "15"
- content-type = "text/html"
- date = "Fri, 01 May 2015 23:06:56 GMT"
- server = "Google Frontend"
-[FrameHeader DATA flags=END_STREAM stream=1 len=15]
- "173.164.155.78\n"
-[FrameHeader PING len=8]
- Data = "\x00\x00\x00\x00\x00\x00\x00\x00"
-h2i> ping
-[FrameHeader PING flags=ACK len=8]
- Data = "h2i_ping"
-h2i> ping
-[FrameHeader PING flags=ACK len=8]
- Data = "h2i_ping"
-h2i> ping
-[FrameHeader GOAWAY len=22]
- Last-Stream-ID = 1; Error-Code = PROTOCOL_ERROR (1)
-
-ReadFrame: EOF
-```
-
-## Status
-
-Quick few hour hack. So much yet to do. Feel free to file issues for
-bugs or wishlist items, but [@bmizerany](https://github.com/bmizerany/)
-and I aren't yet accepting pull requests until things settle down.
-
diff --git a/Godeps/_workspace/src/golang.org/x/net/http2/h2i/h2i.go b/Godeps/_workspace/src/golang.org/x/net/http2/h2i/h2i.go
deleted file mode 100644
index f14fd2005..000000000
--- a/Godeps/_workspace/src/golang.org/x/net/http2/h2i/h2i.go
+++ /dev/null
@@ -1,499 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-The h2i command is an interactive HTTP/2 console.
-
-Usage:
- $ h2i [flags]
-
-Interactive commands in the console: (all parts case-insensitive)
-
- ping [data]
- settings ack
- settings FOO=n BAR=z
- headers (open a new stream by typing HTTP/1.1)
-*/
-package main
-
-import (
- "bufio"
- "bytes"
- "crypto/tls"
- "errors"
- "flag"
- "fmt"
- "io"
- "log"
- "net"
- "net/http"
- "os"
- "regexp"
- "strconv"
- "strings"
-
- "golang.org/x/crypto/ssh/terminal"
- "golang.org/x/net/http2"
- "golang.org/x/net/http2/hpack"
-)
-
-// Flags
-var (
- flagNextProto = flag.String("nextproto", "h2,h2-14", "Comma-separated list of NPN/ALPN protocol names to negotiate.")
- flagInsecure = flag.Bool("insecure", false, "Whether to skip TLS cert validation")
- flagSettings = flag.String("settings", "empty", "comma-separated list of KEY=value settings for the initial SETTINGS frame. The magic value 'empty' sends an empty initial settings frame, and the magic value 'omit' causes no initial settings frame to be sent.")
-)
-
-type command struct {
- run func(*h2i, []string) error // required
-
- // complete optionally specifies tokens (case-insensitive) which are
- // valid for this subcommand.
- complete func() []string
-}
-
-var commands = map[string]command{
- "ping": command{run: (*h2i).cmdPing},
- "settings": command{
- run: (*h2i).cmdSettings,
- complete: func() []string {
- return []string{
- "ACK",
- http2.SettingHeaderTableSize.String(),
- http2.SettingEnablePush.String(),
- http2.SettingMaxConcurrentStreams.String(),
- http2.SettingInitialWindowSize.String(),
- http2.SettingMaxFrameSize.String(),
- http2.SettingMaxHeaderListSize.String(),
- }
- },
- },
- "quit": command{run: (*h2i).cmdQuit},
- "headers": command{run: (*h2i).cmdHeaders},
-}
-
-func usage() {
- fmt.Fprintf(os.Stderr, "Usage: h2i \n\n")
- flag.PrintDefaults()
- os.Exit(1)
-}
-
-// withPort adds ":443" if another port isn't already present.
-func withPort(host string) string {
- if _, _, err := net.SplitHostPort(host); err != nil {
- return net.JoinHostPort(host, "443")
- }
- return host
-}
-
-// h2i is the app's state.
-type h2i struct {
- host string
- tc *tls.Conn
- framer *http2.Framer
- term *terminal.Terminal
-
- // owned by the command loop:
- streamID uint32
- hbuf bytes.Buffer
- henc *hpack.Encoder
-
- // owned by the readFrames loop:
- peerSetting map[http2.SettingID]uint32
- hdec *hpack.Decoder
-}
-
-func main() {
- flag.Usage = usage
- flag.Parse()
- if flag.NArg() != 1 {
- usage()
- }
- log.SetFlags(0)
-
- host := flag.Arg(0)
- app := &h2i{
- host: host,
- peerSetting: make(map[http2.SettingID]uint32),
- }
- app.henc = hpack.NewEncoder(&app.hbuf)
-
- if err := app.Main(); err != nil {
- if app.term != nil {
- app.logf("%v\n", err)
- } else {
- fmt.Fprintf(os.Stderr, "%v\n", err)
- }
- os.Exit(1)
- }
- fmt.Fprintf(os.Stdout, "\n")
-}
-
-func (app *h2i) Main() error {
- cfg := &tls.Config{
- ServerName: app.host,
- NextProtos: strings.Split(*flagNextProto, ","),
- InsecureSkipVerify: *flagInsecure,
- }
-
- hostAndPort := withPort(app.host)
- log.Printf("Connecting to %s ...", hostAndPort)
- tc, err := tls.Dial("tcp", hostAndPort, cfg)
- if err != nil {
- return fmt.Errorf("Error dialing %s: %v", withPort(app.host), err)
- }
- log.Printf("Connected to %v", tc.RemoteAddr())
- defer tc.Close()
-
- if err := tc.Handshake(); err != nil {
- return fmt.Errorf("TLS handshake: %v", err)
- }
- if !*flagInsecure {
- if err := tc.VerifyHostname(app.host); err != nil {
- return fmt.Errorf("VerifyHostname: %v", err)
- }
- }
- state := tc.ConnectionState()
- log.Printf("Negotiated protocol %q", state.NegotiatedProtocol)
- if !state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol == "" {
- return fmt.Errorf("Could not negotiate protocol mutually")
- }
-
- if _, err := io.WriteString(tc, http2.ClientPreface); err != nil {
- return err
- }
-
- app.framer = http2.NewFramer(tc, tc)
-
- oldState, err := terminal.MakeRaw(0)
- if err != nil {
- return err
- }
- defer terminal.Restore(0, oldState)
-
- var screen = struct {
- io.Reader
- io.Writer
- }{os.Stdin, os.Stdout}
-
- app.term = terminal.NewTerminal(screen, "h2i> ")
- lastWord := regexp.MustCompile(`.+\W(\w+)$`)
- app.term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) {
- if key != '\t' {
- return
- }
- if pos != len(line) {
- // TODO: we're being lazy for now, only supporting tab completion at the end.
- return
- }
- // Auto-complete for the command itself.
- if !strings.Contains(line, " ") {
- var name string
- name, _, ok = lookupCommand(line)
- if !ok {
- return
- }
- return name, len(name), true
- }
- _, c, ok := lookupCommand(line[:strings.IndexByte(line, ' ')])
- if !ok || c.complete == nil {
- return
- }
- if strings.HasSuffix(line, " ") {
- app.logf("%s", strings.Join(c.complete(), " "))
- return line, pos, true
- }
- m := lastWord.FindStringSubmatch(line)
- if m == nil {
- return line, len(line), true
- }
- soFar := m[1]
- var match []string
- for _, cand := range c.complete() {
- if len(soFar) > len(cand) || !strings.EqualFold(cand[:len(soFar)], soFar) {
- continue
- }
- match = append(match, cand)
- }
- if len(match) == 0 {
- return
- }
- if len(match) > 1 {
- // TODO: auto-complete any common prefix
- app.logf("%s", strings.Join(match, " "))
- return line, pos, true
- }
- newLine = line[:len(line)-len(soFar)] + match[0]
- return newLine, len(newLine), true
-
- }
-
- errc := make(chan error, 2)
- go func() { errc <- app.readFrames() }()
- go func() { errc <- app.readConsole() }()
- return <-errc
-}
-
-func (app *h2i) logf(format string, args ...interface{}) {
- fmt.Fprintf(app.term, format+"\n", args...)
-}
-
-func (app *h2i) readConsole() error {
- if s := *flagSettings; s != "omit" {
- var args []string
- if s != "empty" {
- args = strings.Split(s, ",")
- }
- _, c, ok := lookupCommand("settings")
- if !ok {
- panic("settings command not found")
- }
- c.run(app, args)
- }
-
- for {
- line, err := app.term.ReadLine()
- if err == io.EOF {
- return nil
- }
- if err != nil {
- return fmt.Errorf("terminal.ReadLine: %v", err)
- }
- f := strings.Fields(line)
- if len(f) == 0 {
- continue
- }
- cmd, args := f[0], f[1:]
- if _, c, ok := lookupCommand(cmd); ok {
- err = c.run(app, args)
- } else {
- app.logf("Unknown command %q", line)
- }
- if err == errExitApp {
- return nil
- }
- if err != nil {
- return err
- }
- }
-}
-
-func lookupCommand(prefix string) (name string, c command, ok bool) {
- prefix = strings.ToLower(prefix)
- if c, ok = commands[prefix]; ok {
- return prefix, c, ok
- }
-
- for full, candidate := range commands {
- if strings.HasPrefix(full, prefix) {
- if c.run != nil {
- return "", command{}, false // ambiguous
- }
- c = candidate
- name = full
- }
- }
- return name, c, c.run != nil
-}
-
-var errExitApp = errors.New("internal sentinel error value to quit the console reading loop")
-
-func (a *h2i) cmdQuit(args []string) error {
- if len(args) > 0 {
- a.logf("the QUIT command takes no argument")
- return nil
- }
- return errExitApp
-}
-
-func (a *h2i) cmdSettings(args []string) error {
- if len(args) == 1 && strings.EqualFold(args[0], "ACK") {
- return a.framer.WriteSettingsAck()
- }
- var settings []http2.Setting
- for _, arg := range args {
- if strings.EqualFold(arg, "ACK") {
- a.logf("Error: ACK must be only argument with the SETTINGS command")
- return nil
- }
- eq := strings.Index(arg, "=")
- if eq == -1 {
- a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg)
- return nil
- }
- sid, ok := settingByName(arg[:eq])
- if !ok {
- a.logf("Error: unknown setting name %q", arg[:eq])
- return nil
- }
- val, err := strconv.ParseUint(arg[eq+1:], 10, 32)
- if err != nil {
- a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg)
- return nil
- }
- settings = append(settings, http2.Setting{
- ID: sid,
- Val: uint32(val),
- })
- }
- a.logf("Sending: %v", settings)
- return a.framer.WriteSettings(settings...)
-}
-
-func settingByName(name string) (http2.SettingID, bool) {
- for _, sid := range [...]http2.SettingID{
- http2.SettingHeaderTableSize,
- http2.SettingEnablePush,
- http2.SettingMaxConcurrentStreams,
- http2.SettingInitialWindowSize,
- http2.SettingMaxFrameSize,
- http2.SettingMaxHeaderListSize,
- } {
- if strings.EqualFold(sid.String(), name) {
- return sid, true
- }
- }
- return 0, false
-}
-
-func (app *h2i) cmdPing(args []string) error {
- if len(args) > 1 {
- app.logf("invalid PING usage: only accepts 0 or 1 args")
- return nil // nil means don't end the program
- }
- var data [8]byte
- if len(args) == 1 {
- copy(data[:], args[0])
- } else {
- copy(data[:], "h2i_ping")
- }
- return app.framer.WritePing(false, data)
-}
-
-func (app *h2i) cmdHeaders(args []string) error {
- if len(args) > 0 {
- app.logf("Error: HEADERS doesn't yet take arguments.")
- // TODO: flags for restricting window size, to force CONTINUATION
- // frames.
- return nil
- }
- var h1req bytes.Buffer
- app.term.SetPrompt("(as HTTP/1.1)> ")
- defer app.term.SetPrompt("h2i> ")
- for {
- line, err := app.term.ReadLine()
- if err != nil {
- return err
- }
- h1req.WriteString(line)
- h1req.WriteString("\r\n")
- if line == "" {
- break
- }
- }
- req, err := http.ReadRequest(bufio.NewReader(&h1req))
- if err != nil {
- app.logf("Invalid HTTP/1.1 request: %v", err)
- return nil
- }
- if app.streamID == 0 {
- app.streamID = 1
- } else {
- app.streamID += 2
- }
- app.logf("Opening Stream-ID %d:", app.streamID)
- hbf := app.encodeHeaders(req)
- if len(hbf) > 16<<10 {
- app.logf("TODO: h2i doesn't yet write CONTINUATION frames. Copy it from transport.go")
- return nil
- }
- return app.framer.WriteHeaders(http2.HeadersFrameParam{
- StreamID: app.streamID,
- BlockFragment: hbf,
- EndStream: req.Method == "GET" || req.Method == "HEAD", // good enough for now
- EndHeaders: true, // for now
- })
-}
-
-func (app *h2i) readFrames() error {
- for {
- f, err := app.framer.ReadFrame()
- if err != nil {
- return fmt.Errorf("ReadFrame: %v", err)
- }
- app.logf("%v", f)
- switch f := f.(type) {
- case *http2.PingFrame:
- app.logf(" Data = %q", f.Data)
- case *http2.SettingsFrame:
- f.ForeachSetting(func(s http2.Setting) error {
- app.logf(" %v", s)
- app.peerSetting[s.ID] = s.Val
- return nil
- })
- case *http2.WindowUpdateFrame:
- app.logf(" Window-Increment = %v\n", f.Increment)
- case *http2.GoAwayFrame:
- app.logf(" Last-Stream-ID = %d; Error-Code = %v (%d)\n", f.LastStreamID, f.ErrCode, f.ErrCode)
- case *http2.DataFrame:
- app.logf(" %q", f.Data())
- case *http2.HeadersFrame:
- if f.HasPriority() {
- app.logf(" PRIORITY = %v", f.Priority)
- }
- if app.hdec == nil {
- // TODO: if the user uses h2i to send a SETTINGS frame advertising
- // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE
- // and stuff here instead of using the 4k default. But for now:
- tableSize := uint32(4 << 10)
- app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField)
- }
- app.hdec.Write(f.HeaderBlockFragment())
- }
- }
-}
-
-// called from readLoop
-func (app *h2i) onNewHeaderField(f hpack.HeaderField) {
- if f.Sensitive {
- app.logf(" %s = %q (SENSITIVE)", f.Name, f.Value)
- }
- app.logf(" %s = %q", f.Name, f.Value)
-}
-
-func (app *h2i) encodeHeaders(req *http.Request) []byte {
- app.hbuf.Reset()
-
- // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go
- host := req.Host
- if host == "" {
- host = req.URL.Host
- }
-
- path := req.URL.Path
- if path == "" {
- path = "/"
- }
-
- app.writeHeader(":authority", host) // probably not right for all sites
- app.writeHeader(":method", req.Method)
- app.writeHeader(":path", path)
- app.writeHeader(":scheme", "https")
-
- for k, vv := range req.Header {
- lowKey := strings.ToLower(k)
- if lowKey == "host" {
- continue
- }
- for _, v := range vv {
- app.writeHeader(lowKey, v)
- }
- }
- return app.hbuf.Bytes()
-}
-
-func (app *h2i) writeHeader(name, value string) {
- app.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
- app.logf(" %s = %s", name, value)
-}
diff --git a/Godeps/_workspace/src/golang.org/x/sys/unix/mkerrors.sh b/Godeps/_workspace/src/golang.org/x/sys/unix/mkerrors.sh
index 8fa8df75b..785855f07 100644
--- a/Godeps/_workspace/src/golang.org/x/sys/unix/mkerrors.sh
+++ b/Godeps/_workspace/src/golang.org/x/sys/unix/mkerrors.sh
@@ -437,7 +437,7 @@ main(void)
printf("\t%d: \"%s\",\n", e, buf);
}
printf("}\n\n");
-
+
printf("\n\n// Signal table\n");
printf("var signals = [...]string {\n");
qsort(signals, nelem(signals), sizeof signals[0], intcmp);
diff --git a/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall.pl b/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall.pl
index 7aee58d5c..b1e7766da 100644
--- a/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall.pl
+++ b/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall.pl
@@ -185,7 +185,7 @@ ($)
}
} elsif($type eq "int64" && $_32bit ne "") {
if(@args % 2 && $arm) {
- # arm abi specifies 64-bit argument uses
+ # arm abi specifies 64-bit argument uses
# (even, odd) pair
push @args, "0"
}
@@ -282,7 +282,7 @@ ($)
$text .= "\t$use\n";
}
$text .= $body;
-
+
if ($plan9 && $ret[2] eq "e1") {
$text .= "\tif int32(r0) == -1 {\n";
$text .= "\t\terr = e1\n";
diff --git a/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall_solaris.pl b/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall_solaris.pl
index 97c7bfe01..06bade768 100644
--- a/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall_solaris.pl
+++ b/Godeps/_workspace/src/golang.org/x/sys/unix/mksyscall_solaris.pl
@@ -12,7 +12,7 @@
# * The parameter lists must give a type for each argument:
# the (x, y, z int) shorthand is not allowed.
# * If the return parameter is an error number, it must be named err.
-# * If go func name needs to be different than its libc name,
+# * If go func name needs to be different than its libc name,
# * or the function is not in libc, name could be specified
# * at the end, after "=" sign, like
# //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
@@ -173,7 +173,7 @@ ($)
push @args, "uintptr($name)", "uintptr($name >> 32)";
}
} elsif($type eq "bool") {
- $text .= "\tvar _p$n uint32\n";
+ $text .= "\tvar _p$n uint32\n";
$text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n";
push @args, "uintptr(_p$n)";
$n++;
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/Documentation/grpc-auth-support.md b/Godeps/_workspace/src/google.golang.org/grpc/Documentation/grpc-auth-support.md
deleted file mode 100644
index 5a075f613..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/Documentation/grpc-auth-support.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# Authentication
-
-As outlined in the [gRPC authentication guide](http://www.grpc.io/docs/guides/auth.html) there are a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it.
-
-# Enabling TLS on a gRPC client
-
-```Go
-conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))
-```
-
-# Enabling TLS on a gRPC server
-
-```Go
-creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
-if err != nil {
- log.Fatalf("Failed to generate credentials %v", err)
-}
-lis, err := net.Listen("tcp", ":0")
-server := grpc.NewServer(grpc.Creds(creds))
-...
-server.Serve(lis)
-```
-
-# Authenticating with Google
-
-## Google Compute Engine (GCE)
-
-```Go
-conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""), grpc.WithPerRPCCredentials(oauth.NewComputeEngine())))
-```
-
-## JWT
-
-```Go
-jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
-if err != nil {
- log.Fatalf("Failed to create JWT credentials: %v", err)
-}
-conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""), grpc.WithPerRPCCredentials(jwtCreds)))
-```
-
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/benchmark.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/benchmark.go
deleted file mode 100644
index 7215d35a5..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/benchmark.go
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- *
- * Copyright 2014, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-/*
-Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks.
-*/
-package benchmark
-
-import (
- "io"
- "math"
- "net"
-
- "golang.org/x/net/context"
- "google.golang.org/grpc"
- testpb "google.golang.org/grpc/benchmark/grpc_testing"
- "google.golang.org/grpc/grpclog"
-)
-
-func newPayload(t testpb.PayloadType, size int) *testpb.Payload {
- if size < 0 {
- grpclog.Fatalf("Requested a response with invalid length %d", size)
- }
- body := make([]byte, size)
- switch t {
- case testpb.PayloadType_COMPRESSABLE:
- case testpb.PayloadType_UNCOMPRESSABLE:
- grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported")
- default:
- grpclog.Fatalf("Unsupported payload type: %d", t)
- }
- return &testpb.Payload{
- Type: t,
- Body: body,
- }
-}
-
-type testServer struct {
-}
-
-func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
- return &testpb.SimpleResponse{
- Payload: newPayload(in.ResponseType, int(in.ResponseSize)),
- }, nil
-}
-
-func (s *testServer) StreamingCall(stream testpb.TestService_StreamingCallServer) error {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- // read done.
- return nil
- }
- if err != nil {
- return err
- }
- if err := stream.Send(&testpb.SimpleResponse{
- Payload: newPayload(in.ResponseType, int(in.ResponseSize)),
- }); err != nil {
- return err
- }
- }
-}
-
-// StartServer starts a gRPC server serving a benchmark service on the given
-// address, which may be something like "localhost:0". It returns its listen
-// address and a function to stop the server.
-func StartServer(addr string) (string, func()) {
- lis, err := net.Listen("tcp", addr)
- if err != nil {
- grpclog.Fatalf("Failed to listen: %v", err)
- }
- s := grpc.NewServer(grpc.MaxConcurrentStreams(math.MaxUint32))
- testpb.RegisterTestServiceServer(s, &testServer{})
- go s.Serve(lis)
- return lis.Addr().String(), func() {
- s.Stop()
- }
-}
-
-// DoUnaryCall performs an unary RPC with given stub and request and response sizes.
-func DoUnaryCall(tc testpb.TestServiceClient, reqSize, respSize int) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize)
- req := &testpb.SimpleRequest{
- ResponseType: pl.Type,
- ResponseSize: int32(respSize),
- Payload: pl,
- }
- if _, err := tc.UnaryCall(context.Background(), req); err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
-}
-
-// DoStreamingRoundTrip performs a round trip for a single streaming rpc.
-func DoStreamingRoundTrip(tc testpb.TestServiceClient, stream testpb.TestService_StreamingCallClient, reqSize, respSize int) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize)
- req := &testpb.SimpleRequest{
- ResponseType: pl.Type,
- ResponseSize: int32(respSize),
- Payload: pl,
- }
- if err := stream.Send(req); err != nil {
- grpclog.Fatalf("StreamingCall(_).Send: %v", err)
- }
- if _, err := stream.Recv(); err != nil {
- grpclog.Fatalf("StreamingCall(_).Recv: %v", err)
- }
-}
-
-// NewClientConn creates a gRPC client connection to addr.
-func NewClientConn(addr string) *grpc.ClientConn {
- conn, err := grpc.Dial(addr, grpc.WithInsecure())
- if err != nil {
- grpclog.Fatalf("NewClientConn(%q) failed to create a ClientConn %v", addr, err)
- }
- return conn
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/client/main.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/client/main.go
deleted file mode 100644
index f9e2a83db..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/client/main.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package main
-
-import (
- "flag"
- "math"
- "net"
- "net/http"
- _ "net/http/pprof"
- "sync"
- "time"
-
- "golang.org/x/net/context"
- "google.golang.org/grpc"
- "google.golang.org/grpc/benchmark"
- testpb "google.golang.org/grpc/benchmark/grpc_testing"
- "google.golang.org/grpc/benchmark/stats"
- "google.golang.org/grpc/grpclog"
-)
-
-var (
- server = flag.String("server", "", "The server address")
- maxConcurrentRPCs = flag.Int("max_concurrent_rpcs", 1, "The max number of concurrent RPCs")
- duration = flag.Int("duration", math.MaxInt32, "The duration in seconds to run the benchmark client")
- trace = flag.Bool("trace", true, "Whether tracing is on")
- rpcType = flag.Int("rpc_type", 0,
- `Configure different client rpc type. Valid options are:
- 0 : unary call;
- 1 : streaming call.`)
-)
-
-func unaryCaller(client testpb.TestServiceClient) {
- benchmark.DoUnaryCall(client, 1, 1)
-}
-
-func streamCaller(client testpb.TestServiceClient, stream testpb.TestService_StreamingCallClient) {
- benchmark.DoStreamingRoundTrip(client, stream, 1, 1)
-}
-
-func buildConnection() (s *stats.Stats, conn *grpc.ClientConn, tc testpb.TestServiceClient) {
- s = stats.NewStats(256)
- conn = benchmark.NewClientConn(*server)
- tc = testpb.NewTestServiceClient(conn)
- return s, conn, tc
-}
-
-func closeLoopUnary() {
- s, conn, tc := buildConnection()
-
- for i := 0; i < 100; i++ {
- unaryCaller(tc)
- }
- ch := make(chan int, *maxConcurrentRPCs*4)
- var (
- mu sync.Mutex
- wg sync.WaitGroup
- )
- wg.Add(*maxConcurrentRPCs)
-
- for i := 0; i < *maxConcurrentRPCs; i++ {
- go func() {
- for _ = range ch {
- start := time.Now()
- unaryCaller(tc)
- elapse := time.Since(start)
- mu.Lock()
- s.Add(elapse)
- mu.Unlock()
- }
- wg.Done()
- }()
- }
- // Stop the client when time is up.
- done := make(chan struct{})
- go func() {
- <-time.After(time.Duration(*duration) * time.Second)
- close(done)
- }()
- ok := true
- for ok {
- select {
- case ch <- 0:
- case <-done:
- ok = false
- }
- }
- close(ch)
- wg.Wait()
- conn.Close()
- grpclog.Println(s.String())
-
-}
-
-func closeLoopStream() {
- s, conn, tc := buildConnection()
- stream, err := tc.StreamingCall(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.StreamingCall(_) = _, %v", tc, err)
- }
- for i := 0; i < 100; i++ {
- streamCaller(tc, stream)
- }
- ch := make(chan int, *maxConcurrentRPCs*4)
- var (
- mu sync.Mutex
- wg sync.WaitGroup
- )
- wg.Add(*maxConcurrentRPCs)
- // Distribute RPCs over maxConcurrentCalls workers.
- for i := 0; i < *maxConcurrentRPCs; i++ {
- go func() {
- for _ = range ch {
- start := time.Now()
- streamCaller(tc, stream)
- elapse := time.Since(start)
- mu.Lock()
- s.Add(elapse)
- mu.Unlock()
- }
- wg.Done()
- }()
- }
- // Stop the client when time is up.
- done := make(chan struct{})
- go func() {
- <-time.After(time.Duration(*duration) * time.Second)
- close(done)
- }()
- ok := true
- for ok {
- select {
- case ch <- 0:
- case <-done:
- ok = false
- }
- }
- close(ch)
- wg.Wait()
- conn.Close()
- grpclog.Println(s.String())
-}
-
-func main() {
- flag.Parse()
- grpc.EnableTracing = *trace
- go func() {
- lis, err := net.Listen("tcp", ":0")
- if err != nil {
- grpclog.Fatalf("Failed to listen: %v", err)
- }
- grpclog.Println("Client profiling address: ", lis.Addr().String())
- if err := http.Serve(lis, nil); err != nil {
- grpclog.Fatalf("Failed to serve: %v", err)
- }
- }()
- switch *rpcType {
- case 0:
- closeLoopUnary()
- case 1:
- closeLoopStream()
- }
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.pb.go
deleted file mode 100644
index 74e13c9e9..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.pb.go
+++ /dev/null
@@ -1,641 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: test.proto
-// DO NOT EDIT!
-
-/*
-Package grpc_testing is a generated protocol buffer package.
-
-It is generated from these files:
- test.proto
-
-It has these top-level messages:
- StatsRequest
- ServerStats
- Payload
- HistogramData
- ClientConfig
- Mark
- ClientArgs
- ClientStats
- ClientStatus
- ServerConfig
- ServerArgs
- ServerStatus
- SimpleRequest
- SimpleResponse
-*/
-package grpc_testing
-
-import proto "github.com/golang/protobuf/proto"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-
-type PayloadType int32
-
-const (
- // Compressable text format.
- PayloadType_COMPRESSABLE PayloadType = 0
- // Uncompressable binary format.
- PayloadType_UNCOMPRESSABLE PayloadType = 1
- // Randomly chosen from all other formats defined in this enum.
- PayloadType_RANDOM PayloadType = 2
-)
-
-var PayloadType_name = map[int32]string{
- 0: "COMPRESSABLE",
- 1: "UNCOMPRESSABLE",
- 2: "RANDOM",
-}
-var PayloadType_value = map[string]int32{
- "COMPRESSABLE": 0,
- "UNCOMPRESSABLE": 1,
- "RANDOM": 2,
-}
-
-func (x PayloadType) String() string {
- return proto.EnumName(PayloadType_name, int32(x))
-}
-
-type ClientType int32
-
-const (
- ClientType_SYNCHRONOUS_CLIENT ClientType = 0
- ClientType_ASYNC_CLIENT ClientType = 1
-)
-
-var ClientType_name = map[int32]string{
- 0: "SYNCHRONOUS_CLIENT",
- 1: "ASYNC_CLIENT",
-}
-var ClientType_value = map[string]int32{
- "SYNCHRONOUS_CLIENT": 0,
- "ASYNC_CLIENT": 1,
-}
-
-func (x ClientType) String() string {
- return proto.EnumName(ClientType_name, int32(x))
-}
-
-type ServerType int32
-
-const (
- ServerType_SYNCHRONOUS_SERVER ServerType = 0
- ServerType_ASYNC_SERVER ServerType = 1
-)
-
-var ServerType_name = map[int32]string{
- 0: "SYNCHRONOUS_SERVER",
- 1: "ASYNC_SERVER",
-}
-var ServerType_value = map[string]int32{
- "SYNCHRONOUS_SERVER": 0,
- "ASYNC_SERVER": 1,
-}
-
-func (x ServerType) String() string {
- return proto.EnumName(ServerType_name, int32(x))
-}
-
-type RpcType int32
-
-const (
- RpcType_UNARY RpcType = 0
- RpcType_STREAMING RpcType = 1
-)
-
-var RpcType_name = map[int32]string{
- 0: "UNARY",
- 1: "STREAMING",
-}
-var RpcType_value = map[string]int32{
- "UNARY": 0,
- "STREAMING": 1,
-}
-
-func (x RpcType) String() string {
- return proto.EnumName(RpcType_name, int32(x))
-}
-
-type StatsRequest struct {
- // run number
- TestNum int32 `protobuf:"varint,1,opt,name=test_num" json:"test_num,omitempty"`
-}
-
-func (m *StatsRequest) Reset() { *m = StatsRequest{} }
-func (m *StatsRequest) String() string { return proto.CompactTextString(m) }
-func (*StatsRequest) ProtoMessage() {}
-
-type ServerStats struct {
- // wall clock time
- TimeElapsed float64 `protobuf:"fixed64,1,opt,name=time_elapsed" json:"time_elapsed,omitempty"`
- // user time used by the server process and threads
- TimeUser float64 `protobuf:"fixed64,2,opt,name=time_user" json:"time_user,omitempty"`
- // server time used by the server process and all threads
- TimeSystem float64 `protobuf:"fixed64,3,opt,name=time_system" json:"time_system,omitempty"`
-}
-
-func (m *ServerStats) Reset() { *m = ServerStats{} }
-func (m *ServerStats) String() string { return proto.CompactTextString(m) }
-func (*ServerStats) ProtoMessage() {}
-
-type Payload struct {
- // The type of data in body.
- Type PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"`
- // Primary contents of payload.
- Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"`
-}
-
-func (m *Payload) Reset() { *m = Payload{} }
-func (m *Payload) String() string { return proto.CompactTextString(m) }
-func (*Payload) ProtoMessage() {}
-
-type HistogramData struct {
- Bucket []uint32 `protobuf:"varint,1,rep,name=bucket" json:"bucket,omitempty"`
- MinSeen float64 `protobuf:"fixed64,2,opt,name=min_seen" json:"min_seen,omitempty"`
- MaxSeen float64 `protobuf:"fixed64,3,opt,name=max_seen" json:"max_seen,omitempty"`
- Sum float64 `protobuf:"fixed64,4,opt,name=sum" json:"sum,omitempty"`
- SumOfSquares float64 `protobuf:"fixed64,5,opt,name=sum_of_squares" json:"sum_of_squares,omitempty"`
- Count float64 `protobuf:"fixed64,6,opt,name=count" json:"count,omitempty"`
-}
-
-func (m *HistogramData) Reset() { *m = HistogramData{} }
-func (m *HistogramData) String() string { return proto.CompactTextString(m) }
-func (*HistogramData) ProtoMessage() {}
-
-type ClientConfig struct {
- ServerTargets []string `protobuf:"bytes,1,rep,name=server_targets" json:"server_targets,omitempty"`
- ClientType ClientType `protobuf:"varint,2,opt,name=client_type,enum=grpc.testing.ClientType" json:"client_type,omitempty"`
- EnableSsl bool `protobuf:"varint,3,opt,name=enable_ssl" json:"enable_ssl,omitempty"`
- OutstandingRpcsPerChannel int32 `protobuf:"varint,4,opt,name=outstanding_rpcs_per_channel" json:"outstanding_rpcs_per_channel,omitempty"`
- ClientChannels int32 `protobuf:"varint,5,opt,name=client_channels" json:"client_channels,omitempty"`
- PayloadSize int32 `protobuf:"varint,6,opt,name=payload_size" json:"payload_size,omitempty"`
- // only for async client:
- AsyncClientThreads int32 `protobuf:"varint,7,opt,name=async_client_threads" json:"async_client_threads,omitempty"`
- RpcType RpcType `protobuf:"varint,8,opt,name=rpc_type,enum=grpc.testing.RpcType" json:"rpc_type,omitempty"`
-}
-
-func (m *ClientConfig) Reset() { *m = ClientConfig{} }
-func (m *ClientConfig) String() string { return proto.CompactTextString(m) }
-func (*ClientConfig) ProtoMessage() {}
-
-// Request current stats
-type Mark struct {
-}
-
-func (m *Mark) Reset() { *m = Mark{} }
-func (m *Mark) String() string { return proto.CompactTextString(m) }
-func (*Mark) ProtoMessage() {}
-
-type ClientArgs struct {
- Setup *ClientConfig `protobuf:"bytes,1,opt,name=setup" json:"setup,omitempty"`
- Mark *Mark `protobuf:"bytes,2,opt,name=mark" json:"mark,omitempty"`
-}
-
-func (m *ClientArgs) Reset() { *m = ClientArgs{} }
-func (m *ClientArgs) String() string { return proto.CompactTextString(m) }
-func (*ClientArgs) ProtoMessage() {}
-
-func (m *ClientArgs) GetSetup() *ClientConfig {
- if m != nil {
- return m.Setup
- }
- return nil
-}
-
-func (m *ClientArgs) GetMark() *Mark {
- if m != nil {
- return m.Mark
- }
- return nil
-}
-
-type ClientStats struct {
- Latencies *HistogramData `protobuf:"bytes,1,opt,name=latencies" json:"latencies,omitempty"`
- TimeElapsed float64 `protobuf:"fixed64,3,opt,name=time_elapsed" json:"time_elapsed,omitempty"`
- TimeUser float64 `protobuf:"fixed64,4,opt,name=time_user" json:"time_user,omitempty"`
- TimeSystem float64 `protobuf:"fixed64,5,opt,name=time_system" json:"time_system,omitempty"`
-}
-
-func (m *ClientStats) Reset() { *m = ClientStats{} }
-func (m *ClientStats) String() string { return proto.CompactTextString(m) }
-func (*ClientStats) ProtoMessage() {}
-
-func (m *ClientStats) GetLatencies() *HistogramData {
- if m != nil {
- return m.Latencies
- }
- return nil
-}
-
-type ClientStatus struct {
- Stats *ClientStats `protobuf:"bytes,1,opt,name=stats" json:"stats,omitempty"`
-}
-
-func (m *ClientStatus) Reset() { *m = ClientStatus{} }
-func (m *ClientStatus) String() string { return proto.CompactTextString(m) }
-func (*ClientStatus) ProtoMessage() {}
-
-func (m *ClientStatus) GetStats() *ClientStats {
- if m != nil {
- return m.Stats
- }
- return nil
-}
-
-type ServerConfig struct {
- ServerType ServerType `protobuf:"varint,1,opt,name=server_type,enum=grpc.testing.ServerType" json:"server_type,omitempty"`
- Threads int32 `protobuf:"varint,2,opt,name=threads" json:"threads,omitempty"`
- EnableSsl bool `protobuf:"varint,3,opt,name=enable_ssl" json:"enable_ssl,omitempty"`
-}
-
-func (m *ServerConfig) Reset() { *m = ServerConfig{} }
-func (m *ServerConfig) String() string { return proto.CompactTextString(m) }
-func (*ServerConfig) ProtoMessage() {}
-
-type ServerArgs struct {
- Setup *ServerConfig `protobuf:"bytes,1,opt,name=setup" json:"setup,omitempty"`
- Mark *Mark `protobuf:"bytes,2,opt,name=mark" json:"mark,omitempty"`
-}
-
-func (m *ServerArgs) Reset() { *m = ServerArgs{} }
-func (m *ServerArgs) String() string { return proto.CompactTextString(m) }
-func (*ServerArgs) ProtoMessage() {}
-
-func (m *ServerArgs) GetSetup() *ServerConfig {
- if m != nil {
- return m.Setup
- }
- return nil
-}
-
-func (m *ServerArgs) GetMark() *Mark {
- if m != nil {
- return m.Mark
- }
- return nil
-}
-
-type ServerStatus struct {
- Stats *ServerStats `protobuf:"bytes,1,opt,name=stats" json:"stats,omitempty"`
- Port int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"`
-}
-
-func (m *ServerStatus) Reset() { *m = ServerStatus{} }
-func (m *ServerStatus) String() string { return proto.CompactTextString(m) }
-func (*ServerStatus) ProtoMessage() {}
-
-func (m *ServerStatus) GetStats() *ServerStats {
- if m != nil {
- return m.Stats
- }
- return nil
-}
-
-type SimpleRequest struct {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,enum=grpc.testing.PayloadType" json:"response_type,omitempty"`
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- ResponseSize int32 `protobuf:"varint,2,opt,name=response_size" json:"response_size,omitempty"`
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
-}
-
-func (m *SimpleRequest) Reset() { *m = SimpleRequest{} }
-func (m *SimpleRequest) String() string { return proto.CompactTextString(m) }
-func (*SimpleRequest) ProtoMessage() {}
-
-func (m *SimpleRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-type SimpleResponse struct {
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
-}
-
-func (m *SimpleResponse) Reset() { *m = SimpleResponse{} }
-func (m *SimpleResponse) String() string { return proto.CompactTextString(m) }
-func (*SimpleResponse) ProtoMessage() {}
-
-func (m *SimpleResponse) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func init() {
- proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value)
- proto.RegisterEnum("grpc.testing.ClientType", ClientType_name, ClientType_value)
- proto.RegisterEnum("grpc.testing.ServerType", ServerType_name, ServerType_value)
- proto.RegisterEnum("grpc.testing.RpcType", RpcType_name, RpcType_value)
-}
-
-// Client API for TestService service
-
-type TestServiceClient interface {
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- StreamingCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingCallClient, error)
-}
-
-type testServiceClient struct {
- cc *grpc.ClientConn
-}
-
-func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient {
- return &testServiceClient{cc}
-}
-
-func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
- out := new(SimpleResponse)
- err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/StreamingCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceStreamingCallClient{stream}
- return x, nil
-}
-
-type TestService_StreamingCallClient interface {
- Send(*SimpleRequest) error
- Recv() (*SimpleResponse, error)
- grpc.ClientStream
-}
-
-type testServiceStreamingCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceStreamingCallClient) Send(m *SimpleRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingCallClient) Recv() (*SimpleResponse, error) {
- m := new(SimpleResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for TestService service
-
-type TestServiceServer interface {
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- StreamingCall(TestService_StreamingCallServer) error
-}
-
-func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
- s.RegisterService(&_TestService_serviceDesc, srv)
-}
-
-func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(SimpleRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(TestServiceServer).UnaryCall(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _TestService_StreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).StreamingCall(&testServiceStreamingCallServer{stream})
-}
-
-type TestService_StreamingCallServer interface {
- Send(*SimpleResponse) error
- Recv() (*SimpleRequest, error)
- grpc.ServerStream
-}
-
-type testServiceStreamingCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceStreamingCallServer) Send(m *SimpleResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingCallServer) Recv() (*SimpleRequest, error) {
- m := new(SimpleRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _TestService_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.testing.TestService",
- HandlerType: (*TestServiceServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "UnaryCall",
- Handler: _TestService_UnaryCall_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "StreamingCall",
- Handler: _TestService_StreamingCall_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
-}
-
-// Client API for Worker service
-
-type WorkerClient interface {
- // Start test with specified workload
- RunTest(ctx context.Context, opts ...grpc.CallOption) (Worker_RunTestClient, error)
- // Start test with specified workload
- RunServer(ctx context.Context, opts ...grpc.CallOption) (Worker_RunServerClient, error)
-}
-
-type workerClient struct {
- cc *grpc.ClientConn
-}
-
-func NewWorkerClient(cc *grpc.ClientConn) WorkerClient {
- return &workerClient{cc}
-}
-
-func (c *workerClient) RunTest(ctx context.Context, opts ...grpc.CallOption) (Worker_RunTestClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_Worker_serviceDesc.Streams[0], c.cc, "/grpc.testing.Worker/RunTest", opts...)
- if err != nil {
- return nil, err
- }
- x := &workerRunTestClient{stream}
- return x, nil
-}
-
-type Worker_RunTestClient interface {
- Send(*ClientArgs) error
- Recv() (*ClientStatus, error)
- grpc.ClientStream
-}
-
-type workerRunTestClient struct {
- grpc.ClientStream
-}
-
-func (x *workerRunTestClient) Send(m *ClientArgs) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *workerRunTestClient) Recv() (*ClientStatus, error) {
- m := new(ClientStatus)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *workerClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (Worker_RunServerClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_Worker_serviceDesc.Streams[1], c.cc, "/grpc.testing.Worker/RunServer", opts...)
- if err != nil {
- return nil, err
- }
- x := &workerRunServerClient{stream}
- return x, nil
-}
-
-type Worker_RunServerClient interface {
- Send(*ServerArgs) error
- Recv() (*ServerStatus, error)
- grpc.ClientStream
-}
-
-type workerRunServerClient struct {
- grpc.ClientStream
-}
-
-func (x *workerRunServerClient) Send(m *ServerArgs) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *workerRunServerClient) Recv() (*ServerStatus, error) {
- m := new(ServerStatus)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for Worker service
-
-type WorkerServer interface {
- // Start test with specified workload
- RunTest(Worker_RunTestServer) error
- // Start test with specified workload
- RunServer(Worker_RunServerServer) error
-}
-
-func RegisterWorkerServer(s *grpc.Server, srv WorkerServer) {
- s.RegisterService(&_Worker_serviceDesc, srv)
-}
-
-func _Worker_RunTest_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(WorkerServer).RunTest(&workerRunTestServer{stream})
-}
-
-type Worker_RunTestServer interface {
- Send(*ClientStatus) error
- Recv() (*ClientArgs, error)
- grpc.ServerStream
-}
-
-type workerRunTestServer struct {
- grpc.ServerStream
-}
-
-func (x *workerRunTestServer) Send(m *ClientStatus) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *workerRunTestServer) Recv() (*ClientArgs, error) {
- m := new(ClientArgs)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _Worker_RunServer_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(WorkerServer).RunServer(&workerRunServerServer{stream})
-}
-
-type Worker_RunServerServer interface {
- Send(*ServerStatus) error
- Recv() (*ServerArgs, error)
- grpc.ServerStream
-}
-
-type workerRunServerServer struct {
- grpc.ServerStream
-}
-
-func (x *workerRunServerServer) Send(m *ServerStatus) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *workerRunServerServer) Recv() (*ServerArgs, error) {
- m := new(ServerArgs)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _Worker_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.testing.Worker",
- HandlerType: (*WorkerServer)(nil),
- Methods: []grpc.MethodDesc{},
- Streams: []grpc.StreamDesc{
- {
- StreamName: "RunTest",
- Handler: _Worker_RunTest_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- {
- StreamName: "RunServer",
- Handler: _Worker_RunServer_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.proto b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.proto
deleted file mode 100644
index e3a27f861..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/grpc_testing/test.proto
+++ /dev/null
@@ -1,148 +0,0 @@
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto3";
-
-package grpc.testing;
-
-enum PayloadType {
- // Compressable text format.
- COMPRESSABLE = 0;
-
- // Uncompressable binary format.
- UNCOMPRESSABLE = 1;
-
- // Randomly chosen from all other formats defined in this enum.
- RANDOM = 2;
-}
-
-message StatsRequest {
- // run number
- optional int32 test_num = 1;
-}
-
-message ServerStats {
- // wall clock time
- double time_elapsed = 1;
-
- // user time used by the server process and threads
- double time_user = 2;
-
- // server time used by the server process and all threads
- double time_system = 3;
-}
-
-message Payload {
- // The type of data in body.
- PayloadType type = 1;
- // Primary contents of payload.
- bytes body = 2;
-}
-
-message HistogramData {
- repeated uint32 bucket = 1;
- double min_seen = 2;
- double max_seen = 3;
- double sum = 4;
- double sum_of_squares = 5;
- double count = 6;
-}
-
-enum ClientType {
- SYNCHRONOUS_CLIENT = 0;
- ASYNC_CLIENT = 1;
-}
-
-enum ServerType {
- SYNCHRONOUS_SERVER = 0;
- ASYNC_SERVER = 1;
-}
-
-enum RpcType {
- UNARY = 0;
- STREAMING = 1;
-}
-
-message ClientConfig {
- repeated string server_targets = 1;
- ClientType client_type = 2;
- bool enable_ssl = 3;
- int32 outstanding_rpcs_per_channel = 4;
- int32 client_channels = 5;
- int32 payload_size = 6;
- // only for async client:
- int32 async_client_threads = 7;
- RpcType rpc_type = 8;
-}
-
-// Request current stats
-message Mark {}
-
-message ClientArgs {
- oneof argtype {
- ClientConfig setup = 1;
- Mark mark = 2;
- }
-}
-
-message ClientStats {
- HistogramData latencies = 1;
- double time_elapsed = 3;
- double time_user = 4;
- double time_system = 5;
-}
-
-message ClientStatus {
- ClientStats stats = 1;
-}
-
-message ServerConfig {
- ServerType server_type = 1;
- int32 threads = 2;
- bool enable_ssl = 3;
-}
-
-message ServerArgs {
- oneof argtype {
- ServerConfig setup = 1;
- Mark mark = 2;
- }
-}
-
-message ServerStatus {
- ServerStats stats = 1;
- int32 port = 2;
-}
-
-message SimpleRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- PayloadType response_type = 1;
-
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- int32 response_size = 2;
-
- // Optional input payload sent along with the request.
- Payload payload = 3;
-}
-
-message SimpleResponse {
- Payload payload = 1;
-}
-
-service TestService {
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse);
-}
-
-service Worker {
- // Start test with specified workload
- rpc RunTest(stream ClientArgs) returns (stream ClientStatus);
- // Start test with specified workload
- rpc RunServer(stream ServerArgs) returns (stream ServerStatus);
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/server/main.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/server/main.go
deleted file mode 100644
index 090f002fa..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/server/main.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package main
-
-import (
- "flag"
- "math"
- "net"
- "net/http"
- _ "net/http/pprof"
- "time"
-
- "google.golang.org/grpc/benchmark"
- "google.golang.org/grpc/grpclog"
-)
-
-var (
- duration = flag.Int("duration", math.MaxInt32, "The duration in seconds to run the benchmark server")
-)
-
-func main() {
- flag.Parse()
- go func() {
- lis, err := net.Listen("tcp", ":0")
- if err != nil {
- grpclog.Fatalf("Failed to listen: %v", err)
- }
- grpclog.Println("Server profiling address: ", lis.Addr().String())
- if err := http.Serve(lis, nil); err != nil {
- grpclog.Fatalf("Failed to serve: %v", err)
- }
- }()
- addr, stopper := benchmark.StartServer(":0") // listen on all interfaces
- grpclog.Println("Server Address: ", addr)
- <-time.After(time.Duration(*duration) * time.Second)
- stopper()
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/counter.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/counter.go
deleted file mode 100644
index 4389bae38..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/counter.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package stats
-
-import (
- "sync"
- "time"
-)
-
-var (
- // TimeNow is used for testing.
- TimeNow = time.Now
-)
-
-const (
- hour = 0
- tenminutes = 1
- minute = 2
-)
-
-// Counter is a counter that keeps track of its recent values over a given
-// period of time, and with a given resolution. Use newCounter() to instantiate.
-type Counter struct {
- mu sync.RWMutex
- ts [3]*timeseries
- lastUpdate time.Time
-}
-
-// newCounter returns a new Counter.
-func newCounter() *Counter {
- now := TimeNow()
- c := &Counter{}
- c.ts[hour] = newTimeSeries(now, time.Hour, time.Minute)
- c.ts[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second)
- c.ts[minute] = newTimeSeries(now, time.Minute, time.Second)
- return c
-}
-
-func (c *Counter) advance() time.Time {
- now := TimeNow()
- for _, ts := range c.ts {
- ts.advanceTime(now)
- }
- return now
-}
-
-// Value returns the current value of the counter.
-func (c *Counter) Value() int64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- return c.ts[minute].headValue()
-}
-
-// LastUpdate returns the last update time of the counter.
-func (c *Counter) LastUpdate() time.Time {
- c.mu.RLock()
- defer c.mu.RUnlock()
- return c.lastUpdate
-}
-
-// Set updates the current value of the counter.
-func (c *Counter) Set(value int64) {
- c.mu.Lock()
- defer c.mu.Unlock()
- c.lastUpdate = c.advance()
- for _, ts := range c.ts {
- ts.set(value)
- }
-}
-
-// Incr increments the current value of the counter by 'delta'.
-func (c *Counter) Incr(delta int64) {
- c.mu.Lock()
- defer c.mu.Unlock()
- c.lastUpdate = c.advance()
- for _, ts := range c.ts {
- ts.incr(delta)
- }
-}
-
-// Delta1h returns the delta for the last hour.
-func (c *Counter) Delta1h() int64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[hour].delta()
-}
-
-// Delta10m returns the delta for the last 10 minutes.
-func (c *Counter) Delta10m() int64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[tenminutes].delta()
-}
-
-// Delta1m returns the delta for the last minute.
-func (c *Counter) Delta1m() int64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[minute].delta()
-}
-
-// Rate1h returns the rate of change of the counter in the last hour.
-func (c *Counter) Rate1h() float64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[hour].rate()
-}
-
-// Rate10m returns the rate of change of the counter in the last 10 minutes.
-func (c *Counter) Rate10m() float64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[tenminutes].rate()
-}
-
-// Rate1m returns the rate of change of the counter in the last minute.
-func (c *Counter) Rate1m() float64 {
- c.mu.RLock()
- defer c.mu.RUnlock()
- c.advance()
- return c.ts[minute].rate()
-}
-
-// Reset resets the counter to an empty state.
-func (c *Counter) Reset() {
- c.mu.Lock()
- defer c.mu.Unlock()
- now := TimeNow()
- for _, ts := range c.ts {
- ts.reset(now)
- }
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/histogram.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/histogram.go
deleted file mode 100644
index 727808c8b..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/histogram.go
+++ /dev/null
@@ -1,255 +0,0 @@
-package stats
-
-import (
- "bytes"
- "fmt"
- "io"
- "strconv"
- "strings"
- "time"
-)
-
-// HistogramValue is the value of Histogram objects.
-type HistogramValue struct {
- // Count is the total number of values added to the histogram.
- Count int64
- // Sum is the sum of all the values added to the histogram.
- Sum int64
- // Min is the minimum of all the values added to the histogram.
- Min int64
- // Max is the maximum of all the values added to the histogram.
- Max int64
- // Buckets contains all the buckets of the histogram.
- Buckets []HistogramBucket
-}
-
-// HistogramBucket is one histogram bucket.
-type HistogramBucket struct {
- // LowBound is the lower bound of the bucket.
- LowBound int64
- // Count is the number of values in the bucket.
- Count int64
-}
-
-// Print writes textual output of the histogram values.
-func (v HistogramValue) Print(w io.Writer) {
- avg := float64(v.Sum) / float64(v.Count)
- fmt.Fprintf(w, "Count: %d Min: %d Max: %d Avg: %.2f\n", v.Count, v.Min, v.Max, avg)
- fmt.Fprintf(w, "%s\n", strings.Repeat("-", 60))
- if v.Count <= 0 {
- return
- }
-
- maxBucketDigitLen := len(strconv.FormatInt(v.Buckets[len(v.Buckets)-1].LowBound, 10))
- if maxBucketDigitLen < 3 {
- // For "inf".
- maxBucketDigitLen = 3
- }
- maxCountDigitLen := len(strconv.FormatInt(v.Count, 10))
- percentMulti := 100 / float64(v.Count)
-
- accCount := int64(0)
- for i, b := range v.Buckets {
- fmt.Fprintf(w, "[%*d, ", maxBucketDigitLen, b.LowBound)
- if i+1 < len(v.Buckets) {
- fmt.Fprintf(w, "%*d)", maxBucketDigitLen, v.Buckets[i+1].LowBound)
- } else {
- fmt.Fprintf(w, "%*s)", maxBucketDigitLen, "inf")
- }
-
- accCount += b.Count
- fmt.Fprintf(w, " %*d %5.1f%% %5.1f%%", maxCountDigitLen, b.Count, float64(b.Count)*percentMulti, float64(accCount)*percentMulti)
-
- const barScale = 0.1
- barLength := int(float64(b.Count)*percentMulti*barScale + 0.5)
- fmt.Fprintf(w, " %s\n", strings.Repeat("#", barLength))
- }
-}
-
-// String returns the textual output of the histogram values as string.
-func (v HistogramValue) String() string {
- var b bytes.Buffer
- v.Print(&b)
- return b.String()
-}
-
-// A Histogram accumulates values in the form of a histogram. The type of the
-// values is int64, which is suitable for keeping track of things like RPC
-// latency in milliseconds. New histogram objects should be obtained via the
-// New() function.
-type Histogram struct {
- opts HistogramOptions
- buckets []bucketInternal
- count *Counter
- sum *Counter
- tracker *Tracker
-}
-
-// HistogramOptions contains the parameters that define the histogram's buckets.
-type HistogramOptions struct {
- // NumBuckets is the number of buckets.
- NumBuckets int
- // GrowthFactor is the growth factor of the buckets. A value of 0.1
- // indicates that bucket N+1 will be 10% larger than bucket N.
- GrowthFactor float64
- // SmallestBucketSize is the size of the first bucket. Bucket sizes are
- // rounded down to the nearest integer.
- SmallestBucketSize float64
- // MinValue is the lower bound of the first bucket.
- MinValue int64
-}
-
-// bucketInternal is the internal representation of a bucket, which includes a
-// rate counter.
-type bucketInternal struct {
- lowBound int64
- count *Counter
-}
-
-// NewHistogram returns a pointer to a new Histogram object that was created
-// with the provided options.
-func NewHistogram(opts HistogramOptions) *Histogram {
- if opts.NumBuckets == 0 {
- opts.NumBuckets = 32
- }
- if opts.SmallestBucketSize == 0.0 {
- opts.SmallestBucketSize = 1.0
- }
- h := Histogram{
- opts: opts,
- buckets: make([]bucketInternal, opts.NumBuckets),
- count: newCounter(),
- sum: newCounter(),
- tracker: newTracker(),
- }
- low := opts.MinValue
- delta := opts.SmallestBucketSize
- for i := 0; i < opts.NumBuckets; i++ {
- h.buckets[i].lowBound = low
- h.buckets[i].count = newCounter()
- low = low + int64(delta)
- delta = delta * (1.0 + opts.GrowthFactor)
- }
- return &h
-}
-
-// Opts returns a copy of the options used to create the Histogram.
-func (h *Histogram) Opts() HistogramOptions {
- return h.opts
-}
-
-// Add adds a value to the histogram.
-func (h *Histogram) Add(value int64) error {
- bucket, err := h.findBucket(value)
- if err != nil {
- return err
- }
- h.buckets[bucket].count.Incr(1)
- h.count.Incr(1)
- h.sum.Incr(value)
- h.tracker.Push(value)
- return nil
-}
-
-// LastUpdate returns the time at which the object was last updated.
-func (h *Histogram) LastUpdate() time.Time {
- return h.count.LastUpdate()
-}
-
-// Value returns the accumulated state of the histogram since it was created.
-func (h *Histogram) Value() HistogramValue {
- b := make([]HistogramBucket, len(h.buckets))
- for i, v := range h.buckets {
- b[i] = HistogramBucket{
- LowBound: v.lowBound,
- Count: v.count.Value(),
- }
- }
-
- v := HistogramValue{
- Count: h.count.Value(),
- Sum: h.sum.Value(),
- Min: h.tracker.Min(),
- Max: h.tracker.Max(),
- Buckets: b,
- }
- return v
-}
-
-// Delta1h returns the change in the last hour.
-func (h *Histogram) Delta1h() HistogramValue {
- b := make([]HistogramBucket, len(h.buckets))
- for i, v := range h.buckets {
- b[i] = HistogramBucket{
- LowBound: v.lowBound,
- Count: v.count.Delta1h(),
- }
- }
-
- v := HistogramValue{
- Count: h.count.Delta1h(),
- Sum: h.sum.Delta1h(),
- Min: h.tracker.Min1h(),
- Max: h.tracker.Max1h(),
- Buckets: b,
- }
- return v
-}
-
-// Delta10m returns the change in the last 10 minutes.
-func (h *Histogram) Delta10m() HistogramValue {
- b := make([]HistogramBucket, len(h.buckets))
- for i, v := range h.buckets {
- b[i] = HistogramBucket{
- LowBound: v.lowBound,
- Count: v.count.Delta10m(),
- }
- }
-
- v := HistogramValue{
- Count: h.count.Delta10m(),
- Sum: h.sum.Delta10m(),
- Min: h.tracker.Min10m(),
- Max: h.tracker.Max10m(),
- Buckets: b,
- }
- return v
-}
-
-// Delta1m returns the change in the last 10 minutes.
-func (h *Histogram) Delta1m() HistogramValue {
- b := make([]HistogramBucket, len(h.buckets))
- for i, v := range h.buckets {
- b[i] = HistogramBucket{
- LowBound: v.lowBound,
- Count: v.count.Delta1m(),
- }
- }
-
- v := HistogramValue{
- Count: h.count.Delta1m(),
- Sum: h.sum.Delta1m(),
- Min: h.tracker.Min1m(),
- Max: h.tracker.Max1m(),
- Buckets: b,
- }
- return v
-}
-
-// findBucket does a binary search to find in which bucket the value goes.
-func (h *Histogram) findBucket(value int64) (int, error) {
- lastBucket := len(h.buckets) - 1
- min, max := 0, lastBucket
- for max >= min {
- b := (min + max) / 2
- if value >= h.buckets[b].lowBound && (b == lastBucket || value < h.buckets[b+1].lowBound) {
- return b, nil
- }
- if value < h.buckets[b].lowBound {
- max = b - 1
- continue
- }
- min = b + 1
- }
- return 0, fmt.Errorf("no bucket for value: %d", value)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/stats.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/stats.go
deleted file mode 100644
index 4290ad77e..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/stats.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package stats
-
-import (
- "bytes"
- "fmt"
- "io"
- "math"
- "time"
-)
-
-// Stats is a simple helper for gathering additional statistics like histogram
-// during benchmarks. This is not thread safe.
-type Stats struct {
- numBuckets int
- unit time.Duration
- min, max int64
- histogram *Histogram
-
- durations durationSlice
- dirty bool
-}
-
-type durationSlice []time.Duration
-
-// NewStats creates a new Stats instance. If numBuckets is not positive,
-// the default value (16) will be used.
-func NewStats(numBuckets int) *Stats {
- if numBuckets <= 0 {
- numBuckets = 16
- }
- return &Stats{
- // Use one more bucket for the last unbounded bucket.
- numBuckets: numBuckets + 1,
- durations: make(durationSlice, 0, 100000),
- }
-}
-
-// Add adds an elapsed time per operation to the stats.
-func (stats *Stats) Add(d time.Duration) {
- stats.durations = append(stats.durations, d)
- stats.dirty = true
-}
-
-// Clear resets the stats, removing all values.
-func (stats *Stats) Clear() {
- stats.durations = stats.durations[:0]
- stats.histogram = nil
- stats.dirty = false
-}
-
-// maybeUpdate updates internal stat data if there was any newly added
-// stats since this was updated.
-func (stats *Stats) maybeUpdate() {
- if !stats.dirty {
- return
- }
-
- stats.min = math.MaxInt64
- stats.max = 0
- for _, d := range stats.durations {
- if stats.min > int64(d) {
- stats.min = int64(d)
- }
- if stats.max < int64(d) {
- stats.max = int64(d)
- }
- }
-
- // Use the largest unit that can represent the minimum time duration.
- stats.unit = time.Nanosecond
- for _, u := range []time.Duration{time.Microsecond, time.Millisecond, time.Second} {
- if stats.min <= int64(u) {
- break
- }
- stats.unit = u
- }
-
- // Adjust the min/max according to the new unit.
- stats.min /= int64(stats.unit)
- stats.max /= int64(stats.unit)
- numBuckets := stats.numBuckets
- if n := int(stats.max - stats.min + 1); n < numBuckets {
- numBuckets = n
- }
- stats.histogram = NewHistogram(HistogramOptions{
- NumBuckets: numBuckets,
- // max(i.e., Nth lower bound) = min + (1 + growthFactor)^(numBuckets-2).
- GrowthFactor: math.Pow(float64(stats.max-stats.min), 1/float64(stats.numBuckets-2)) - 1,
- SmallestBucketSize: 1.0,
- MinValue: stats.min})
-
- for _, d := range stats.durations {
- stats.histogram.Add(int64(d / stats.unit))
- }
-
- stats.dirty = false
-}
-
-// Print writes textual output of the Stats.
-func (stats *Stats) Print(w io.Writer) {
- stats.maybeUpdate()
-
- if stats.histogram == nil {
- fmt.Fprint(w, "Histogram (empty)\n")
- } else {
- fmt.Fprintf(w, "Histogram (unit: %s)\n", fmt.Sprintf("%v", stats.unit)[1:])
- stats.histogram.Value().Print(w)
- }
-}
-
-// String returns the textual output of the Stats as string.
-func (stats *Stats) String() string {
- var b bytes.Buffer
- stats.Print(&b)
- return b.String()
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/timeseries.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/timeseries.go
deleted file mode 100644
index 2ba18a4d4..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/timeseries.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package stats
-
-import (
- "math"
- "time"
-)
-
-// timeseries holds the history of a changing value over a predefined period of
-// time.
-type timeseries struct {
- size int // The number of time slots. Equivalent to len(slots).
- resolution time.Duration // The time resolution of each slot.
- stepCount int64 // The number of intervals seen since creation.
- head int // The position of the current time in slots.
- time time.Time // The time at the beginning of the current time slot.
- slots []int64 // A circular buffer of time slots.
-}
-
-// newTimeSeries returns a newly allocated timeseries that covers the requested
-// period with the given resolution.
-func newTimeSeries(initialTime time.Time, period, resolution time.Duration) *timeseries {
- size := int(period.Nanoseconds()/resolution.Nanoseconds()) + 1
- return ×eries{
- size: size,
- resolution: resolution,
- stepCount: 1,
- time: initialTime,
- slots: make([]int64, size),
- }
-}
-
-// advanceTimeWithFill moves the timeseries forward to time t and fills in any
-// slots that get skipped in the process with the given value. Values older than
-// the timeseries period are lost.
-func (ts *timeseries) advanceTimeWithFill(t time.Time, value int64) {
- advanceTo := t.Truncate(ts.resolution)
- if !advanceTo.After(ts.time) {
- // This is shortcut for the most common case of a busy counter
- // where updates come in many times per ts.resolution.
- ts.time = advanceTo
- return
- }
- steps := int(advanceTo.Sub(ts.time).Nanoseconds() / ts.resolution.Nanoseconds())
- ts.stepCount += int64(steps)
- if steps > ts.size {
- steps = ts.size
- }
- for steps > 0 {
- ts.head = (ts.head + 1) % ts.size
- ts.slots[ts.head] = value
- steps--
- }
- ts.time = advanceTo
-}
-
-// advanceTime moves the timeseries forward to time t and fills in any slots
-// that get skipped in the process with the head value. Values older than the
-// timeseries period are lost.
-func (ts *timeseries) advanceTime(t time.Time) {
- ts.advanceTimeWithFill(t, ts.slots[ts.head])
-}
-
-// set sets the current value of the timeseries.
-func (ts *timeseries) set(value int64) {
- ts.slots[ts.head] = value
-}
-
-// incr sets the current value of the timeseries.
-func (ts *timeseries) incr(delta int64) {
- ts.slots[ts.head] += delta
-}
-
-// headValue returns the latest value from the timeseries.
-func (ts *timeseries) headValue() int64 {
- return ts.slots[ts.head]
-}
-
-// headTime returns the time of the latest value from the timeseries.
-func (ts *timeseries) headTime() time.Time {
- return ts.time
-}
-
-// tailValue returns the oldest value from the timeseries.
-func (ts *timeseries) tailValue() int64 {
- if ts.stepCount < int64(ts.size) {
- return 0
- }
- return ts.slots[(ts.head+1)%ts.size]
-}
-
-// tailTime returns the time of the oldest value from the timeseries.
-func (ts *timeseries) tailTime() time.Time {
- size := int64(ts.size)
- if ts.stepCount < size {
- size = ts.stepCount
- }
- return ts.time.Add(-time.Duration(size-1) * ts.resolution)
-}
-
-// delta returns the difference between the newest and oldest values from the
-// timeseries.
-func (ts *timeseries) delta() int64 {
- return ts.headValue() - ts.tailValue()
-}
-
-// rate returns the rate of change between the oldest and newest values from
-// the timeseries in units per second.
-func (ts *timeseries) rate() float64 {
- deltaTime := ts.headTime().Sub(ts.tailTime()).Seconds()
- if deltaTime == 0 {
- return 0
- }
- return float64(ts.delta()) / deltaTime
-}
-
-// min returns the smallest value from the timeseries.
-func (ts *timeseries) min() int64 {
- to := ts.size
- if ts.stepCount < int64(ts.size) {
- to = ts.head + 1
- }
- tail := (ts.head + 1) % ts.size
- min := int64(math.MaxInt64)
- for b := 0; b < to; b++ {
- if b != tail && ts.slots[b] < min {
- min = ts.slots[b]
- }
- }
- return min
-}
-
-// max returns the largest value from the timeseries.
-func (ts *timeseries) max() int64 {
- to := ts.size
- if ts.stepCount < int64(ts.size) {
- to = ts.head + 1
- }
- tail := (ts.head + 1) % ts.size
- max := int64(math.MinInt64)
- for b := 0; b < to; b++ {
- if b != tail && ts.slots[b] > max {
- max = ts.slots[b]
- }
- }
- return max
-}
-
-// reset resets the timeseries to an empty state.
-func (ts *timeseries) reset(t time.Time) {
- ts.head = 0
- ts.time = t
- ts.stepCount = 1
- ts.slots = make([]int64, ts.size)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/tracker.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/tracker.go
deleted file mode 100644
index 802f72957..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/tracker.go
+++ /dev/null
@@ -1,159 +0,0 @@
-package stats
-
-import (
- "math"
- "sync"
- "time"
-)
-
-// Tracker is a min/max value tracker that keeps track of its min/max values
-// over a given period of time, and with a given resolution. The initial min
-// and max values are math.MaxInt64 and math.MinInt64 respectively.
-type Tracker struct {
- mu sync.RWMutex
- min, max int64 // All time min/max.
- minTS, maxTS [3]*timeseries
- lastUpdate time.Time
-}
-
-// newTracker returns a new Tracker.
-func newTracker() *Tracker {
- now := TimeNow()
- t := &Tracker{}
- t.minTS[hour] = newTimeSeries(now, time.Hour, time.Minute)
- t.minTS[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second)
- t.minTS[minute] = newTimeSeries(now, time.Minute, time.Second)
- t.maxTS[hour] = newTimeSeries(now, time.Hour, time.Minute)
- t.maxTS[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second)
- t.maxTS[minute] = newTimeSeries(now, time.Minute, time.Second)
- t.init()
- return t
-}
-
-func (t *Tracker) init() {
- t.min = math.MaxInt64
- t.max = math.MinInt64
- for _, ts := range t.minTS {
- ts.set(math.MaxInt64)
- }
- for _, ts := range t.maxTS {
- ts.set(math.MinInt64)
- }
-}
-
-func (t *Tracker) advance() time.Time {
- now := TimeNow()
- for _, ts := range t.minTS {
- ts.advanceTimeWithFill(now, math.MaxInt64)
- }
- for _, ts := range t.maxTS {
- ts.advanceTimeWithFill(now, math.MinInt64)
- }
- return now
-}
-
-// LastUpdate returns the last update time of the range.
-func (t *Tracker) LastUpdate() time.Time {
- t.mu.RLock()
- defer t.mu.RUnlock()
- return t.lastUpdate
-}
-
-// Push adds a new value if it is a new minimum or maximum.
-func (t *Tracker) Push(value int64) {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.lastUpdate = t.advance()
- if t.min > value {
- t.min = value
- }
- if t.max < value {
- t.max = value
- }
- for _, ts := range t.minTS {
- if ts.headValue() > value {
- ts.set(value)
- }
- }
- for _, ts := range t.maxTS {
- if ts.headValue() < value {
- ts.set(value)
- }
- }
-}
-
-// Min returns the minimum value of the tracker
-func (t *Tracker) Min() int64 {
- t.mu.RLock()
- defer t.mu.RUnlock()
- return t.min
-}
-
-// Max returns the maximum value of the tracker.
-func (t *Tracker) Max() int64 {
- t.mu.RLock()
- defer t.mu.RUnlock()
- return t.max
-}
-
-// Min1h returns the minimum value for the last hour.
-func (t *Tracker) Min1h() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.minTS[hour].min()
-}
-
-// Max1h returns the maximum value for the last hour.
-func (t *Tracker) Max1h() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.maxTS[hour].max()
-}
-
-// Min10m returns the minimum value for the last 10 minutes.
-func (t *Tracker) Min10m() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.minTS[tenminutes].min()
-}
-
-// Max10m returns the maximum value for the last 10 minutes.
-func (t *Tracker) Max10m() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.maxTS[tenminutes].max()
-}
-
-// Min1m returns the minimum value for the last 1 minute.
-func (t *Tracker) Min1m() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.minTS[minute].min()
-}
-
-// Max1m returns the maximum value for the last 1 minute.
-func (t *Tracker) Max1m() int64 {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.advance()
- return t.maxTS[minute].max()
-}
-
-// Reset resets the range to an empty state.
-func (t *Tracker) Reset() {
- t.mu.Lock()
- defer t.mu.Unlock()
- now := TimeNow()
- for _, ts := range t.minTS {
- ts.reset(now)
- }
- for _, ts := range t.maxTS {
- ts.reset(now)
- }
- t.init()
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/util.go b/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/util.go
deleted file mode 100644
index a9922f985..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/benchmark/stats/util.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package stats
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "os"
- "runtime"
- "sort"
- "strings"
- "sync"
- "testing"
-)
-
-var (
- curB *testing.B
- curBenchName string
- curStats map[string]*Stats
-
- orgStdout *os.File
- nextOutPos int
-
- injectCond *sync.Cond
- injectDone chan struct{}
-)
-
-// AddStats adds a new unnamed Stats instance to the current benchmark. You need
-// to run benchmarks by calling RunTestMain() to inject the stats to the
-// benchmark results. If numBuckets is not positive, the default value (16) will
-// be used. Please note that this calls b.ResetTimer() since it may be blocked
-// until the previous benchmark stats is printed out. So AddStats() should
-// typically be called at the very beginning of each benchmark function.
-func AddStats(b *testing.B, numBuckets int) *Stats {
- return AddStatsWithName(b, "", numBuckets)
-}
-
-// AddStatsWithName adds a new named Stats instance to the current benchmark.
-// With this, you can add multiple stats in a single benchmark. You need
-// to run benchmarks by calling RunTestMain() to inject the stats to the
-// benchmark results. If numBuckets is not positive, the default value (16) will
-// be used. Please note that this calls b.ResetTimer() since it may be blocked
-// until the previous benchmark stats is printed out. So AddStatsWithName()
-// should typically be called at the very beginning of each benchmark function.
-func AddStatsWithName(b *testing.B, name string, numBuckets int) *Stats {
- var benchName string
- for i := 1; ; i++ {
- pc, _, _, ok := runtime.Caller(i)
- if !ok {
- panic("benchmark function not found")
- }
- p := strings.Split(runtime.FuncForPC(pc).Name(), ".")
- benchName = p[len(p)-1]
- if strings.HasPrefix(benchName, "Benchmark") {
- break
- }
- }
- procs := runtime.GOMAXPROCS(-1)
- if procs != 1 {
- benchName = fmt.Sprintf("%s-%d", benchName, procs)
- }
-
- stats := NewStats(numBuckets)
-
- if injectCond != nil {
- // We need to wait until the previous benchmark stats is printed out.
- injectCond.L.Lock()
- for curB != nil && curBenchName != benchName {
- injectCond.Wait()
- }
-
- curB = b
- curBenchName = benchName
- curStats[name] = stats
-
- injectCond.L.Unlock()
- }
-
- b.ResetTimer()
- return stats
-}
-
-// RunTestMain runs the tests with enabling injection of benchmark stats. It
-// returns an exit code to pass to os.Exit.
-func RunTestMain(m *testing.M) int {
- startStatsInjector()
- defer stopStatsInjector()
- return m.Run()
-}
-
-// startStatsInjector starts stats injection to benchmark results.
-func startStatsInjector() {
- orgStdout = os.Stdout
- r, w, _ := os.Pipe()
- os.Stdout = w
- nextOutPos = 0
-
- resetCurBenchStats()
-
- injectCond = sync.NewCond(&sync.Mutex{})
- injectDone = make(chan struct{})
- go func() {
- defer close(injectDone)
-
- scanner := bufio.NewScanner(r)
- scanner.Split(splitLines)
- for scanner.Scan() {
- injectStatsIfFinished(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- panic(err)
- }
- }()
-}
-
-// stopStatsInjector stops stats injection and restores os.Stdout.
-func stopStatsInjector() {
- os.Stdout.Close()
- <-injectDone
- injectCond = nil
- os.Stdout = orgStdout
-}
-
-// splitLines is a split function for a bufio.Scanner that returns each line
-// of text, teeing texts to the original stdout even before each line ends.
-func splitLines(data []byte, eof bool) (advance int, token []byte, err error) {
- if eof && len(data) == 0 {
- return 0, nil, nil
- }
-
- if i := bytes.IndexByte(data, '\n'); i >= 0 {
- orgStdout.Write(data[nextOutPos : i+1])
- nextOutPos = 0
- return i + 1, data[0:i], nil
- }
-
- orgStdout.Write(data[nextOutPos:])
- nextOutPos = len(data)
-
- if eof {
- // This is a final, non-terminated line. Return it.
- return len(data), data, nil
- }
-
- return 0, nil, nil
-}
-
-// injectStatsIfFinished prints out the stats if the current benchmark finishes.
-func injectStatsIfFinished(line string) {
- injectCond.L.Lock()
- defer injectCond.L.Unlock()
-
- // We assume that the benchmark results start with the benchmark name.
- if curB == nil || !strings.HasPrefix(line, curBenchName) {
- return
- }
-
- if !curB.Failed() {
- // Output all stats in alphabetical order.
- names := make([]string, 0, len(curStats))
- for name := range curStats {
- names = append(names, name)
- }
- sort.Strings(names)
- for _, name := range names {
- stats := curStats[name]
- // The output of stats starts with a header like "Histogram (unit: ms)"
- // followed by statistical properties and the buckets. Add the stats name
- // if it is a named stats and indent them as Go testing outputs.
- lines := strings.Split(stats.String(), "\n")
- if n := len(lines); n > 0 {
- if name != "" {
- name = ": " + name
- }
- fmt.Fprintf(orgStdout, "--- %s%s\n", lines[0], name)
- for _, line := range lines[1 : n-1] {
- fmt.Fprintf(orgStdout, "\t%s\n", line)
- }
- }
- }
- }
-
- resetCurBenchStats()
- injectCond.Signal()
-}
-
-// resetCurBenchStats resets the current benchmark stats.
-func resetCurBenchStats() {
- curB = nil
- curBenchName = ""
- curStats = make(map[string]*Stats)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/credentials/oauth/oauth.go b/Godeps/_workspace/src/google.golang.org/grpc/credentials/oauth/oauth.go
deleted file mode 100644
index 04943fdf0..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/credentials/oauth/oauth.go
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-// Package oauth implements gRPC credentials using OAuth.
-package oauth
-
-import (
- "fmt"
- "io/ioutil"
-
- "golang.org/x/net/context"
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/google"
- "golang.org/x/oauth2/jwt"
- "google.golang.org/grpc/credentials"
-)
-
-// TokenSource supplies credentials from an oauth2.TokenSource.
-type TokenSource struct {
- oauth2.TokenSource
-}
-
-// GetRequestMetadata gets the request metadata as a map from a TokenSource.
-func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
- token, err := ts.Token()
- if err != nil {
- return nil, err
- }
- return map[string]string{
- "authorization": token.TokenType + " " + token.AccessToken,
- }, nil
-}
-
-func (ts TokenSource) RequireTransportSecurity() bool {
- return true
-}
-
-type jwtAccess struct {
- jsonKey []byte
-}
-
-func NewJWTAccessFromFile(keyFile string) (credentials.Credentials, error) {
- jsonKey, err := ioutil.ReadFile(keyFile)
- if err != nil {
- return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
- }
- return NewJWTAccessFromKey(jsonKey)
-}
-
-func NewJWTAccessFromKey(jsonKey []byte) (credentials.Credentials, error) {
- return jwtAccess{jsonKey}, nil
-}
-
-func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
- ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0])
- if err != nil {
- return nil, err
- }
- token, err := ts.Token()
- if err != nil {
- return nil, err
- }
- return map[string]string{
- "authorization": token.TokenType + " " + token.AccessToken,
- }, nil
-}
-
-func (j jwtAccess) RequireTransportSecurity() bool {
- return true
-}
-
-// oauthAccess supplies credentials from a given token.
-type oauthAccess struct {
- token oauth2.Token
-}
-
-// NewOauthAccess constructs the credentials using a given token.
-func NewOauthAccess(token *oauth2.Token) credentials.Credentials {
- return oauthAccess{token: *token}
-}
-
-func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
- return map[string]string{
- "authorization": oa.token.TokenType + " " + oa.token.AccessToken,
- }, nil
-}
-
-func (oa oauthAccess) RequireTransportSecurity() bool {
- return true
-}
-
-// NewComputeEngine constructs the credentials that fetches access tokens from
-// Google Compute Engine (GCE)'s metadata server. It is only valid to use this
-// if your program is running on a GCE instance.
-// TODO(dsymonds): Deprecate and remove this.
-func NewComputeEngine() credentials.Credentials {
- return TokenSource{google.ComputeTokenSource("")}
-}
-
-// serviceAccount represents credentials via JWT signing key.
-type serviceAccount struct {
- config *jwt.Config
-}
-
-func (s serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
- token, err := s.config.TokenSource(ctx).Token()
- if err != nil {
- return nil, err
- }
- return map[string]string{
- "authorization": token.TokenType + " " + token.AccessToken,
- }, nil
-}
-
-func (s serviceAccount) RequireTransportSecurity() bool {
- return true
-}
-
-// NewServiceAccountFromKey constructs the credentials using the JSON key slice
-// from a Google Developers service account.
-func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.Credentials, error) {
- config, err := google.JWTConfigFromJSON(jsonKey, scope...)
- if err != nil {
- return nil, err
- }
- return serviceAccount{config: config}, nil
-}
-
-// NewServiceAccountFromFile constructs the credentials using the JSON key file
-// of a Google Developers service account.
-func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.Credentials, error) {
- jsonKey, err := ioutil.ReadFile(keyFile)
- if err != nil {
- return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err)
- }
- return NewServiceAccountFromKey(jsonKey, scope...)
-}
-
-// NewApplicationDefault returns "Application Default Credentials". For more
-// detail, see https://developers.google.com/accounts/docs/application-default-credentials.
-func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.Credentials, error) {
- t, err := google.DefaultTokenSource(ctx, scope...)
- if err != nil {
- return nil, err
- }
- return TokenSource{t}, nil
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/README.md b/Godeps/_workspace/src/google.golang.org/grpc/examples/README.md
deleted file mode 100644
index aea0f0206..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/README.md
+++ /dev/null
@@ -1,57 +0,0 @@
-gRPC in 3 minutes (Go)
-======================
-
-BACKGROUND
--------------
-For this sample, we've already generated the server and client stubs from [helloworld.proto](helloworld/helloworld/helloworld.proto).
-
-PREREQUISITES
--------------
-
-- This requires Go 1.4
-- Requires that [GOPATH is set](https://golang.org/doc/code.html#GOPATH)
-
-```
-$ go help gopath
-$ # ensure the PATH contains $GOPATH/bin
-$ export PATH=$PATH:$GOPATH/bin
-```
-
-INSTALL
--------
-
-```
-$ go get -u google.golang.org/grpc/examples/helloworld/greeter_client
-$ go get -u google.golang.org/grpc/examples/helloworld/greeter_server
-```
-
-TRY IT!
--------
-
-- Run the server
-
-```
-$ greeter_server &
-```
-
-- Run the client
-
-```
-$ greeter_client
-```
-
-OPTIONAL - Rebuilding the generated code
-----------------------------------------
-
-1 First [install protoc](https://github.com/google/protobuf/blob/master/INSTALL.txt)
- - For now, this needs to be installed from source
- - This is will change once proto3 is officially released
-
-2 Install the protoc Go plugin.
-
-```
-$ go get -a github.com/golang/protobuf/protoc-gen-go
-$
-$ # from this dir; invoke protoc
-$ protoc -I ./helloworld/helloworld/ ./helloworld/helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
-```
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/gotutorial.md b/Godeps/_workspace/src/google.golang.org/grpc/examples/gotutorial.md
deleted file mode 100644
index 39833fdf3..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/gotutorial.md
+++ /dev/null
@@ -1,431 +0,0 @@
-#gRPC Basics: Go
-
-This tutorial provides a basic Go programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
-
-- Define a service in a .proto file.
-- Generate server and client code using the protocol buffer compiler.
-- Use the Go gRPC API to write a simple client and server for your service.
-
-It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release:you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
-
-This isn't a comprehensive guide to using gRPC in Go: more reference documentation is coming soon.
-
-## Why use gRPC?
-
-Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
-
-With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
-
-## Example code and setup
-
-The example code for our tutorial is in [grpc/grpc-go/examples/route_guide](https://github.com/grpc/grpc-go/tree/master/examples/route_guide). To download the example, clone the `grpc-go` repository by running the following command:
-```shell
-$ go get google.golang.org/grpc
-```
-
-Then change your current directory to `grpc-go/examples/route_guide`:
-```shell
-$ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide
-```
-
-You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Go quick start guide](examples/).
-
-
-## Defining the service
-
-Our first step (as you'll know from the [quick start](http://www.grpc.io/docs/#quick-start)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers] (https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/route_guide/proto/route_guide.proto`](examples/route_guide/proto/route_guide.proto).
-
-To define a service, you specify a named `service` in your .proto file:
-
-```proto
-service RouteGuide {
- ...
-}
-```
-
-Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
-
-- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
-```proto
- // Obtains the feature at a given position.
- rpc GetFeature(Point) returns (Feature) {}
-```
-
-- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
-```proto
- // Obtains the Features available within the given Rectangle. Results are
- // streamed rather than returned at once (e.g. in a response message with a
- // repeated field), as the rectangle may cover a large area and contain a
- // huge number of features.
- rpc ListFeatures(Rectangle) returns (stream Feature) {}
-```
-
-- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type.
-```proto
- // Accepts a stream of Points on a route being traversed, returning a
- // RouteSummary when traversal is completed.
- rpc RecordRoute(stream Point) returns (RouteSummary) {}
-```
-
-- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
-```proto
- // Accepts a stream of RouteNotes sent while a route is being traversed,
- // while receiving other RouteNotes (e.g. from other users).
- rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
-```
-
-Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
-```proto
-// Points are represented as latitude-longitude pairs in the E7 representation
-// (degrees multiplied by 10**7 and rounded to the nearest integer).
-// Latitudes should be in the range +/- 90 degrees and longitude should be in
-// the range +/- 180 degrees (inclusive).
-message Point {
- int32 latitude = 1;
- int32 longitude = 2;
-}
-```
-
-
-## Generating client and server code
-
-Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Go plugin.
-
-For simplicity, we've provided a [bash script](https://github.com/grpc/grpc-go/blob/master/codegen.sh) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this by yourself, make sure you've installed protoc and followed the gRPC-Go [installation instructions](https://github.com/grpc/grpc-go/blob/master/README.md) first):
-
-```shell
-$ codegen.sh route_guide.proto
-```
-
-which actually runs:
-
-```shell
-$ protoc --go_out=plugins=grpc:. route_guide.proto
-```
-
-Running this command generates the following file in your current directory:
-- `route_guide.pb.go`
-
-This contains:
-- All the protocol buffer code to populate, serialize, and retrieve our request and response message types
-- An interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service.
-- An interface type for servers to implement, also with the methods defined in the `RouteGuide` service.
-
-
-
-## Creating the server
-
-First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!).
-
-There are two parts to making our `RouteGuide` service do its job:
-- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
-- Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
-
-You can find our example `RouteGuide` server in [grpc-go/examples/route_guide/server/server.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/server/server.go). Let's take a closer look at how it works.
-
-### Implementing RouteGuide
-
-As you can see, our server has a `routeGuideServer` struct type that implements the generated `RouteGuideServer` interface:
-
-```go
-type routeGuideServer struct {
- ...
-}
-...
-
-func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
- ...
-}
-...
-
-func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
- ...
-}
-...
-
-func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
- ...
-}
-...
-
-func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
- ...
-}
-...
-```
-
-#### Simple RPC
-`routeGuideServer` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
-
-```go
-func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
- for _, feature := range s.savedFeatures {
- if proto.Equal(feature.Location, point) {
- return feature, nil
- }
- }
- // No feature was found, return an unnamed feature
- return &pb.Feature{"", point}, nil
-}
-```
-
-The method is passed a context object for the RPC and the client's `Point` protocol buffer request. It returns a `Feature` protocol buffer object with the response information and an `error`. In the method we populate the `Feature` with the appropriate information, and then `return` it along with an `nil` error to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client.
-
-#### Server-side streaming RPC
-Now let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client.
-
-```go
-func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
- for _, feature := range s.savedFeatures {
- if inRange(feature.Location, rect) {
- if err := stream.Send(feature); err != nil {
- return err
- }
- }
- }
- return nil
-}
-```
-
-As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `RouteGuide_ListFeaturesServer` object to write our responses.
-
-In the method, we populate as many `Feature` objects as we need to return, writing them to the `RouteGuide_ListFeaturesServer` using its `Send()` method. Finally, as in our simple RPC, we return a `nil` error to tell gRPC that we've finished writing responses. Should any error happen in this call, we return a non-`nil` error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire.
-
-#### Client-side streaming RPC
-Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. As you can see, this time the method doesn't have a request parameter at all. Instead, it gets a `RouteGuide_RecordRouteServer` stream, which the server can use to both read *and* write messages - it can receive client messages using its `Recv()` method and return its single response using its `SendAndClose()` method.
-
-```go
-func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
- var pointCount, featureCount, distance int32
- var lastPoint *pb.Point
- startTime := time.Now()
- for {
- point, err := stream.Recv()
- if err == io.EOF {
- endTime := time.Now()
- return stream.SendAndClose(&pb.RouteSummary{
- PointCount: pointCount,
- FeatureCount: featureCount,
- Distance: distance,
- ElapsedTime: int32(endTime.Sub(startTime).Seconds()),
- })
- }
- if err != nil {
- return err
- }
- pointCount++
- for _, feature := range s.savedFeatures {
- if proto.Equal(feature.Location, point) {
- featureCount++
- }
- }
- if lastPoint != nil {
- distance += calcDistance(lastPoint, point)
- }
- lastPoint = point
- }
-}
-```
-
-In the method body we use the `RouteGuide_RecordRouteServer`s `Recv()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the the error returned from `Recv()` after each call. If this is `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended and the server can return its `RouteSummary`. If it has any other value, we return the error "as is" so that it'll be translated to an RPC status by the gRPC layer.
-
-#### Bidirectional streaming RPC
-Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
-
-```go
-func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- return nil
- }
- if err != nil {
- return err
- }
- key := serialize(in.Location)
- ... // look for notes to be sent to client
- for _, note := range s.routeNotes[key] {
- if err := stream.Send(note); err != nil {
- return err
- }
- }
- }
-}
-```
-
-This time we get a `RouteGuide_RouteChatServer` stream that, as in our client-side streaming example, can be used to read and write messages. However, this time we return values via our method's stream while the client is still writing messages to *their* message stream.
-
-The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream's `Send()` method rather than `SendAndClose()` because it's writing multiple responses. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
-
-### Starting the server
-
-Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
-
-```go
-flag.Parse()
-lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
-if err != nil {
- log.Fatalf("failed to listen: %v", err)
-}
-grpcServer := grpc.NewServer()
-pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
-... // determine whether to use TLS
-grpcServer.Serve(lis)
-```
-To build and start a server, we:
-
-1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))`.
-2. Create an instance of the gRPC server using `grpc.NewServer()`.
-3. Register our service implementation with the gRPC server.
-4. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called.
-
-
-## Creating the client
-
-In this section, we'll look at creating a Go client for our `RouteGuide` service. You can see our complete example client code in [grpc-go/examples/route_guide/client/client.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/client/client.go).
-
-### Creating a stub
-
-To call service methods, we first need to create a gRPC *channel* to communicate with the server. We create this by passing the server address and port number to `grpc.Dial()` as follows:
-
-```go
-conn, err := grpc.Dial(*serverAddr)
-if err != nil {
- ...
-}
-defer conn.Close()
-```
-
-You can use `DialOptions` to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in `grpc.Dial` if the service you request requires that - however, we don't need to do this for our `RouteGuide` service.
-
-Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs. We get this using the `NewRouteGuideClient` method provided in the `pb` package we generated from our .proto.
-
-```go
-client := pb.NewRouteGuideClient(conn)
-```
-
-### Calling service methods
-
-Now let's look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error.
-
-#### Simple RPC
-
-Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
-
-```go
-feature, err := client.GetFeature(context.Background(), &pb.Point{409146138, -746188906})
-if err != nil {
- ...
-}
-```
-
-As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which lets us change our RPC's behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn't return an error, then we can read the response information from the server from the first return value.
-
-```go
-log.Println(feature)
-```
-
-#### Server-side streaming RPC
-
-Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides.
-
-```go
-rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle
-stream, err := client.ListFeatures(context.Background(), rect)
-if err != nil {
- ...
-}
-for {
- feature, err := stream.Recv()
- if err == io.EOF {
- break
- }
- if err != nil {
- log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
- }
- log.Println(feature)
-}
-```
-
-As in the simple RPC, we pass the method a context and a request. However, instead of getting a response object back, we get back an instance of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses.
-
-We use the `RouteGuide_ListFeaturesClient`'s `Recv()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the error `err` returned from `Recv()` after each call. If `nil`, the stream is still good and it can continue reading; if it's `io.EOF` then the message stream has ended; otherwise there must be an RPC error, which is passed over through `err`.
-
-#### Client-side streaming RPC
-
-The client-side streaming method `RecordRoute` is similar to the server-side method, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` stream back, which we can use to both write *and* read messages.
-
-```go
-// Create a random number of random points
-r := rand.New(rand.NewSource(time.Now().UnixNano()))
-pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
-var points []*pb.Point
-for i := 0; i < pointCount; i++ {
- points = append(points, randomPoint(r))
-}
-log.Printf("Traversing %d points.", len(points))
-stream, err := client.RecordRoute(context.Background())
-if err != nil {
- log.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
-}
-for _, point := range points {
- if err := stream.Send(point); err != nil {
- log.Fatalf("%v.Send(%v) = %v", stream, point, err)
- }
-}
-reply, err := stream.CloseAndRecv()
-if err != nil {
- log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
-}
-log.Printf("Route summary: %v", reply)
-```
-
-The `RouteGuide_RecordRouteClient` has a `Send()` method that we can use to send requests to the server. Once we've finished writing our client's requests to the stream using `Send()`, we need to call `CloseAndRecv()` on the stream to let gRPC know that we've finished writing and are expecting to receive a response. We get our RPC status from the `err` returned from `CloseAndRecv()`. If the status is `nil`, then the first return value from `CloseAndRecv()` will be a valid server response.
-
-#### Bidirectional streaming RPC
-
-Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method's stream while the server is still writing messages to *their* message stream.
-
-```go
-stream, err := client.RouteChat(context.Background())
-waitc := make(chan struct{})
-go func() {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- // read done.
- close(waitc)
- return
- }
- if err != nil {
- log.Fatalf("Failed to receive a note : %v", err)
- }
- log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
- }
-}()
-for _, note := range notes {
- if err := stream.Send(note); err != nil {
- log.Fatalf("Failed to send a note: %v", err)
- }
-}
-stream.CloseSend()
-<-waitc
-```
-
-The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream's `CloseSend()` method once we've finished our call. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
-
-## Try it out!
-
-To compile and run the server, assuming you are in the folder
-`$GOPATH/src/google.golang.org/grpc/examples/route_guide`, simply:
-
-```sh
-$ go run server/server.go
-```
-
-Likewise, to run the client:
-
-```sh
-$ go run client/client.go
-```
-
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_client/main.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_client/main.go
deleted file mode 100644
index 1e02ab154..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_client/main.go
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-package main
-
-import (
- "log"
- "os"
-
- pb "google.golang.org/grpc/examples/helloworld/helloworld"
- "golang.org/x/net/context"
- "google.golang.org/grpc"
-)
-
-const (
- address = "localhost:50051"
- defaultName = "world"
-)
-
-func main() {
- // Set up a connection to the server.
- conn, err := grpc.Dial(address, grpc.WithInsecure())
- if err != nil {
- log.Fatalf("did not connect: %v", err)
- }
- defer conn.Close()
- c := pb.NewGreeterClient(conn)
-
- // Contact the server and print out its response.
- name := defaultName
- if len(os.Args) > 1 {
- name = os.Args[1]
- }
- r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
- if err != nil {
- log.Fatalf("could not greet: %v", err)
- }
- log.Printf("Greeting: %s", r.Message)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_server/main.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_server/main.go
deleted file mode 100644
index 66010a512..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/greeter_server/main.go
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-package main
-
-import (
- "log"
- "net"
-
- pb "google.golang.org/grpc/examples/helloworld/helloworld"
- "golang.org/x/net/context"
- "google.golang.org/grpc"
-)
-
-const (
- port = ":50051"
-)
-
-// server is used to implement helloworld.GreeterServer.
-type server struct{}
-
-// SayHello implements helloworld.GreeterServer
-func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
- return &pb.HelloReply{Message: "Hello " + in.Name}, nil
-}
-
-func main() {
- lis, err := net.Listen("tcp", port)
- if err != nil {
- log.Fatalf("failed to listen: %v", err)
- }
- s := grpc.NewServer()
- pb.RegisterGreeterServer(s, &server{})
- s.Serve(lis)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go
deleted file mode 100644
index 366b23b6d..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go
+++ /dev/null
@@ -1,109 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: helloworld.proto
-// DO NOT EDIT!
-
-/*
-Package helloworld is a generated protocol buffer package.
-
-It is generated from these files:
- helloworld.proto
-
-It has these top-level messages:
- HelloRequest
- HelloReply
-*/
-package helloworld
-
-import proto "github.com/golang/protobuf/proto"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-
-// The request message containing the user's name.
-type HelloRequest struct {
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
-}
-
-func (m *HelloRequest) Reset() { *m = HelloRequest{} }
-func (m *HelloRequest) String() string { return proto.CompactTextString(m) }
-func (*HelloRequest) ProtoMessage() {}
-
-// The response message containing the greetings
-type HelloReply struct {
- Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"`
-}
-
-func (m *HelloReply) Reset() { *m = HelloReply{} }
-func (m *HelloReply) String() string { return proto.CompactTextString(m) }
-func (*HelloReply) ProtoMessage() {}
-
-func init() {
-}
-
-// Client API for Greeter service
-
-type GreeterClient interface {
- // Sends a greeting
- SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
-}
-
-type greeterClient struct {
- cc *grpc.ClientConn
-}
-
-func NewGreeterClient(cc *grpc.ClientConn) GreeterClient {
- return &greeterClient{cc}
-}
-
-func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
- out := new(HelloReply)
- err := grpc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// Server API for Greeter service
-
-type GreeterServer interface {
- // Sends a greeting
- SayHello(context.Context, *HelloRequest) (*HelloReply, error)
-}
-
-func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) {
- s.RegisterService(&_Greeter_serviceDesc, srv)
-}
-
-func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(HelloRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(GreeterServer).SayHello(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-var _Greeter_serviceDesc = grpc.ServiceDesc{
- ServiceName: "helloworld.Greeter",
- HandlerType: (*GreeterServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "SayHello",
- Handler: _Greeter_SayHello_Handler,
- },
- },
- Streams: []grpc.StreamDesc{},
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto b/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto
deleted file mode 100644
index 7d58870a7..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-option java_package = "io.grpc.examples";
-option objc_class_prefix = "HLW";
-
-package helloworld;
-
-// The greeting service definition.
-service Greeter {
- // Sends a greeting
- rpc SayHello (HelloRequest) returns (HelloReply) {}
-}
-
-// The request message containing the user's name.
-message HelloRequest {
- string name = 1;
-}
-
-// The response message containing the greetings
-message HelloReply {
- string message = 1;
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/README.md b/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/README.md
deleted file mode 100644
index a7c0c2b0e..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/README.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# Description
-The route guide server and client demonstrate how to use grpc go libraries to
-perform unary, client streaming, server streaming and full duplex RPCs.
-
-Please refer to [gRPC Basics: Go] (http://www.grpc.io/docs/tutorials/basic/go.html) for more information.
-
-See the definition of the route guide service in proto/route_guide.proto.
-
-# Run the sample code
-To compile and run the server, assuming you are in the root of the route_guide
-folder, i.e., .../examples/route_guide/, simply:
-
-```sh
-$ go run server/server.go
-```
-
-Likewise, to run the client:
-
-```sh
-$ go run client/client.go
-```
-
-# Optional command line flags
-The server and client both take optional command line flags. For example, the
-client and server run without TLS by default. To enable TLS:
-
-```sh
-$ go run server/server.go -tls=true
-```
-
-and
-
-```sh
-$ go run client/client.go -tls=true
-```
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/client/client.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/client/client.go
deleted file mode 100644
index a96c0302c..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/client/client.go
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries
-// to perform unary, client streaming, server streaming and full duplex RPCs.
-//
-// It interacts with the route guide service whose definition can be found in proto/route_guide.proto.
-package main
-
-import (
- "flag"
- "io"
- "math/rand"
- "time"
-
- "golang.org/x/net/context"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials"
- pb "google.golang.org/grpc/examples/route_guide/routeguide"
- "google.golang.org/grpc/grpclog"
-)
-
-var (
- tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
- caFile = flag.String("ca_file", "testdata/ca.pem", "The file containning the CA root cert file")
- serverAddr = flag.String("server_addr", "127.0.0.1:10000", "The server address in the format of host:port")
- serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake")
-)
-
-// printFeature gets the feature for the given point.
-func printFeature(client pb.RouteGuideClient, point *pb.Point) {
- grpclog.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude)
- feature, err := client.GetFeature(context.Background(), point)
- if err != nil {
- grpclog.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err)
- }
- grpclog.Println(feature)
-}
-
-// printFeatures lists all the features within the given bounding Rectangle.
-func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) {
- grpclog.Printf("Looking for features within %v", rect)
- stream, err := client.ListFeatures(context.Background(), rect)
- if err != nil {
- grpclog.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
- }
- for {
- feature, err := stream.Recv()
- if err == io.EOF {
- break
- }
- if err != nil {
- grpclog.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
- }
- grpclog.Println(feature)
- }
-}
-
-// runRecordRoute sends a sequence of points to server and expects to get a RouteSummary from server.
-func runRecordRoute(client pb.RouteGuideClient) {
- // Create a random number of random points
- r := rand.New(rand.NewSource(time.Now().UnixNano()))
- pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points
- var points []*pb.Point
- for i := 0; i < pointCount; i++ {
- points = append(points, randomPoint(r))
- }
- grpclog.Printf("Traversing %d points.", len(points))
- stream, err := client.RecordRoute(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.RecordRoute(_) = _, %v", client, err)
- }
- for _, point := range points {
- if err := stream.Send(point); err != nil {
- grpclog.Fatalf("%v.Send(%v) = %v", stream, point, err)
- }
- }
- reply, err := stream.CloseAndRecv()
- if err != nil {
- grpclog.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
- }
- grpclog.Printf("Route summary: %v", reply)
-}
-
-// runRouteChat receives a sequence of route notes, while sending notes for various locations.
-func runRouteChat(client pb.RouteGuideClient) {
- notes := []*pb.RouteNote{
- {&pb.Point{0, 1}, "First message"},
- {&pb.Point{0, 2}, "Second message"},
- {&pb.Point{0, 3}, "Third message"},
- {&pb.Point{0, 1}, "Fourth message"},
- {&pb.Point{0, 2}, "Fifth message"},
- {&pb.Point{0, 3}, "Sixth message"},
- }
- stream, err := client.RouteChat(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.RouteChat(_) = _, %v", client, err)
- }
- waitc := make(chan struct{})
- go func() {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- // read done.
- close(waitc)
- return
- }
- if err != nil {
- grpclog.Fatalf("Failed to receive a note : %v", err)
- }
- grpclog.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude)
- }
- }()
- for _, note := range notes {
- if err := stream.Send(note); err != nil {
- grpclog.Fatalf("Failed to send a note: %v", err)
- }
- }
- stream.CloseSend()
- <-waitc
-}
-
-func randomPoint(r *rand.Rand) *pb.Point {
- lat := (r.Int31n(180) - 90) * 1e7
- long := (r.Int31n(360) - 180) * 1e7
- return &pb.Point{lat, long}
-}
-
-func main() {
- flag.Parse()
- var opts []grpc.DialOption
- if *tls {
- var sn string
- if *serverHostOverride != "" {
- sn = *serverHostOverride
- }
- var creds credentials.TransportAuthenticator
- if *caFile != "" {
- var err error
- creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
- if err != nil {
- grpclog.Fatalf("Failed to create TLS credentials %v", err)
- }
- } else {
- creds = credentials.NewClientTLSFromCert(nil, sn)
- }
- opts = append(opts, grpc.WithTransportCredentials(creds))
- } else {
- opts = append(opts, grpc.WithInsecure())
- }
- conn, err := grpc.Dial(*serverAddr, opts...)
- if err != nil {
- grpclog.Fatalf("fail to dial: %v", err)
- }
- defer conn.Close()
- client := pb.NewRouteGuideClient(conn)
-
- // Looking for a valid feature
- printFeature(client, &pb.Point{409146138, -746188906})
-
- // Feature missing.
- printFeature(client, &pb.Point{0, 0})
-
- // Looking for features between 40, -75 and 42, -73.
- printFeatures(client, &pb.Rectangle{&pb.Point{400000000, -750000000}, &pb.Point{420000000, -730000000}})
-
- // RecordRoute
- runRecordRoute(client)
-
- // RouteChat
- runRouteChat(client)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go
deleted file mode 100644
index 7b209472f..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go
+++ /dev/null
@@ -1,426 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto
-// DO NOT EDIT!
-
-/*
-Package routeguide is a generated protocol buffer package.
-
-It is generated from these files:
- google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto
-
-It has these top-level messages:
- Point
- Rectangle
- Feature
- RouteNote
- RouteSummary
-*/
-package routeguide
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// Points are represented as latitude-longitude pairs in the E7 representation
-// (degrees multiplied by 10**7 and rounded to the nearest integer).
-// Latitudes should be in the range +/- 90 degrees and longitude should be in
-// the range +/- 180 degrees (inclusive).
-type Point struct {
- Latitude int32 `protobuf:"varint,1,opt,name=latitude" json:"latitude,omitempty"`
- Longitude int32 `protobuf:"varint,2,opt,name=longitude" json:"longitude,omitempty"`
-}
-
-func (m *Point) Reset() { *m = Point{} }
-func (m *Point) String() string { return proto.CompactTextString(m) }
-func (*Point) ProtoMessage() {}
-
-// A latitude-longitude rectangle, represented as two diagonally opposite
-// points "lo" and "hi".
-type Rectangle struct {
- // One corner of the rectangle.
- Lo *Point `protobuf:"bytes,1,opt,name=lo" json:"lo,omitempty"`
- // The other corner of the rectangle.
- Hi *Point `protobuf:"bytes,2,opt,name=hi" json:"hi,omitempty"`
-}
-
-func (m *Rectangle) Reset() { *m = Rectangle{} }
-func (m *Rectangle) String() string { return proto.CompactTextString(m) }
-func (*Rectangle) ProtoMessage() {}
-
-func (m *Rectangle) GetLo() *Point {
- if m != nil {
- return m.Lo
- }
- return nil
-}
-
-func (m *Rectangle) GetHi() *Point {
- if m != nil {
- return m.Hi
- }
- return nil
-}
-
-// A feature names something at a given point.
-//
-// If a feature could not be named, the name is empty.
-type Feature struct {
- // The name of the feature.
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // The point where the feature is detected.
- Location *Point `protobuf:"bytes,2,opt,name=location" json:"location,omitempty"`
-}
-
-func (m *Feature) Reset() { *m = Feature{} }
-func (m *Feature) String() string { return proto.CompactTextString(m) }
-func (*Feature) ProtoMessage() {}
-
-func (m *Feature) GetLocation() *Point {
- if m != nil {
- return m.Location
- }
- return nil
-}
-
-// A RouteNote is a message sent while at a given point.
-type RouteNote struct {
- // The location from which the message is sent.
- Location *Point `protobuf:"bytes,1,opt,name=location" json:"location,omitempty"`
- // The message to be sent.
- Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
-}
-
-func (m *RouteNote) Reset() { *m = RouteNote{} }
-func (m *RouteNote) String() string { return proto.CompactTextString(m) }
-func (*RouteNote) ProtoMessage() {}
-
-func (m *RouteNote) GetLocation() *Point {
- if m != nil {
- return m.Location
- }
- return nil
-}
-
-// A RouteSummary is received in response to a RecordRoute rpc.
-//
-// It contains the number of individual points received, the number of
-// detected features, and the total distance covered as the cumulative sum of
-// the distance between each point.
-type RouteSummary struct {
- // The number of points received.
- PointCount int32 `protobuf:"varint,1,opt,name=point_count" json:"point_count,omitempty"`
- // The number of known features passed while traversing the route.
- FeatureCount int32 `protobuf:"varint,2,opt,name=feature_count" json:"feature_count,omitempty"`
- // The distance covered in metres.
- Distance int32 `protobuf:"varint,3,opt,name=distance" json:"distance,omitempty"`
- // The duration of the traversal in seconds.
- ElapsedTime int32 `protobuf:"varint,4,opt,name=elapsed_time" json:"elapsed_time,omitempty"`
-}
-
-func (m *RouteSummary) Reset() { *m = RouteSummary{} }
-func (m *RouteSummary) String() string { return proto.CompactTextString(m) }
-func (*RouteSummary) ProtoMessage() {}
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Client API for RouteGuide service
-
-type RouteGuideClient interface {
- // A simple RPC.
- //
- // Obtains the feature at a given position.
- //
- // If no feature is found for the given point, a feature with an empty name
- // should be returned.
- GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error)
- // A server-to-client streaming RPC.
- //
- // Obtains the Features available within the given Rectangle. Results are
- // streamed rather than returned at once (e.g. in a response message with a
- // repeated field), as the rectangle may cover a large area and contain a
- // huge number of features.
- ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error)
- // A client-to-server streaming RPC.
- //
- // Accepts a stream of Points on a route being traversed, returning a
- // RouteSummary when traversal is completed.
- RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error)
- // A Bidirectional streaming RPC.
- //
- // Accepts a stream of RouteNotes sent while a route is being traversed,
- // while receiving other RouteNotes (e.g. from other users).
- RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error)
-}
-
-type routeGuideClient struct {
- cc *grpc.ClientConn
-}
-
-func NewRouteGuideClient(cc *grpc.ClientConn) RouteGuideClient {
- return &routeGuideClient{cc}
-}
-
-func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) {
- out := new(Feature)
- err := grpc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[0], c.cc, "/routeguide.RouteGuide/ListFeatures", opts...)
- if err != nil {
- return nil, err
- }
- x := &routeGuideListFeaturesClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type RouteGuide_ListFeaturesClient interface {
- Recv() (*Feature, error)
- grpc.ClientStream
-}
-
-type routeGuideListFeaturesClient struct {
- grpc.ClientStream
-}
-
-func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) {
- m := new(Feature)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[1], c.cc, "/routeguide.RouteGuide/RecordRoute", opts...)
- if err != nil {
- return nil, err
- }
- x := &routeGuideRecordRouteClient{stream}
- return x, nil
-}
-
-type RouteGuide_RecordRouteClient interface {
- Send(*Point) error
- CloseAndRecv() (*RouteSummary, error)
- grpc.ClientStream
-}
-
-type routeGuideRecordRouteClient struct {
- grpc.ClientStream
-}
-
-func (x *routeGuideRecordRouteClient) Send(m *Point) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) {
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- m := new(RouteSummary)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[2], c.cc, "/routeguide.RouteGuide/RouteChat", opts...)
- if err != nil {
- return nil, err
- }
- x := &routeGuideRouteChatClient{stream}
- return x, nil
-}
-
-type RouteGuide_RouteChatClient interface {
- Send(*RouteNote) error
- Recv() (*RouteNote, error)
- grpc.ClientStream
-}
-
-type routeGuideRouteChatClient struct {
- grpc.ClientStream
-}
-
-func (x *routeGuideRouteChatClient) Send(m *RouteNote) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) {
- m := new(RouteNote)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for RouteGuide service
-
-type RouteGuideServer interface {
- // A simple RPC.
- //
- // Obtains the feature at a given position.
- //
- // If no feature is found for the given point, a feature with an empty name
- // should be returned.
- GetFeature(context.Context, *Point) (*Feature, error)
- // A server-to-client streaming RPC.
- //
- // Obtains the Features available within the given Rectangle. Results are
- // streamed rather than returned at once (e.g. in a response message with a
- // repeated field), as the rectangle may cover a large area and contain a
- // huge number of features.
- ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error
- // A client-to-server streaming RPC.
- //
- // Accepts a stream of Points on a route being traversed, returning a
- // RouteSummary when traversal is completed.
- RecordRoute(RouteGuide_RecordRouteServer) error
- // A Bidirectional streaming RPC.
- //
- // Accepts a stream of RouteNotes sent while a route is being traversed,
- // while receiving other RouteNotes (e.g. from other users).
- RouteChat(RouteGuide_RouteChatServer) error
-}
-
-func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) {
- s.RegisterService(&_RouteGuide_serviceDesc, srv)
-}
-
-func _RouteGuide_GetFeature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(Point)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(RouteGuideServer).GetFeature(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(Rectangle)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream})
-}
-
-type RouteGuide_ListFeaturesServer interface {
- Send(*Feature) error
- grpc.ServerStream
-}
-
-type routeGuideListFeaturesServer struct {
- grpc.ServerStream
-}
-
-func (x *routeGuideListFeaturesServer) Send(m *Feature) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _RouteGuide_RecordRoute_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(RouteGuideServer).RecordRoute(&routeGuideRecordRouteServer{stream})
-}
-
-type RouteGuide_RecordRouteServer interface {
- SendAndClose(*RouteSummary) error
- Recv() (*Point, error)
- grpc.ServerStream
-}
-
-type routeGuideRecordRouteServer struct {
- grpc.ServerStream
-}
-
-func (x *routeGuideRecordRouteServer) SendAndClose(m *RouteSummary) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *routeGuideRecordRouteServer) Recv() (*Point, error) {
- m := new(Point)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream})
-}
-
-type RouteGuide_RouteChatServer interface {
- Send(*RouteNote) error
- Recv() (*RouteNote, error)
- grpc.ServerStream
-}
-
-type routeGuideRouteChatServer struct {
- grpc.ServerStream
-}
-
-func (x *routeGuideRouteChatServer) Send(m *RouteNote) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) {
- m := new(RouteNote)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _RouteGuide_serviceDesc = grpc.ServiceDesc{
- ServiceName: "routeguide.RouteGuide",
- HandlerType: (*RouteGuideServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "GetFeature",
- Handler: _RouteGuide_GetFeature_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "ListFeatures",
- Handler: _RouteGuide_ListFeatures_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "RecordRoute",
- Handler: _RouteGuide_RecordRoute_Handler,
- ClientStreams: true,
- },
- {
- StreamName: "RouteChat",
- Handler: _RouteGuide_RouteChat_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto b/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto
deleted file mode 100644
index bee7ac51a..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2015, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-syntax = "proto3";
-
-package routeguide;
-
-// Interface exported by the server.
-service RouteGuide {
- // A simple RPC.
- //
- // Obtains the feature at a given position.
- //
- // If no feature is found for the given point, a feature with an empty name
- // should be returned.
- rpc GetFeature(Point) returns (Feature) {}
-
- // A server-to-client streaming RPC.
- //
- // Obtains the Features available within the given Rectangle. Results are
- // streamed rather than returned at once (e.g. in a response message with a
- // repeated field), as the rectangle may cover a large area and contain a
- // huge number of features.
- rpc ListFeatures(Rectangle) returns (stream Feature) {}
-
- // A client-to-server streaming RPC.
- //
- // Accepts a stream of Points on a route being traversed, returning a
- // RouteSummary when traversal is completed.
- rpc RecordRoute(stream Point) returns (RouteSummary) {}
-
- // A Bidirectional streaming RPC.
- //
- // Accepts a stream of RouteNotes sent while a route is being traversed,
- // while receiving other RouteNotes (e.g. from other users).
- rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
-}
-
-// Points are represented as latitude-longitude pairs in the E7 representation
-// (degrees multiplied by 10**7 and rounded to the nearest integer).
-// Latitudes should be in the range +/- 90 degrees and longitude should be in
-// the range +/- 180 degrees (inclusive).
-message Point {
- int32 latitude = 1;
- int32 longitude = 2;
-}
-
-// A latitude-longitude rectangle, represented as two diagonally opposite
-// points "lo" and "hi".
-message Rectangle {
- // One corner of the rectangle.
- Point lo = 1;
-
- // The other corner of the rectangle.
- Point hi = 2;
-}
-
-// A feature names something at a given point.
-//
-// If a feature could not be named, the name is empty.
-message Feature {
- // The name of the feature.
- string name = 1;
-
- // The point where the feature is detected.
- Point location = 2;
-}
-
-// A RouteNote is a message sent while at a given point.
-message RouteNote {
- // The location from which the message is sent.
- Point location = 1;
-
- // The message to be sent.
- string message = 2;
-}
-
-// A RouteSummary is received in response to a RecordRoute rpc.
-//
-// It contains the number of individual points received, the number of
-// detected features, and the total distance covered as the cumulative sum of
-// the distance between each point.
-message RouteSummary {
- // The number of points received.
- int32 point_count = 1;
-
- // The number of known features passed while traversing the route.
- int32 feature_count = 2;
-
- // The distance covered in metres.
- int32 distance = 3;
-
- // The duration of the traversal in seconds.
- int32 elapsed_time = 4;
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/server/server.go b/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/server/server.go
deleted file mode 100644
index 09b3942d1..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/examples/route_guide/server/server.go
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-// Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries
-// to perform unary, client streaming, server streaming and full duplex RPCs.
-//
-// It implements the route guide service whose definition can be found in proto/route_guide.proto.
-package main
-
-import (
- "encoding/json"
- "flag"
- "fmt"
- "io"
- "io/ioutil"
- "math"
- "net"
- "time"
-
- "golang.org/x/net/context"
- "google.golang.org/grpc"
-
- "google.golang.org/grpc/credentials"
- "google.golang.org/grpc/grpclog"
-
- "github.com/golang/protobuf/proto"
-
- pb "google.golang.org/grpc/examples/route_guide/routeguide"
-)
-
-var (
- tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
- certFile = flag.String("cert_file", "testdata/server1.pem", "The TLS cert file")
- keyFile = flag.String("key_file", "testdata/server1.key", "The TLS key file")
- jsonDBFile = flag.String("json_db_file", "testdata/route_guide_db.json", "A json file containing a list of features")
- port = flag.Int("port", 10000, "The server port")
-)
-
-type routeGuideServer struct {
- savedFeatures []*pb.Feature
- routeNotes map[string][]*pb.RouteNote
-}
-
-// GetFeature returns the feature at the given point.
-func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
- for _, feature := range s.savedFeatures {
- if proto.Equal(feature.Location, point) {
- return feature, nil
- }
- }
- // No feature was found, return an unnamed feature
- return &pb.Feature{"", point}, nil
-}
-
-// ListFeatures lists all features comtained within the given bounding Rectangle.
-func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
- for _, feature := range s.savedFeatures {
- if inRange(feature.Location, rect) {
- if err := stream.Send(feature); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// RecordRoute records a route composited of a sequence of points.
-//
-// It gets a stream of points, and responds with statistics about the "trip":
-// number of points, number of known features visited, total distance traveled, and
-// total time spent.
-func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
- var pointCount, featureCount, distance int32
- var lastPoint *pb.Point
- startTime := time.Now()
- for {
- point, err := stream.Recv()
- if err == io.EOF {
- endTime := time.Now()
- return stream.SendAndClose(&pb.RouteSummary{
- PointCount: pointCount,
- FeatureCount: featureCount,
- Distance: distance,
- ElapsedTime: int32(endTime.Sub(startTime).Seconds()),
- })
- }
- if err != nil {
- return err
- }
- pointCount++
- for _, feature := range s.savedFeatures {
- if proto.Equal(feature.Location, point) {
- featureCount++
- }
- }
- if lastPoint != nil {
- distance += calcDistance(lastPoint, point)
- }
- lastPoint = point
- }
-}
-
-// RouteChat receives a stream of message/location pairs, and responds with a stream of all
-// previous messages at each of those locations.
-func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- return nil
- }
- if err != nil {
- return err
- }
- key := serialize(in.Location)
- if _, present := s.routeNotes[key]; !present {
- s.routeNotes[key] = []*pb.RouteNote{in}
- } else {
- s.routeNotes[key] = append(s.routeNotes[key], in)
- }
- for _, note := range s.routeNotes[key] {
- if err := stream.Send(note); err != nil {
- return err
- }
- }
- }
-}
-
-// loadFeatures loads features from a JSON file.
-func (s *routeGuideServer) loadFeatures(filePath string) {
- file, err := ioutil.ReadFile(filePath)
- if err != nil {
- grpclog.Fatalf("Failed to load default features: %v", err)
- }
- if err := json.Unmarshal(file, &s.savedFeatures); err != nil {
- grpclog.Fatalf("Failed to load default features: %v", err)
- }
-}
-
-func toRadians(num float64) float64 {
- return num * math.Pi / float64(180)
-}
-
-// calcDistance calculates the distance between two points using the "haversine" formula.
-// This code was taken from http://www.movable-type.co.uk/scripts/latlong.html.
-func calcDistance(p1 *pb.Point, p2 *pb.Point) int32 {
- const CordFactor float64 = 1e7
- const R float64 = float64(6371000) // metres
- lat1 := float64(p1.Latitude) / CordFactor
- lat2 := float64(p2.Latitude) / CordFactor
- lng1 := float64(p1.Longitude) / CordFactor
- lng2 := float64(p2.Longitude) / CordFactor
- φ1 := toRadians(lat1)
- φ2 := toRadians(lat2)
- Δφ := toRadians(lat2 - lat1)
- Δλ := toRadians(lng2 - lng1)
-
- a := math.Sin(Δφ/2)*math.Sin(Δφ/2) +
- math.Cos(φ1)*math.Cos(φ2)*
- math.Sin(Δλ/2)*math.Sin(Δλ/2)
- c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
-
- distance := R * c
- return int32(distance)
-}
-
-func inRange(point *pb.Point, rect *pb.Rectangle) bool {
- left := math.Min(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude))
- right := math.Max(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude))
- top := math.Max(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude))
- bottom := math.Min(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude))
-
- if float64(point.Longitude) >= left &&
- float64(point.Longitude) <= right &&
- float64(point.Latitude) >= bottom &&
- float64(point.Latitude) <= top {
- return true
- }
- return false
-}
-
-func serialize(point *pb.Point) string {
- return fmt.Sprintf("%d %d", point.Latitude, point.Longitude)
-}
-
-func newServer() *routeGuideServer {
- s := new(routeGuideServer)
- s.loadFeatures(*jsonDBFile)
- s.routeNotes = make(map[string][]*pb.RouteNote)
- return s
-}
-
-func main() {
- flag.Parse()
- lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
- if err != nil {
- grpclog.Fatalf("failed to listen: %v", err)
- }
- var opts []grpc.ServerOption
- if *tls {
- creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
- if err != nil {
- grpclog.Fatalf("Failed to generate credentials %v", err)
- }
- opts = []grpc.ServerOption{grpc.Creds(creds)}
- }
- grpcServer := grpc.NewServer(opts...)
- pb.RegisterRouteGuideServer(grpcServer, newServer())
- grpcServer.Serve(lis)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/grpclog/glogger/glogger.go b/Godeps/_workspace/src/google.golang.org/grpc/grpclog/glogger/glogger.go
deleted file mode 100644
index 53e3c539f..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/grpclog/glogger/glogger.go
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Copyright 2015, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-/*
-Package glogger defines glog-based logging for grpc.
-*/
-package glogger
-
-import (
- "github.com/golang/glog"
- "google.golang.org/grpc/grpclog"
-)
-
-func init() {
- grpclog.SetLogger(&glogger{})
-}
-
-type glogger struct{}
-
-func (g *glogger) Fatal(args ...interface{}) {
- glog.Fatal(args...)
-}
-
-func (g *glogger) Fatalf(format string, args ...interface{}) {
- glog.Fatalf(format, args...)
-}
-
-func (g *glogger) Fatalln(args ...interface{}) {
- glog.Fatalln(args...)
-}
-
-func (g *glogger) Print(args ...interface{}) {
- glog.Info(args...)
-}
-
-func (g *glogger) Printf(format string, args ...interface{}) {
- glog.Infof(format, args...)
-}
-
-func (g *glogger) Println(args ...interface{}) {
- glog.Infoln(args...)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.pb.go
deleted file mode 100644
index 96eba6f85..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.pb.go
+++ /dev/null
@@ -1,133 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: health.proto
-// DO NOT EDIT!
-
-/*
-Package grpc_health_v1alpha is a generated protocol buffer package.
-
-It is generated from these files:
- health.proto
-
-It has these top-level messages:
- HealthCheckRequest
- HealthCheckResponse
-*/
-package grpc_health_v1alpha
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-type HealthCheckResponse_ServingStatus int32
-
-const (
- HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0
- HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1
- HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2
-)
-
-var HealthCheckResponse_ServingStatus_name = map[int32]string{
- 0: "UNKNOWN",
- 1: "SERVING",
- 2: "NOT_SERVING",
-}
-var HealthCheckResponse_ServingStatus_value = map[string]int32{
- "UNKNOWN": 0,
- "SERVING": 1,
- "NOT_SERVING": 2,
-}
-
-func (x HealthCheckResponse_ServingStatus) String() string {
- return proto.EnumName(HealthCheckResponse_ServingStatus_name, int32(x))
-}
-
-type HealthCheckRequest struct {
- Service string `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"`
-}
-
-func (m *HealthCheckRequest) Reset() { *m = HealthCheckRequest{} }
-func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) }
-func (*HealthCheckRequest) ProtoMessage() {}
-
-type HealthCheckResponse struct {
- Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,enum=grpc.health.v1alpha.HealthCheckResponse_ServingStatus" json:"status,omitempty"`
-}
-
-func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} }
-func (m *HealthCheckResponse) String() string { return proto.CompactTextString(m) }
-func (*HealthCheckResponse) ProtoMessage() {}
-
-func init() {
- proto.RegisterEnum("grpc.health.v1alpha.HealthCheckResponse_ServingStatus", HealthCheckResponse_ServingStatus_name, HealthCheckResponse_ServingStatus_value)
-}
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Client API for Health service
-
-type HealthClient interface {
- Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error)
-}
-
-type healthClient struct {
- cc *grpc.ClientConn
-}
-
-func NewHealthClient(cc *grpc.ClientConn) HealthClient {
- return &healthClient{cc}
-}
-
-func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) {
- out := new(HealthCheckResponse)
- err := grpc.Invoke(ctx, "/grpc.health.v1alpha.Health/Check", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// Server API for Health service
-
-type HealthServer interface {
- Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
-}
-
-func RegisterHealthServer(s *grpc.Server, srv HealthServer) {
- s.RegisterService(&_Health_serviceDesc, srv)
-}
-
-func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(HealthCheckRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(HealthServer).Check(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-var _Health_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.health.v1alpha.Health",
- HandlerType: (*HealthServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "Check",
- Handler: _Health_Check_Handler,
- },
- },
- Streams: []grpc.StreamDesc{},
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.proto b/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.proto
deleted file mode 100644
index 91c7f06e9..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/health/grpc_health_v1alpha/health.proto
+++ /dev/null
@@ -1,20 +0,0 @@
-syntax = "proto3";
-
-package grpc.health.v1alpha;
-
-message HealthCheckRequest {
- string service = 1;
-}
-
-message HealthCheckResponse {
- enum ServingStatus {
- UNKNOWN = 0;
- SERVING = 1;
- NOT_SERVING = 2;
- }
- ServingStatus status = 1;
-}
-
-service Health{
- rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/health/health.go b/Godeps/_workspace/src/google.golang.org/grpc/health/health.go
deleted file mode 100644
index 7930bde7f..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/health/health.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Package health provides some utility functions to health-check a server. The implementation
-// is based on protobuf. Users need to write their own implementations if other IDLs are used.
-package health
-
-import (
- "sync"
-
- "golang.org/x/net/context"
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- healthpb "google.golang.org/grpc/health/grpc_health_v1alpha"
-)
-
-type HealthServer struct {
- mu sync.Mutex
- // statusMap stores the serving status of the services this HealthServer monitors.
- statusMap map[string]healthpb.HealthCheckResponse_ServingStatus
-}
-
-func NewHealthServer() *HealthServer {
- return &HealthServer{
- statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),
- }
-}
-
-func (s *HealthServer) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
- s.mu.Lock()
- defer s.mu.Unlock()
- if in.Service == "" {
- // check the server overall health status.
- return &healthpb.HealthCheckResponse{
- Status: healthpb.HealthCheckResponse_SERVING,
- }, nil
- }
- if status, ok := s.statusMap[in.Service]; ok {
- return &healthpb.HealthCheckResponse{
- Status: status,
- }, nil
- }
- return nil, grpc.Errorf(codes.NotFound, "unknown service")
-}
-
-// SetServingStatus is called when need to reset the serving status of a service
-// or insert a new service entry into the statusMap.
-func (s *HealthServer) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) {
- s.mu.Lock()
- s.statusMap[service] = status
- s.mu.Unlock()
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/interop/client/client.go b/Godeps/_workspace/src/google.golang.org/grpc/interop/client/client.go
deleted file mode 100644
index 0ea4a1b90..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/interop/client/client.go
+++ /dev/null
@@ -1,584 +0,0 @@
-/*
- *
- * Copyright 2014, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-package main
-
-import (
- "flag"
- "io"
- "io/ioutil"
- "net"
- "strconv"
- "strings"
- "time"
-
- "github.com/golang/protobuf/proto"
- "golang.org/x/net/context"
- "golang.org/x/oauth2"
- "golang.org/x/oauth2/google"
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/credentials"
- "google.golang.org/grpc/credentials/oauth"
- "google.golang.org/grpc/grpclog"
- testpb "google.golang.org/grpc/interop/grpc_testing"
- "google.golang.org/grpc/metadata"
-)
-
-var (
- useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
- testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root")
- serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file")
- oauthScope = flag.String("oauth_scope", "", "The scope for OAuth2 tokens")
- defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account")
- serverHost = flag.String("server_host", "127.0.0.1", "The server host name")
- serverPort = flag.Int("server_port", 10000, "The server port number")
- tlsServerName = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.")
- testCase = flag.String("test_case", "large_unary",
- `Configure different test cases. Valid options are:
- empty_unary : empty (zero bytes) request and response;
- large_unary : single request and (large) response;
- client_streaming : request streaming with single response;
- server_streaming : single request with response streaming;
- ping_pong : full-duplex streaming;
- empty_stream : full-duplex streaming with zero message;
- timeout_on_sleeping_server: fullduplex streaming;
- compute_engine_creds: large_unary with compute engine auth;
- service_account_creds: large_unary with service account auth;
- jwt_token_creds: large_unary with jwt token auth;
- per_rpc_creds: large_unary with per rpc token;
- oauth2_auth_token: large_unary with oauth2 token auth;
- cancel_after_begin: cancellation after metadata has been sent but before payloads are sent;
- cancel_after_first_response: cancellation after receiving 1st message from the server.`)
-)
-
-var (
- reqSizes = []int{27182, 8, 1828, 45904}
- respSizes = []int{31415, 9, 2653, 58979}
- largeReqSize = 271828
- largeRespSize = 314159
-
- // The test CA root cert file
- testCAFile = "testdata/ca.pem"
-)
-
-func newPayload(t testpb.PayloadType, size int) *testpb.Payload {
- if size < 0 {
- grpclog.Fatalf("Requested a response with invalid length %d", size)
- }
- body := make([]byte, size)
- switch t {
- case testpb.PayloadType_COMPRESSABLE:
- case testpb.PayloadType_UNCOMPRESSABLE:
- grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported")
- default:
- grpclog.Fatalf("Unsupported payload type: %d", t)
- }
- return &testpb.Payload{
- Type: t.Enum(),
- Body: body,
- }
-}
-
-func doEmptyUnaryCall(tc testpb.TestServiceClient) {
- reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{})
- if err != nil {
- grpclog.Fatal("/TestService/EmptyCall RPC failed: ", err)
- }
- if !proto.Equal(&testpb.Empty{}, reply) {
- grpclog.Fatalf("/TestService/EmptyCall receives %v, want %v", reply, testpb.Empty{})
- }
- grpclog.Println("EmptyUnaryCall done")
-}
-
-func doLargeUnaryCall(tc testpb.TestServiceClient) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- }
- reply, err := tc.UnaryCall(context.Background(), req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- t := reply.GetPayload().GetType()
- s := len(reply.GetPayload().GetBody())
- if t != testpb.PayloadType_COMPRESSABLE || s != largeRespSize {
- grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, largeRespSize)
- }
- grpclog.Println("LargeUnaryCall done")
-}
-
-func doClientStreaming(tc testpb.TestServiceClient) {
- stream, err := tc.StreamingInputCall(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err)
- }
- var sum int
- for _, s := range reqSizes {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, s)
- req := &testpb.StreamingInputCallRequest{
- Payload: pl,
- }
- if err := stream.Send(req); err != nil {
- grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
- }
- sum += s
- grpclog.Printf("Sent a request of size %d, aggregated size %d", s, sum)
-
- }
- reply, err := stream.CloseAndRecv()
- if err != nil {
- grpclog.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
- }
- if reply.GetAggregatedPayloadSize() != int32(sum) {
- grpclog.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum)
- }
- grpclog.Println("ClientStreaming done")
-}
-
-func doServerStreaming(tc testpb.TestServiceClient) {
- respParam := make([]*testpb.ResponseParameters, len(respSizes))
- for i, s := range respSizes {
- respParam[i] = &testpb.ResponseParameters{
- Size: proto.Int32(int32(s)),
- }
- }
- req := &testpb.StreamingOutputCallRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseParameters: respParam,
- }
- stream, err := tc.StreamingOutputCall(context.Background(), req)
- if err != nil {
- grpclog.Fatalf("%v.StreamingOutputCall(_) = _, %v", tc, err)
- }
- var rpcStatus error
- var respCnt int
- var index int
- for {
- reply, err := stream.Recv()
- if err != nil {
- rpcStatus = err
- break
- }
- t := reply.GetPayload().GetType()
- if t != testpb.PayloadType_COMPRESSABLE {
- grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE)
- }
- size := len(reply.GetPayload().GetBody())
- if size != int(respSizes[index]) {
- grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
- }
- index++
- respCnt++
- }
- if rpcStatus != io.EOF {
- grpclog.Fatalf("Failed to finish the server streaming rpc: %v", err)
- }
- if respCnt != len(respSizes) {
- grpclog.Fatalf("Got %d reply, want %d", len(respSizes), respCnt)
- }
- grpclog.Println("ServerStreaming done")
-}
-
-func doPingPong(tc testpb.TestServiceClient) {
- stream, err := tc.FullDuplexCall(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
- }
- var index int
- for index < len(reqSizes) {
- respParam := []*testpb.ResponseParameters{
- {
- Size: proto.Int32(int32(respSizes[index])),
- },
- }
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSizes[index])
- req := &testpb.StreamingOutputCallRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseParameters: respParam,
- Payload: pl,
- }
- if err := stream.Send(req); err != nil {
- grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
- }
- reply, err := stream.Recv()
- if err != nil {
- grpclog.Fatalf("%v.Recv() = %v", stream, err)
- }
- t := reply.GetPayload().GetType()
- if t != testpb.PayloadType_COMPRESSABLE {
- grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE)
- }
- size := len(reply.GetPayload().GetBody())
- if size != int(respSizes[index]) {
- grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
- }
- index++
- }
- if err := stream.CloseSend(); err != nil {
- grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
- }
- if _, err := stream.Recv(); err != io.EOF {
- grpclog.Fatalf("%v failed to complele the ping pong test: %v", stream, err)
- }
- grpclog.Println("Pingpong done")
-}
-
-func doEmptyStream(tc testpb.TestServiceClient) {
- stream, err := tc.FullDuplexCall(context.Background())
- if err != nil {
- grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
- }
- if err := stream.CloseSend(); err != nil {
- grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
- }
- if _, err := stream.Recv(); err != io.EOF {
- grpclog.Fatalf("%v failed to complete the empty stream test: %v", stream, err)
- }
- grpclog.Println("Emptystream done")
-}
-
-func doTimeoutOnSleepingServer(tc testpb.TestServiceClient) {
- ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
- stream, err := tc.FullDuplexCall(ctx)
- if err != nil {
- if grpc.Code(err) == codes.DeadlineExceeded {
- grpclog.Println("TimeoutOnSleepingServer done")
- return
- }
- grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
- }
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, 27182)
- req := &testpb.StreamingOutputCallRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- Payload: pl,
- }
- if err := stream.Send(req); err != nil {
- grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
- }
- if _, err := stream.Recv(); grpc.Code(err) != codes.DeadlineExceeded {
- grpclog.Fatalf("%v.Recv() = _, %v, want error code %d", stream, err, codes.DeadlineExceeded)
- }
- grpclog.Println("TimeoutOnSleepingServer done")
-}
-
-func doComputeEngineCreds(tc testpb.TestServiceClient) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- FillUsername: proto.Bool(true),
- FillOauthScope: proto.Bool(true),
- }
- reply, err := tc.UnaryCall(context.Background(), req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- user := reply.GetUsername()
- scope := reply.GetOauthScope()
- if user != *defaultServiceAccount {
- grpclog.Fatalf("Got user name %q, want %q.", user, *defaultServiceAccount)
- }
- if !strings.Contains(*oauthScope, scope) {
- grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
- }
- grpclog.Println("ComputeEngineCreds done")
-}
-
-func getServiceAccountJSONKey() []byte {
- jsonKey, err := ioutil.ReadFile(*serviceAccountKeyFile)
- if err != nil {
- grpclog.Fatalf("Failed to read the service account key file: %v", err)
- }
- return jsonKey
-}
-
-func doServiceAccountCreds(tc testpb.TestServiceClient) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- FillUsername: proto.Bool(true),
- FillOauthScope: proto.Bool(true),
- }
- reply, err := tc.UnaryCall(context.Background(), req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- jsonKey := getServiceAccountJSONKey()
- user := reply.GetUsername()
- scope := reply.GetOauthScope()
- if !strings.Contains(string(jsonKey), user) {
- grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
- }
- if !strings.Contains(*oauthScope, scope) {
- grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
- }
- grpclog.Println("ServiceAccountCreds done")
-}
-
-func doJWTTokenCreds(tc testpb.TestServiceClient) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- FillUsername: proto.Bool(true),
- }
- reply, err := tc.UnaryCall(context.Background(), req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- jsonKey := getServiceAccountJSONKey()
- user := reply.GetUsername()
- if !strings.Contains(string(jsonKey), user) {
- grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
- }
- grpclog.Println("JWTtokenCreds done")
-}
-
-func getToken() *oauth2.Token {
- jsonKey := getServiceAccountJSONKey()
- config, err := google.JWTConfigFromJSON(jsonKey, *oauthScope)
- if err != nil {
- grpclog.Fatalf("Failed to get the config: %v", err)
- }
- token, err := config.TokenSource(context.Background()).Token()
- if err != nil {
- grpclog.Fatalf("Failed to get the token: %v", err)
- }
- return token
-}
-
-func doOauth2TokenCreds(tc testpb.TestServiceClient) {
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- FillUsername: proto.Bool(true),
- FillOauthScope: proto.Bool(true),
- }
- reply, err := tc.UnaryCall(context.Background(), req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- jsonKey := getServiceAccountJSONKey()
- user := reply.GetUsername()
- scope := reply.GetOauthScope()
- if !strings.Contains(string(jsonKey), user) {
- grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
- }
- if !strings.Contains(*oauthScope, scope) {
- grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
- }
- grpclog.Println("Oauth2TokenCreds done")
-}
-
-func doPerRPCCreds(tc testpb.TestServiceClient) {
- jsonKey := getServiceAccountJSONKey()
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
- req := &testpb.SimpleRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseSize: proto.Int32(int32(largeRespSize)),
- Payload: pl,
- FillUsername: proto.Bool(true),
- FillOauthScope: proto.Bool(true),
- }
- token := getToken()
- kv := map[string]string{"authorization": token.TokenType + " " + token.AccessToken}
- ctx := metadata.NewContext(context.Background(), metadata.MD{"authorization": []string{kv["authorization"]}})
- reply, err := tc.UnaryCall(ctx, req)
- if err != nil {
- grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
- }
- user := reply.GetUsername()
- scope := reply.GetOauthScope()
- if !strings.Contains(string(jsonKey), user) {
- grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
- }
- if !strings.Contains(*oauthScope, scope) {
- grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
- }
- grpclog.Println("PerRPCCreds done")
-}
-
-var (
- testMetadata = metadata.MD{
- "key1": []string{"value1"},
- "key2": []string{"value2"},
- }
-)
-
-func doCancelAfterBegin(tc testpb.TestServiceClient) {
- ctx, cancel := context.WithCancel(metadata.NewContext(context.Background(), testMetadata))
- stream, err := tc.StreamingInputCall(ctx)
- if err != nil {
- grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err)
- }
- cancel()
- _, err = stream.CloseAndRecv()
- if grpc.Code(err) != codes.Canceled {
- grpclog.Fatalf("%v.CloseAndRecv() got error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
- }
- grpclog.Println("CancelAfterBegin done")
-}
-
-func doCancelAfterFirstResponse(tc testpb.TestServiceClient) {
- ctx, cancel := context.WithCancel(context.Background())
- stream, err := tc.FullDuplexCall(ctx)
- if err != nil {
- grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
- }
- respParam := []*testpb.ResponseParameters{
- {
- Size: proto.Int32(31415),
- },
- }
- pl := newPayload(testpb.PayloadType_COMPRESSABLE, 27182)
- req := &testpb.StreamingOutputCallRequest{
- ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
- ResponseParameters: respParam,
- Payload: pl,
- }
- if err := stream.Send(req); err != nil {
- grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
- }
- if _, err := stream.Recv(); err != nil {
- grpclog.Fatalf("%v.Recv() = %v", stream, err)
- }
- cancel()
- if _, err := stream.Recv(); grpc.Code(err) != codes.Canceled {
- grpclog.Fatalf("%v compleled with error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
- }
- grpclog.Println("CancelAfterFirstResponse done")
-}
-
-func main() {
- flag.Parse()
- serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
- var opts []grpc.DialOption
- if *useTLS {
- var sn string
- if *tlsServerName != "" {
- sn = *tlsServerName
- }
- var creds credentials.TransportAuthenticator
- if *testCA {
- var err error
- creds, err = credentials.NewClientTLSFromFile(testCAFile, sn)
- if err != nil {
- grpclog.Fatalf("Failed to create TLS credentials %v", err)
- }
- } else {
- creds = credentials.NewClientTLSFromCert(nil, sn)
- }
- opts = append(opts, grpc.WithTransportCredentials(creds))
- if *testCase == "compute_engine_creds" {
- opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))
- } else if *testCase == "service_account_creds" {
- jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
- if err != nil {
- grpclog.Fatalf("Failed to create JWT credentials: %v", err)
- }
- opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
- } else if *testCase == "jwt_token_creds" {
- jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile)
- if err != nil {
- grpclog.Fatalf("Failed to create JWT credentials: %v", err)
- }
- opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
- } else if *testCase == "oauth2_auth_token" {
- opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(getToken())))
- }
- } else {
- opts = append(opts, grpc.WithInsecure())
- }
- conn, err := grpc.Dial(serverAddr, opts...)
- if err != nil {
- grpclog.Fatalf("Fail to dial: %v", err)
- }
- defer conn.Close()
- tc := testpb.NewTestServiceClient(conn)
- switch *testCase {
- case "empty_unary":
- doEmptyUnaryCall(tc)
- case "large_unary":
- doLargeUnaryCall(tc)
- case "client_streaming":
- doClientStreaming(tc)
- case "server_streaming":
- doServerStreaming(tc)
- case "ping_pong":
- doPingPong(tc)
- case "empty_stream":
- doEmptyStream(tc)
- case "timeout_on_sleeping_server":
- doTimeoutOnSleepingServer(tc)
- case "compute_engine_creds":
- if !*useTLS {
- grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
- }
- doComputeEngineCreds(tc)
- case "service_account_creds":
- if !*useTLS {
- grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
- }
- doServiceAccountCreds(tc)
- case "jwt_token_creds":
- if !*useTLS {
- grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.")
- }
- doJWTTokenCreds(tc)
- case "per_rpc_creds":
- if !*useTLS {
- grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.")
- }
- doPerRPCCreds(tc)
- case "oauth2_auth_token":
- if !*useTLS {
- grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.")
- }
- doOauth2TokenCreds(tc)
- case "cancel_after_begin":
- doCancelAfterBegin(tc)
- case "cancel_after_first_response":
- doCancelAfterFirstResponse(tc)
- default:
- grpclog.Fatal("Unsupported test case: ", *testCase)
- }
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.pb.go
deleted file mode 100644
index bd492fef4..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.pb.go
+++ /dev/null
@@ -1,702 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: test.proto
-// DO NOT EDIT!
-
-/*
-Package grpc_testing is a generated protocol buffer package.
-
-It is generated from these files:
- test.proto
-
-It has these top-level messages:
- Empty
- Payload
- SimpleRequest
- SimpleResponse
- StreamingInputCallRequest
- StreamingInputCallResponse
- ResponseParameters
- StreamingOutputCallRequest
- StreamingOutputCallResponse
-*/
-package grpc_testing
-
-import proto "github.com/golang/protobuf/proto"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = math.Inf
-
-// The type of payload that should be returned.
-type PayloadType int32
-
-const (
- // Compressable text format.
- PayloadType_COMPRESSABLE PayloadType = 0
- // Uncompressable binary format.
- PayloadType_UNCOMPRESSABLE PayloadType = 1
- // Randomly chosen from all other formats defined in this enum.
- PayloadType_RANDOM PayloadType = 2
-)
-
-var PayloadType_name = map[int32]string{
- 0: "COMPRESSABLE",
- 1: "UNCOMPRESSABLE",
- 2: "RANDOM",
-}
-var PayloadType_value = map[string]int32{
- "COMPRESSABLE": 0,
- "UNCOMPRESSABLE": 1,
- "RANDOM": 2,
-}
-
-func (x PayloadType) Enum() *PayloadType {
- p := new(PayloadType)
- *p = x
- return p
-}
-func (x PayloadType) String() string {
- return proto.EnumName(PayloadType_name, int32(x))
-}
-func (x *PayloadType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(PayloadType_value, data, "PayloadType")
- if err != nil {
- return err
- }
- *x = PayloadType(value)
- return nil
-}
-
-type Empty struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Empty) Reset() { *m = Empty{} }
-func (m *Empty) String() string { return proto.CompactTextString(m) }
-func (*Empty) ProtoMessage() {}
-
-// A block of data, to simply increase gRPC message size.
-type Payload struct {
- // The type of data in body.
- Type *PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"`
- // Primary contents of payload.
- Body []byte `protobuf:"bytes,2,opt,name=body" json:"body,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Payload) Reset() { *m = Payload{} }
-func (m *Payload) String() string { return proto.CompactTextString(m) }
-func (*Payload) ProtoMessage() {}
-
-func (m *Payload) GetType() PayloadType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *Payload) GetBody() []byte {
- if m != nil {
- return m.Body
- }
- return nil
-}
-
-// Unary request.
-type SimpleRequest struct {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,enum=grpc.testing.PayloadType" json:"response_type,omitempty"`
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- ResponseSize *int32 `protobuf:"varint,2,opt,name=response_size" json:"response_size,omitempty"`
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
- // Whether SimpleResponse should include username.
- FillUsername *bool `protobuf:"varint,4,opt,name=fill_username" json:"fill_username,omitempty"`
- // Whether SimpleResponse should include OAuth scope.
- FillOauthScope *bool `protobuf:"varint,5,opt,name=fill_oauth_scope" json:"fill_oauth_scope,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SimpleRequest) Reset() { *m = SimpleRequest{} }
-func (m *SimpleRequest) String() string { return proto.CompactTextString(m) }
-func (*SimpleRequest) ProtoMessage() {}
-
-func (m *SimpleRequest) GetResponseType() PayloadType {
- if m != nil && m.ResponseType != nil {
- return *m.ResponseType
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *SimpleRequest) GetResponseSize() int32 {
- if m != nil && m.ResponseSize != nil {
- return *m.ResponseSize
- }
- return 0
-}
-
-func (m *SimpleRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *SimpleRequest) GetFillUsername() bool {
- if m != nil && m.FillUsername != nil {
- return *m.FillUsername
- }
- return false
-}
-
-func (m *SimpleRequest) GetFillOauthScope() bool {
- if m != nil && m.FillOauthScope != nil {
- return *m.FillOauthScope
- }
- return false
-}
-
-// Unary response, as configured by the request.
-type SimpleResponse struct {
- // Payload to increase message size.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- // The user the request came from, for verifying authentication was
- // successful when the client expected it.
- Username *string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"`
- // OAuth scope.
- OauthScope *string `protobuf:"bytes,3,opt,name=oauth_scope" json:"oauth_scope,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SimpleResponse) Reset() { *m = SimpleResponse{} }
-func (m *SimpleResponse) String() string { return proto.CompactTextString(m) }
-func (*SimpleResponse) ProtoMessage() {}
-
-func (m *SimpleResponse) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *SimpleResponse) GetUsername() string {
- if m != nil && m.Username != nil {
- return *m.Username
- }
- return ""
-}
-
-func (m *SimpleResponse) GetOauthScope() string {
- if m != nil && m.OauthScope != nil {
- return *m.OauthScope
- }
- return ""
-}
-
-// Client-streaming request.
-type StreamingInputCallRequest struct {
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} }
-func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) }
-func (*StreamingInputCallRequest) ProtoMessage() {}
-
-func (m *StreamingInputCallRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-// Client-streaming response.
-type StreamingInputCallResponse struct {
- // Aggregated size of payloads received from the client.
- AggregatedPayloadSize *int32 `protobuf:"varint,1,opt,name=aggregated_payload_size" json:"aggregated_payload_size,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} }
-func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) }
-func (*StreamingInputCallResponse) ProtoMessage() {}
-
-func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 {
- if m != nil && m.AggregatedPayloadSize != nil {
- return *m.AggregatedPayloadSize
- }
- return 0
-}
-
-// Configuration for a particular response.
-type ResponseParameters struct {
- // Desired payload sizes in responses from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- Size *int32 `protobuf:"varint,1,opt,name=size" json:"size,omitempty"`
- // Desired interval between consecutive responses in the response stream in
- // microseconds.
- IntervalUs *int32 `protobuf:"varint,2,opt,name=interval_us" json:"interval_us,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ResponseParameters) Reset() { *m = ResponseParameters{} }
-func (m *ResponseParameters) String() string { return proto.CompactTextString(m) }
-func (*ResponseParameters) ProtoMessage() {}
-
-func (m *ResponseParameters) GetSize() int32 {
- if m != nil && m.Size != nil {
- return *m.Size
- }
- return 0
-}
-
-func (m *ResponseParameters) GetIntervalUs() int32 {
- if m != nil && m.IntervalUs != nil {
- return *m.IntervalUs
- }
- return 0
-}
-
-// Server-streaming request.
-type StreamingOutputCallRequest struct {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, the payload from each response in the stream
- // might be of different types. This is to simulate a mixed type of payload
- // stream.
- ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,enum=grpc.testing.PayloadType" json:"response_type,omitempty"`
- // Configuration for each expected response message.
- ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters" json:"response_parameters,omitempty"`
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} }
-func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) }
-func (*StreamingOutputCallRequest) ProtoMessage() {}
-
-func (m *StreamingOutputCallRequest) GetResponseType() PayloadType {
- if m != nil && m.ResponseType != nil {
- return *m.ResponseType
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters {
- if m != nil {
- return m.ResponseParameters
- }
- return nil
-}
-
-func (m *StreamingOutputCallRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-// Server-streaming response, as configured by the request and parameters.
-type StreamingOutputCallResponse struct {
- // Payload to increase response size.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} }
-func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) }
-func (*StreamingOutputCallResponse) ProtoMessage() {}
-
-func (m *StreamingOutputCallResponse) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func init() {
- proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value)
-}
-
-// Client API for TestService service
-
-type TestServiceClient interface {
- // One empty request followed by one empty response.
- EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error)
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error)
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error)
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error)
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error)
-}
-
-type testServiceClient struct {
- cc *grpc.ClientConn
-}
-
-func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient {
- return &testServiceClient{cc}
-}
-
-func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {
- out := new(Empty)
- err := grpc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
- out := new(SimpleResponse)
- err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/StreamingOutputCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceStreamingOutputCallClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type TestService_StreamingOutputCallClient interface {
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceStreamingOutputCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[1], c.cc, "/grpc.testing.TestService/StreamingInputCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceStreamingInputCallClient{stream}
- return x, nil
-}
-
-type TestService_StreamingInputCallClient interface {
- Send(*StreamingInputCallRequest) error
- CloseAndRecv() (*StreamingInputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceStreamingInputCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) {
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- m := new(StreamingInputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[2], c.cc, "/grpc.testing.TestService/FullDuplexCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceFullDuplexCallClient{stream}
- return x, nil
-}
-
-type TestService_FullDuplexCallClient interface {
- Send(*StreamingOutputCallRequest) error
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceFullDuplexCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[3], c.cc, "/grpc.testing.TestService/HalfDuplexCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceHalfDuplexCallClient{stream}
- return x, nil
-}
-
-type TestService_HalfDuplexCallClient interface {
- Send(*StreamingOutputCallRequest) error
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceHalfDuplexCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for TestService service
-
-type TestServiceServer interface {
- // One empty request followed by one empty response.
- EmptyCall(context.Context, *Empty) (*Empty, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- StreamingInputCall(TestService_StreamingInputCallServer) error
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- FullDuplexCall(TestService_FullDuplexCallServer) error
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- HalfDuplexCall(TestService_HalfDuplexCallServer) error
-}
-
-func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
- s.RegisterService(&_TestService_serviceDesc, srv)
-}
-
-func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(Empty)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(TestServiceServer).EmptyCall(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(SimpleRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(TestServiceServer).UnaryCall(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(StreamingOutputCallRequest)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream})
-}
-
-type TestService_StreamingOutputCallServer interface {
- Send(*StreamingOutputCallResponse) error
- grpc.ServerStream
-}
-
-type testServiceStreamingOutputCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream})
-}
-
-type TestService_StreamingInputCallServer interface {
- SendAndClose(*StreamingInputCallResponse) error
- Recv() (*StreamingInputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceStreamingInputCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) {
- m := new(StreamingInputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream})
-}
-
-type TestService_FullDuplexCallServer interface {
- Send(*StreamingOutputCallResponse) error
- Recv() (*StreamingOutputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceFullDuplexCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) {
- m := new(StreamingOutputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
-}
-
-type TestService_HalfDuplexCallServer interface {
- Send(*StreamingOutputCallResponse) error
- Recv() (*StreamingOutputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceHalfDuplexCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) {
- m := new(StreamingOutputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _TestService_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.testing.TestService",
- HandlerType: (*TestServiceServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "EmptyCall",
- Handler: _TestService_EmptyCall_Handler,
- },
- {
- MethodName: "UnaryCall",
- Handler: _TestService_UnaryCall_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "StreamingOutputCall",
- Handler: _TestService_StreamingOutputCall_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "StreamingInputCall",
- Handler: _TestService_StreamingInputCall_Handler,
- ClientStreams: true,
- },
- {
- StreamName: "FullDuplexCall",
- Handler: _TestService_FullDuplexCall_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- {
- StreamName: "HalfDuplexCall",
- Handler: _TestService_HalfDuplexCall_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.proto b/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.proto
deleted file mode 100644
index b5bfe0537..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing/test.proto
+++ /dev/null
@@ -1,140 +0,0 @@
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto2";
-
-package grpc.testing;
-
-message Empty {}
-
-// The type of payload that should be returned.
-enum PayloadType {
- // Compressable text format.
- COMPRESSABLE = 0;
-
- // Uncompressable binary format.
- UNCOMPRESSABLE = 1;
-
- // Randomly chosen from all other formats defined in this enum.
- RANDOM = 2;
-}
-
-// A block of data, to simply increase gRPC message size.
-message Payload {
- // The type of data in body.
- optional PayloadType type = 1;
- // Primary contents of payload.
- optional bytes body = 2;
-}
-
-// Unary request.
-message SimpleRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- optional PayloadType response_type = 1;
-
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 response_size = 2;
-
- // Optional input payload sent along with the request.
- optional Payload payload = 3;
-
- // Whether SimpleResponse should include username.
- optional bool fill_username = 4;
-
- // Whether SimpleResponse should include OAuth scope.
- optional bool fill_oauth_scope = 5;
-}
-
-// Unary response, as configured by the request.
-message SimpleResponse {
- // Payload to increase message size.
- optional Payload payload = 1;
-
- // The user the request came from, for verifying authentication was
- // successful when the client expected it.
- optional string username = 2;
-
- // OAuth scope.
- optional string oauth_scope = 3;
-}
-
-// Client-streaming request.
-message StreamingInputCallRequest {
- // Optional input payload sent along with the request.
- optional Payload payload = 1;
-
- // Not expecting any payload from the response.
-}
-
-// Client-streaming response.
-message StreamingInputCallResponse {
- // Aggregated size of payloads received from the client.
- optional int32 aggregated_payload_size = 1;
-}
-
-// Configuration for a particular response.
-message ResponseParameters {
- // Desired payload sizes in responses from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 size = 1;
-
- // Desired interval between consecutive responses in the response stream in
- // microseconds.
- optional int32 interval_us = 2;
-}
-
-// Server-streaming request.
-message StreamingOutputCallRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, the payload from each response in the stream
- // might be of different types. This is to simulate a mixed type of payload
- // stream.
- optional PayloadType response_type = 1;
-
- // Configuration for each expected response message.
- repeated ResponseParameters response_parameters = 2;
-
- // Optional input payload sent along with the request.
- optional Payload payload = 3;
-}
-
-// Server-streaming response, as configured by the request and parameters.
-message StreamingOutputCallResponse {
- // Payload to increase response size.
- optional Payload payload = 1;
-}
-
-// A simple service to test the various types of RPCs and experiment with
-// performance with various types of payload.
-service TestService {
- // One empty request followed by one empty response.
- rpc EmptyCall(Empty) returns (Empty);
-
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- rpc StreamingOutputCall(StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- rpc StreamingInputCall(stream StreamingInputCallRequest)
- returns (StreamingInputCallResponse);
-
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- rpc FullDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- rpc HalfDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/interop/server/server.go b/Godeps/_workspace/src/google.golang.org/grpc/interop/server/server.go
deleted file mode 100644
index f781c9d53..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/interop/server/server.go
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- *
- * Copyright 2014, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-package main
-
-import (
- "flag"
- "fmt"
- "io"
- "net"
- "strconv"
- "time"
-
- "github.com/golang/protobuf/proto"
- "golang.org/x/net/context"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials"
- "google.golang.org/grpc/grpclog"
- testpb "google.golang.org/grpc/interop/grpc_testing"
-)
-
-var (
- useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
- certFile = flag.String("tls_cert_file", "testdata/server1.pem", "The TLS cert file")
- keyFile = flag.String("tls_key_file", "testdata/server1.key", "The TLS key file")
- port = flag.Int("port", 10000, "The server port")
-)
-
-type testServer struct {
-}
-
-func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
- return new(testpb.Empty), nil
-}
-
-func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) {
- if size < 0 {
- return nil, fmt.Errorf("requested a response with invalid length %d", size)
- }
- body := make([]byte, size)
- switch t {
- case testpb.PayloadType_COMPRESSABLE:
- case testpb.PayloadType_UNCOMPRESSABLE:
- return nil, fmt.Errorf("payloadType UNCOMPRESSABLE is not supported")
- default:
- return nil, fmt.Errorf("unsupported payload type: %d", t)
- }
- return &testpb.Payload{
- Type: t.Enum(),
- Body: body,
- }, nil
-}
-
-func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
- pl, err := newPayload(in.GetResponseType(), in.GetResponseSize())
- if err != nil {
- return nil, err
- }
- return &testpb.SimpleResponse{
- Payload: pl,
- }, nil
-}
-
-func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error {
- cs := args.GetResponseParameters()
- for _, c := range cs {
- if us := c.GetIntervalUs(); us > 0 {
- time.Sleep(time.Duration(us) * time.Microsecond)
- }
- pl, err := newPayload(args.GetResponseType(), c.GetSize())
- if err != nil {
- return err
- }
- if err := stream.Send(&testpb.StreamingOutputCallResponse{
- Payload: pl,
- }); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error {
- var sum int
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- return stream.SendAndClose(&testpb.StreamingInputCallResponse{
- AggregatedPayloadSize: proto.Int32(int32(sum)),
- })
- }
- if err != nil {
- return err
- }
- p := in.GetPayload().GetBody()
- sum += len(p)
- }
-}
-
-func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- // read done.
- return nil
- }
- if err != nil {
- return err
- }
- cs := in.GetResponseParameters()
- for _, c := range cs {
- if us := c.GetIntervalUs(); us > 0 {
- time.Sleep(time.Duration(us) * time.Microsecond)
- }
- pl, err := newPayload(in.GetResponseType(), c.GetSize())
- if err != nil {
- return err
- }
- if err := stream.Send(&testpb.StreamingOutputCallResponse{
- Payload: pl,
- }); err != nil {
- return err
- }
- }
- }
-}
-
-func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error {
- var msgBuf []*testpb.StreamingOutputCallRequest
- for {
- in, err := stream.Recv()
- if err == io.EOF {
- // read done.
- break
- }
- if err != nil {
- return err
- }
- msgBuf = append(msgBuf, in)
- }
- for _, m := range msgBuf {
- cs := m.GetResponseParameters()
- for _, c := range cs {
- if us := c.GetIntervalUs(); us > 0 {
- time.Sleep(time.Duration(us) * time.Microsecond)
- }
- pl, err := newPayload(m.GetResponseType(), c.GetSize())
- if err != nil {
- return err
- }
- if err := stream.Send(&testpb.StreamingOutputCallResponse{
- Payload: pl,
- }); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-func main() {
- flag.Parse()
- p := strconv.Itoa(*port)
- lis, err := net.Listen("tcp", ":"+p)
- if err != nil {
- grpclog.Fatalf("failed to listen: %v", err)
- }
- var opts []grpc.ServerOption
- if *useTLS {
- creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
- if err != nil {
- grpclog.Fatalf("Failed to generate credentials %v", err)
- }
- opts = []grpc.ServerOption{grpc.Creds(creds)}
- }
- server := grpc.NewServer(opts...)
- testpb.RegisterTestServiceServer(server, &testServer{})
- server.Serve(lis)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/naming/etcd/etcd.go b/Godeps/_workspace/src/google.golang.org/grpc/naming/etcd/etcd.go
deleted file mode 100644
index 9072e85fd..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/naming/etcd/etcd.go
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- *
- * Copyright 2014, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-package etcd
-
-import (
- "sync"
-
- etcdcl "github.com/coreos/etcd/client"
- "golang.org/x/net/context"
- "google.golang.org/grpc/naming"
-)
-
-// getNode builds the key-value map starting from node recursively. It returns the
-// max etcdcl.Node.ModifiedIndex starting from that node.
-func getNode(node *etcdcl.Node, kv map[string]string) uint64 {
- if !node.Dir {
- kv[node.Key] = node.Value
- return node.ModifiedIndex
- }
- var max uint64
- for _, v := range node.Nodes {
- i := getNode(v, kv)
- if max < i {
- max = i
- }
- }
- return max
-}
-
-type resolver struct {
- kapi etcdcl.KeysAPI
-}
-
-func (r *resolver) Resolve(target string) (naming.Watcher, error) {
- resp, err := r.kapi.Get(context.Background(), target, &etcdcl.GetOptions{Recursive: true})
- if err != nil {
- return nil, err
- }
- kv := make(map[string]string)
- // Record the index in order to avoid missing updates between Get returning and
- // watch starting.
- index := getNode(resp.Node, kv)
- return &watcher{
- wr: r.kapi.Watcher(target, &etcdcl.WatcherOptions{
- AfterIndex: index,
- Recursive: true}),
- kv: kv,
- }, nil
-}
-
-// NewResolver creates an etcd-based naming.Resolver.
-func NewResolver(cfg etcdcl.Config) (naming.Resolver, error) {
- c, err := etcdcl.New(cfg)
- if err != nil {
- return nil, err
- }
- return &resolver{
- kapi: etcdcl.NewKeysAPI(c),
- }, nil
-}
-
-type watcher struct {
- wr etcdcl.Watcher
- mu sync.Mutex
- kv map[string]string
-}
-
-var once sync.Once
-
-func (w *watcher) Next(ctx context.Context) (nu []*naming.Update, err error) {
- once.Do(func() {
- select {
- case <-ctx.Done():
- err = ctx.Err()
- default:
- for _, v := range w.kv {
- nu = append(nu, &naming.Update{
- Op: naming.Add,
- Addr: v,
- })
- }
- }
- })
- if len(nu) > 0 || err != nil {
- // once.Do ran. Return directly.
- return
- }
- for {
- resp, err := w.wr.Next(ctx)
- if err != nil {
- return nil, err
- }
- if resp.Node.Dir {
- continue
- }
- w.mu.Lock()
- switch resp.Action {
- case "set":
- if resp.PrevNode == nil {
- nu = append(nu, &naming.Update{
- Op: naming.Add,
- Addr: resp.Node.Value,
- })
- w.kv[resp.Node.Key] = resp.Node.Value
- } else {
- nu = append(nu, &naming.Update{
- Op: naming.Delete,
- Addr: w.kv[resp.Node.Key],
- })
- nu = append(nu, &naming.Update{
- Op: naming.Add,
- Addr: resp.Node.Value,
- })
- w.kv[resp.Node.Key] = resp.Node.Value
- }
- case "delete":
- nu = append(nu, &naming.Update{
- Op: naming.Delete,
- Addr: resp.Node.Value,
- })
- delete(w.kv, resp.Node.Key)
- }
- w.mu.Unlock()
- return nu, nil
- }
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/naming/naming.go b/Godeps/_workspace/src/google.golang.org/grpc/naming/naming.go
deleted file mode 100644
index d0a4f46f2..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/naming/naming.go
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- *
- * Copyright 2014, Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-// Package naming defines the naming API and related data structures for gRPC.
-// The interface is EXPERIMENTAL and may be suject to change.
-package naming
-
-import (
- "golang.org/x/net/context"
-)
-
-// Operation defines the corresponding operations for a name resolution change.
-type Operation uint8
-
-const (
- // Add indicates a new address is added.
- Add Operation = iota
- // Delete indicates an exisiting address is deleted.
- Delete
-)
-
-// Update defines a name resolution update. Notice that it is not valid having both
-// empty string Addr and nil Metadata in an Update.
-type Update struct {
- // Op indicates the operation of the update.
- Op Operation
- // Addr is the updated address. It is empty string if there is no address update.
- Addr string
- // Metadata is the updated metadata. It is nil if there is no metadata update.
- // Metadata is not required for a custom naming implementation.
- Metadata interface{}
-}
-
-// Resolver creates a Watcher for a target to track its resolution changes.
-type Resolver interface {
- // Resolve creates a Watcher for target.
- Resolve(target string) (Watcher, error)
-}
-
-// Watcher watches for the updates on the specified target.
-type Watcher interface {
- // Next blocks until an update or error happens. It may return one or more
- // updates. The first call should get the full set of the results.
- Next(ctx context.Context) ([]*Update, error)
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.pb.go
deleted file mode 100644
index 5f72c5570..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.pb.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: perf.proto
-// DO NOT EDIT!
-
-/*
-Package codec_perf is a generated protocol buffer package.
-
-It is generated from these files:
- perf.proto
-
-It has these top-level messages:
- Buffer
-*/
-package codec_perf
-
-import proto "github.com/golang/protobuf/proto"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = math.Inf
-
-// Buffer is a message that contains a body of bytes that is used to exercise
-// encoding and decoding overheads.
-type Buffer struct {
- Body []byte `protobuf:"bytes,1,opt,name=body" json:"body,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Buffer) Reset() { *m = Buffer{} }
-func (m *Buffer) String() string { return proto.CompactTextString(m) }
-func (*Buffer) ProtoMessage() {}
-
-func (m *Buffer) GetBody() []byte {
- if m != nil {
- return m.Body
- }
- return nil
-}
-
-func init() {
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.proto b/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.proto
deleted file mode 100644
index 4cf561f7f..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/test/codec_perf/perf.proto
+++ /dev/null
@@ -1,11 +0,0 @@
-// Messages used for performance tests that may not reference grpc directly for
-// reasons of import cycles.
-syntax = "proto2";
-
-package codec.perf;
-
-// Buffer is a message that contains a body of bytes that is used to exercise
-// encoding and decoding overheads.
-message Buffer {
- optional bytes body = 1;
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.pb.go b/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.pb.go
deleted file mode 100644
index bd492fef4..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.pb.go
+++ /dev/null
@@ -1,702 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: test.proto
-// DO NOT EDIT!
-
-/*
-Package grpc_testing is a generated protocol buffer package.
-
-It is generated from these files:
- test.proto
-
-It has these top-level messages:
- Empty
- Payload
- SimpleRequest
- SimpleResponse
- StreamingInputCallRequest
- StreamingInputCallResponse
- ResponseParameters
- StreamingOutputCallRequest
- StreamingOutputCallResponse
-*/
-package grpc_testing
-
-import proto "github.com/golang/protobuf/proto"
-import math "math"
-
-import (
- context "golang.org/x/net/context"
- grpc "google.golang.org/grpc"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = math.Inf
-
-// The type of payload that should be returned.
-type PayloadType int32
-
-const (
- // Compressable text format.
- PayloadType_COMPRESSABLE PayloadType = 0
- // Uncompressable binary format.
- PayloadType_UNCOMPRESSABLE PayloadType = 1
- // Randomly chosen from all other formats defined in this enum.
- PayloadType_RANDOM PayloadType = 2
-)
-
-var PayloadType_name = map[int32]string{
- 0: "COMPRESSABLE",
- 1: "UNCOMPRESSABLE",
- 2: "RANDOM",
-}
-var PayloadType_value = map[string]int32{
- "COMPRESSABLE": 0,
- "UNCOMPRESSABLE": 1,
- "RANDOM": 2,
-}
-
-func (x PayloadType) Enum() *PayloadType {
- p := new(PayloadType)
- *p = x
- return p
-}
-func (x PayloadType) String() string {
- return proto.EnumName(PayloadType_name, int32(x))
-}
-func (x *PayloadType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(PayloadType_value, data, "PayloadType")
- if err != nil {
- return err
- }
- *x = PayloadType(value)
- return nil
-}
-
-type Empty struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Empty) Reset() { *m = Empty{} }
-func (m *Empty) String() string { return proto.CompactTextString(m) }
-func (*Empty) ProtoMessage() {}
-
-// A block of data, to simply increase gRPC message size.
-type Payload struct {
- // The type of data in body.
- Type *PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"`
- // Primary contents of payload.
- Body []byte `protobuf:"bytes,2,opt,name=body" json:"body,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Payload) Reset() { *m = Payload{} }
-func (m *Payload) String() string { return proto.CompactTextString(m) }
-func (*Payload) ProtoMessage() {}
-
-func (m *Payload) GetType() PayloadType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *Payload) GetBody() []byte {
- if m != nil {
- return m.Body
- }
- return nil
-}
-
-// Unary request.
-type SimpleRequest struct {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,enum=grpc.testing.PayloadType" json:"response_type,omitempty"`
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- ResponseSize *int32 `protobuf:"varint,2,opt,name=response_size" json:"response_size,omitempty"`
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
- // Whether SimpleResponse should include username.
- FillUsername *bool `protobuf:"varint,4,opt,name=fill_username" json:"fill_username,omitempty"`
- // Whether SimpleResponse should include OAuth scope.
- FillOauthScope *bool `protobuf:"varint,5,opt,name=fill_oauth_scope" json:"fill_oauth_scope,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SimpleRequest) Reset() { *m = SimpleRequest{} }
-func (m *SimpleRequest) String() string { return proto.CompactTextString(m) }
-func (*SimpleRequest) ProtoMessage() {}
-
-func (m *SimpleRequest) GetResponseType() PayloadType {
- if m != nil && m.ResponseType != nil {
- return *m.ResponseType
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *SimpleRequest) GetResponseSize() int32 {
- if m != nil && m.ResponseSize != nil {
- return *m.ResponseSize
- }
- return 0
-}
-
-func (m *SimpleRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *SimpleRequest) GetFillUsername() bool {
- if m != nil && m.FillUsername != nil {
- return *m.FillUsername
- }
- return false
-}
-
-func (m *SimpleRequest) GetFillOauthScope() bool {
- if m != nil && m.FillOauthScope != nil {
- return *m.FillOauthScope
- }
- return false
-}
-
-// Unary response, as configured by the request.
-type SimpleResponse struct {
- // Payload to increase message size.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- // The user the request came from, for verifying authentication was
- // successful when the client expected it.
- Username *string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"`
- // OAuth scope.
- OauthScope *string `protobuf:"bytes,3,opt,name=oauth_scope" json:"oauth_scope,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SimpleResponse) Reset() { *m = SimpleResponse{} }
-func (m *SimpleResponse) String() string { return proto.CompactTextString(m) }
-func (*SimpleResponse) ProtoMessage() {}
-
-func (m *SimpleResponse) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func (m *SimpleResponse) GetUsername() string {
- if m != nil && m.Username != nil {
- return *m.Username
- }
- return ""
-}
-
-func (m *SimpleResponse) GetOauthScope() string {
- if m != nil && m.OauthScope != nil {
- return *m.OauthScope
- }
- return ""
-}
-
-// Client-streaming request.
-type StreamingInputCallRequest struct {
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} }
-func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) }
-func (*StreamingInputCallRequest) ProtoMessage() {}
-
-func (m *StreamingInputCallRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-// Client-streaming response.
-type StreamingInputCallResponse struct {
- // Aggregated size of payloads received from the client.
- AggregatedPayloadSize *int32 `protobuf:"varint,1,opt,name=aggregated_payload_size" json:"aggregated_payload_size,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} }
-func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) }
-func (*StreamingInputCallResponse) ProtoMessage() {}
-
-func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 {
- if m != nil && m.AggregatedPayloadSize != nil {
- return *m.AggregatedPayloadSize
- }
- return 0
-}
-
-// Configuration for a particular response.
-type ResponseParameters struct {
- // Desired payload sizes in responses from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- Size *int32 `protobuf:"varint,1,opt,name=size" json:"size,omitempty"`
- // Desired interval between consecutive responses in the response stream in
- // microseconds.
- IntervalUs *int32 `protobuf:"varint,2,opt,name=interval_us" json:"interval_us,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ResponseParameters) Reset() { *m = ResponseParameters{} }
-func (m *ResponseParameters) String() string { return proto.CompactTextString(m) }
-func (*ResponseParameters) ProtoMessage() {}
-
-func (m *ResponseParameters) GetSize() int32 {
- if m != nil && m.Size != nil {
- return *m.Size
- }
- return 0
-}
-
-func (m *ResponseParameters) GetIntervalUs() int32 {
- if m != nil && m.IntervalUs != nil {
- return *m.IntervalUs
- }
- return 0
-}
-
-// Server-streaming request.
-type StreamingOutputCallRequest struct {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, the payload from each response in the stream
- // might be of different types. This is to simulate a mixed type of payload
- // stream.
- ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,enum=grpc.testing.PayloadType" json:"response_type,omitempty"`
- // Configuration for each expected response message.
- ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters" json:"response_parameters,omitempty"`
- // Optional input payload sent along with the request.
- Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} }
-func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) }
-func (*StreamingOutputCallRequest) ProtoMessage() {}
-
-func (m *StreamingOutputCallRequest) GetResponseType() PayloadType {
- if m != nil && m.ResponseType != nil {
- return *m.ResponseType
- }
- return PayloadType_COMPRESSABLE
-}
-
-func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters {
- if m != nil {
- return m.ResponseParameters
- }
- return nil
-}
-
-func (m *StreamingOutputCallRequest) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-// Server-streaming response, as configured by the request and parameters.
-type StreamingOutputCallResponse struct {
- // Payload to increase response size.
- Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} }
-func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) }
-func (*StreamingOutputCallResponse) ProtoMessage() {}
-
-func (m *StreamingOutputCallResponse) GetPayload() *Payload {
- if m != nil {
- return m.Payload
- }
- return nil
-}
-
-func init() {
- proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value)
-}
-
-// Client API for TestService service
-
-type TestServiceClient interface {
- // One empty request followed by one empty response.
- EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error)
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error)
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error)
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error)
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error)
-}
-
-type testServiceClient struct {
- cc *grpc.ClientConn
-}
-
-func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient {
- return &testServiceClient{cc}
-}
-
-func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {
- out := new(Empty)
- err := grpc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
- out := new(SimpleResponse)
- err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/StreamingOutputCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceStreamingOutputCallClient{stream}
- if err := x.ClientStream.SendMsg(in); err != nil {
- return nil, err
- }
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- return x, nil
-}
-
-type TestService_StreamingOutputCallClient interface {
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceStreamingOutputCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[1], c.cc, "/grpc.testing.TestService/StreamingInputCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceStreamingInputCallClient{stream}
- return x, nil
-}
-
-type TestService_StreamingInputCallClient interface {
- Send(*StreamingInputCallRequest) error
- CloseAndRecv() (*StreamingInputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceStreamingInputCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) {
- if err := x.ClientStream.CloseSend(); err != nil {
- return nil, err
- }
- m := new(StreamingInputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[2], c.cc, "/grpc.testing.TestService/FullDuplexCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceFullDuplexCallClient{stream}
- return x, nil
-}
-
-type TestService_FullDuplexCallClient interface {
- Send(*StreamingOutputCallRequest) error
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceFullDuplexCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) {
- stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[3], c.cc, "/grpc.testing.TestService/HalfDuplexCall", opts...)
- if err != nil {
- return nil, err
- }
- x := &testServiceHalfDuplexCallClient{stream}
- return x, nil
-}
-
-type TestService_HalfDuplexCallClient interface {
- Send(*StreamingOutputCallRequest) error
- Recv() (*StreamingOutputCallResponse, error)
- grpc.ClientStream
-}
-
-type testServiceHalfDuplexCallClient struct {
- grpc.ClientStream
-}
-
-func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error {
- return x.ClientStream.SendMsg(m)
-}
-
-func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) {
- m := new(StreamingOutputCallResponse)
- if err := x.ClientStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-// Server API for TestService service
-
-type TestServiceServer interface {
- // One empty request followed by one empty response.
- EmptyCall(context.Context, *Empty) (*Empty, error)
- // One request followed by one response.
- // The server returns the client payload as-is.
- UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- StreamingInputCall(TestService_StreamingInputCallServer) error
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- FullDuplexCall(TestService_FullDuplexCallServer) error
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- HalfDuplexCall(TestService_HalfDuplexCallServer) error
-}
-
-func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
- s.RegisterService(&_TestService_serviceDesc, srv)
-}
-
-func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(Empty)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(TestServiceServer).EmptyCall(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) {
- in := new(SimpleRequest)
- if err := dec(in); err != nil {
- return nil, err
- }
- out, err := srv.(TestServiceServer).UnaryCall(ctx, in)
- if err != nil {
- return nil, err
- }
- return out, nil
-}
-
-func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- m := new(StreamingOutputCallRequest)
- if err := stream.RecvMsg(m); err != nil {
- return err
- }
- return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream})
-}
-
-type TestService_StreamingOutputCallServer interface {
- Send(*StreamingOutputCallResponse) error
- grpc.ServerStream
-}
-
-type testServiceStreamingOutputCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream})
-}
-
-type TestService_StreamingInputCallServer interface {
- SendAndClose(*StreamingInputCallResponse) error
- Recv() (*StreamingInputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceStreamingInputCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) {
- m := new(StreamingInputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream})
-}
-
-type TestService_FullDuplexCallServer interface {
- Send(*StreamingOutputCallResponse) error
- Recv() (*StreamingOutputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceFullDuplexCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) {
- m := new(StreamingOutputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
- return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
-}
-
-type TestService_HalfDuplexCallServer interface {
- Send(*StreamingOutputCallResponse) error
- Recv() (*StreamingOutputCallRequest, error)
- grpc.ServerStream
-}
-
-type testServiceHalfDuplexCallServer struct {
- grpc.ServerStream
-}
-
-func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error {
- return x.ServerStream.SendMsg(m)
-}
-
-func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) {
- m := new(StreamingOutputCallRequest)
- if err := x.ServerStream.RecvMsg(m); err != nil {
- return nil, err
- }
- return m, nil
-}
-
-var _TestService_serviceDesc = grpc.ServiceDesc{
- ServiceName: "grpc.testing.TestService",
- HandlerType: (*TestServiceServer)(nil),
- Methods: []grpc.MethodDesc{
- {
- MethodName: "EmptyCall",
- Handler: _TestService_EmptyCall_Handler,
- },
- {
- MethodName: "UnaryCall",
- Handler: _TestService_UnaryCall_Handler,
- },
- },
- Streams: []grpc.StreamDesc{
- {
- StreamName: "StreamingOutputCall",
- Handler: _TestService_StreamingOutputCall_Handler,
- ServerStreams: true,
- },
- {
- StreamName: "StreamingInputCall",
- Handler: _TestService_StreamingInputCall_Handler,
- ClientStreams: true,
- },
- {
- StreamName: "FullDuplexCall",
- Handler: _TestService_FullDuplexCall_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- {
- StreamName: "HalfDuplexCall",
- Handler: _TestService_HalfDuplexCall_Handler,
- ServerStreams: true,
- ClientStreams: true,
- },
- },
-}
diff --git a/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.proto b/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.proto
deleted file mode 100644
index b5bfe0537..000000000
--- a/Godeps/_workspace/src/google.golang.org/grpc/test/grpc_testing/test.proto
+++ /dev/null
@@ -1,140 +0,0 @@
-// An integration test service that covers all the method signature permutations
-// of unary/streaming requests/responses.
-syntax = "proto2";
-
-package grpc.testing;
-
-message Empty {}
-
-// The type of payload that should be returned.
-enum PayloadType {
- // Compressable text format.
- COMPRESSABLE = 0;
-
- // Uncompressable binary format.
- UNCOMPRESSABLE = 1;
-
- // Randomly chosen from all other formats defined in this enum.
- RANDOM = 2;
-}
-
-// A block of data, to simply increase gRPC message size.
-message Payload {
- // The type of data in body.
- optional PayloadType type = 1;
- // Primary contents of payload.
- optional bytes body = 2;
-}
-
-// Unary request.
-message SimpleRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, server randomly chooses one from other formats.
- optional PayloadType response_type = 1;
-
- // Desired payload size in the response from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 response_size = 2;
-
- // Optional input payload sent along with the request.
- optional Payload payload = 3;
-
- // Whether SimpleResponse should include username.
- optional bool fill_username = 4;
-
- // Whether SimpleResponse should include OAuth scope.
- optional bool fill_oauth_scope = 5;
-}
-
-// Unary response, as configured by the request.
-message SimpleResponse {
- // Payload to increase message size.
- optional Payload payload = 1;
-
- // The user the request came from, for verifying authentication was
- // successful when the client expected it.
- optional string username = 2;
-
- // OAuth scope.
- optional string oauth_scope = 3;
-}
-
-// Client-streaming request.
-message StreamingInputCallRequest {
- // Optional input payload sent along with the request.
- optional Payload payload = 1;
-
- // Not expecting any payload from the response.
-}
-
-// Client-streaming response.
-message StreamingInputCallResponse {
- // Aggregated size of payloads received from the client.
- optional int32 aggregated_payload_size = 1;
-}
-
-// Configuration for a particular response.
-message ResponseParameters {
- // Desired payload sizes in responses from the server.
- // If response_type is COMPRESSABLE, this denotes the size before compression.
- optional int32 size = 1;
-
- // Desired interval between consecutive responses in the response stream in
- // microseconds.
- optional int32 interval_us = 2;
-}
-
-// Server-streaming request.
-message StreamingOutputCallRequest {
- // Desired payload type in the response from the server.
- // If response_type is RANDOM, the payload from each response in the stream
- // might be of different types. This is to simulate a mixed type of payload
- // stream.
- optional PayloadType response_type = 1;
-
- // Configuration for each expected response message.
- repeated ResponseParameters response_parameters = 2;
-
- // Optional input payload sent along with the request.
- optional Payload payload = 3;
-}
-
-// Server-streaming response, as configured by the request and parameters.
-message StreamingOutputCallResponse {
- // Payload to increase response size.
- optional Payload payload = 1;
-}
-
-// A simple service to test the various types of RPCs and experiment with
-// performance with various types of payload.
-service TestService {
- // One empty request followed by one empty response.
- rpc EmptyCall(Empty) returns (Empty);
-
- // One request followed by one response.
- // The server returns the client payload as-is.
- rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
-
- // One request followed by a sequence of responses (streamed download).
- // The server returns the payload with client desired type and sizes.
- rpc StreamingOutputCall(StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by one response (streamed upload).
- // The server returns the aggregated size of client payload as the result.
- rpc StreamingInputCall(stream StreamingInputCallRequest)
- returns (StreamingInputCallResponse);
-
- // A sequence of requests with each request served by the server immediately.
- // As one request could lead to multiple responses, this interface
- // demonstrates the idea of full duplexing.
- rpc FullDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-
- // A sequence of requests followed by a sequence of responses.
- // The server buffers all the client requests and then serves them in order. A
- // stream of responses are returned to the client when the server starts with
- // first request.
- rpc HalfDuplexCall(stream StreamingOutputCallRequest)
- returns (stream StreamingOutputCallResponse);
-}
diff --git a/Godeps/_workspace/src/gopkg.in/check.v1/LICENSE b/Godeps/_workspace/src/gopkg.in/check.v1/LICENSE
index 5ba025a98..545cf2d33 100644
--- a/Godeps/_workspace/src/gopkg.in/check.v1/LICENSE
+++ b/Godeps/_workspace/src/gopkg.in/check.v1/LICENSE
@@ -1,17 +1,17 @@
Gocheck - A rich testing framework for Go
-
+
Copyright (c) 2010-2013 Gustavo Niemeyer
All rights reserved.
Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
+modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
+ list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
+ and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
diff --git a/Godeps/_workspace/src/gopkg.in/check.v1/README.md b/Godeps/_workspace/src/gopkg.in/check.v1/README.md
index a82b885e6..0ca9e5726 100644
--- a/Godeps/_workspace/src/gopkg.in/check.v1/README.md
+++ b/Godeps/_workspace/src/gopkg.in/check.v1/README.md
@@ -4,7 +4,7 @@ Instructions
Install the package with:
go get gopkg.in/check.v1
-
+
Import it with:
import "gopkg.in/check.v1"
diff --git a/Godeps/_workspace/src/gopkg.in/check.v1/benchmark.go b/Godeps/_workspace/src/gopkg.in/check.v1/benchmark.go
index b2d351948..46ea9dc6d 100644
--- a/Godeps/_workspace/src/gopkg.in/check.v1/benchmark.go
+++ b/Godeps/_workspace/src/gopkg.in/check.v1/benchmark.go
@@ -1,9 +1,9 @@
// Copyright (c) 2012 The Go Authors. All rights reserved.
-//
+//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
-//
+//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
@@ -13,7 +13,7 @@
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
-//
+//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR