From 6e2cb00008cbf09e556b00f87603797fcaa47e09 Mon Sep 17 00:00:00 2001 From: Christopher Speller Date: Mon, 16 Apr 2018 05:37:14 -0700 Subject: Depenancy upgrades and movign to dep. (#8630) --- .../github.com/prometheus/client_golang/.gitignore | 30 - .../prometheus/client_golang/.travis.yml | 10 - .../github.com/prometheus/client_golang/AUTHORS.md | 18 + .../prometheus/client_golang/CHANGELOG.md | 109 - .../prometheus/client_golang/CONTRIBUTING.md | 18 - .../prometheus/client_golang/ISSUE_TEMPLATE.md | 8 - .../prometheus/client_golang/MAINTAINERS.md | 1 - .../github.com/prometheus/client_golang/README.md | 94 - vendor/github.com/prometheus/client_golang/VERSION | 1 - .../prometheus/client_golang/api/client.go | 131 - .../prometheus/client_golang/api/client_test.go | 115 - .../client_golang/api/prometheus/v1/api.go | 293 -- .../client_golang/api/prometheus/v1/api_test.go | 424 --- .../client_golang/examples/random/Dockerfile | 20 - .../client_golang/examples/random/main.go | 106 - .../client_golang/examples/simple/Dockerfile | 20 - .../client_golang/examples/simple/main.go | 31 - .../client_golang/prometheus/benchmark_test.go | 199 -- .../prometheus/client_golang/prometheus/counter.go | 191 +- .../client_golang/prometheus/counter_test.go | 212 -- .../prometheus/client_golang/prometheus/desc.go | 39 +- .../client_golang/prometheus/desc_test.go | 17 - .../prometheus/client_golang/prometheus/doc.go | 77 +- .../prometheus/example_clustermanager_test.go | 118 - .../prometheus/example_timer_complex_test.go | 71 - .../prometheus/example_timer_gauge_test.go | 48 - .../client_golang/prometheus/example_timer_test.go | 40 - .../client_golang/prometheus/examples_test.go | 754 ----- .../prometheus/expvar_collector_test.go | 97 - .../prometheus/client_golang/prometheus/gauge.go | 204 +- .../client_golang/prometheus/gauge_test.go | 202 -- .../client_golang/prometheus/go_collector.go | 51 +- .../client_golang/prometheus/go_collector_test.go | 123 - .../client_golang/prometheus/graphite/bridge.go | 280 -- .../prometheus/graphite/bridge_test.go | 309 -- .../client_golang/prometheus/histogram.go | 147 +- .../client_golang/prometheus/histogram_test.go | 348 -- .../prometheus/client_golang/prometheus/http.go | 111 +- .../client_golang/prometheus/http_test.go | 154 - .../prometheus/client_golang/prometheus/labels.go | 57 - .../prometheus/client_golang/prometheus/metric.go | 20 +- .../client_golang/prometheus/metric_test.go | 35 - .../client_golang/prometheus/observer.go | 52 - .../client_golang/prometheus/process_collector.go | 118 +- .../prometheus/process_collector_test.go | 58 - .../client_golang/prometheus/promhttp/delegator.go | 199 -- .../prometheus/promhttp/delegator_1_8.go | 181 -- .../prometheus/promhttp/delegator_pre_1_8.go | 44 - .../client_golang/prometheus/promhttp/http.go | 160 +- .../client_golang/prometheus/promhttp/http_test.go | 250 -- .../prometheus/promhttp/instrument_client.go | 97 - .../prometheus/promhttp/instrument_client_1_8.go | 144 - .../promhttp/instrument_client_1_8_test.go | 195 -- .../prometheus/promhttp/instrument_server.go | 447 --- .../prometheus/promhttp/instrument_server_test.go | 401 --- .../client_golang/prometheus/push/deprecated.go | 172 - .../push/example_add_from_gatherer_test.go | 80 - .../client_golang/prometheus/push/examples_test.go | 35 - .../client_golang/prometheus/push/push.go | 236 -- .../client_golang/prometheus/push/push_test.go | 194 -- .../client_golang/prometheus/registry.go | 359 ++- .../client_golang/prometheus/registry_test.go | 590 ---- .../prometheus/client_golang/prometheus/summary.go | 173 +- .../client_golang/prometheus/summary_test.go | 388 --- .../prometheus/client_golang/prometheus/timer.go | 51 - .../client_golang/prometheus/timer_test.go | 152 - .../prometheus/client_golang/prometheus/untyped.go | 102 +- .../prometheus/client_golang/prometheus/value.go | 78 +- .../client_golang/prometheus/value_test.go | 43 - .../prometheus/client_golang/prometheus/vec.go | 491 ++- .../client_golang/prometheus/vec_test.go | 535 ---- .../github.com/prometheus/client_model/.gitignore | 1 - .../prometheus/client_model/CONTRIBUTING.md | 18 - .../prometheus/client_model/MAINTAINERS.md | 1 - vendor/github.com/prometheus/client_model/Makefile | 62 - .../github.com/prometheus/client_model/README.md | 26 - .../prometheus/client_model/cpp/metrics.pb.cc | 3380 -------------------- .../prometheus/client_model/cpp/metrics.pb.h | 2072 ------------ .../prometheus/client_model/metrics.proto | 81 - vendor/github.com/prometheus/client_model/pom.xml | 130 - .../client_model/python/prometheus/__init__.py | 12 - .../prometheus/client_model/ruby/.gitignore | 5 - .../prometheus/client_model/ruby/Gemfile | 4 - .../prometheus/client_model/ruby/Makefile | 17 - .../prometheus/client_model/ruby/README.md | 31 - .../prometheus/client_model/ruby/Rakefile | 1 - .../ruby/prometheus-client-model.gemspec | 22 - vendor/github.com/prometheus/client_model/setup.py | 23 - vendor/github.com/prometheus/common/.travis.yml | 6 - .../github.com/prometheus/common/CONTRIBUTING.md | 18 - vendor/github.com/prometheus/common/MAINTAINERS.md | 1 - vendor/github.com/prometheus/common/README.md | 12 - .../github.com/prometheus/common/config/config.go | 47 - .../prometheus/common/config/http_config.go | 281 -- .../prometheus/common/config/http_config_test.go | 157 - .../http.conf.bearer-token-and-file-set.bad.yml | 5 - .../common/config/testdata/http.conf.empty.bad.yml | 4 - .../common/config/testdata/http.conf.good.yml | 4 - .../http.conf.invalid-bearer-token-file.bad.yml | 1 - .../config/testdata/tls_config.cert_no_key.bad.yml | 1 - .../config/testdata/tls_config.empty.good.yml | 0 .../config/testdata/tls_config.insecure.good.yml | 1 - .../testdata/tls_config.invalid_field.bad.yml | 1 - .../config/testdata/tls_config.key_no_cert.bad.yml | 1 - .../prometheus/common/config/tls_config_test.go | 92 - .../prometheus/common/expfmt/bench_test.go | 167 - .../github.com/prometheus/common/expfmt/decode.go | 4 +- .../prometheus/common/expfmt/decode_test.go | 435 --- .../github.com/prometheus/common/expfmt/expfmt.go | 2 +- .../common/expfmt/fuzz/corpus/from_test_parse_0 | 2 - .../common/expfmt/fuzz/corpus/from_test_parse_1 | 6 - .../common/expfmt/fuzz/corpus/from_test_parse_2 | 12 - .../common/expfmt/fuzz/corpus/from_test_parse_3 | 22 - .../common/expfmt/fuzz/corpus/from_test_parse_4 | 10 - .../expfmt/fuzz/corpus/from_test_parse_error_0 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_1 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_10 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_11 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_12 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_13 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_14 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_15 | 2 - .../expfmt/fuzz/corpus/from_test_parse_error_16 | 2 - .../expfmt/fuzz/corpus/from_test_parse_error_17 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_18 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_19 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_2 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_3 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_4 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_5 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_6 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_7 | 3 - .../expfmt/fuzz/corpus/from_test_parse_error_8 | 1 - .../expfmt/fuzz/corpus/from_test_parse_error_9 | 1 - .../prometheus/common/expfmt/fuzz/corpus/minimal | 1 - .../prometheus/common/expfmt/testdata/json2 | 46 - .../prometheus/common/expfmt/testdata/json2_bad | 46 - .../prometheus/common/expfmt/testdata/protobuf | Bin 8239 -> 0 bytes .../prometheus/common/expfmt/testdata/protobuf.gz | Bin 2097 -> 0 bytes .../prometheus/common/expfmt/testdata/text | 322 -- .../prometheus/common/expfmt/testdata/text.gz | Bin 2598 -> 0 bytes .../prometheus/common/expfmt/text_create_test.go | 443 --- .../prometheus/common/expfmt/text_parse.go | 4 +- .../prometheus/common/expfmt/text_parse_test.go | 593 ---- .../bitbucket.org/ww/goautoneg/autoneg_test.go | 33 - .../prometheus/common/log/eventlog_formatter.go | 89 - vendor/github.com/prometheus/common/log/log.go | 364 --- .../github.com/prometheus/common/log/log_test.go | 39 - .../prometheus/common/log/syslog_formatter.go | 126 - .../prometheus/common/log/syslog_formatter_test.go | 52 - .../prometheus/common/model/alert_test.go | 118 - .../prometheus/common/model/labels_test.go | 140 - .../prometheus/common/model/metric_test.go | 132 - .../prometheus/common/model/signature_test.go | 314 -- .../github.com/prometheus/common/model/silence.go | 4 +- .../prometheus/common/model/silence_test.go | 228 -- .../prometheus/common/model/time_test.go | 132 - vendor/github.com/prometheus/common/model/value.go | 4 +- .../prometheus/common/model/value_test.go | 468 --- .../prometheus/common/promlog/flag/flag.go | 33 - vendor/github.com/prometheus/common/promlog/log.go | 63 - vendor/github.com/prometheus/common/route/route.go | 100 - .../prometheus/common/route/route_test.go | 44 - .../github.com/prometheus/common/version/info.go | 89 - vendor/github.com/prometheus/procfs/.gitignore | 1 + vendor/github.com/prometheus/procfs/.travis.yml | 6 + vendor/github.com/prometheus/procfs/Makefile | 77 +- .../github.com/prometheus/procfs/bcache/bcache.go | 84 - vendor/github.com/prometheus/procfs/bcache/get.go | 330 -- .../prometheus/procfs/bcache/get_test.go | 114 - .../github.com/prometheus/procfs/buddyinfo_test.go | 64 - vendor/github.com/prometheus/procfs/fixtures.ttar | 446 +++ .../prometheus/procfs/fixtures/26231/cmdline | Bin 16 -> 0 bytes .../prometheus/procfs/fixtures/26231/comm | 1 - .../prometheus/procfs/fixtures/26231/exe | 1 - .../prometheus/procfs/fixtures/26231/fd/0 | 1 - .../prometheus/procfs/fixtures/26231/fd/1 | 1 - .../prometheus/procfs/fixtures/26231/fd/10 | 1 - .../prometheus/procfs/fixtures/26231/fd/2 | 1 - .../prometheus/procfs/fixtures/26231/fd/3 | 1 - .../github.com/prometheus/procfs/fixtures/26231/io | 7 - .../prometheus/procfs/fixtures/26231/limits | 17 - .../prometheus/procfs/fixtures/26231/mountstats | 19 - .../prometheus/procfs/fixtures/26231/net/dev | 4 - .../prometheus/procfs/fixtures/26231/ns/mnt | 1 - .../prometheus/procfs/fixtures/26231/ns/net | 1 - .../prometheus/procfs/fixtures/26231/stat | 1 - .../prometheus/procfs/fixtures/26232/cmdline | 0 .../prometheus/procfs/fixtures/26232/comm | 1 - .../prometheus/procfs/fixtures/26232/fd/0 | 1 - .../prometheus/procfs/fixtures/26232/fd/1 | 1 - .../prometheus/procfs/fixtures/26232/fd/2 | 1 - .../prometheus/procfs/fixtures/26232/fd/3 | 1 - .../prometheus/procfs/fixtures/26232/fd/4 | 1 - .../prometheus/procfs/fixtures/26232/limits | 17 - .../prometheus/procfs/fixtures/26232/stat | 1 - .../github.com/prometheus/procfs/fixtures/584/stat | 2 - .../procfs/fixtures/buddyinfo/short/buddyinfo | 3 - .../fixtures/buddyinfo/sizemismatch/buddyinfo | 3 - .../procfs/fixtures/buddyinfo/valid/buddyinfo | 3 - .../prometheus/procfs/fixtures/fs/xfs/stat | 23 - .../github.com/prometheus/procfs/fixtures/mdstat | 26 - .../github.com/prometheus/procfs/fixtures/net/dev | 6 - .../prometheus/procfs/fixtures/net/ip_vs | 21 - .../prometheus/procfs/fixtures/net/ip_vs_stats | 6 - .../prometheus/procfs/fixtures/net/rpc/nfs | 5 - .../prometheus/procfs/fixtures/net/rpc/nfsd | 11 - .../prometheus/procfs/fixtures/net/xfrm_stat | 28 - vendor/github.com/prometheus/procfs/fixtures/self | 1 - vendor/github.com/prometheus/procfs/fixtures/stat | 16 - .../procfs/fixtures/symlinktargets/README | 2 - .../prometheus/procfs/fixtures/symlinktargets/abc | 0 .../prometheus/procfs/fixtures/symlinktargets/def | 0 .../prometheus/procfs/fixtures/symlinktargets/ghi | 0 .../prometheus/procfs/fixtures/symlinktargets/uvw | 0 .../prometheus/procfs/fixtures/symlinktargets/xyz | 0 vendor/github.com/prometheus/procfs/fs.go | 13 + vendor/github.com/prometheus/procfs/fs_test.go | 26 - vendor/github.com/prometheus/procfs/ipvs.go | 13 + vendor/github.com/prometheus/procfs/ipvs_test.go | 237 -- vendor/github.com/prometheus/procfs/mdstat.go | 13 + vendor/github.com/prometheus/procfs/mdstat_test.go | 31 - vendor/github.com/prometheus/procfs/mountstats.go | 13 + .../prometheus/procfs/mountstats_test.go | 273 -- vendor/github.com/prometheus/procfs/net_dev.go | 15 +- .../github.com/prometheus/procfs/net_dev_test.go | 73 - vendor/github.com/prometheus/procfs/nfs/nfs.go | 20 +- vendor/github.com/prometheus/procfs/nfs/parse.go | 16 +- .../prometheus/procfs/nfs/parse_nfs_test.go | 305 -- .../prometheus/procfs/nfs/parse_nfsd_test.go | 196 -- vendor/github.com/prometheus/procfs/proc.go | 16 +- vendor/github.com/prometheus/procfs/proc_io.go | 13 + .../github.com/prometheus/procfs/proc_io_test.go | 33 - vendor/github.com/prometheus/procfs/proc_limits.go | 13 + .../prometheus/procfs/proc_limits_test.go | 31 - vendor/github.com/prometheus/procfs/proc_ns.go | 13 + .../github.com/prometheus/procfs/proc_ns_test.go | 31 - vendor/github.com/prometheus/procfs/proc_stat.go | 13 + .../github.com/prometheus/procfs/proc_stat_test.go | 110 - vendor/github.com/prometheus/procfs/proc_test.go | 160 - vendor/github.com/prometheus/procfs/stat.go | 13 + vendor/github.com/prometheus/procfs/stat_test.go | 61 - .../github.com/prometheus/procfs/sysfs/.gitignore | 1 - vendor/github.com/prometheus/procfs/sysfs/doc.go | 16 - .../prometheus/procfs/sysfs/fixtures.ttar | 721 ----- vendor/github.com/prometheus/procfs/sysfs/fs.go | 108 - .../github.com/prometheus/procfs/sysfs/fs_test.go | 108 - vendor/github.com/prometheus/procfs/ttar | 133 +- vendor/github.com/prometheus/procfs/xfrm_test.go | 66 - .../github.com/prometheus/procfs/xfs/parse_test.go | 442 --- 250 files changed, 1786 insertions(+), 25516 deletions(-) delete mode 100644 vendor/github.com/prometheus/client_golang/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/.travis.yml create mode 100644 vendor/github.com/prometheus/client_golang/AUTHORS.md delete mode 100644 vendor/github.com/prometheus/client_golang/CHANGELOG.md delete mode 100644 vendor/github.com/prometheus/client_golang/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/client_golang/ISSUE_TEMPLATE.md delete mode 100644 vendor/github.com/prometheus/client_golang/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/client_golang/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/VERSION delete mode 100644 vendor/github.com/prometheus/client_golang/api/client.go delete mode 100644 vendor/github.com/prometheus/client_golang/api/client_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go delete mode 100644 vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/examples/random/Dockerfile delete mode 100644 vendor/github.com/prometheus/client_golang/examples/random/main.go delete mode 100644 vendor/github.com/prometheus/client_golang/examples/simple/Dockerfile delete mode 100644 vendor/github.com/prometheus/client_golang/examples/simple/main.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/desc_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/examples_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/http_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/labels.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/metric_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/observer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/push/deprecated.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/push/push.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/value_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec_test.go delete mode 100644 vendor/github.com/prometheus/client_model/.gitignore delete mode 100644 vendor/github.com/prometheus/client_model/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/client_model/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/client_model/Makefile delete mode 100644 vendor/github.com/prometheus/client_model/README.md delete mode 100644 vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc delete mode 100644 vendor/github.com/prometheus/client_model/cpp/metrics.pb.h delete mode 100644 vendor/github.com/prometheus/client_model/metrics.proto delete mode 100644 vendor/github.com/prometheus/client_model/pom.xml delete mode 100644 vendor/github.com/prometheus/client_model/python/prometheus/__init__.py delete mode 100644 vendor/github.com/prometheus/client_model/ruby/.gitignore delete mode 100644 vendor/github.com/prometheus/client_model/ruby/Gemfile delete mode 100644 vendor/github.com/prometheus/client_model/ruby/Makefile delete mode 100644 vendor/github.com/prometheus/client_model/ruby/README.md delete mode 100644 vendor/github.com/prometheus/client_model/ruby/Rakefile delete mode 100644 vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec delete mode 100644 vendor/github.com/prometheus/client_model/setup.py delete mode 100644 vendor/github.com/prometheus/common/.travis.yml delete mode 100644 vendor/github.com/prometheus/common/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/common/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/common/README.md delete mode 100644 vendor/github.com/prometheus/common/config/config.go delete mode 100644 vendor/github.com/prometheus/common/config/http_config.go delete mode 100644 vendor/github.com/prometheus/common/config/http_config_test.go delete mode 100644 vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/tls_config.empty.good.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml delete mode 100644 vendor/github.com/prometheus/common/config/tls_config_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/bench_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/json2 delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/json2_bad delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/protobuf delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/text delete mode 100644 vendor/github.com/prometheus/common/expfmt/testdata/text.gz delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse_test.go delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go delete mode 100644 vendor/github.com/prometheus/common/log/eventlog_formatter.go delete mode 100644 vendor/github.com/prometheus/common/log/log.go delete mode 100644 vendor/github.com/prometheus/common/log/log_test.go delete mode 100644 vendor/github.com/prometheus/common/log/syslog_formatter.go delete mode 100644 vendor/github.com/prometheus/common/log/syslog_formatter_test.go delete mode 100644 vendor/github.com/prometheus/common/model/alert_test.go delete mode 100644 vendor/github.com/prometheus/common/model/labels_test.go delete mode 100644 vendor/github.com/prometheus/common/model/metric_test.go delete mode 100644 vendor/github.com/prometheus/common/model/signature_test.go delete mode 100644 vendor/github.com/prometheus/common/model/silence_test.go delete mode 100644 vendor/github.com/prometheus/common/model/time_test.go delete mode 100644 vendor/github.com/prometheus/common/model/value_test.go delete mode 100644 vendor/github.com/prometheus/common/promlog/flag/flag.go delete mode 100644 vendor/github.com/prometheus/common/promlog/log.go delete mode 100644 vendor/github.com/prometheus/common/route/route.go delete mode 100644 vendor/github.com/prometheus/common/route/route_test.go delete mode 100644 vendor/github.com/prometheus/common/version/info.go create mode 100644 vendor/github.com/prometheus/procfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/bcache/bcache.go delete mode 100644 vendor/github.com/prometheus/procfs/bcache/get.go delete mode 100644 vendor/github.com/prometheus/procfs/bcache/get_test.go delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo_test.go create mode 100644 vendor/github.com/prometheus/procfs/fixtures.ttar delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/cmdline delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/comm delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/exe delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/10 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/io delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/limits delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/mountstats delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/net/dev delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/ns/mnt delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26231/ns/net delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26231/stat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26232/cmdline delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26232/comm delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/0 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/1 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/2 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/3 delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/26232/fd/4 delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26232/limits delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/26232/stat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/584/stat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/buddyinfo/short/buddyinfo delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/buddyinfo/sizemismatch/buddyinfo delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/buddyinfo/valid/buddyinfo delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/fs/xfs/stat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/mdstat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/dev delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/ip_vs delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/ip_vs_stats delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfs delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfsd delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat delete mode 120000 vendor/github.com/prometheus/procfs/fixtures/self delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/stat delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/README delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/abc delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/def delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/ghi delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/uvw delete mode 100644 vendor/github.com/prometheus/procfs/fixtures/symlinktargets/xyz delete mode 100644 vendor/github.com/prometheus/procfs/fs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats_test.go delete mode 100644 vendor/github.com/prometheus/procfs/net_dev_test.go delete mode 100644 vendor/github.com/prometheus/procfs/nfs/parse_nfs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/nfs/parse_nfsd_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_ns_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_test.go delete mode 100644 vendor/github.com/prometheus/procfs/stat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/sysfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/sysfs/doc.go delete mode 100644 vendor/github.com/prometheus/procfs/sysfs/fixtures.ttar delete mode 100644 vendor/github.com/prometheus/procfs/sysfs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/sysfs/fs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/xfrm_test.go delete mode 100644 vendor/github.com/prometheus/procfs/xfs/parse_test.go (limited to 'vendor/github.com/prometheus') diff --git a/vendor/github.com/prometheus/client_golang/.gitignore b/vendor/github.com/prometheus/client_golang/.gitignore deleted file mode 100644 index 5725b80fd..000000000 --- a/vendor/github.com/prometheus/client_golang/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Examples -/examples/simple/simple -/examples/random/random - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -*~ -*# -.build diff --git a/vendor/github.com/prometheus/client_golang/.travis.yml b/vendor/github.com/prometheus/client_golang/.travis.yml deleted file mode 100644 index e9bca4ec7..000000000 --- a/vendor/github.com/prometheus/client_golang/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -sudo: false -language: go - -go: - - 1.7.x - - 1.8.x - - 1.9.x - -script: - - go test -short ./... diff --git a/vendor/github.com/prometheus/client_golang/AUTHORS.md b/vendor/github.com/prometheus/client_golang/AUTHORS.md new file mode 100644 index 000000000..c5275d5ab --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/AUTHORS.md @@ -0,0 +1,18 @@ +The Prometheus project was started by Matt T. Proud (emeritus) and +Julius Volz in 2012. + +Maintainers of this repository: + +* Björn Rabenstein + +The following individuals have contributed code to this repository +(listed in alphabetical order): + +* Bernerd Schaefer +* Björn Rabenstein +* Daniel Bornkessel +* Jeff Younker +* Julius Volz +* Matt T. Proud +* Tobias Schmidt + diff --git a/vendor/github.com/prometheus/client_golang/CHANGELOG.md b/vendor/github.com/prometheus/client_golang/CHANGELOG.md deleted file mode 100644 index 330788a4e..000000000 --- a/vendor/github.com/prometheus/client_golang/CHANGELOG.md +++ /dev/null @@ -1,109 +0,0 @@ -## 0.8.0 / 2016-08-17 -* [CHANGE] Registry is doing more consistency checks. This might break - existing setups that used to export inconsistent metrics. -* [CHANGE] Pushing to Pushgateway moved to package `push` and changed to allow - arbitrary grouping. -* [CHANGE] Removed `SelfCollector`. -* [CHANGE] Removed `PanicOnCollectError` and `EnableCollectChecks` methods. -* [CHANGE] Moved packages to the prometheus/common repo: `text`, `model`, - `extraction`. -* [CHANGE] Deprecated a number of functions. -* [FEATURE] Allow custom registries. Added `Registerer` and `Gatherer` - interfaces. -* [FEATURE] Separated HTTP exposition, allowing custom HTTP handlers (package - `promhttp`) and enabling the creation of other exposition mechanisms. -* [FEATURE] `MustRegister` is variadic now, allowing registration of many - collectors in one call. -* [FEATURE] Added HTTP API v1 package. -* [ENHANCEMENT] Numerous documentation improvements. -* [ENHANCEMENT] Improved metric sorting. -* [ENHANCEMENT] Inlined fnv64a hashing for improved performance. -* [ENHANCEMENT] Several test improvements. -* [BUGFIX] Handle collisions in MetricVec. - -## 0.7.0 / 2015-07-27 -* [CHANGE] Rename ExporterLabelPrefix to ExportedLabelPrefix. -* [BUGFIX] Closed gaps in metric consistency check. -* [BUGFIX] Validate LabelName/LabelSet on JSON unmarshaling. -* [ENHANCEMENT] Document the possibility to create "empty" metrics in - a metric vector. -* [ENHANCEMENT] Fix and clarify various doc comments and the README.md. -* [ENHANCEMENT] (Kind of) solve "The Proxy Problem" of http.InstrumentHandler. -* [ENHANCEMENT] Change responseWriterDelegator.written to int64. - -## 0.6.0 / 2015-06-01 -* [CHANGE] Rename process_goroutines to go_goroutines. -* [ENHANCEMENT] Validate label names during YAML decoding. -* [ENHANCEMENT] Add LabelName regular expression. -* [BUGFIX] Ensure alignment of struct members for 32-bit systems. - -## 0.5.0 / 2015-05-06 -* [BUGFIX] Removed a weakness in the fingerprinting aka signature code. - This makes fingerprinting slower and more allocation-heavy, but the - weakness was too severe to be tolerated. -* [CHANGE] As a result of the above, Metric.Fingerprint is now returning - a different fingerprint. To keep the same fingerprint, the new method - Metric.FastFingerprint was introduced, which will be used by the - Prometheus server for storage purposes (implying that a collision - detection has to be added, too). -* [ENHANCEMENT] The Metric.Equal and Metric.Before do not depend on - fingerprinting anymore, removing the possibility of an undetected - fingerprint collision. -* [FEATURE] The Go collector in the exposition library includes garbage - collection stats. -* [FEATURE] The exposition library allows to create constant "throw-away" - summaries and histograms. -* [CHANGE] A number of new reserved labels and prefixes. - -## 0.4.0 / 2015-04-08 -* [CHANGE] Return NaN when Summaries have no observations yet. -* [BUGFIX] Properly handle Summary decay upon Write(). -* [BUGFIX] Fix the documentation link to the consumption library. -* [FEATURE] Allow the metric family injection hook to merge with existing - metric families. -* [ENHANCEMENT] Removed cgo dependency and conditional compilation of procfs. -* [MAINTENANCE] Adjusted to changes in matttproud/golang_protobuf_extensions. - -## 0.3.2 / 2015-03-11 -* [BUGFIX] Fixed the receiver type of COWMetric.Set(). This method is - only used by the Prometheus server internally. -* [CLEANUP] Added licenses of vendored code left out by godep. - -## 0.3.1 / 2015-03-04 -* [ENHANCEMENT] Switched fingerprinting functions from own free list to - sync.Pool. -* [CHANGE] Makefile uses Go 1.4.2 now (only relevant for examples and tests). - -## 0.3.0 / 2015-03-03 -* [CHANGE] Changed the fingerprinting for metrics. THIS WILL INVALIDATE ALL - PERSISTED FINGERPRINTS. IF YOU COMPILE THE PROMETHEUS SERVER WITH THIS - VERSION, YOU HAVE TO WIPE THE PREVIOUSLY CREATED STORAGE. -* [CHANGE] LabelValuesToSignature removed. (Nobody had used it, and it was - arguably broken.) -* [CHANGE] Vendored dependencies. Those are only used by the Makefile. If - client_golang is used as a library, the vendoring will stay out of your way. -* [BUGFIX] Remove a weakness in the fingerprinting for metrics. (This made - the fingerprinting change above necessary.) -* [FEATURE] Added new fingerprinting functions SignatureForLabels and - SignatureWithoutLabels to be used by the Prometheus server. These functions - require fewer allocations than the ones currently used by the server. - -## 0.2.0 / 2015-02-23 -* [FEATURE] Introduce new Histagram metric type. -* [CHANGE] Ignore process collector errors for now (better error handling - pending). -* [CHANGE] Use clear error interface for process pidFn. -* [BUGFIX] Fix Go download links for several archs and OSes. -* [ENHANCEMENT] Massively improve Gauge and Counter performance. -* [ENHANCEMENT] Catch illegal label names for summaries in histograms. -* [ENHANCEMENT] Reduce allocations during fingerprinting. -* [ENHANCEMENT] Remove cgo dependency. procfs package will only be included if - both cgo is available and the build is for an OS with procfs. -* [CLEANUP] Clean up code style issues. -* [CLEANUP] Mark slow test as such and exclude them from travis. -* [CLEANUP] Update protobuf library package name. -* [CLEANUP] Updated vendoring of beorn7/perks. - -## 0.1.0 / 2015-02-02 -* [CLEANUP] Introduced semantic versioning and changelog. From now on, - changes will be reported in this file. diff --git a/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md b/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md deleted file mode 100644 index 40503edbf..000000000 --- a/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contributing - -Prometheus uses GitHub to manage reviews of pull requests. - -* If you have a trivial fix or improvement, go ahead and create a pull request, - addressing (with `@...`) the maintainer of this repository (see - [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request. - -* If you plan to do something more involved, first discuss your ideas - on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). - This will avoid unnecessary work and surely give you and us a good deal - of inspiration. - -* Relevant coding style guidelines are the [Go Code Review - Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) - and the _Formatting and style_ section of Peter Bourgon's [Go: Best - Practices for Production - Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). diff --git a/vendor/github.com/prometheus/client_golang/ISSUE_TEMPLATE.md b/vendor/github.com/prometheus/client_golang/ISSUE_TEMPLATE.md deleted file mode 100644 index a456acf5b..000000000 --- a/vendor/github.com/prometheus/client_golang/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/vendor/github.com/prometheus/client_golang/MAINTAINERS.md b/vendor/github.com/prometheus/client_golang/MAINTAINERS.md deleted file mode 100644 index 3ede55fe1..000000000 --- a/vendor/github.com/prometheus/client_golang/MAINTAINERS.md +++ /dev/null @@ -1 +0,0 @@ -* Björn Rabenstein diff --git a/vendor/github.com/prometheus/client_golang/README.md b/vendor/github.com/prometheus/client_golang/README.md deleted file mode 100644 index 17d46ecaf..000000000 --- a/vendor/github.com/prometheus/client_golang/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Prometheus Go client library - -[![Build Status](https://travis-ci.org/prometheus/client_golang.svg?branch=master)](https://travis-ci.org/prometheus/client_golang) -[![Go Report Card](https://goreportcard.com/badge/github.com/prometheus/client_golang)](https://goreportcard.com/report/github.com/prometheus/client_golang) -[![go-doc](https://godoc.org/github.com/prometheus/client_golang?status.svg)](https://godoc.org/github.com/prometheus/client_golang) - -This is the [Go](http://golang.org) client library for -[Prometheus](http://prometheus.io). It has two separate parts, one for -instrumenting application code, and one for creating clients that talk to the -Prometheus HTTP API. - -__This library requires Go1.7 or later.__ - -## Important note about releases, versioning, tagging, stability, and your favorite Go dependency management tool - -While our goal is to follow [Semantic Versioning](https://semver.org/), this -repository is still pre-1.0.0. To quote the -[Semantic Versioning spec](https://semver.org/#spec-item-4): “Anything may -change at any time. The public API should not be considered stable.” We know -that this is at odds with the widespread use of this library. However, just -declaring something 1.0.0 doesn't make it 1.0.0. Instead, we are working -towards a 1.0.0 release that actually deserves its major version number. - -Having said that, we aim for always keeping the tip of master in a workable -state and for only introducing ”mildly” breaking changes up to and including -[v0.9.0](https://github.com/prometheus/client_golang/milestone/1). After that, -a number of ”hard” breaking changes are planned, see the -[v0.10.0 milestone](https://github.com/prometheus/client_golang/milestone/2), -which should get the library much closer to 1.0.0 state. - -Dependency management in Go projects is still in flux, and there are many tools -floating around. While [dep](https://golang.github.io/dep/) might develop into -the de-facto standard tool, it is still officially experimental. The roadmap -for this library has been laid out with a lot of sometimes painful experience -in mind. We really cannot adjust it every other month to the needs of the -currently most popular or most promising Go dependency management tool. The -recommended course of action with dependency management tools is the following: - -- Do not expect strict post-1.0.0 semver semantics prior to the 1.0.0 - release. If your dependency management tool expects strict post-1.0.0 semver - semantics, you have to wait. Sorry. -- If you want absolute certainty, please lock to a specific commit. You can - also lock to tags, but please don't ask for more tagging. This would suggest - some release or stability testing procedure that simply is not in place. As - said above, we are aiming for stability of the tip of master, but if we - tagged every single commit, locking to tags would be the same as locking to - commits. -- If you want to get the newer features and improvements and are willing to - take the minor risk of newly introduced bugs and “mild” breakage, just always - update to the tip of master (which is essentially the original idea of Go - dependency management). We recommend to not use features marked as - _deprecated_ in this case. -- Once [v0.9.0](https://github.com/prometheus/client_golang/milestone/1) is - out, you could lock to v0.9.x to get bugfixes (and perhaps minor new - features) while avoiding the “hard” breakage that will come with post-0.9 - features. - -## Instrumenting applications - -[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/prometheus)](http://gocover.io/github.com/prometheus/client_golang/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus) - -The -[`prometheus` directory](https://github.com/prometheus/client_golang/tree/master/prometheus) -contains the instrumentation library. See the -[best practices section](http://prometheus.io/docs/practices/naming/) of the -Prometheus documentation to learn more about instrumenting applications. - -The -[`examples` directory](https://github.com/prometheus/client_golang/tree/master/examples) -contains simple examples of instrumented code. - -## Client for the Prometheus HTTP API - -[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/api/prometheus/v1)](http://gocover.io/github.com/prometheus/client_golang/api/prometheus/v1) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/api/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/api) - -The -[`api/prometheus` directory](https://github.com/prometheus/client_golang/tree/master/api/prometheus) -contains the client for the -[Prometheus HTTP API](http://prometheus.io/docs/querying/api/). It allows you -to write Go applications that query time series data from a Prometheus -server. It is still in alpha stage. - -## Where is `model`, `extraction`, and `text`? - -The `model` packages has been moved to -[`prometheus/common/model`](https://github.com/prometheus/common/tree/master/model). - -The `extraction` and `text` packages are now contained in -[`prometheus/common/expfmt`](https://github.com/prometheus/common/tree/master/expfmt). - -## Contributing and community - -See the [contributing guidelines](CONTRIBUTING.md) and the -[Community section](http://prometheus.io/community/) of the homepage. diff --git a/vendor/github.com/prometheus/client_golang/VERSION b/vendor/github.com/prometheus/client_golang/VERSION deleted file mode 100644 index a3df0a695..000000000 --- a/vendor/github.com/prometheus/client_golang/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.8.0 diff --git a/vendor/github.com/prometheus/client_golang/api/client.go b/vendor/github.com/prometheus/client_golang/api/client.go deleted file mode 100644 index bf2672466..000000000 --- a/vendor/github.com/prometheus/client_golang/api/client.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.7 - -// Package api provides clients for the HTTP APIs. -package api - -import ( - "context" - "io/ioutil" - "net" - "net/http" - "net/url" - "path" - "strings" - "time" -) - -// DefaultRoundTripper is used if no RoundTripper is set in Config. -var DefaultRoundTripper http.RoundTripper = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, -} - -// Config defines configuration parameters for a new client. -type Config struct { - // The address of the Prometheus to connect to. - Address string - - // RoundTripper is used by the Client to drive HTTP requests. If not - // provided, DefaultRoundTripper will be used. - RoundTripper http.RoundTripper -} - -func (cfg *Config) roundTripper() http.RoundTripper { - if cfg.RoundTripper == nil { - return DefaultRoundTripper - } - return cfg.RoundTripper -} - -// Client is the interface for an API client. -type Client interface { - URL(ep string, args map[string]string) *url.URL - Do(context.Context, *http.Request) (*http.Response, []byte, error) -} - -// NewClient returns a new Client. -// -// It is safe to use the returned Client from multiple goroutines. -func NewClient(cfg Config) (Client, error) { - u, err := url.Parse(cfg.Address) - if err != nil { - return nil, err - } - u.Path = strings.TrimRight(u.Path, "/") - - return &httpClient{ - endpoint: u, - client: http.Client{Transport: cfg.roundTripper()}, - }, nil -} - -type httpClient struct { - endpoint *url.URL - client http.Client -} - -func (c *httpClient) URL(ep string, args map[string]string) *url.URL { - p := path.Join(c.endpoint.Path, ep) - - for arg, val := range args { - arg = ":" + arg - p = strings.Replace(p, arg, val, -1) - } - - u := *c.endpoint - u.Path = p - - return &u -} - -func (c *httpClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { - if ctx != nil { - req = req.WithContext(ctx) - } - resp, err := c.client.Do(req) - defer func() { - if resp != nil { - resp.Body.Close() - } - }() - - if err != nil { - return nil, nil, err - } - - var body []byte - done := make(chan struct{}) - go func() { - body, err = ioutil.ReadAll(resp.Body) - close(done) - }() - - select { - case <-ctx.Done(): - err = resp.Body.Close() - <-done - if err == nil { - err = ctx.Err() - } - case <-done: - } - - return resp, body, err -} diff --git a/vendor/github.com/prometheus/client_golang/api/client_test.go b/vendor/github.com/prometheus/client_golang/api/client_test.go deleted file mode 100644 index 53226d7d2..000000000 --- a/vendor/github.com/prometheus/client_golang/api/client_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.7 - -package api - -import ( - "net/http" - "net/url" - "testing" -) - -func TestConfig(t *testing.T) { - c := Config{} - if c.roundTripper() != DefaultRoundTripper { - t.Fatalf("expected default roundtripper for nil RoundTripper field") - } -} - -func TestClientURL(t *testing.T) { - tests := []struct { - address string - endpoint string - args map[string]string - expected string - }{ - { - address: "http://localhost:9090", - endpoint: "/test", - expected: "http://localhost:9090/test", - }, - { - address: "http://localhost", - endpoint: "/test", - expected: "http://localhost/test", - }, - { - address: "http://localhost:9090", - endpoint: "test", - expected: "http://localhost:9090/test", - }, - { - address: "http://localhost:9090/prefix", - endpoint: "/test", - expected: "http://localhost:9090/prefix/test", - }, - { - address: "https://localhost:9090/", - endpoint: "/test/", - expected: "https://localhost:9090/test", - }, - { - address: "http://localhost:9090", - endpoint: "/test/:param", - args: map[string]string{ - "param": "content", - }, - expected: "http://localhost:9090/test/content", - }, - { - address: "http://localhost:9090", - endpoint: "/test/:param/more/:param", - args: map[string]string{ - "param": "content", - }, - expected: "http://localhost:9090/test/content/more/content", - }, - { - address: "http://localhost:9090", - endpoint: "/test/:param/more/:foo", - args: map[string]string{ - "param": "content", - "foo": "bar", - }, - expected: "http://localhost:9090/test/content/more/bar", - }, - { - address: "http://localhost:9090", - endpoint: "/test/:param", - args: map[string]string{ - "nonexistant": "content", - }, - expected: "http://localhost:9090/test/:param", - }, - } - - for _, test := range tests { - ep, err := url.Parse(test.address) - if err != nil { - t.Fatal(err) - } - - hclient := &httpClient{ - endpoint: ep, - client: http.Client{Transport: DefaultRoundTripper}, - } - - u := hclient.URL(test.endpoint, test.args) - if u.String() != test.expected { - t.Errorf("unexpected result: got %s, want %s", u, test.expected) - continue - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go b/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go deleted file mode 100644 index cb07022bc..000000000 --- a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.7 - -// Package v1 provides bindings to the Prometheus HTTP API v1: -// http://prometheus.io/docs/querying/api/ -package v1 - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/prometheus/client_golang/api" - "github.com/prometheus/common/model" -) - -const ( - statusAPIError = 422 - - apiPrefix = "/api/v1" - - epQuery = apiPrefix + "/query" - epQueryRange = apiPrefix + "/query_range" - epLabelValues = apiPrefix + "/label/:name/values" - epSeries = apiPrefix + "/series" -) - -// ErrorType models the different API error types. -type ErrorType string - -// Possible values for ErrorType. -const ( - ErrBadData ErrorType = "bad_data" - ErrTimeout = "timeout" - ErrCanceled = "canceled" - ErrExec = "execution" - ErrBadResponse = "bad_response" -) - -// Error is an error returned by the API. -type Error struct { - Type ErrorType - Msg string -} - -func (e *Error) Error() string { - return fmt.Sprintf("%s: %s", e.Type, e.Msg) -} - -// Range represents a sliced time range. -type Range struct { - // The boundaries of the time range. - Start, End time.Time - // The maximum time between two slices within the boundaries. - Step time.Duration -} - -// API provides bindings for Prometheus's v1 API. -type API interface { - // Query performs a query for the given time. - Query(ctx context.Context, query string, ts time.Time) (model.Value, error) - // QueryRange performs a query for the given range. - QueryRange(ctx context.Context, query string, r Range) (model.Value, error) - // LabelValues performs a query for the values of the given label. - LabelValues(ctx context.Context, label string) (model.LabelValues, error) - // Series finds series by label matchers. - Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, error) -} - -// queryResult contains result data for a query. -type queryResult struct { - Type model.ValueType `json:"resultType"` - Result interface{} `json:"result"` - - // The decoded value. - v model.Value -} - -func (qr *queryResult) UnmarshalJSON(b []byte) error { - v := struct { - Type model.ValueType `json:"resultType"` - Result json.RawMessage `json:"result"` - }{} - - err := json.Unmarshal(b, &v) - if err != nil { - return err - } - - switch v.Type { - case model.ValScalar: - var sv model.Scalar - err = json.Unmarshal(v.Result, &sv) - qr.v = &sv - - case model.ValVector: - var vv model.Vector - err = json.Unmarshal(v.Result, &vv) - qr.v = vv - - case model.ValMatrix: - var mv model.Matrix - err = json.Unmarshal(v.Result, &mv) - qr.v = mv - - default: - err = fmt.Errorf("unexpected value type %q", v.Type) - } - return err -} - -// NewAPI returns a new API for the client. -// -// It is safe to use the returned API from multiple goroutines. -func NewAPI(c api.Client) API { - return &httpAPI{client: apiClient{c}} -} - -type httpAPI struct { - client api.Client -} - -func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time) (model.Value, error) { - u := h.client.URL(epQuery, nil) - q := u.Query() - - q.Set("query", query) - if !ts.IsZero() { - q.Set("time", ts.Format(time.RFC3339Nano)) - } - - u.RawQuery = q.Encode() - - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return nil, err - } - - _, body, err := h.client.Do(ctx, req) - if err != nil { - return nil, err - } - - var qres queryResult - err = json.Unmarshal(body, &qres) - - return model.Value(qres.v), err -} - -func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range) (model.Value, error) { - u := h.client.URL(epQueryRange, nil) - q := u.Query() - - var ( - start = r.Start.Format(time.RFC3339Nano) - end = r.End.Format(time.RFC3339Nano) - step = strconv.FormatFloat(r.Step.Seconds(), 'f', 3, 64) - ) - - q.Set("query", query) - q.Set("start", start) - q.Set("end", end) - q.Set("step", step) - - u.RawQuery = q.Encode() - - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return nil, err - } - - _, body, err := h.client.Do(ctx, req) - if err != nil { - return nil, err - } - - var qres queryResult - err = json.Unmarshal(body, &qres) - - return model.Value(qres.v), err -} - -func (h *httpAPI) LabelValues(ctx context.Context, label string) (model.LabelValues, error) { - u := h.client.URL(epLabelValues, map[string]string{"name": label}) - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - _, body, err := h.client.Do(ctx, req) - if err != nil { - return nil, err - } - var labelValues model.LabelValues - err = json.Unmarshal(body, &labelValues) - return labelValues, err -} - -func (h *httpAPI) Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, error) { - u := h.client.URL(epSeries, nil) - q := u.Query() - - for _, m := range matches { - q.Add("match[]", m) - } - - q.Set("start", startTime.Format(time.RFC3339Nano)) - q.Set("end", endTime.Format(time.RFC3339Nano)) - - u.RawQuery = q.Encode() - - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return nil, err - } - - _, body, err := h.client.Do(ctx, req) - if err != nil { - return nil, err - } - - var mset []model.LabelSet - err = json.Unmarshal(body, &mset) - return mset, err -} - -// apiClient wraps a regular client and processes successful API responses. -// Successful also includes responses that errored at the API level. -type apiClient struct { - api.Client -} - -type apiResponse struct { - Status string `json:"status"` - Data json.RawMessage `json:"data"` - ErrorType ErrorType `json:"errorType"` - Error string `json:"error"` -} - -func (c apiClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { - resp, body, err := c.Client.Do(ctx, req) - if err != nil { - return resp, body, err - } - - code := resp.StatusCode - - if code/100 != 2 && code != statusAPIError { - return resp, body, &Error{ - Type: ErrBadResponse, - Msg: fmt.Sprintf("bad response code %d", resp.StatusCode), - } - } - - var result apiResponse - - if err = json.Unmarshal(body, &result); err != nil { - return resp, body, &Error{ - Type: ErrBadResponse, - Msg: err.Error(), - } - } - - if (code == statusAPIError) != (result.Status == "error") { - err = &Error{ - Type: ErrBadResponse, - Msg: "inconsistent body for response code", - } - } - - if code == statusAPIError && result.Status == "error" { - err = &Error{ - Type: result.ErrorType, - Msg: result.Error, - } - } - - return resp, []byte(result.Data), err -} diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go b/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go deleted file mode 100644 index e557d68f9..000000000 --- a/vendor/github.com/prometheus/client_golang/api/prometheus/v1/api_test.go +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.7 - -package v1 - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "reflect" - "strings" - "testing" - "time" - - "github.com/prometheus/common/model" -) - -type apiTest struct { - do func() (interface{}, error) - inErr error - inRes interface{} - - reqPath string - reqParam url.Values - reqMethod string - res interface{} - err error -} - -type apiTestClient struct { - *testing.T - curTest apiTest -} - -func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL { - path := ep - for k, v := range args { - path = strings.Replace(path, ":"+k, v, -1) - } - u := &url.URL{ - Host: "test:9090", - Path: path, - } - return u -} - -func (c *apiTestClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { - - test := c.curTest - - if req.URL.Path != test.reqPath { - c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path) - } - if req.Method != test.reqMethod { - c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method) - } - - b, err := json.Marshal(test.inRes) - if err != nil { - c.Fatal(err) - } - - resp := &http.Response{} - if test.inErr != nil { - resp.StatusCode = statusAPIError - } else { - resp.StatusCode = http.StatusOK - } - - return resp, b, test.inErr -} - -func TestAPIs(t *testing.T) { - - testTime := time.Now() - - client := &apiTestClient{T: t} - - queryAPI := &httpAPI{ - client: client, - } - - doQuery := func(q string, ts time.Time) func() (interface{}, error) { - return func() (interface{}, error) { - return queryAPI.Query(context.Background(), q, ts) - } - } - - doQueryRange := func(q string, rng Range) func() (interface{}, error) { - return func() (interface{}, error) { - return queryAPI.QueryRange(context.Background(), q, rng) - } - } - - doLabelValues := func(label string) func() (interface{}, error) { - return func() (interface{}, error) { - return queryAPI.LabelValues(context.Background(), label) - } - } - - doSeries := func(matcher string, startTime time.Time, endTime time.Time) func() (interface{}, error) { - return func() (interface{}, error) { - return queryAPI.Series(context.Background(), []string{matcher}, startTime, endTime) - } - } - - queryTests := []apiTest{ - { - do: doQuery("2", testTime), - inRes: &queryResult{ - Type: model.ValScalar, - Result: &model.Scalar{ - Value: 2, - Timestamp: model.TimeFromUnix(testTime.Unix()), - }, - }, - - reqMethod: "GET", - reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - res: &model.Scalar{ - Value: 2, - Timestamp: model.TimeFromUnix(testTime.Unix()), - }, - }, - { - do: doQuery("2", testTime), - inErr: fmt.Errorf("some error"), - - reqMethod: "GET", - reqPath: "/api/v1/query", - reqParam: url.Values{ - "query": []string{"2"}, - "time": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), - }, - - { - do: doQueryRange("2", Range{ - Start: testTime.Add(-time.Minute), - End: testTime, - Step: time.Minute, - }), - inErr: fmt.Errorf("some error"), - - reqMethod: "GET", - reqPath: "/api/v1/query_range", - reqParam: url.Values{ - "query": []string{"2"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - "step": []string{time.Minute.String()}, - }, - err: fmt.Errorf("some error"), - }, - - { - do: doLabelValues("mylabel"), - inRes: []string{"val1", "val2"}, - reqMethod: "GET", - reqPath: "/api/v1/label/mylabel/values", - res: model.LabelValues{"val1", "val2"}, - }, - - { - do: doLabelValues("mylabel"), - inErr: fmt.Errorf("some error"), - reqMethod: "GET", - reqPath: "/api/v1/label/mylabel/values", - err: fmt.Errorf("some error"), - }, - - { - do: doSeries("up", testTime.Add(-time.Minute), testTime), - inRes: []map[string]string{ - { - "__name__": "up", - "job": "prometheus", - "instance": "localhost:9090"}, - }, - reqMethod: "GET", - reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, - res: []model.LabelSet{ - model.LabelSet{ - "__name__": "up", - "job": "prometheus", - "instance": "localhost:9090", - }, - }, - }, - - { - do: doSeries("up", testTime.Add(-time.Minute), testTime), - inErr: fmt.Errorf("some error"), - reqMethod: "GET", - reqPath: "/api/v1/series", - reqParam: url.Values{ - "match": []string{"up"}, - "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, - "end": []string{testTime.Format(time.RFC3339Nano)}, - }, - err: fmt.Errorf("some error"), - }, - } - - var tests []apiTest - tests = append(tests, queryTests...) - - for _, test := range tests { - client.curTest = test - - res, err := test.do() - - if test.err != nil { - if err == nil { - t.Errorf("expected error %q but got none", test.err) - continue - } - if err.Error() != test.err.Error() { - t.Errorf("unexpected error: want %s, got %s", test.err, err) - } - continue - } - if err != nil { - t.Errorf("unexpected error: %s", err) - continue - } - - if !reflect.DeepEqual(res, test.res) { - t.Errorf("unexpected result: want %v, got %v", test.res, res) - } - } -} - -type testClient struct { - *testing.T - - ch chan apiClientTest - req *http.Request -} - -type apiClientTest struct { - code int - response interface{} - expected string - err *Error -} - -func (c *testClient) URL(ep string, args map[string]string) *url.URL { - return nil -} - -func (c *testClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { - if ctx == nil { - c.Fatalf("context was not passed down") - } - if req != c.req { - c.Fatalf("request was not passed down") - } - - test := <-c.ch - - var b []byte - var err error - - switch v := test.response.(type) { - case string: - b = []byte(v) - default: - b, err = json.Marshal(v) - if err != nil { - c.Fatal(err) - } - } - - resp := &http.Response{ - StatusCode: test.code, - } - - return resp, b, nil -} - -func TestAPIClientDo(t *testing.T) { - tests := []apiClientTest{ - { - response: &apiResponse{ - Status: "error", - Data: json.RawMessage(`null`), - ErrorType: ErrBadData, - Error: "failed", - }, - err: &Error{ - Type: ErrBadData, - Msg: "failed", - }, - code: statusAPIError, - expected: `null`, - }, - { - response: &apiResponse{ - Status: "error", - Data: json.RawMessage(`"test"`), - ErrorType: ErrTimeout, - Error: "timed out", - }, - err: &Error{ - Type: ErrTimeout, - Msg: "timed out", - }, - code: statusAPIError, - expected: `test`, - }, - { - response: "bad json", - err: &Error{ - Type: ErrBadResponse, - Msg: "bad response code 400", - }, - code: http.StatusBadRequest, - }, - { - response: "bad json", - err: &Error{ - Type: ErrBadResponse, - Msg: "invalid character 'b' looking for beginning of value", - }, - code: statusAPIError, - }, - { - response: &apiResponse{ - Status: "success", - Data: json.RawMessage(`"test"`), - }, - err: &Error{ - Type: ErrBadResponse, - Msg: "inconsistent body for response code", - }, - code: statusAPIError, - }, - { - response: &apiResponse{ - Status: "success", - Data: json.RawMessage(`"test"`), - ErrorType: ErrTimeout, - Error: "timed out", - }, - err: &Error{ - Type: ErrBadResponse, - Msg: "inconsistent body for response code", - }, - code: statusAPIError, - }, - { - response: &apiResponse{ - Status: "error", - Data: json.RawMessage(`"test"`), - ErrorType: ErrTimeout, - Error: "timed out", - }, - err: &Error{ - Type: ErrBadResponse, - Msg: "inconsistent body for response code", - }, - code: http.StatusOK, - }, - } - - tc := &testClient{ - T: t, - ch: make(chan apiClientTest, 1), - req: &http.Request{}, - } - client := &apiClient{tc} - - for _, test := range tests { - - tc.ch <- test - - _, body, err := client.Do(context.Background(), tc.req) - - if test.err != nil { - if err == nil { - t.Errorf("expected error %q but got none", test.err) - continue - } - if test.err.Error() != err.Error() { - t.Errorf("unexpected error: want %q, got %q", test.err, err) - } - continue - } - if err != nil { - t.Errorf("unexpeceted error %s", err) - continue - } - - want, got := test.expected, string(body) - if want != got { - t.Errorf("unexpected body: want %q, got %q", want, got) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/examples/random/Dockerfile b/vendor/github.com/prometheus/client_golang/examples/random/Dockerfile deleted file mode 100644 index 32b6846ea..000000000 --- a/vendor/github.com/prometheus/client_golang/examples/random/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -# This Dockerfile builds an image for a client_golang example. -# -# Use as (from the root for the client_golang repository): -# docker build -f examples/$name/Dockerfile -t prometheus/golang-example-$name . - -# Builder image, where we build the example. -FROM golang:1.9.0 AS builder -WORKDIR /go/src/github.com/prometheus/client_golang -COPY . . -WORKDIR /go/src/github.com/prometheus/client_golang/prometheus -RUN go get -d -WORKDIR /go/src/github.com/prometheus/client_golang/examples/random -RUN CGO_ENABLED=0 GOOS=linux go build -a -tags netgo -ldflags '-w' - -# Final image. -FROM scratch -LABEL maintainer "The Prometheus Authors " -COPY --from=builder /go/src/github.com/prometheus/client_golang/examples/random . -EXPOSE 8080 -ENTRYPOINT ["/random"] diff --git a/vendor/github.com/prometheus/client_golang/examples/random/main.go b/vendor/github.com/prometheus/client_golang/examples/random/main.go deleted file mode 100644 index eef50d200..000000000 --- a/vendor/github.com/prometheus/client_golang/examples/random/main.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A simple example exposing fictional RPC latencies with different types of -// random distributions (uniform, normal, and exponential) as Prometheus -// metrics. -package main - -import ( - "flag" - "log" - "math" - "math/rand" - "net/http" - "time" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -var ( - addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") - uniformDomain = flag.Float64("uniform.domain", 0.0002, "The domain for the uniform distribution.") - normDomain = flag.Float64("normal.domain", 0.0002, "The domain for the normal distribution.") - normMean = flag.Float64("normal.mean", 0.00001, "The mean for the normal distribution.") - oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.") -) - -var ( - // Create a summary to track fictional interservice RPC latencies for three - // distinct services with different latency distributions. These services are - // differentiated via a "service" label. - rpcDurations = prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "rpc_durations_seconds", - Help: "RPC latency distributions.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"service"}, - ) - // The same as above, but now as a histogram, and only for the normal - // distribution. The buckets are targeted to the parameters of the - // normal distribution, with 20 buckets centered on the mean, each - // half-sigma wide. - rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "rpc_durations_histogram_seconds", - Help: "RPC latency distributions.", - Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20), - }) -) - -func init() { - // Register the summary and the histogram with Prometheus's default registry. - prometheus.MustRegister(rpcDurations) - prometheus.MustRegister(rpcDurationsHistogram) -} - -func main() { - flag.Parse() - - start := time.Now() - - oscillationFactor := func() float64 { - return 2 + math.Sin(math.Sin(2*math.Pi*float64(time.Since(start))/float64(*oscillationPeriod))) - } - - // Periodically record some sample latencies for the three services. - go func() { - for { - v := rand.Float64() * *uniformDomain - rpcDurations.WithLabelValues("uniform").Observe(v) - time.Sleep(time.Duration(100*oscillationFactor()) * time.Millisecond) - } - }() - - go func() { - for { - v := (rand.NormFloat64() * *normDomain) + *normMean - rpcDurations.WithLabelValues("normal").Observe(v) - rpcDurationsHistogram.Observe(v) - time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond) - } - }() - - go func() { - for { - v := rand.ExpFloat64() / 1e6 - rpcDurations.WithLabelValues("exponential").Observe(v) - time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond) - } - }() - - // Expose the registered metrics via HTTP. - http.Handle("/metrics", promhttp.Handler()) - log.Fatal(http.ListenAndServe(*addr, nil)) -} diff --git a/vendor/github.com/prometheus/client_golang/examples/simple/Dockerfile b/vendor/github.com/prometheus/client_golang/examples/simple/Dockerfile deleted file mode 100644 index 99b49d781..000000000 --- a/vendor/github.com/prometheus/client_golang/examples/simple/Dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -# This Dockerfile builds an image for a client_golang example. -# -# Use as (from the root for the client_golang repository): -# docker build -f examples/$name/Dockerfile -t prometheus/golang-example-$name . - -# Builder image, where we build the example. -FROM golang:1.9.0 AS builder -WORKDIR /go/src/github.com/prometheus/client_golang -COPY . . -WORKDIR /go/src/github.com/prometheus/client_golang/prometheus -RUN go get -d -WORKDIR /go/src/github.com/prometheus/client_golang/examples/simple -RUN CGO_ENABLED=0 GOOS=linux go build -a -tags netgo -ldflags '-w' - -# Final image. -FROM scratch -LABEL maintainer "The Prometheus Authors " -COPY --from=builder /go/src/github.com/prometheus/client_golang/examples/simple . -EXPOSE 8080 -ENTRYPOINT ["/simple"] diff --git a/vendor/github.com/prometheus/client_golang/examples/simple/main.go b/vendor/github.com/prometheus/client_golang/examples/simple/main.go deleted file mode 100644 index 1fc23249a..000000000 --- a/vendor/github.com/prometheus/client_golang/examples/simple/main.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A minimal example of how to include Prometheus instrumentation. -package main - -import ( - "flag" - "log" - "net/http" - - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") - -func main() { - flag.Parse() - http.Handle("/metrics", promhttp.Handler()) - log.Fatal(http.ListenAndServe(*addr, nil)) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go deleted file mode 100644 index 4a05721dc..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "sync" - "testing" -) - -func BenchmarkCounterWithLabelValues(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } -} - -func BenchmarkCounterWithLabelValuesConcurrent(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - for j := 0; j < b.N/10; j++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } - wg.Done() - }() - } - wg.Wait() -} - -func BenchmarkCounterWithMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() - } -} - -func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} - for i := 0; i < b.N; i++ { - m.With(labels).Inc() - } -} - -func BenchmarkCounterNoLabels(b *testing.B) { - m := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Inc() - } -} - -func BenchmarkGaugeWithLabelValues(b *testing.B) { - m := NewGaugeVec( - GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) - } -} - -func BenchmarkGaugeNoLabels(b *testing.B) { - m := NewGauge(GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Set(3.1415) - } -} - -func BenchmarkSummaryWithLabelValues(b *testing.B) { - m := NewSummaryVec( - SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkSummaryNoLabels(b *testing.B) { - m := NewSummary(SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkHistogramWithLabelValues(b *testing.B) { - m := NewHistogramVec( - HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkHistogramNoLabels(b *testing.B) { - m := NewHistogram(HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkParallelCounter(b *testing.B) { - c := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A Counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - c.Inc() - } - }) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go index 765e4550c..ee37949ad 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go @@ -15,10 +15,6 @@ package prometheus import ( "errors" - "math" - "sync/atomic" - - dto "github.com/prometheus/client_model/go" ) // Counter is a Metric that represents a single numerical value that only ever @@ -34,8 +30,16 @@ type Counter interface { Metric Collector - // Inc increments the counter by 1. Use Add to increment it by arbitrary - // non-negative values. + // Set is used to set the Counter to an arbitrary value. It is only used + // if you have to transfer a value from an external counter into this + // Prometheus metric. Do not use it for regular handling of a + // Prometheus counter (as it can be used to break the contract of + // monotonically increasing values). + // + // Deprecated: Use NewConstMetric to create a counter for an external + // value. A Counter should never be set. + Set(float64) + // Inc increments the counter by 1. Inc() // Add adds the given value to the counter. It panics if the value is < // 0. @@ -46,14 +50,6 @@ type Counter interface { type CounterOpts Opts // NewCounter creates a new Counter based on the provided CounterOpts. -// -// The returned implementation tracks the counter value in two separate -// variables, a float64 and a uint64. The latter is used to track calls of the -// Inc method and calls of the Add method with a value that can be represented -// as a uint64. This allows atomic increments of the counter with optimal -// performance. (It is common to have an Inc call in very hot execution paths.) -// Both internal tracking values are added up in the Write method. This has to -// be taken into account when it comes to precision and overflow behavior. func NewCounter(opts CounterOpts) Counter { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), @@ -61,58 +57,20 @@ func NewCounter(opts CounterOpts) Counter { nil, opts.ConstLabels, ) - result := &counter{desc: desc, labelPairs: desc.constLabelPairs} + result := &counter{value: value{desc: desc, valType: CounterValue, labelPairs: desc.constLabelPairs}} result.init(result) // Init self-collection. return result } type counter struct { - // valBits contains the bits of the represented float64 value, while - // valInt stores values that are exact integers. Both have to go first - // in the struct to guarantee alignment for atomic operations. - // http://golang.org/pkg/sync/atomic/#pkg-note-BUG - valBits uint64 - valInt uint64 - - selfCollector - desc *Desc - - labelPairs []*dto.LabelPair -} - -func (c *counter) Desc() *Desc { - return c.desc + value } func (c *counter) Add(v float64) { if v < 0 { panic(errors.New("counter cannot decrease in value")) } - ival := uint64(v) - if float64(ival) == v { - atomic.AddUint64(&c.valInt, ival) - return - } - - for { - oldBits := atomic.LoadUint64(&c.valBits) - newBits := math.Float64bits(math.Float64frombits(oldBits) + v) - if atomic.CompareAndSwapUint64(&c.valBits, oldBits, newBits) { - return - } - } -} - -func (c *counter) Inc() { - atomic.AddUint64(&c.valInt, 1) -} - -func (c *counter) Write(out *dto.Metric) error { - fval := math.Float64frombits(atomic.LoadUint64(&c.valBits)) - ival := atomic.LoadUint64(&c.valInt) - val := fval + float64(ival) - - return populateMetric(CounterValue, val, c.labelPairs, out) + c.value.Add(v) } // CounterVec is a Collector that bundles a set of Counters that all share the @@ -120,12 +78,16 @@ func (c *counter) Write(out *dto.Metric) error { // if you want to count the same thing partitioned by various dimensions // (e.g. number of HTTP requests, partitioned by response code and // method). Create instances with NewCounterVec. +// +// CounterVec embeds MetricVec. See there for a full list of methods with +// detailed documentation. type CounterVec struct { - *metricVec + *MetricVec } // NewCounterVec creates a new CounterVec based on the provided CounterOpts and -// partitioned by the given label names. +// partitioned by the given label names. At least one label name must be +// provided. func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), @@ -134,62 +96,34 @@ func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec { opts.ConstLabels, ) return &CounterVec{ - metricVec: newMetricVec(desc, func(lvs ...string) Metric { - if len(lvs) != len(desc.variableLabels) { - panic(errInconsistentCardinality) - } - result := &counter{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} + MetricVec: newMetricVec(desc, func(lvs ...string) Metric { + result := &counter{value: value{ + desc: desc, + valType: CounterValue, + labelPairs: makeLabelPairs(desc, lvs), + }} result.init(result) // Init self-collection. return result }), } } -// GetMetricWithLabelValues returns the Counter for the given slice of label -// values (same order as the VariableLabels in Desc). If that combination of -// label values is accessed for the first time, a new Counter is created. -// -// It is possible to call this method without using the returned Counter to only -// create the new Counter but leave it at its starting value 0. See also the -// SummaryVec example. -// -// Keeping the Counter for later use is possible (and should be considered if -// performance is critical), but keep in mind that Reset, DeleteLabelValues and -// Delete can be used to delete the Counter from the CounterVec. In that case, -// the Counter will still exist, but it will not be exported anymore, even if a -// Counter with the same label values is created later. -// -// An error is returned if the number of label values is not the same as the -// number of VariableLabels in Desc (minus any curried labels). -// -// Note that for more than one label value, this method is prone to mistakes -// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as -// an alternative to avoid that type of mistake. For higher label numbers, the -// latter has a much more readable (albeit more verbose) syntax, but it comes -// with a performance overhead (for creating and processing the Labels map). -// See also the GaugeVec example. -func (v *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) { - metric, err := v.metricVec.getMetricWithLabelValues(lvs...) +// GetMetricWithLabelValues replaces the method of the same name in +// MetricVec. The difference is that this method returns a Counter and not a +// Metric so that no type conversion is required. +func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) { + metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) if metric != nil { return metric.(Counter), err } return nil, err } -// GetMetricWith returns the Counter for the given Labels map (the label names -// must match those of the VariableLabels in Desc). If that label map is -// accessed for the first time, a new Counter is created. Implications of -// creating a Counter without using it and keeping the Counter for later use are -// the same as for GetMetricWithLabelValues. -// -// An error is returned if the number and names of the Labels are inconsistent -// with those of the VariableLabels in Desc (minus any curried labels). -// -// This method is used for the same purpose as -// GetMetricWithLabelValues(...string). See there for pros and cons of the two -// methods. -func (v *CounterVec) GetMetricWith(labels Labels) (Counter, error) { - metric, err := v.metricVec.getMetricWith(labels) +// GetMetricWith replaces the method of the same name in MetricVec. The +// difference is that this method returns a Counter and not a Metric so that no +// type conversion is required. +func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error) { + metric, err := m.MetricVec.GetMetricWith(labels) if metric != nil { return metric.(Counter), err } @@ -197,57 +131,18 @@ func (v *CounterVec) GetMetricWith(labels Labels) (Counter, error) { } // WithLabelValues works as GetMetricWithLabelValues, but panics where -// GetMetricWithLabelValues would have returned an error. Not returning an -// error allows shortcuts like +// GetMetricWithLabelValues would have returned an error. By not returning an +// error, WithLabelValues allows shortcuts like // myVec.WithLabelValues("404", "GET").Add(42) -func (v *CounterVec) WithLabelValues(lvs ...string) Counter { - c, err := v.GetMetricWithLabelValues(lvs...) - if err != nil { - panic(err) - } - return c +func (m *CounterVec) WithLabelValues(lvs ...string) Counter { + return m.MetricVec.WithLabelValues(lvs...).(Counter) } // With works as GetMetricWith, but panics where GetMetricWithLabels would have -// returned an error. Not returning an error allows shortcuts like -// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42) -func (v *CounterVec) With(labels Labels) Counter { - c, err := v.GetMetricWith(labels) - if err != nil { - panic(err) - } - return c -} - -// CurryWith returns a vector curried with the provided labels, i.e. the -// returned vector has those labels pre-set for all labeled operations performed -// on it. The cardinality of the curried vector is reduced accordingly. The -// order of the remaining labels stays the same (just with the curried labels -// taken out of the sequence – which is relevant for the -// (GetMetric)WithLabelValues methods). It is possible to curry a curried -// vector, but only with labels not yet used for currying before. -// -// The metrics contained in the CounterVec are shared between the curried and -// uncurried vectors. They are just accessed differently. Curried and uncurried -// vectors behave identically in terms of collection. Only one must be -// registered with a given registry (usually the uncurried version). The Reset -// method deletes all metrics, even if called on a curried vector. -func (v *CounterVec) CurryWith(labels Labels) (*CounterVec, error) { - vec, err := v.curryWith(labels) - if vec != nil { - return &CounterVec{vec}, err - } - return nil, err -} - -// MustCurryWith works as CurryWith but panics where CurryWith would have -// returned an error. -func (v *CounterVec) MustCurryWith(labels Labels) *CounterVec { - vec, err := v.CurryWith(labels) - if err != nil { - panic(err) - } - return vec +// returned an error. By not returning an error, With allows shortcuts like +// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) +func (m *CounterVec) With(labels Labels) Counter { + return m.MetricVec.With(labels).(Counter) } // CounterFunc is a Counter whose value is determined at collect time by calling a diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go b/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go deleted file mode 100644 index 5062f51af..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "fmt" - "math" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestCounterAdd(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }).(*counter) - counter.Inc() - if expected, got := 0.0, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - if expected, got := uint64(1), counter.valInt; expected != got { - t.Errorf("Expected %d, got %d.", expected, got) - } - counter.Add(42) - if expected, got := 0.0, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - if expected, got := uint64(43), counter.valInt; expected != got { - t.Errorf("Expected %d, got %d.", expected, got) - } - - counter.Add(24.42) - if expected, got := 24.42, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - if expected, got := uint64(43), counter.valInt; expected != got { - t.Errorf("Expected %d, got %d.", expected, got) - } - - if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { - t.Errorf("Expected error %q, got %q.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `label: label: counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func decreaseCounter(c *counter) (err error) { - defer func() { - if e := recover(); e != nil { - err = e.(error) - } - }() - c.Add(-1) - return nil -} - -func TestCounterVecGetMetricWithInvalidLabelValues(t *testing.T) { - testCases := []struct { - desc string - labels Labels - }{ - { - desc: "non utf8 label value", - labels: Labels{"a": "\xFF"}, - }, - { - desc: "not enough label values", - labels: Labels{}, - }, - { - desc: "too many label values", - labels: Labels{"a": "1", "b": "2"}, - }, - } - - for _, test := range testCases { - counterVec := NewCounterVec(CounterOpts{ - Name: "test", - }, []string{"a"}) - - labelValues := make([]string, len(test.labels)) - for _, val := range test.labels { - labelValues = append(labelValues, val) - } - - expectPanic(t, func() { - counterVec.WithLabelValues(labelValues...) - }, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) - expectPanic(t, func() { - counterVec.With(test.labels) - }, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) - - if _, err := counterVec.GetMetricWithLabelValues(labelValues...); err == nil { - t.Errorf("GetMetricWithLabelValues: expected error because: %s", test.desc) - } - if _, err := counterVec.GetMetricWith(test.labels); err == nil { - t.Errorf("GetMetricWith: expected error because: %s", test.desc) - } - } -} - -func expectPanic(t *testing.T, op func(), errorMsg string) { - defer func() { - if err := recover(); err == nil { - t.Error(errorMsg) - } - }() - - op() -} - -func TestCounterAddInf(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - }).(*counter) - - counter.Inc() - if expected, got := 0.0, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - if expected, got := uint64(1), counter.valInt; expected != got { - t.Errorf("Expected %d, got %d.", expected, got) - } - - counter.Add(math.Inf(1)) - if expected, got := math.Inf(1), math.Float64frombits(counter.valBits); expected != got { - t.Errorf("valBits expected %f, got %f.", expected, got) - } - if expected, got := uint64(1), counter.valInt; expected != got { - t.Errorf("valInts expected %d, got %d.", expected, got) - } - - counter.Inc() - if expected, got := math.Inf(1), math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - if expected, got := uint64(2), counter.valInt; expected != got { - t.Errorf("Expected %d, got %d.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func TestCounterAddLarge(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - }).(*counter) - - // large overflows the underlying type and should therefore be stored in valBits. - large := float64(math.MaxUint64 + 1) - counter.Add(large) - if expected, got := large, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("valBits expected %f, got %f.", expected, got) - } - if expected, got := uint64(0), counter.valInt; expected != got { - t.Errorf("valInts expected %d, got %d.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := fmt.Sprintf("counter: ", large), m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func TestCounterAddSmall(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - }).(*counter) - small := 0.000000000001 - counter.Add(small) - if expected, got := small, math.Float64frombits(counter.valBits); expected != got { - t.Errorf("valBits expected %f, got %f.", expected, got) - } - if expected, got := uint64(0), counter.valInt; expected != got { - t.Errorf("valInts expected %d, got %d.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := fmt.Sprintf("counter: ", small), m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go index 4a755b0fa..77f4b30e8 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go @@ -16,15 +16,33 @@ package prometheus import ( "errors" "fmt" + "regexp" "sort" "strings" "github.com/golang/protobuf/proto" - "github.com/prometheus/common/model" dto "github.com/prometheus/client_model/go" ) +var ( + metricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`) + labelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$") +) + +// reservedLabelPrefix is a prefix which is not legal in user-supplied +// label names. +const reservedLabelPrefix = "__" + +// Labels represents a collection of label name -> value mappings. This type is +// commonly used with the With(Labels) and GetMetricWith(Labels) methods of +// metric vector Collectors, e.g.: +// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) +// +// The other use-case is the specification of constant label pairs in Opts or to +// create a Desc. +type Labels map[string]string + // Desc is the descriptor used by every Prometheus Metric. It is essentially // the immutable meta-data of a Metric. The normal Metric implementations // included in this package manage their Desc under the hood. Users only have to @@ -60,7 +78,7 @@ type Desc struct { // Help string. Each Desc with the same fqName must have the same // dimHash. dimHash uint64 - // err is an error that occurred during construction. It is reported on + // err is an error that occured during construction. It is reported on // registration time. err error } @@ -73,7 +91,8 @@ type Desc struct { // and therefore not part of the Desc. (They are managed within the Metric.) // // For constLabels, the label values are constant. Therefore, they are fully -// specified in the Desc. See the Collector example for a usage pattern. +// specified in the Desc. See the Opts documentation for the implications of +// constant labels. func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc { d := &Desc{ fqName: fqName, @@ -84,7 +103,7 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) * d.err = errors.New("empty help string") return d } - if !model.IsValidMetricName(model.LabelValue(fqName)) { + if !metricNameRE.MatchString(fqName) { d.err = fmt.Errorf("%q is not a valid metric name", fqName) return d } @@ -108,12 +127,6 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) * for _, labelName := range labelNames { labelValues = append(labelValues, constLabels[labelName]) } - // Validate the const label values. They can't have a wrong cardinality, so - // use in len(labelValues) as expectedNumberOfValues. - if err := validateLabelValues(labelValues, len(labelValues)); err != nil { - d.err = err - return d - } // Now add the variable label names, but prefix them with something that // cannot be in a regular label name. That prevents matching the label // dimension with a different mix between preset and variable labels. @@ -129,7 +142,6 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) * d.err = errors.New("duplicate label names") return d } - vh := hashNew() for _, val := range labelValues { vh = hashAdd(vh, val) @@ -186,3 +198,8 @@ func (d *Desc) String() string { d.variableLabels, ) } + +func checkLabelName(l string) bool { + return labelNameRE.MatchString(l) && + !strings.HasPrefix(l, reservedLabelPrefix) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc_test.go b/vendor/github.com/prometheus/client_golang/prometheus/desc_test.go deleted file mode 100644 index 2f962652c..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package prometheus - -import ( - "testing" -) - -func TestNewDescInvalidLabelValues(t *testing.T) { - desc := NewDesc( - "sample_label", - "sample label", - nil, - Labels{"a": "\xFF"}, - ) - if desc.err == nil { - t.Errorf("NewDesc: expected error because: %s", desc.err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/doc.go b/vendor/github.com/prometheus/client_golang/prometheus/doc.go index f727c991d..b15a2d3b9 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/doc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/doc.go @@ -11,13 +11,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package prometheus is the core instrumentation package. It provides metrics -// primitives to instrument code for monitoring. It also offers a registry for -// metrics. Sub-packages allow to expose the registered metrics via HTTP -// (package promhttp) or push them to a Pushgateway (package push). +// Package prometheus provides metrics primitives to instrument code for +// monitoring. It also offers a registry for metrics. Sub-packages allow to +// expose the registered metrics via HTTP (package promhttp) or push them to a +// Pushgateway (package push). // // All exported functions and methods are safe to be used concurrently unless -// specified otherwise. +//specified otherwise. // // A Basic Example // @@ -26,7 +26,6 @@ // package main // // import ( -// "log" // "net/http" // // "github.com/prometheus/client_golang/prometheus" @@ -60,7 +59,7 @@ // // The Handler function provides a default handler to expose metrics // // via an HTTP server. "/metrics" is the usual endpoint for that. // http.Handle("/metrics", promhttp.Handler()) -// log.Fatal(http.ListenAndServe(":8080", nil)) +// http.ListenAndServe(":8080", nil) // } // // @@ -70,7 +69,7 @@ // Metrics // // The number of exported identifiers in this package might appear a bit -// overwhelming. However, in addition to the basic plumbing shown in the example +// overwhelming. Hovever, in addition to the basic plumbing shown in the example // above, you only need to understand the different metric types and their // vector versions for basic usage. // @@ -96,8 +95,8 @@ // SummaryVec, HistogramVec, and UntypedVec are not. // // To create instances of Metrics and their vector versions, you need a suitable -// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts, HistogramOpts, or -// UntypedOpts. +// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts, +// HistogramOpts, or UntypedOpts. // // Custom Collectors and constant Metrics // @@ -115,8 +114,8 @@ // Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and // NewConstSummary (and their respective Must… versions). That will happen in // the Collect method. The Describe method has to return separate Desc -// instances, representative of the “throw-away” metrics to be created later. -// NewDesc comes in handy to create those Desc instances. +// instances, representative of the “throw-away” metrics to be created +// later. NewDesc comes in handy to create those Desc instances. // // The Collector example illustrates the use case. You can also look at the // source code of the processCollector (mirroring process metrics), the @@ -130,34 +129,34 @@ // Advanced Uses of the Registry // // While MustRegister is the by far most common way of registering a Collector, -// sometimes you might want to handle the errors the registration might cause. -// As suggested by the name, MustRegister panics if an error occurs. With the -// Register function, the error is returned and can be handled. +// sometimes you might want to handle the errors the registration might +// cause. As suggested by the name, MustRegister panics if an error occurs. With +// the Register function, the error is returned and can be handled. // // An error is returned if the registered Collector is incompatible or // inconsistent with already registered metrics. The registry aims for -// consistency of the collected metrics according to the Prometheus data model. -// Inconsistencies are ideally detected at registration time, not at collect -// time. The former will usually be detected at start-up time of a program, -// while the latter will only happen at scrape time, possibly not even on the -// first scrape if the inconsistency only becomes relevant later. That is the -// main reason why a Collector and a Metric have to describe themselves to the -// registry. +// consistency of the collected metrics according to the Prometheus data +// model. Inconsistencies are ideally detected at registration time, not at +// collect time. The former will usually be detected at start-up time of a +// program, while the latter will only happen at scrape time, possibly not even +// on the first scrape if the inconsistency only becomes relevant later. That is +// the main reason why a Collector and a Metric have to describe themselves to +// the registry. // // So far, everything we did operated on the so-called default registry, as it -// can be found in the global DefaultRegisterer variable. With NewRegistry, you +// can be found in the global DefaultRegistry variable. With NewRegistry, you // can create a custom registry, or you can even implement the Registerer or -// Gatherer interfaces yourself. The methods Register and Unregister work in the -// same way on a custom registry as the global functions Register and Unregister -// on the default registry. -// -// There are a number of uses for custom registries: You can use registries with -// special properties, see NewPedanticRegistry. You can avoid global state, as -// it is imposed by the DefaultRegisterer. You can use multiple registries at -// the same time to expose different metrics in different ways. You can use +// Gatherer interfaces yourself. The methods Register and Unregister work in +// the same way on a custom registry as the global functions Register and +// Unregister on the default registry. +// +// There are a number of uses for custom registries: You can use registries +// with special properties, see NewPedanticRegistry. You can avoid global state, +// as it is imposed by the DefaultRegistry. You can use multiple registries at +// the same time to expose different metrics in different ways. You can use // separate registries for testing purposes. // -// Also note that the DefaultRegisterer comes registered with a Collector for Go +// Also note that the DefaultRegistry comes registered with a Collector for Go // runtime metrics (via NewGoCollector) and a Collector for process metrics (via // NewProcessCollector). With a custom registry, you are in control and decide // yourself about the Collectors to register. @@ -167,20 +166,16 @@ // The Registry implements the Gatherer interface. The caller of the Gather // method can then expose the gathered metrics in some way. Usually, the metrics // are served via HTTP on the /metrics endpoint. That's happening in the example -// above. The tools to expose metrics via HTTP are in the promhttp sub-package. -// (The top-level functions in the prometheus package are deprecated.) +// above. The tools to expose metrics via HTTP are in the promhttp +// sub-package. (The top-level functions in the prometheus package are +// deprecated.) // // Pushing to the Pushgateway // // Function for pushing to the Pushgateway can be found in the push sub-package. // -// Graphite Bridge -// -// Functions and examples to push metrics from a Gatherer to Graphite can be -// found in the graphite sub-package. -// // Other Means of Exposition // -// More ways of exposing metrics can easily be added by following the approaches -// of the existing implementations. +// More ways of exposing metrics can easily be added. Sending metrics to +// Graphite would be an example that will soon be implemented. package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go deleted file mode 100644 index 260c1b52d..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import "github.com/prometheus/client_golang/prometheus" - -// ClusterManager is an example for a system that might have been built without -// Prometheus in mind. It models a central manager of jobs running in a -// cluster. To turn it into something that collects Prometheus metrics, we -// simply add the two methods required for the Collector interface. -// -// An additional challenge is that multiple instances of the ClusterManager are -// run within the same binary, each in charge of a different zone. We need to -// make use of ConstLabels to be able to register each ClusterManager instance -// with Prometheus. -type ClusterManager struct { - Zone string - OOMCountDesc *prometheus.Desc - RAMUsageDesc *prometheus.Desc - // ... many more fields -} - -// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a -// real cluster manager would have to do. Since it may actually be really -// expensive, it must only be called once per collection. This implementation, -// obviously, only returns some made-up data. -func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( - oomCountByHost map[string]int, ramUsageByHost map[string]float64, -) { - // Just example fake data. - oomCountByHost = map[string]int{ - "foo.example.org": 42, - "bar.example.org": 2001, - } - ramUsageByHost = map[string]float64{ - "foo.example.org": 6.023e23, - "bar.example.org": 3.14, - } - return -} - -// Describe simply sends the two Descs in the struct to the channel. -func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { - ch <- c.OOMCountDesc - ch <- c.RAMUsageDesc -} - -// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it -// creates constant metrics for each host on the fly based on the returned data. -// -// Note that Collect could be called concurrently, so we depend on -// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe. -func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { - oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() - for host, oomCount := range oomCountByHost { - ch <- prometheus.MustNewConstMetric( - c.OOMCountDesc, - prometheus.CounterValue, - float64(oomCount), - host, - ) - } - for host, ramUsage := range ramUsageByHost { - ch <- prometheus.MustNewConstMetric( - c.RAMUsageDesc, - prometheus.GaugeValue, - ramUsage, - host, - ) - } -} - -// NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note -// that the zone is set as a ConstLabel. (It's different in each instance of the -// ClusterManager, but constant over the lifetime of an instance.) Then there is -// a variable label "host", since we want to partition the collected metrics by -// host. Since all Descs created in this way are consistent across instances, -// with a guaranteed distinction by the "zone" label, we can register different -// ClusterManager instances with the same registry. -func NewClusterManager(zone string) *ClusterManager { - return &ClusterManager{ - Zone: zone, - OOMCountDesc: prometheus.NewDesc( - "clustermanager_oom_crashes_total", - "Number of OOM crashes.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - RAMUsageDesc: prometheus.NewDesc( - "clustermanager_ram_usage_bytes", - "RAM usage as reported to the cluster manager.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - } -} - -func ExampleCollector() { - workerDB := NewClusterManager("db") - workerCA := NewClusterManager("ca") - - // Since we are dealing with custom Collector implementations, it might - // be a good idea to try it out with a pedantic registry. - reg := prometheus.NewPedanticRegistry() - reg.MustRegister(workerDB) - reg.MustRegister(workerCA) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go deleted file mode 100644 index c5e7de5e5..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_complex_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "net/http" - - "github.com/prometheus/client_golang/prometheus" -) - -var ( - // apiRequestDuration tracks the duration separate for each HTTP status - // class (1xx, 2xx, ...). This creates a fair amount of time series on - // the Prometheus server. Usually, you would track the duration of - // serving HTTP request without partitioning by outcome. Do something - // like this only if needed. Also note how only status classes are - // tracked, not every single status code. The latter would create an - // even larger amount of time series. Request counters partitioned by - // status code are usually OK as each counter only creates one time - // series. Histograms are way more expensive, so partition with care and - // only where you really need separate latency tracking. Partitioning by - // status class is only an example. In concrete cases, other partitions - // might make more sense. - apiRequestDuration = prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "api_request_duration_seconds", - Help: "Histogram for the request duration of the public API, partitioned by status class.", - Buckets: prometheus.ExponentialBuckets(0.1, 1.5, 5), - }, - []string{"status_class"}, - ) -) - -func handler(w http.ResponseWriter, r *http.Request) { - status := http.StatusOK - // The ObserverFunc gets called by the deferred ObserveDuration and - // decides which Histogram's Observe method is called. - timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) { - switch { - case status >= 500: // Server error. - apiRequestDuration.WithLabelValues("5xx").Observe(v) - case status >= 400: // Client error. - apiRequestDuration.WithLabelValues("4xx").Observe(v) - case status >= 300: // Redirection. - apiRequestDuration.WithLabelValues("3xx").Observe(v) - case status >= 200: // Success. - apiRequestDuration.WithLabelValues("2xx").Observe(v) - default: // Informational. - apiRequestDuration.WithLabelValues("1xx").Observe(v) - } - })) - defer timer.ObserveDuration() - - // Handle the request. Set status accordingly. - // ... -} - -func ExampleTimer_complex() { - http.HandleFunc("/api", handler) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go deleted file mode 100644 index 7184a0d1d..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_gauge_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "os" - - "github.com/prometheus/client_golang/prometheus" -) - -var ( - // If a function is called rarely (i.e. not more often than scrapes - // happen) or ideally only once (like in a batch job), it can make sense - // to use a Gauge for timing the function call. For timing a batch job - // and pushing the result to a Pushgateway, see also the comprehensive - // example in the push package. - funcDuration = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "example_function_duration_seconds", - Help: "Duration of the last call of an example function.", - }) -) - -func run() error { - // The Set method of the Gauge is used to observe the duration. - timer := prometheus.NewTimer(prometheus.ObserverFunc(funcDuration.Set)) - defer timer.ObserveDuration() - - // Do something. Return errors as encountered. The use of 'defer' above - // makes sure the function is still timed properly. - return nil -} - -func ExampleTimer_gauge() { - if err := run(); err != nil { - os.Exit(1) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go deleted file mode 100644 index bd86bb472..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_timer_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "math/rand" - "time" - - "github.com/prometheus/client_golang/prometheus" -) - -var ( - requestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "example_request_duration_seconds", - Help: "Histogram for the runtime of a simple example function.", - Buckets: prometheus.LinearBuckets(0.01, 0.01, 10), - }) -) - -func ExampleTimer() { - // timer times this example function. It uses a Histogram, but a Summary - // would also work, as both implement Observer. Check out - // https://prometheus.io/docs/practices/histograms/ for differences. - timer := prometheus.NewTimer(requestDuration) - defer timer.ObserveDuration() - - // Do something here that takes time. - time.Sleep(time.Duration(rand.NormFloat64()*10000+50000) * time.Microsecond) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go deleted file mode 100644 index 45f60650f..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go +++ /dev/null @@ -1,754 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "bytes" - "fmt" - "math" - "net/http" - "runtime" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/expfmt" - - "github.com/golang/protobuf/proto" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleGauge() { - opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed.", - }) - prometheus.MustRegister(opsQueued) - - // 10 operations queued by the goroutine managing incoming requests. - opsQueued.Add(10) - // A worker goroutine has picked up a waiting operation. - opsQueued.Dec() - // And once more... - opsQueued.Dec() -} - -func ExampleGaugeVec() { - opsQueued := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", - }, - []string{ - // Which user has requested the operation? - "user", - // Of what type is the operation? - "type", - }, - ) - prometheus.MustRegister(opsQueued) - - // Increase a value using compact (but order-sensitive!) WithLabelValues(). - opsQueued.WithLabelValues("bob", "put").Add(4) - // Increase a value with a map using WithLabels. More verbose, but order - // doesn't matter anymore. - opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() -} - -func ExampleGaugeFunc() { - if err := prometheus.Register(prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Subsystem: "runtime", - Name: "goroutines_count", - Help: "Number of goroutines that currently exist.", - }, - func() float64 { return float64(runtime.NumGoroutine()) }, - )); err == nil { - fmt.Println("GaugeFunc 'goroutines_count' registered.") - } - // Note that the count of goroutines is a gauge (and not a counter) as - // it can go up and down. - - // Output: - // GaugeFunc 'goroutines_count' registered. -} - -func ExampleCounter() { - pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", // Note: No help string... - }) - err := prometheus.Register(pushCounter) // ... so this will return an error. - if err != nil { - fmt.Println("Push counter couldn't be registered, no counting will happen:", err) - return - } - - // Try it once more, this time with a help string. - pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", - Help: "Number of pushes to external repository.", - }) - err = prometheus.Register(pushCounter) - if err != nil { - fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) - return - } - - pushComplete := make(chan struct{}) - // TODO: Start a goroutine that performs repository pushes and reports - // each completion via the channel. - for range pushComplete { - pushCounter.Inc() - } - // Output: - // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string -} - -func ExampleCounterVec() { - httpReqs := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", - }, - []string{"code", "method"}, - ) - prometheus.MustRegister(httpReqs) - - httpReqs.WithLabelValues("404", "POST").Add(42) - - // If you have to access the same set of labels very frequently, it - // might be good to retrieve the metric only once and keep a handle to - // it. But beware of deletion of that metric, see below! - m := httpReqs.WithLabelValues("200", "GET") - for i := 0; i < 1000000; i++ { - m.Inc() - } - // Delete a metric from the vector. If you have previously kept a handle - // to that metric (as above), future updates via that handle will go - // unseen (even if you re-create a metric with the same label set - // later). - httpReqs.DeleteLabelValues("200", "GET") - // Same thing with the more verbose Labels syntax. - httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) -} - -func ExampleInstrumentHandler() { - // Handle the "/doc" endpoint with the standard http.FileServer handler. - // By wrapping the handler with InstrumentHandler, request count, - // request and response sizes, and request latency are automatically - // exported to Prometheus, partitioned by HTTP status code and method - // and by the handler name (here "fileserver"). - http.Handle("/doc", prometheus.InstrumentHandler( - "fileserver", http.FileServer(http.Dir("/usr/share/doc")), - )) - // The Prometheus handler still has to be registered to handle the - // "/metrics" endpoint. The handler returned by prometheus.Handler() is - // already instrumented - with "prometheus" as the handler name. In this - // example, we want the handler name to be "metrics", so we instrument - // the uninstrumented Prometheus handler ourselves. - http.Handle("/metrics", prometheus.InstrumentHandler( - "metrics", prometheus.UninstrumentedHandler(), - )) -} - -func ExampleLabelPairSorter() { - labelPairs := []*dto.LabelPair{ - {Name: proto.String("status"), Value: proto.String("404")}, - {Name: proto.String("method"), Value: proto.String("get")}, - } - - sort.Sort(prometheus.LabelPairSorter(labelPairs)) - - fmt.Println(labelPairs) - // Output: - // [name:"method" value:"get" name:"status" value:"404" ] -} - -func ExampleRegister() { - // Imagine you have a worker pool and want to count the tasks completed. - taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }) - // This will register fine. - if err := prometheus.Register(taskCounter); err != nil { - fmt.Println(err) - } else { - fmt.Println("taskCounter registered.") - } - // Don't forget to tell the HTTP server about the Prometheus handler. - // (In a real program, you still need to start the HTTP server...) - http.Handle("/metrics", prometheus.Handler()) - - // Now you can start workers and give every one of them a pointer to - // taskCounter and let it increment it whenever it completes a task. - taskCounter.Inc() // This has to happen somewhere in the worker code. - - // But wait, you want to see how individual workers perform. So you need - // a vector of counters, with one element for each worker. - taskCounterVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - - // Registering will fail because we already have a metric of that name. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - - // To fix, first unregister the old taskCounter. - if prometheus.Unregister(taskCounter) { - fmt.Println("taskCounter unregistered.") - } - - // Try registering taskCounterVec again. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Bummer! Still doesn't work. - - // Prometheus will not allow you to ever export metrics with - // inconsistent help strings or label names. After unregistering, the - // unregistered metrics will cease to show up in the /metrics HTTP - // response, but the registry still remembers that those metrics had - // been exported before. For this example, we will now choose a - // different name. (In a real program, you would obviously not export - // the obsolete metric in the first place.) - taskCounterVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_by_id", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Finally it worked! - - // The workers have to tell taskCounterVec their id to increment the - // right element in the metric vector. - taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. - - // Each worker could also keep a reference to their own counter element - // around. Pick the counter at initialization time of the worker. - myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. - myCounter.Inc() // Somewhere in the code of that worker. - - // Note that something like WithLabelValues("42", "spurious arg") would - // panic (because you have provided too many label values). If you want - // to get an error instead, use GetMetricWithLabelValues(...) instead. - notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") - if err != nil { - fmt.Println("Worker initialization failed:", err) - } - if notMyCounter == nil { - fmt.Println("notMyCounter is nil.") - } - - // A different (and somewhat tricky) approach is to use - // ConstLabels. ConstLabels are pairs of label names and label values - // that never change. You might ask what those labels are good for (and - // rightfully so - if they never change, they could as well be part of - // the metric name). There are essentially two use-cases: The first is - // if labels are constant throughout the lifetime of a binary execution, - // but they vary over time or between different instances of a running - // binary. The second is what we have here: Each worker creates and - // registers an own Counter instance where the only difference is in the - // value of the ConstLabels. Those Counters can all be registered - // because the different ConstLabel values guarantee that each worker - // will increment a different Counter metric. - counterOpts := prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks", - Help: "Total number of tasks completed.", - ConstLabels: prometheus.Labels{"worker_id": "42"}, - } - taskCounterForWorker42 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker42); err != nil { - fmt.Println("taskCounterVForWorker42 not registered:", err) - } else { - fmt.Println("taskCounterForWorker42 registered.") - } - // Obviously, in real code, taskCounterForWorker42 would be a member - // variable of a worker struct, and the "42" would be retrieved with a - // GetId() method or something. The Counter would be created and - // registered in the initialization code of the worker. - - // For the creation of the next Counter, we can recycle - // counterOpts. Just change the ConstLabels. - counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} - taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker2001); err != nil { - fmt.Println("taskCounterVForWorker2001 not registered:", err) - } else { - fmt.Println("taskCounterForWorker2001 registered.") - } - - taskCounterForWorker2001.Inc() - taskCounterForWorker42.Inc() - taskCounterForWorker2001.Inc() - - // Yet another approach would be to turn the workers themselves into - // Collectors and register them. See the Collector example for details. - - // Output: - // taskCounter registered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounter unregistered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounterVec registered. - // Worker initialization failed: inconsistent label cardinality - // notMyCounter is nil. - // taskCounterForWorker42 registered. - // taskCounterForWorker2001 registered. -} - -func ExampleSummary() { - temps := prometheus.NewSummary(prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > -} - -func ExampleSummaryVec() { - temps := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"species"}, - ) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) - } - - // Create a Summary without any observations. - temps.WithLabelValues("leiopelma-hochstetteri") - - // Just for demonstration, let's check the state of the summary vector - // by registering it with a custom registry and then let it collect the - // metrics. - reg := prometheus.NewRegistry() - reg.MustRegister(temps) - - metricFamilies, err := reg.Gather() - if err != nil || len(metricFamilies) != 1 { - panic("unexpected behavior of custom test registry") - } - fmt.Println(proto.MarshalTextString(metricFamilies[0])) - - // Output: - // name: "pond_temperature_celsius" - // help: "The temperature of the frog pond." - // type: SUMMARY - // metric: < - // label: < - // name: "species" - // value: "leiopelma-hochstetteri" - // > - // summary: < - // sample_count: 0 - // sample_sum: 0 - // quantile: < - // quantile: 0.5 - // value: nan - // > - // quantile: < - // quantile: 0.9 - // value: nan - // > - // quantile: < - // quantile: 0.99 - // value: nan - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "lithobates-catesbeianus" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 31956.100000000017 - // quantile: < - // quantile: 0.5 - // value: 32.4 - // > - // quantile: < - // quantile: 0.9 - // value: 41.4 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "litoria-caerulea" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > -} - -func ExampleNewConstSummary() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A summary of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant summary from values we got from a 3rd party telemetry system. - s := prometheus.MustNewConstSummary( - desc, - 4711, 403.34, - map[float64]float64{0.5: 42.3, 0.9: 323.3}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - s.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // summary: < - // sample_count: 4711 - // sample_sum: 403.34 - // quantile: < - // quantile: 0.5 - // value: 42.3 - // > - // quantile: < - // quantile: 0.9 - // value: 323.3 - // > - // > -} - -func ExampleHistogram() { - temps := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // histogram: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // bucket: < - // cumulative_count: 192 - // upper_bound: 20 - // > - // bucket: < - // cumulative_count: 366 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 501 - // upper_bound: 30 - // > - // bucket: < - // cumulative_count: 638 - // upper_bound: 35 - // > - // bucket: < - // cumulative_count: 816 - // upper_bound: 40 - // > - // > -} - -func ExampleNewConstHistogram() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A histogram of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant histogram from values we got from a 3rd party telemetry system. - h := prometheus.MustNewConstHistogram( - desc, - 4711, 403.34, - map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - h.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // histogram: < - // sample_count: 4711 - // sample_sum: 403.34 - // bucket: < - // cumulative_count: 121 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 2403 - // upper_bound: 50 - // > - // bucket: < - // cumulative_count: 3221 - // upper_bound: 100 - // > - // bucket: < - // cumulative_count: 4233 - // upper_bound: 200 - // > - // > -} - -func ExampleAlreadyRegisteredError() { - reqCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "requests_total", - Help: "The total number of requests served.", - }) - if err := prometheus.Register(reqCounter); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - // A counter for that metric has been registered before. - // Use the old counter from now on. - reqCounter = are.ExistingCollector.(prometheus.Counter) - } else { - // Something else went wrong! - panic(err) - } - } - reqCounter.Inc() -} - -func ExampleGatherers() { - reg := prometheus.NewRegistry() - temp := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "temperature_kelvin", - Help: "Temperature in Kelvin.", - }, - []string{"location"}, - ) - reg.MustRegister(temp) - temp.WithLabelValues("outside").Set(273.14) - temp.WithLabelValues("inside").Set(298.44) - - var parser expfmt.TextParser - - text := ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -temperature_kelvin{location="somewhere else"} 4.5 -` - - parseText := func() ([]*dto.MetricFamily, error) { - parsed, err := parser.TextToMetricFamilies(strings.NewReader(text)) - if err != nil { - return nil, err - } - var result []*dto.MetricFamily - for _, mf := range parsed { - result = append(result, mf) - } - return result, nil - } - - gatherers := prometheus.Gatherers{ - reg, - prometheus.GathererFunc(parseText), - } - - gathering, err := gatherers.Gather() - if err != nil { - fmt.Println(err) - } - - out := &bytes.Buffer{} - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - fmt.Println("----------") - - // Note how the temperature_kelvin metric family has been merged from - // different sources. Now try - text = ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -# Duplicate metric: -temperature_kelvin{location="outside"} 265.3 - # Wrong labels: -temperature_kelvin 4.5 -` - - gathering, err = gatherers.Gather() - if err != nil { - fmt.Println(err) - } - // Note that still as many metrics as possible are returned: - out.Reset() - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - - // Output: - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 - // temperature_kelvin{location="somewhere else"} 4.5 - // ---------- - // 2 error(s) occurred: - // * collected metric temperature_kelvin label: gauge: was collected before with the same name and label values - // * collected metric temperature_kelvin gauge: has label dimensions inconsistent with previously collected metrics in the same metric family - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go deleted file mode 100644 index 910dac325..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "expvar" - "fmt" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleNewExpvarCollector() { - expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ - "memstats": prometheus.NewDesc( - "expvar_memstats", - "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", - []string{"type"}, nil, - ), - "lone-int": prometheus.NewDesc( - "expvar_lone_int", - "Just an expvar int as an example.", - nil, nil, - ), - "http-request-map": prometheus.NewDesc( - "expvar_http_request_total", - "How many http requests processed, partitioned by status code and http method.", - []string{"code", "method"}, nil, - ), - }) - prometheus.MustRegister(expvarCollector) - - // The Prometheus part is done here. But to show that this example is - // doing anything, we have to manually export something via expvar. In - // real-life use-cases, some library would already have exported via - // expvar what we want to re-export as Prometheus metrics. - expvar.NewInt("lone-int").Set(42) - expvarMap := expvar.NewMap("http-request-map") - var ( - expvarMap1, expvarMap2 expvar.Map - expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int - ) - expvarMap1.Init() - expvarMap2.Init() - expvarInt11.Set(3) - expvarInt12.Set(13) - expvarInt21.Set(11) - expvarInt22.Set(212) - expvarMap1.Set("POST", &expvarInt11) - expvarMap1.Set("GET", &expvarInt12) - expvarMap2.Set("POST", &expvarInt21) - expvarMap2.Set("GET", &expvarInt22) - expvarMap.Set("404", &expvarMap1) - expvarMap.Set("200", &expvarMap2) - // Results in the following expvar map: - // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} - - // Let's see what the scrape would yield, but exclude the memstats metrics. - metricStrings := []string{} - metric := dto.Metric{} - metricChan := make(chan prometheus.Metric) - go func() { - expvarCollector.Collect(metricChan) - close(metricChan) - }() - for m := range metricChan { - if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { - metric.Reset() - m.Write(&metric) - metricStrings = append(metricStrings, metric.String()) - } - } - sort.Strings(metricStrings) - for _, s := range metricStrings { - fmt.Println(strings.TrimRight(s, " ")) - } - // Output: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // untyped: -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go index 17c72d7eb..8b70e5141 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go @@ -13,14 +13,6 @@ package prometheus -import ( - "math" - "sync/atomic" - "time" - - dto "github.com/prometheus/client_model/go" -) - // Gauge is a Metric that represents a single numerical value that can // arbitrarily go up and down. // @@ -35,95 +27,29 @@ type Gauge interface { // Set sets the Gauge to an arbitrary value. Set(float64) - // Inc increments the Gauge by 1. Use Add to increment it by arbitrary - // values. + // Inc increments the Gauge by 1. Inc() - // Dec decrements the Gauge by 1. Use Sub to decrement it by arbitrary - // values. + // Dec decrements the Gauge by 1. Dec() - // Add adds the given value to the Gauge. (The value can be negative, - // resulting in a decrease of the Gauge.) + // Add adds the given value to the Gauge. (The value can be + // negative, resulting in a decrease of the Gauge.) Add(float64) // Sub subtracts the given value from the Gauge. (The value can be // negative, resulting in an increase of the Gauge.) Sub(float64) - - // SetToCurrentTime sets the Gauge to the current Unix time in seconds. - SetToCurrentTime() } // GaugeOpts is an alias for Opts. See there for doc comments. type GaugeOpts Opts // NewGauge creates a new Gauge based on the provided GaugeOpts. -// -// The returned implementation is optimized for a fast Set method. If you have a -// choice for managing the value of a Gauge via Set vs. Inc/Dec/Add/Sub, pick -// the former. For example, the Inc method of the returned Gauge is slower than -// the Inc method of a Counter returned by NewCounter. This matches the typical -// scenarios for Gauges and Counters, where the former tends to be Set-heavy and -// the latter Inc-heavy. func NewGauge(opts GaugeOpts) Gauge { - desc := NewDesc( + return newValue(NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, nil, opts.ConstLabels, - ) - result := &gauge{desc: desc, labelPairs: desc.constLabelPairs} - result.init(result) // Init self-collection. - return result -} - -type gauge struct { - // valBits contains the bits of the represented float64 value. It has - // to go first in the struct to guarantee alignment for atomic - // operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG - valBits uint64 - - selfCollector - - desc *Desc - labelPairs []*dto.LabelPair -} - -func (g *gauge) Desc() *Desc { - return g.desc -} - -func (g *gauge) Set(val float64) { - atomic.StoreUint64(&g.valBits, math.Float64bits(val)) -} - -func (g *gauge) SetToCurrentTime() { - g.Set(float64(time.Now().UnixNano()) / 1e9) -} - -func (g *gauge) Inc() { - g.Add(1) -} - -func (g *gauge) Dec() { - g.Add(-1) -} - -func (g *gauge) Add(val float64) { - for { - oldBits := atomic.LoadUint64(&g.valBits) - newBits := math.Float64bits(math.Float64frombits(oldBits) + val) - if atomic.CompareAndSwapUint64(&g.valBits, oldBits, newBits) { - return - } - } -} - -func (g *gauge) Sub(val float64) { - g.Add(val * -1) -} - -func (g *gauge) Write(out *dto.Metric) error { - val := math.Float64frombits(atomic.LoadUint64(&g.valBits)) - return populateMetric(GaugeValue, val, g.labelPairs, out) + ), GaugeValue, 0) } // GaugeVec is a Collector that bundles a set of Gauges that all share the same @@ -132,11 +58,12 @@ func (g *gauge) Write(out *dto.Metric) error { // (e.g. number of operations queued, partitioned by user and operation // type). Create instances with NewGaugeVec. type GaugeVec struct { - *metricVec + *MetricVec } // NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and -// partitioned by the given label names. +// partitioned by the given label names. At least one label name must be +// provided. func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), @@ -145,62 +72,28 @@ func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec { opts.ConstLabels, ) return &GaugeVec{ - metricVec: newMetricVec(desc, func(lvs ...string) Metric { - if len(lvs) != len(desc.variableLabels) { - panic(errInconsistentCardinality) - } - result := &gauge{desc: desc, labelPairs: makeLabelPairs(desc, lvs)} - result.init(result) // Init self-collection. - return result + MetricVec: newMetricVec(desc, func(lvs ...string) Metric { + return newValue(desc, GaugeValue, 0, lvs...) }), } } -// GetMetricWithLabelValues returns the Gauge for the given slice of label -// values (same order as the VariableLabels in Desc). If that combination of -// label values is accessed for the first time, a new Gauge is created. -// -// It is possible to call this method without using the returned Gauge to only -// create the new Gauge but leave it at its starting value 0. See also the -// SummaryVec example. -// -// Keeping the Gauge for later use is possible (and should be considered if -// performance is critical), but keep in mind that Reset, DeleteLabelValues and -// Delete can be used to delete the Gauge from the GaugeVec. In that case, the -// Gauge will still exist, but it will not be exported anymore, even if a -// Gauge with the same label values is created later. See also the CounterVec -// example. -// -// An error is returned if the number of label values is not the same as the -// number of VariableLabels in Desc (minus any curried labels). -// -// Note that for more than one label value, this method is prone to mistakes -// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as -// an alternative to avoid that type of mistake. For higher label numbers, the -// latter has a much more readable (albeit more verbose) syntax, but it comes -// with a performance overhead (for creating and processing the Labels map). -func (v *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) { - metric, err := v.metricVec.getMetricWithLabelValues(lvs...) +// GetMetricWithLabelValues replaces the method of the same name in +// MetricVec. The difference is that this method returns a Gauge and not a +// Metric so that no type conversion is required. +func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) { + metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) if metric != nil { return metric.(Gauge), err } return nil, err } -// GetMetricWith returns the Gauge for the given Labels map (the label names -// must match those of the VariableLabels in Desc). If that label map is -// accessed for the first time, a new Gauge is created. Implications of -// creating a Gauge without using it and keeping the Gauge for later use are -// the same as for GetMetricWithLabelValues. -// -// An error is returned if the number and names of the Labels are inconsistent -// with those of the VariableLabels in Desc (minus any curried labels). -// -// This method is used for the same purpose as -// GetMetricWithLabelValues(...string). See there for pros and cons of the two -// methods. -func (v *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) { - metric, err := v.metricVec.getMetricWith(labels) +// GetMetricWith replaces the method of the same name in MetricVec. The +// difference is that this method returns a Gauge and not a Metric so that no +// type conversion is required. +func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) { + metric, err := m.MetricVec.GetMetricWith(labels) if metric != nil { return metric.(Gauge), err } @@ -208,57 +101,18 @@ func (v *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) { } // WithLabelValues works as GetMetricWithLabelValues, but panics where -// GetMetricWithLabelValues would have returned an error. Not returning an -// error allows shortcuts like +// GetMetricWithLabelValues would have returned an error. By not returning an +// error, WithLabelValues allows shortcuts like // myVec.WithLabelValues("404", "GET").Add(42) -func (v *GaugeVec) WithLabelValues(lvs ...string) Gauge { - g, err := v.GetMetricWithLabelValues(lvs...) - if err != nil { - panic(err) - } - return g +func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge { + return m.MetricVec.WithLabelValues(lvs...).(Gauge) } // With works as GetMetricWith, but panics where GetMetricWithLabels would have -// returned an error. Not returning an error allows shortcuts like -// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42) -func (v *GaugeVec) With(labels Labels) Gauge { - g, err := v.GetMetricWith(labels) - if err != nil { - panic(err) - } - return g -} - -// CurryWith returns a vector curried with the provided labels, i.e. the -// returned vector has those labels pre-set for all labeled operations performed -// on it. The cardinality of the curried vector is reduced accordingly. The -// order of the remaining labels stays the same (just with the curried labels -// taken out of the sequence – which is relevant for the -// (GetMetric)WithLabelValues methods). It is possible to curry a curried -// vector, but only with labels not yet used for currying before. -// -// The metrics contained in the GaugeVec are shared between the curried and -// uncurried vectors. They are just accessed differently. Curried and uncurried -// vectors behave identically in terms of collection. Only one must be -// registered with a given registry (usually the uncurried version). The Reset -// method deletes all metrics, even if called on a curried vector. -func (v *GaugeVec) CurryWith(labels Labels) (*GaugeVec, error) { - vec, err := v.curryWith(labels) - if vec != nil { - return &GaugeVec{vec}, err - } - return nil, err -} - -// MustCurryWith works as CurryWith but panics where CurryWith would have -// returned an error. -func (v *GaugeVec) MustCurryWith(labels Labels) *GaugeVec { - vec, err := v.CurryWith(labels) - if err != nil { - panic(err) - } - return vec +// returned an error. By not returning an error, With allows shortcuts like +// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) +func (m *GaugeVec) With(labels Labels) Gauge { + return m.MetricVec.With(labels).(Gauge) } // GaugeFunc is a Gauge whose value is determined at collect time by calling a diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go deleted file mode 100644 index a2e3c1416..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func listenGaugeStream(vals, result chan float64, done chan struct{}) { - var sum float64 -outer: - for { - select { - case <-done: - close(vals) - for v := range vals { - sum += v - } - break outer - case v := <-vals: - sum += v - } - } - result <- sum - close(result) -} - -func TestGaugeConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStream := make(chan float64, mutations*concLevel) - result := make(chan float64) - done := make(chan struct{}) - - go listenGaugeStream(sStream, result, done) - go func() { - end.Wait() - close(done) - }() - - gge := NewGauge(GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sStream <- v - gge.Add(v) - } - end.Done() - }(vals) - } - start.Done() - - if expected, got := <-result, math.Float64frombits(gge.(*gauge).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeVecConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - vecLength := int(n%5 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStreams := make([]chan float64, vecLength) - results := make([]chan float64, vecLength) - done := make(chan struct{}) - - for i := 0; i < vecLength; i++ { - sStreams[i] = make(chan float64, mutations*concLevel) - results[i] = make(chan float64) - go listenGaugeStream(sStreams[i], results[i], done) - } - - go func() { - end.Wait() - close(done) - }() - - gge := NewGaugeVec( - GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }, - []string{"label"}, - ) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - pick := make([]int, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - pick[j] = rand.Intn(vecLength) - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sStreams[pick[i]] <- v - gge.WithLabelValues(string('A' + pick[i])).Add(v) - } - end.Done() - }(vals) - } - start.Done() - - for i := range sStreams { - if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*gauge).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeFunc(t *testing.T) { - gf := NewGaugeFunc( - GaugeOpts{ - Name: "test_name", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }, - func() float64 { return 3.1415 }, - ) - - if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } - - m := &dto.Metric{} - gf.Write(m) - - if expected, got := `label: label: gauge: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func TestGaugeSetCurrentTime(t *testing.T) { - g := NewGauge(GaugeOpts{ - Name: "test_name", - Help: "test help", - }) - g.SetToCurrentTime() - unixTime := float64(time.Now().Unix()) - - m := &dto.Metric{} - g.Write(m) - - delta := unixTime - m.GetGauge().GetValue() - // This is just a smoke test to make sure SetToCurrentTime is not - // totally off. Tests with current time involved are hard... - if math.Abs(delta) > 5 { - t.Errorf("Gauge set to current time deviates from current time by more than 5s, delta is %f seconds", delta) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go index 096454af9..abc9d4ec4 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go @@ -8,10 +8,8 @@ import ( ) type goCollector struct { - goroutinesDesc *Desc - threadsDesc *Desc - gcDesc *Desc - goInfoDesc *Desc + goroutines Gauge + gcDesc *Desc // metrics to describe and collect metrics memStatsMetrics @@ -21,22 +19,15 @@ type goCollector struct { // go process. func NewGoCollector() Collector { return &goCollector{ - goroutinesDesc: NewDesc( - "go_goroutines", - "Number of goroutines that currently exist.", - nil, nil), - threadsDesc: NewDesc( - "go_threads", - "Number of OS threads created.", - nil, nil), + goroutines: NewGauge(GaugeOpts{ + Namespace: "go", + Name: "goroutines", + Help: "Number of goroutines that currently exist.", + }), gcDesc: NewDesc( "go_gc_duration_seconds", "A summary of the GC invocation durations.", nil, nil), - goInfoDesc: NewDesc( - "go_info", - "Information about the Go environment.", - nil, Labels{"version": runtime.Version()}), metrics: memStatsMetrics{ { desc: NewDesc( @@ -57,7 +48,7 @@ func NewGoCollector() Collector { }, { desc: NewDesc( memstatNamespace("sys_bytes"), - "Number of bytes obtained from system.", + "Number of bytes obtained by system. Sum of all system allocations.", nil, nil, ), eval: func(ms *runtime.MemStats) float64 { return float64(ms.Sys) }, @@ -120,12 +111,12 @@ func NewGoCollector() Collector { valType: GaugeValue, }, { desc: NewDesc( - memstatNamespace("heap_released_bytes"), - "Number of heap bytes released to OS.", + memstatNamespace("heap_released_bytes_total"), + "Total number of heap bytes released to OS.", nil, nil, ), eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) }, - valType: GaugeValue, + valType: CounterValue, }, { desc: NewDesc( memstatNamespace("heap_objects"), @@ -222,14 +213,6 @@ func NewGoCollector() Collector { ), eval: func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 }, valType: GaugeValue, - }, { - desc: NewDesc( - memstatNamespace("gc_cpu_fraction"), - "The fraction of this program's available CPU time used by the GC since the program started.", - nil, nil, - ), - eval: func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction }, - valType: GaugeValue, }, }, } @@ -241,10 +224,9 @@ func memstatNamespace(s string) string { // Describe returns all descriptions of the collector. func (c *goCollector) Describe(ch chan<- *Desc) { - ch <- c.goroutinesDesc - ch <- c.threadsDesc + ch <- c.goroutines.Desc() ch <- c.gcDesc - ch <- c.goInfoDesc + for _, i := range c.metrics { ch <- i.desc } @@ -252,9 +234,8 @@ func (c *goCollector) Describe(ch chan<- *Desc) { // Collect returns the current state of all metrics of the collector. func (c *goCollector) Collect(ch chan<- Metric) { - ch <- MustNewConstMetric(c.goroutinesDesc, GaugeValue, float64(runtime.NumGoroutine())) - n, _ := runtime.ThreadCreateProfile(nil) - ch <- MustNewConstMetric(c.threadsDesc, GaugeValue, float64(n)) + c.goroutines.Set(float64(runtime.NumGoroutine())) + ch <- c.goroutines var stats debug.GCStats stats.PauseQuantiles = make([]time.Duration, 5) @@ -267,8 +248,6 @@ func (c *goCollector) Collect(ch chan<- Metric) { quantiles[0.0] = stats.PauseQuantiles[0].Seconds() ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), float64(stats.PauseTotal.Seconds()), quantiles) - ch <- MustNewConstMetric(c.goInfoDesc, GaugeValue, 1) - ms := &runtime.MemStats{} runtime.ReadMemStats(ms) for _, i := range c.metrics { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go deleted file mode 100644 index 72264da9a..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package prometheus - -import ( - "runtime" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestGoCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - old = -1 - ) - defer close(closec) - - go func() { - c.Collect(ch) - go func(c <-chan struct{}) { - <-c - }(closec) - <-waitc - c.Collect(ch) - }() - - for { - select { - case m := <-ch: - // m can be Gauge or Counter, - // currently just test the go_goroutines Gauge - // and ignore others. - if m.Desc().fqName != "go_goroutines" { - continue - } - pb := &dto.Metric{} - m.Write(pb) - if pb.GetGauge() == nil { - continue - } - - if old == -1 { - old = int(pb.GetGauge().GetValue()) - close(waitc) - continue - } - - if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { - // TODO: This is flaky in highly concurrent situations. - t.Errorf("want 1 new goroutine, got %d", diff) - } - - // GoCollector performs three sends per call. - // On line 27 we need to receive three more sends - // to shut down cleanly. - <-ch - <-ch - <-ch - return - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} - -func TestGCCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - oldGC uint64 - oldPause float64 - ) - defer close(closec) - - go func() { - c.Collect(ch) - // force GC - runtime.GC() - <-waitc - c.Collect(ch) - }() - - first := true - for { - select { - case metric := <-ch: - pb := &dto.Metric{} - metric.Write(pb) - if pb.GetSummary() == nil { - continue - } - if len(pb.GetSummary().Quantile) != 5 { - t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) - } - for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { - if *pb.GetSummary().Quantile[idx].Quantile != want { - t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) - } - } - if first { - first = false - oldGC = *pb.GetSummary().SampleCount - oldPause = *pb.GetSummary().SampleSum - close(waitc) - continue - } - if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { - t.Errorf("want 1 new garbage collection run, got %d", diff) - } - if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { - t.Errorf("want moar pause, got %f", diff) - } - return - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go b/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go deleted file mode 100644 index 11533374b..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge.go +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package graphite provides a bridge to push Prometheus metrics to a Graphite -// server. -package graphite - -import ( - "bufio" - "errors" - "fmt" - "io" - "net" - "sort" - "time" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/common/model" - "golang.org/x/net/context" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -const ( - defaultInterval = 15 * time.Second - millisecondsPerSecond = 1000 -) - -// HandlerErrorHandling defines how a Handler serving metrics will handle -// errors. -type HandlerErrorHandling int - -// These constants cause handlers serving metrics to behave as described if -// errors are encountered. -const ( - // Ignore errors and try to push as many metrics to Graphite as possible. - ContinueOnError HandlerErrorHandling = iota - - // Abort the push to Graphite upon the first error encountered. - AbortOnError -) - -// Config defines the Graphite bridge config. -type Config struct { - // The url to push data to. Required. - URL string - - // The prefix for the pushed Graphite metrics. Defaults to empty string. - Prefix string - - // The interval to use for pushing data to Graphite. Defaults to 15 seconds. - Interval time.Duration - - // The timeout for pushing metrics to Graphite. Defaults to 15 seconds. - Timeout time.Duration - - // The Gatherer to use for metrics. Defaults to prometheus.DefaultGatherer. - Gatherer prometheus.Gatherer - - // The logger that messages are written to. Defaults to no logging. - Logger Logger - - // ErrorHandling defines how errors are handled. Note that errors are - // logged regardless of the configured ErrorHandling provided Logger - // is not nil. - ErrorHandling HandlerErrorHandling -} - -// Bridge pushes metrics to the configured Graphite server. -type Bridge struct { - url string - prefix string - interval time.Duration - timeout time.Duration - - errorHandling HandlerErrorHandling - logger Logger - - g prometheus.Gatherer -} - -// Logger is the minimal interface Bridge needs for logging. Note that -// log.Logger from the standard library implements this interface, and it is -// easy to implement by custom loggers, if they don't do so already anyway. -type Logger interface { - Println(v ...interface{}) -} - -// NewBridge returns a pointer to a new Bridge struct. -func NewBridge(c *Config) (*Bridge, error) { - b := &Bridge{} - - if c.URL == "" { - return nil, errors.New("missing URL") - } - b.url = c.URL - - if c.Gatherer == nil { - b.g = prometheus.DefaultGatherer - } else { - b.g = c.Gatherer - } - - if c.Logger != nil { - b.logger = c.Logger - } - - if c.Prefix != "" { - b.prefix = c.Prefix - } - - var z time.Duration - if c.Interval == z { - b.interval = defaultInterval - } else { - b.interval = c.Interval - } - - if c.Timeout == z { - b.timeout = defaultInterval - } else { - b.timeout = c.Timeout - } - - b.errorHandling = c.ErrorHandling - - return b, nil -} - -// Run starts the event loop that pushes Prometheus metrics to Graphite at the -// configured interval. -func (b *Bridge) Run(ctx context.Context) { - ticker := time.NewTicker(b.interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - if err := b.Push(); err != nil && b.logger != nil { - b.logger.Println("error pushing to Graphite:", err) - } - case <-ctx.Done(): - return - } - } -} - -// Push pushes Prometheus metrics to the configured Graphite server. -func (b *Bridge) Push() error { - mfs, err := b.g.Gather() - if err != nil || len(mfs) == 0 { - switch b.errorHandling { - case AbortOnError: - return err - case ContinueOnError: - if b.logger != nil { - b.logger.Println("continue on error:", err) - } - default: - panic("unrecognized error handling value") - } - } - - conn, err := net.DialTimeout("tcp", b.url, b.timeout) - if err != nil { - return err - } - defer conn.Close() - - return writeMetrics(conn, mfs, b.prefix, model.Now()) -} - -func writeMetrics(w io.Writer, mfs []*dto.MetricFamily, prefix string, now model.Time) error { - vec, err := expfmt.ExtractSamples(&expfmt.DecodeOptions{ - Timestamp: now, - }, mfs...) - if err != nil { - return err - } - - buf := bufio.NewWriter(w) - for _, s := range vec { - if err := writeSanitized(buf, prefix); err != nil { - return err - } - if err := buf.WriteByte('.'); err != nil { - return err - } - if err := writeMetric(buf, s.Metric); err != nil { - return err - } - if _, err := fmt.Fprintf(buf, " %g %d\n", s.Value, int64(s.Timestamp)/millisecondsPerSecond); err != nil { - return err - } - if err := buf.Flush(); err != nil { - return err - } - } - - return nil -} - -func writeMetric(buf *bufio.Writer, m model.Metric) error { - metricName, hasName := m[model.MetricNameLabel] - numLabels := len(m) - 1 - if !hasName { - numLabels = len(m) - } - - labelStrings := make([]string, 0, numLabels) - for label, value := range m { - if label != model.MetricNameLabel { - labelStrings = append(labelStrings, fmt.Sprintf("%s %s", string(label), string(value))) - } - } - - var err error - switch numLabels { - case 0: - if hasName { - return writeSanitized(buf, string(metricName)) - } - default: - sort.Strings(labelStrings) - if err = writeSanitized(buf, string(metricName)); err != nil { - return err - } - for _, s := range labelStrings { - if err = buf.WriteByte('.'); err != nil { - return err - } - if err = writeSanitized(buf, s); err != nil { - return err - } - } - } - return nil -} - -func writeSanitized(buf *bufio.Writer, s string) error { - prevUnderscore := false - - for _, c := range s { - c = replaceInvalidRune(c) - if c == '_' { - if prevUnderscore { - continue - } - prevUnderscore = true - } else { - prevUnderscore = false - } - if _, err := buf.WriteRune(c); err != nil { - return err - } - } - - return nil -} - -func replaceInvalidRune(c rune) rune { - if c == ' ' { - return '.' - } - if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':' || (c >= '0' && c <= '9')) { - return '_' - } - return c -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go deleted file mode 100644 index c2b274c6a..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/graphite/bridge_test.go +++ /dev/null @@ -1,309 +0,0 @@ -package graphite - -import ( - "bufio" - "bytes" - "io" - "log" - "net" - "os" - "regexp" - "testing" - "time" - - "github.com/prometheus/common/model" - "golang.org/x/net/context" - - "github.com/prometheus/client_golang/prometheus" -) - -func TestSanitize(t *testing.T) { - testCases := []struct { - in, out string - }{ - {in: "hello", out: "hello"}, - {in: "hE/l1o", out: "hE_l1o"}, - {in: "he,*ll(.o", out: "he_ll_o"}, - {in: "hello_there%^&", out: "hello_there_"}, - } - - var buf bytes.Buffer - w := bufio.NewWriter(&buf) - - for i, tc := range testCases { - if err := writeSanitized(w, tc.in); err != nil { - t.Fatalf("write failed: %v", err) - } - if err := w.Flush(); err != nil { - t.Fatalf("flush failed: %v", err) - } - - if want, got := tc.out, buf.String(); want != got { - t.Fatalf("test case index %d: got sanitized string %s, want %s", i, got, want) - } - - buf.Reset() - } -} - -func TestWriteSummary(t *testing.T) { - sumVec := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"labelname"}, - ) - - sumVec.WithLabelValues("val1").Observe(float64(10)) - sumVec.WithLabelValues("val1").Observe(float64(20)) - sumVec.WithLabelValues("val1").Observe(float64(30)) - sumVec.WithLabelValues("val2").Observe(float64(20)) - sumVec.WithLabelValues("val2").Observe(float64(30)) - sumVec.WithLabelValues("val2").Observe(float64(40)) - - reg := prometheus.NewRegistry() - reg.MustRegister(sumVec) - - mfs, err := reg.Gather() - if err != nil { - t.Fatalf("error: %v", err) - } - - now := model.Time(1477043083) - var buf bytes.Buffer - err = writeMetrics(&buf, mfs, "prefix", now) - if err != nil { - t.Fatalf("error: %v", err) - } - - want := `prefix.name.constname.constvalue.labelname.val1.quantile.0_5 20 1477043 -prefix.name.constname.constvalue.labelname.val1.quantile.0_9 30 1477043 -prefix.name.constname.constvalue.labelname.val1.quantile.0_99 30 1477043 -prefix.name_sum.constname.constvalue.labelname.val1 60 1477043 -prefix.name_count.constname.constvalue.labelname.val1 3 1477043 -prefix.name.constname.constvalue.labelname.val2.quantile.0_5 30 1477043 -prefix.name.constname.constvalue.labelname.val2.quantile.0_9 40 1477043 -prefix.name.constname.constvalue.labelname.val2.quantile.0_99 40 1477043 -prefix.name_sum.constname.constvalue.labelname.val2 90 1477043 -prefix.name_count.constname.constvalue.labelname.val2 3 1477043 -` - - if got := buf.String(); want != got { - t.Fatalf("wanted \n%s\n, got \n%s\n", want, got) - } -} - -func TestWriteHistogram(t *testing.T) { - histVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - Buckets: []float64{0.01, 0.02, 0.05, 0.1}, - }, - []string{"labelname"}, - ) - - histVec.WithLabelValues("val1").Observe(float64(10)) - histVec.WithLabelValues("val1").Observe(float64(20)) - histVec.WithLabelValues("val1").Observe(float64(30)) - histVec.WithLabelValues("val2").Observe(float64(20)) - histVec.WithLabelValues("val2").Observe(float64(30)) - histVec.WithLabelValues("val2").Observe(float64(40)) - - reg := prometheus.NewRegistry() - reg.MustRegister(histVec) - - mfs, err := reg.Gather() - if err != nil { - t.Fatalf("error: %v", err) - } - - now := model.Time(1477043083) - var buf bytes.Buffer - err = writeMetrics(&buf, mfs, "prefix", now) - if err != nil { - t.Fatalf("error: %v", err) - } - - want := `prefix.name_bucket.constname.constvalue.labelname.val1.le.0_01 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val1.le.0_02 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val1.le.0_05 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val1.le.0_1 0 1477043 -prefix.name_sum.constname.constvalue.labelname.val1 60 1477043 -prefix.name_count.constname.constvalue.labelname.val1 3 1477043 -prefix.name_bucket.constname.constvalue.labelname.val1.le._Inf 3 1477043 -prefix.name_bucket.constname.constvalue.labelname.val2.le.0_01 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val2.le.0_02 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val2.le.0_05 0 1477043 -prefix.name_bucket.constname.constvalue.labelname.val2.le.0_1 0 1477043 -prefix.name_sum.constname.constvalue.labelname.val2 90 1477043 -prefix.name_count.constname.constvalue.labelname.val2 3 1477043 -prefix.name_bucket.constname.constvalue.labelname.val2.le._Inf 3 1477043 -` - if got := buf.String(); want != got { - t.Fatalf("wanted \n%s\n, got \n%s\n", want, got) - } -} - -func TestToReader(t *testing.T) { - cntVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - cntVec.WithLabelValues("val1").Inc() - cntVec.WithLabelValues("val2").Inc() - - reg := prometheus.NewRegistry() - reg.MustRegister(cntVec) - - want := `prefix.name.constname.constvalue.labelname.val1 1 1477043 -prefix.name.constname.constvalue.labelname.val2 1 1477043 -` - mfs, err := reg.Gather() - if err != nil { - t.Fatalf("error: %v", err) - } - - now := model.Time(1477043083) - var buf bytes.Buffer - err = writeMetrics(&buf, mfs, "prefix", now) - if err != nil { - t.Fatalf("error: %v", err) - } - - if got := buf.String(); want != got { - t.Fatalf("wanted \n%s\n, got \n%s\n", want, got) - } -} - -func TestPush(t *testing.T) { - reg := prometheus.NewRegistry() - cntVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - cntVec.WithLabelValues("val1").Inc() - cntVec.WithLabelValues("val2").Inc() - reg.MustRegister(cntVec) - - host := "localhost" - port := ":56789" - b, err := NewBridge(&Config{ - URL: host + port, - Gatherer: reg, - Prefix: "prefix", - }) - if err != nil { - t.Fatalf("error creating bridge: %v", err) - } - - nmg, err := newMockGraphite(port) - if err != nil { - t.Fatalf("error creating mock graphite: %v", err) - } - defer nmg.Close() - - err = b.Push() - if err != nil { - t.Fatalf("error pushing: %v", err) - } - - wants := []string{ - "prefix.name.constname.constvalue.labelname.val1 1", - "prefix.name.constname.constvalue.labelname.val2 1", - } - - select { - case got := <-nmg.readc: - for _, want := range wants { - matched, err := regexp.MatchString(want, got) - if err != nil { - t.Fatalf("error pushing: %v", err) - } - if !matched { - t.Fatalf("missing metric:\nno match for %s received by server:\n%s", want, got) - } - } - return - case err := <-nmg.errc: - t.Fatalf("error reading push: %v", err) - case <-time.After(50 * time.Millisecond): - t.Fatalf("no result from graphite server") - } -} - -func newMockGraphite(port string) (*mockGraphite, error) { - readc := make(chan string) - errc := make(chan error) - ln, err := net.Listen("tcp", port) - if err != nil { - return nil, err - } - - go func() { - conn, err := ln.Accept() - if err != nil { - errc <- err - } - var b bytes.Buffer - io.Copy(&b, conn) - readc <- b.String() - }() - - return &mockGraphite{ - readc: readc, - errc: errc, - Listener: ln, - }, nil -} - -type mockGraphite struct { - readc chan string - errc chan error - - net.Listener -} - -func ExampleBridge() { - b, err := NewBridge(&Config{ - URL: "graphite.example.org:3099", - Gatherer: prometheus.DefaultGatherer, - Prefix: "prefix", - Interval: 15 * time.Second, - Timeout: 10 * time.Second, - ErrorHandling: AbortOnError, - Logger: log.New(os.Stdout, "graphite bridge: ", log.Lshortfile), - }) - if err != nil { - panic(err) - } - - go func() { - // Start something in a goroutine that uses metrics. - }() - - // Push initial metrics to Graphite. Fail fast if the push fails. - if err := b.Push(); err != nil { - panic(err) - } - - // Create a Context to control stopping the Run() loop that pushes - // metrics to Graphite. - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - // Start pushing metrics to Graphite in the Run() loop. - b.Run(ctx) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 331783a75..9719e8fac 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -126,16 +126,23 @@ type HistogramOpts struct { // string. Help string - // ConstLabels are used to attach fixed labels to this metric. Metrics - // with the same fully-qualified name must have the same label names in - // their ConstLabels. + // ConstLabels are used to attach fixed labels to this + // Histogram. Histograms with the same fully-qualified name must have the + // same label names in their ConstLabels. // - // ConstLabels are only used rarely. In particular, do not use them to - // attach the same labels to all your metrics. Those use cases are - // better covered by target labels set by the scraping Prometheus - // server, or by one specific metric (e.g. a build_info or a - // machine_role metric). See also - // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a + // HistogramVec. ConstLabels serve only special purposes. One is for the + // special case where the value of a label does not change during the + // lifetime of a process, e.g. if the revision of the running binary is + // put into a label. Another, more advanced purpose is if more than one + // Collector needs to collect Histograms with the same fully-qualified + // name. In that case, those Summaries must differ in the values of + // their ConstLabels. See the Collector examples. + // + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). ConstLabels Labels // Buckets defines the buckets into which observations are counted. Each @@ -280,11 +287,12 @@ func (h *histogram) Write(out *dto.Metric) error { // (e.g. HTTP request latencies, partitioned by status code and method). Create // instances with NewHistogramVec. type HistogramVec struct { - *metricVec + *MetricVec } // NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and -// partitioned by the given label names. +// partitioned by the given label names. At least one label name must be +// provided. func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), @@ -293,116 +301,47 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec { opts.ConstLabels, ) return &HistogramVec{ - metricVec: newMetricVec(desc, func(lvs ...string) Metric { + MetricVec: newMetricVec(desc, func(lvs ...string) Metric { return newHistogram(desc, opts, lvs...) }), } } -// GetMetricWithLabelValues returns the Histogram for the given slice of label -// values (same order as the VariableLabels in Desc). If that combination of -// label values is accessed for the first time, a new Histogram is created. -// -// It is possible to call this method without using the returned Histogram to only -// create the new Histogram but leave it at its starting value, a Histogram without -// any observations. -// -// Keeping the Histogram for later use is possible (and should be considered if -// performance is critical), but keep in mind that Reset, DeleteLabelValues and -// Delete can be used to delete the Histogram from the HistogramVec. In that case, the -// Histogram will still exist, but it will not be exported anymore, even if a -// Histogram with the same label values is created later. See also the CounterVec -// example. -// -// An error is returned if the number of label values is not the same as the -// number of VariableLabels in Desc (minus any curried labels). -// -// Note that for more than one label value, this method is prone to mistakes -// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as -// an alternative to avoid that type of mistake. For higher label numbers, the -// latter has a much more readable (albeit more verbose) syntax, but it comes -// with a performance overhead (for creating and processing the Labels map). -// See also the GaugeVec example. -func (v *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) { - metric, err := v.metricVec.getMetricWithLabelValues(lvs...) +// GetMetricWithLabelValues replaces the method of the same name in +// MetricVec. The difference is that this method returns a Histogram and not a +// Metric so that no type conversion is required. +func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error) { + metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) if metric != nil { - return metric.(Observer), err + return metric.(Histogram), err } return nil, err } -// GetMetricWith returns the Histogram for the given Labels map (the label names -// must match those of the VariableLabels in Desc). If that label map is -// accessed for the first time, a new Histogram is created. Implications of -// creating a Histogram without using it and keeping the Histogram for later use -// are the same as for GetMetricWithLabelValues. -// -// An error is returned if the number and names of the Labels are inconsistent -// with those of the VariableLabels in Desc (minus any curried labels). -// -// This method is used for the same purpose as -// GetMetricWithLabelValues(...string). See there for pros and cons of the two -// methods. -func (v *HistogramVec) GetMetricWith(labels Labels) (Observer, error) { - metric, err := v.metricVec.getMetricWith(labels) +// GetMetricWith replaces the method of the same name in MetricVec. The +// difference is that this method returns a Histogram and not a Metric so that no +// type conversion is required. +func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error) { + metric, err := m.MetricVec.GetMetricWith(labels) if metric != nil { - return metric.(Observer), err + return metric.(Histogram), err } return nil, err } // WithLabelValues works as GetMetricWithLabelValues, but panics where -// GetMetricWithLabelValues would have returned an error. Not returning an -// error allows shortcuts like +// GetMetricWithLabelValues would have returned an error. By not returning an +// error, WithLabelValues allows shortcuts like // myVec.WithLabelValues("404", "GET").Observe(42.21) -func (v *HistogramVec) WithLabelValues(lvs ...string) Observer { - h, err := v.GetMetricWithLabelValues(lvs...) - if err != nil { - panic(err) - } - return h -} - -// With works as GetMetricWith but panics where GetMetricWithLabels would have -// returned an error. Not returning an error allows shortcuts like -// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21) -func (v *HistogramVec) With(labels Labels) Observer { - h, err := v.GetMetricWith(labels) - if err != nil { - panic(err) - } - return h +func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram { + return m.MetricVec.WithLabelValues(lvs...).(Histogram) } -// CurryWith returns a vector curried with the provided labels, i.e. the -// returned vector has those labels pre-set for all labeled operations performed -// on it. The cardinality of the curried vector is reduced accordingly. The -// order of the remaining labels stays the same (just with the curried labels -// taken out of the sequence – which is relevant for the -// (GetMetric)WithLabelValues methods). It is possible to curry a curried -// vector, but only with labels not yet used for currying before. -// -// The metrics contained in the HistogramVec are shared between the curried and -// uncurried vectors. They are just accessed differently. Curried and uncurried -// vectors behave identically in terms of collection. Only one must be -// registered with a given registry (usually the uncurried version). The Reset -// method deletes all metrics, even if called on a curried vector. -func (v *HistogramVec) CurryWith(labels Labels) (ObserverVec, error) { - vec, err := v.curryWith(labels) - if vec != nil { - return &HistogramVec{vec}, err - } - return nil, err -} - -// MustCurryWith works as CurryWith but panics where CurryWith would have -// returned an error. -func (v *HistogramVec) MustCurryWith(labels Labels) ObserverVec { - vec, err := v.CurryWith(labels) - if err != nil { - panic(err) - } - return vec +// With works as GetMetricWith, but panics where GetMetricWithLabels would have +// returned an error. By not returning an error, With allows shortcuts like +// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21) +func (m *HistogramVec) With(labels Labels) Histogram { + return m.MetricVec.With(labels).(Histogram) } type constHistogram struct { @@ -462,8 +401,8 @@ func NewConstHistogram( buckets map[float64]uint64, labelValues ...string, ) (Metric, error) { - if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil { - return nil, err + if len(desc.variableLabels) != len(labelValues) { + return nil, errInconsistentCardinality } return &constHistogram{ desc: desc, diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go deleted file mode 100644 index 5a20f4b6b..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "reflect" - "sort" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkHistogramObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramObserve1(b *testing.B) { - benchmarkHistogramObserve(1, b) -} - -func BenchmarkHistogramObserve2(b *testing.B) { - benchmarkHistogramObserve(2, b) -} - -func BenchmarkHistogramObserve4(b *testing.B) { - benchmarkHistogramObserve(4, b) -} - -func BenchmarkHistogramObserve8(b *testing.B) { - benchmarkHistogramObserve(8, b) -} - -func benchmarkHistogramWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramWrite1(b *testing.B) { - benchmarkHistogramWrite(1, b) -} - -func BenchmarkHistogramWrite2(b *testing.B) { - benchmarkHistogramWrite(2, b) -} - -func BenchmarkHistogramWrite4(b *testing.B) { - benchmarkHistogramWrite(4, b) -} - -func BenchmarkHistogramWrite8(b *testing.B) { - benchmarkHistogramWrite(8, b) -} - -func TestHistogramNonMonotonicBuckets(t *testing.T) { - testCases := map[string][]float64{ - "not strictly monotonic": {1, 2, 2, 3}, - "not monotonic at all": {1, 2, 4, 3, 5}, - "have +Inf in the middle": {1, 2, math.Inf(+1), 3}, - } - for name, buckets := range testCases { - func() { - defer func() { - if r := recover(); r == nil { - t.Errorf("Buckets %v are %s but NewHistogram did not panic.", buckets, name) - } - }() - _ = NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: buckets, - }) - }() - } -} - -// Intentionally adding +Inf here to test if that case is handled correctly. -// Also, getCumulativeCounts depends on it. -var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} - -func TestHistogramConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: testBuckets, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Histogram.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - for i, wantBound := range testBuckets { - if i == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestHistogramVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - his := NewHistogramVec( - HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - his.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := his.WithLabelValues(string('A' + i)) - s.(Histogram).Write(m) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars[i]) - - for j, wantBound := range testBuckets { - if j == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func getCumulativeCounts(vars []float64) []uint64 { - counts := make([]uint64, len(testBuckets)) - for _, v := range vars { - for i := len(testBuckets) - 1; i >= 0; i-- { - if v > testBuckets[i] { - break - } - counts[i]++ - } - } - return counts -} - -func TestBuckets(t *testing.T) { - got := LinearBuckets(-15, 5, 6) - want := []float64{-15, -10, -5, 0, 5, 10} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } - - got = ExponentialBuckets(100, 1.2, 3) - want = []float64{100, 120, 144} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http.go b/vendor/github.com/prometheus/client_golang/prometheus/http.go index dd0f8197f..67ee5ac79 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/http.go @@ -61,8 +61,8 @@ func giveBuf(buf *bytes.Buffer) { // name). // // Deprecated: Please note the issues described in the doc comment of -// InstrumentHandler. You might want to consider using -// promhttp.InstrumentedHandler instead. +// InstrumentHandler. You might want to consider using promhttp.Handler instead +// (which is non instrumented). func Handler() http.Handler { return InstrumentHandler("prometheus", UninstrumentedHandler()) } @@ -95,7 +95,7 @@ func UninstrumentedHandler() http.Handler { closer.Close() } if lastErr != nil && buf.Len() == 0 { - http.Error(w, "No metrics encoded, last error:\n\n"+lastErr.Error(), http.StatusInternalServerError) + http.Error(w, "No metrics encoded, last error:\n\n"+err.Error(), http.StatusInternalServerError) return } header := w.Header() @@ -158,8 +158,7 @@ func nowSeries(t ...time.Time) nower { // value. http_requests_total is a metric vector partitioned by HTTP method // (label name "method") and HTTP status code (label name "code"). // -// Deprecated: InstrumentHandler has several issues. Use the tooling provided in -// package promhttp instead. The issues are the following: +// Deprecated: InstrumentHandler has several issues: // // - It uses Summaries rather than Histograms. Summaries are not useful if // aggregation across multiple instances is required. @@ -173,8 +172,9 @@ func nowSeries(t ...time.Time) nower { // httputil.ReverseProxy is a prominent example for a handler // performing such writes. // -// - It has additional issues with HTTP/2, cf. -// https://github.com/prometheus/client_golang/issues/272. +// Upcoming versions of this package will provide ways of instrumenting HTTP +// handlers that are more flexible and have fewer issues. Please prefer direct +// instrumentation in the meantime. func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc { return InstrumentHandlerFunc(handlerName, handler.ServeHTTP) } @@ -184,13 +184,12 @@ func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFun // issues). // // Deprecated: InstrumentHandlerFunc is deprecated for the same reasons as -// InstrumentHandler is. Use the tooling provided in package promhttp instead. +// InstrumentHandler is. func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc { return InstrumentHandlerFuncWithOpts( SummaryOpts{ Subsystem: "http", ConstLabels: Labels{"handler": handlerName}, - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, }, handlerFunc, ) @@ -223,7 +222,7 @@ func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWri // SummaryOpts. // // Deprecated: InstrumentHandlerWithOpts is deprecated for the same reasons as -// InstrumentHandler is. Use the tooling provided in package promhttp instead. +// InstrumentHandler is. func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc { return InstrumentHandlerFuncWithOpts(opts, handler.ServeHTTP) } @@ -234,7 +233,7 @@ func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.Hand // SummaryOpts are used. // // Deprecated: InstrumentHandlerFuncWithOpts is deprecated for the same reasons -// as InstrumentHandler is. Use the tooling provided in package promhttp instead. +// as InstrumentHandler is. func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc { reqCnt := NewCounterVec( CounterOpts{ @@ -246,52 +245,34 @@ func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.Respo }, instLabels, ) - if err := Register(reqCnt); err != nil { - if are, ok := err.(AlreadyRegisteredError); ok { - reqCnt = are.ExistingCollector.(*CounterVec) - } else { - panic(err) - } - } opts.Name = "request_duration_microseconds" opts.Help = "The HTTP request latencies in microseconds." reqDur := NewSummary(opts) - if err := Register(reqDur); err != nil { - if are, ok := err.(AlreadyRegisteredError); ok { - reqDur = are.ExistingCollector.(Summary) - } else { - panic(err) - } - } opts.Name = "request_size_bytes" opts.Help = "The HTTP request sizes in bytes." reqSz := NewSummary(opts) - if err := Register(reqSz); err != nil { - if are, ok := err.(AlreadyRegisteredError); ok { - reqSz = are.ExistingCollector.(Summary) - } else { - panic(err) - } - } opts.Name = "response_size_bytes" opts.Help = "The HTTP response sizes in bytes." resSz := NewSummary(opts) - if err := Register(resSz); err != nil { - if are, ok := err.(AlreadyRegisteredError); ok { - resSz = are.ExistingCollector.(Summary) - } else { - panic(err) - } - } + + regReqCnt := MustRegisterOrGet(reqCnt).(*CounterVec) + regReqDur := MustRegisterOrGet(reqDur).(Summary) + regReqSz := MustRegisterOrGet(reqSz).(Summary) + regResSz := MustRegisterOrGet(resSz).(Summary) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { now := time.Now() delegate := &responseWriterDelegator{ResponseWriter: w} - out := computeApproximateRequestSize(r) + out := make(chan int) + urlLen := 0 + if r.URL != nil { + urlLen = len(r.URL.String()) + } + go computeApproximateRequestSize(r, out, urlLen) _, cn := w.(http.CloseNotifier) _, fl := w.(http.Flusher) @@ -309,44 +290,30 @@ func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.Respo method := sanitizeMethod(r.Method) code := sanitizeCode(delegate.status) - reqCnt.WithLabelValues(method, code).Inc() - reqDur.Observe(elapsed) - resSz.Observe(float64(delegate.written)) - reqSz.Observe(float64(<-out)) + regReqCnt.WithLabelValues(method, code).Inc() + regReqDur.Observe(elapsed) + regResSz.Observe(float64(delegate.written)) + regReqSz.Observe(float64(<-out)) }) } -func computeApproximateRequestSize(r *http.Request) <-chan int { - // Get URL length in current go routine for avoiding a race condition. - // HandlerFunc that runs in parallel may modify the URL. - s := 0 - if r.URL != nil { - s += len(r.URL.String()) - } - - out := make(chan int, 1) - - go func() { - s += len(r.Method) - s += len(r.Proto) - for name, values := range r.Header { - s += len(name) - for _, value := range values { - s += len(value) - } +func computeApproximateRequestSize(r *http.Request, out chan int, s int) { + s += len(r.Method) + s += len(r.Proto) + for name, values := range r.Header { + s += len(name) + for _, value := range values { + s += len(value) } - s += len(r.Host) + } + s += len(r.Host) - // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. + // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. - if r.ContentLength != -1 { - s += int(r.ContentLength) - } - out <- s - close(out) - }() - - return out + if r.ContentLength != -1 { + s += int(r.ContentLength) + } + out <- s } type responseWriterDelegator struct { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/http_test.go deleted file mode 100644 index 0c7fa2347..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -type respBody string - -func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - w.Write([]byte(b)) -} - -func TestInstrumentHandler(t *testing.T) { - defer func(n nower) { - now = n.(nower) - }(now) - - instant := time.Now() - end := instant.Add(30 * time.Second) - now = nowSeries(instant, end) - respBody := respBody("Howdy there!") - - hndlr := InstrumentHandler("test-handler", respBody) - - opts := SummaryOpts{ - Subsystem: "http", - ConstLabels: Labels{"handler": "test-handler"}, - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - } - - reqCnt := NewCounterVec( - CounterOpts{ - Namespace: opts.Namespace, - Subsystem: opts.Subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: opts.ConstLabels, - }, - instLabels, - ) - err := Register(reqCnt) - if err == nil { - t.Fatal("expected reqCnt to be registered already") - } - if are, ok := err.(AlreadyRegisteredError); ok { - reqCnt = are.ExistingCollector.(*CounterVec) - } else { - t.Fatal("unexpected registration error:", err) - } - - opts.Name = "request_duration_microseconds" - opts.Help = "The HTTP request latencies in microseconds." - reqDur := NewSummary(opts) - err = Register(reqDur) - if err == nil { - t.Fatal("expected reqDur to be registered already") - } - if are, ok := err.(AlreadyRegisteredError); ok { - reqDur = are.ExistingCollector.(Summary) - } else { - t.Fatal("unexpected registration error:", err) - } - - opts.Name = "request_size_bytes" - opts.Help = "The HTTP request sizes in bytes." - reqSz := NewSummary(opts) - err = Register(reqSz) - if err == nil { - t.Fatal("expected reqSz to be registered already") - } - if _, ok := err.(AlreadyRegisteredError); !ok { - t.Fatal("unexpected registration error:", err) - } - - opts.Name = "response_size_bytes" - opts.Help = "The HTTP response sizes in bytes." - resSz := NewSummary(opts) - err = Register(resSz) - if err == nil { - t.Fatal("expected resSz to be registered already") - } - if _, ok := err.(AlreadyRegisteredError); !ok { - t.Fatal("unexpected registration error:", err) - } - - reqCnt.Reset() - - resp := httptest.NewRecorder() - req := &http.Request{ - Method: "GET", - } - - hndlr.ServeHTTP(resp, req) - - if resp.Code != http.StatusTeapot { - t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) - } - if string(resp.Body.Bytes()) != "Howdy there!" { - t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) - } - - out := &dto.Metric{} - reqDur.Write(out) - if want, got := "test-handler", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqDur, got %q", want, got) - } - if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { - t.Errorf("want sample count %d in reqDur, got %d", want, got) - } - - out.Reset() - if want, got := 1, len(reqCnt.metricMap.metrics); want != got { - t.Errorf("want %d children in reqCnt, got %d", want, got) - } - cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") - if err != nil { - t.Fatal(err) - } - cnt.Write(out) - if want, got := "418", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "test-handler", out.Label[1].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "get", out.Label[2].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if out.Counter == nil { - t.Fatal("expected non-nil counter in reqCnt") - } - if want, got := 1., out.Counter.GetValue(); want != got { - t.Errorf("want reqCnt of %f, got %f", want, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/labels.go b/vendor/github.com/prometheus/client_golang/prometheus/labels.go deleted file mode 100644 index 2502e3734..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/labels.go +++ /dev/null @@ -1,57 +0,0 @@ -package prometheus - -import ( - "errors" - "fmt" - "strings" - "unicode/utf8" - - "github.com/prometheus/common/model" -) - -// Labels represents a collection of label name -> value mappings. This type is -// commonly used with the With(Labels) and GetMetricWith(Labels) methods of -// metric vector Collectors, e.g.: -// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) -// -// The other use-case is the specification of constant label pairs in Opts or to -// create a Desc. -type Labels map[string]string - -// reservedLabelPrefix is a prefix which is not legal in user-supplied -// label names. -const reservedLabelPrefix = "__" - -var errInconsistentCardinality = errors.New("inconsistent label cardinality") - -func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { - if len(labels) != expectedNumberOfValues { - return errInconsistentCardinality - } - - for name, val := range labels { - if !utf8.ValidString(val) { - return fmt.Errorf("label %s: value %q is not valid UTF-8", name, val) - } - } - - return nil -} - -func validateLabelValues(vals []string, expectedNumberOfValues int) error { - if len(vals) != expectedNumberOfValues { - return errInconsistentCardinality - } - - for _, val := range vals { - if !utf8.ValidString(val) { - return fmt.Errorf("label value %q is not valid UTF-8", val) - } - } - - return nil -} - -func checkLabelName(l string) bool { - return model.LabelName(l).IsValid() && !strings.HasPrefix(l, reservedLabelPrefix) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go index 6213ee812..d4063d98f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go @@ -79,12 +79,20 @@ type Opts struct { // with the same fully-qualified name must have the same label names in // their ConstLabels. // - // ConstLabels are only used rarely. In particular, do not use them to - // attach the same labels to all your metrics. Those use cases are - // better covered by target labels set by the scraping Prometheus - // server, or by one specific metric (e.g. a build_info or a - // machine_role metric). See also - // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a metric + // vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels + // serve only special purposes. One is for the special case where the + // value of a label does not change during the lifetime of a process, + // e.g. if the revision of the running binary is put into a + // label. Another, more advanced purpose is if more than one Collector + // needs to collect Metrics with the same fully-qualified name. In that + // case, those Metrics must differ in the values of their + // ConstLabels. See the Collector examples. + // + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). ConstLabels Labels } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go b/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go deleted file mode 100644 index 7145f5e53..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import "testing" - -func TestBuildFQName(t *testing.T) { - scenarios := []struct{ namespace, subsystem, name, result string }{ - {"a", "b", "c", "a_b_c"}, - {"", "b", "c", "b_c"}, - {"a", "", "c", "a_c"}, - {"", "", "c", "c"}, - {"a", "b", "", ""}, - {"a", "", "", ""}, - {"", "b", "", ""}, - {" ", "", "", ""}, - } - - for i, s := range scenarios { - if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { - t.Errorf("%d. want %s, got %s", i, want, got) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/observer.go b/vendor/github.com/prometheus/client_golang/prometheus/observer.go deleted file mode 100644 index 5806cd09e..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/observer.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -// Observer is the interface that wraps the Observe method, which is used by -// Histogram and Summary to add observations. -type Observer interface { - Observe(float64) -} - -// The ObserverFunc type is an adapter to allow the use of ordinary -// functions as Observers. If f is a function with the appropriate -// signature, ObserverFunc(f) is an Observer that calls f. -// -// This adapter is usually used in connection with the Timer type, and there are -// two general use cases: -// -// The most common one is to use a Gauge as the Observer for a Timer. -// See the "Gauge" Timer example. -// -// The more advanced use case is to create a function that dynamically decides -// which Observer to use for observing the duration. See the "Complex" Timer -// example. -type ObserverFunc func(float64) - -// Observe calls f(value). It implements Observer. -func (f ObserverFunc) Observe(value float64) { - f(value) -} - -// ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`. -type ObserverVec interface { - GetMetricWith(Labels) (Observer, error) - GetMetricWithLabelValues(lvs ...string) (Observer, error) - With(Labels) Observer - WithLabelValues(...string) Observer - CurryWith(Labels) (ObserverVec, error) - MustCurryWith(Labels) ObserverVec - - Collector -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go index 32ac74a7f..e31e62e78 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go @@ -19,18 +19,15 @@ type processCollector struct { pid int collectFn func(chan<- Metric) pidFn func() (int, error) - cpuTotal *Desc - openFDs, maxFDs *Desc - vsize, rss *Desc - startTime *Desc + cpuTotal Counter + openFDs, maxFDs Gauge + vsize, rss Gauge + startTime Gauge } // NewProcessCollector returns a collector which exports the current state of -// process metrics including CPU, memory and file descriptor usage as well as -// the process start time for the given process ID under the given namespace. -// -// Currently, the collector depends on a Linux-style proc filesystem and -// therefore only exports metrics for Linux. +// process metrics including cpu, memory and file descriptor usage as well as +// the process start time for the given process id under the given namespace. func NewProcessCollector(pid int, namespace string) Collector { return NewProcessCollectorPIDFn( func() (int, error) { return pid, nil }, @@ -38,51 +35,49 @@ func NewProcessCollector(pid int, namespace string) Collector { ) } -// NewProcessCollectorPIDFn works like NewProcessCollector but the process ID is -// determined on each collect anew by calling the given pidFn function. +// NewProcessCollectorPIDFn returns a collector which exports the current state +// of process metrics including cpu, memory and file descriptor usage as well +// as the process start time under the given namespace. The given pidFn is +// called on each collect and is used to determine the process to export +// metrics for. func NewProcessCollectorPIDFn( pidFn func() (int, error), namespace string, ) Collector { - ns := "" - if len(namespace) > 0 { - ns = namespace + "_" - } - c := processCollector{ pidFn: pidFn, collectFn: func(chan<- Metric) {}, - cpuTotal: NewDesc( - ns+"process_cpu_seconds_total", - "Total user and system CPU time spent in seconds.", - nil, nil, - ), - openFDs: NewDesc( - ns+"process_open_fds", - "Number of open file descriptors.", - nil, nil, - ), - maxFDs: NewDesc( - ns+"process_max_fds", - "Maximum number of open file descriptors.", - nil, nil, - ), - vsize: NewDesc( - ns+"process_virtual_memory_bytes", - "Virtual memory size in bytes.", - nil, nil, - ), - rss: NewDesc( - ns+"process_resident_memory_bytes", - "Resident memory size in bytes.", - nil, nil, - ), - startTime: NewDesc( - ns+"process_start_time_seconds", - "Start time of the process since unix epoch in seconds.", - nil, nil, - ), + cpuTotal: NewCounter(CounterOpts{ + Namespace: namespace, + Name: "process_cpu_seconds_total", + Help: "Total user and system CPU time spent in seconds.", + }), + openFDs: NewGauge(GaugeOpts{ + Namespace: namespace, + Name: "process_open_fds", + Help: "Number of open file descriptors.", + }), + maxFDs: NewGauge(GaugeOpts{ + Namespace: namespace, + Name: "process_max_fds", + Help: "Maximum number of open file descriptors.", + }), + vsize: NewGauge(GaugeOpts{ + Namespace: namespace, + Name: "process_virtual_memory_bytes", + Help: "Virtual memory size in bytes.", + }), + rss: NewGauge(GaugeOpts{ + Namespace: namespace, + Name: "process_resident_memory_bytes", + Help: "Resident memory size in bytes.", + }), + startTime: NewGauge(GaugeOpts{ + Namespace: namespace, + Name: "process_start_time_seconds", + Help: "Start time of the process since unix epoch in seconds.", + }), } // Set up process metric collection if supported by the runtime. @@ -95,12 +90,12 @@ func NewProcessCollectorPIDFn( // Describe returns all descriptions of the collector. func (c *processCollector) Describe(ch chan<- *Desc) { - ch <- c.cpuTotal - ch <- c.openFDs - ch <- c.maxFDs - ch <- c.vsize - ch <- c.rss - ch <- c.startTime + ch <- c.cpuTotal.Desc() + ch <- c.openFDs.Desc() + ch <- c.maxFDs.Desc() + ch <- c.vsize.Desc() + ch <- c.rss.Desc() + ch <- c.startTime.Desc() } // Collect returns the current state of all metrics of the collector. @@ -122,19 +117,26 @@ func (c *processCollector) processCollect(ch chan<- Metric) { } if stat, err := p.NewStat(); err == nil { - ch <- MustNewConstMetric(c.cpuTotal, CounterValue, stat.CPUTime()) - ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(stat.VirtualMemory())) - ch <- MustNewConstMetric(c.rss, GaugeValue, float64(stat.ResidentMemory())) + c.cpuTotal.Set(stat.CPUTime()) + ch <- c.cpuTotal + c.vsize.Set(float64(stat.VirtualMemory())) + ch <- c.vsize + c.rss.Set(float64(stat.ResidentMemory())) + ch <- c.rss + if startTime, err := stat.StartTime(); err == nil { - ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime) + c.startTime.Set(startTime) + ch <- c.startTime } } if fds, err := p.FileDescriptorsLen(); err == nil { - ch <- MustNewConstMetric(c.openFDs, GaugeValue, float64(fds)) + c.openFDs.Set(float64(fds)) + ch <- c.openFDs } if limits, err := p.NewLimits(); err == nil { - ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(limits.OpenFiles)) + c.maxFDs.Set(float64(limits.OpenFiles)) + ch <- c.maxFDs } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go deleted file mode 100644 index c7acb47fe..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package prometheus - -import ( - "bytes" - "os" - "regexp" - "testing" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/procfs" -) - -func TestProcessCollector(t *testing.T) { - if _, err := procfs.Self(); err != nil { - t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) - } - - registry := NewRegistry() - if err := registry.Register(NewProcessCollector(os.Getpid(), "")); err != nil { - t.Fatal(err) - } - if err := registry.Register(NewProcessCollectorPIDFn( - func() (int, error) { return os.Getpid(), nil }, "foobar"), - ); err != nil { - t.Fatal(err) - } - - mfs, err := registry.Gather() - if err != nil { - t.Fatal(err) - } - - var buf bytes.Buffer - for _, mf := range mfs { - if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil { - t.Fatal(err) - } - } - - for _, re := range []*regexp.Regexp{ - regexp.MustCompile("\nprocess_cpu_seconds_total [0-9]"), - regexp.MustCompile("\nprocess_max_fds [1-9]"), - regexp.MustCompile("\nprocess_open_fds [1-9]"), - regexp.MustCompile("\nprocess_virtual_memory_bytes [1-9]"), - regexp.MustCompile("\nprocess_resident_memory_bytes [1-9]"), - regexp.MustCompile("\nprocess_start_time_seconds [0-9.]{10,}"), - regexp.MustCompile("\nfoobar_process_cpu_seconds_total [0-9]"), - regexp.MustCompile("\nfoobar_process_max_fds [1-9]"), - regexp.MustCompile("\nfoobar_process_open_fds [1-9]"), - regexp.MustCompile("\nfoobar_process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("\nfoobar_process_resident_memory_bytes [1-9]"), - regexp.MustCompile("\nfoobar_process_start_time_seconds [0-9.]{10,}"), - } { - if !re.Match(buf.Bytes()) { - t.Errorf("want body to match %s\n%s", re, buf.String()) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go deleted file mode 100644 index 9c1c66dcc..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package promhttp - -import ( - "bufio" - "io" - "net" - "net/http" -) - -const ( - closeNotifier = 1 << iota - flusher - hijacker - readerFrom - pusher -) - -type delegator interface { - http.ResponseWriter - - Status() int - Written() int64 -} - -type responseWriterDelegator struct { - http.ResponseWriter - - handler, method string - status int - written int64 - wroteHeader bool - observeWriteHeader func(int) -} - -func (r *responseWriterDelegator) Status() int { - return r.status -} - -func (r *responseWriterDelegator) Written() int64 { - return r.written -} - -func (r *responseWriterDelegator) WriteHeader(code int) { - r.status = code - r.wroteHeader = true - r.ResponseWriter.WriteHeader(code) - if r.observeWriteHeader != nil { - r.observeWriteHeader(code) - } -} - -func (r *responseWriterDelegator) Write(b []byte) (int, error) { - if !r.wroteHeader { - r.WriteHeader(http.StatusOK) - } - n, err := r.ResponseWriter.Write(b) - r.written += int64(n) - return n, err -} - -type closeNotifierDelegator struct{ *responseWriterDelegator } -type flusherDelegator struct{ *responseWriterDelegator } -type hijackerDelegator struct{ *responseWriterDelegator } -type readerFromDelegator struct{ *responseWriterDelegator } - -func (d *closeNotifierDelegator) CloseNotify() <-chan bool { - return d.ResponseWriter.(http.CloseNotifier).CloseNotify() -} -func (d *flusherDelegator) Flush() { - d.ResponseWriter.(http.Flusher).Flush() -} -func (d *hijackerDelegator) Hijack() (net.Conn, *bufio.ReadWriter, error) { - return d.ResponseWriter.(http.Hijacker).Hijack() -} -func (d *readerFromDelegator) ReadFrom(re io.Reader) (int64, error) { - if !d.wroteHeader { - d.WriteHeader(http.StatusOK) - } - n, err := d.ResponseWriter.(io.ReaderFrom).ReadFrom(re) - d.written += n - return n, err -} - -var pickDelegator = make([]func(*responseWriterDelegator) delegator, 32) - -func init() { - // TODO(beorn7): Code generation would help here. - pickDelegator[0] = func(d *responseWriterDelegator) delegator { // 0 - return d - } - pickDelegator[closeNotifier] = func(d *responseWriterDelegator) delegator { // 1 - return &closeNotifierDelegator{d} - } - pickDelegator[flusher] = func(d *responseWriterDelegator) delegator { // 2 - return &flusherDelegator{d} - } - pickDelegator[flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 3 - return struct { - *responseWriterDelegator - http.Flusher - http.CloseNotifier - }{d, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[hijacker] = func(d *responseWriterDelegator) delegator { // 4 - return &hijackerDelegator{d} - } - pickDelegator[hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 5 - return struct { - *responseWriterDelegator - http.Hijacker - http.CloseNotifier - }{d, &hijackerDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 6 - return struct { - *responseWriterDelegator - http.Hijacker - http.Flusher - }{d, &hijackerDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 7 - return struct { - *responseWriterDelegator - http.Hijacker - http.Flusher - http.CloseNotifier - }{d, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[readerFrom] = func(d *responseWriterDelegator) delegator { // 8 - return readerFromDelegator{d} - } - pickDelegator[readerFrom+closeNotifier] = func(d *responseWriterDelegator) delegator { // 9 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.CloseNotifier - }{d, &readerFromDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[readerFrom+flusher] = func(d *responseWriterDelegator) delegator { // 10 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Flusher - }{d, &readerFromDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[readerFrom+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 11 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Flusher - http.CloseNotifier - }{d, &readerFromDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[readerFrom+hijacker] = func(d *responseWriterDelegator) delegator { // 12 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Hijacker - }{d, &readerFromDelegator{d}, &hijackerDelegator{d}} - } - pickDelegator[readerFrom+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 13 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Hijacker - http.CloseNotifier - }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[readerFrom+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 14 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Hijacker - http.Flusher - }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[readerFrom+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 15 - return struct { - *responseWriterDelegator - io.ReaderFrom - http.Hijacker - http.Flusher - http.CloseNotifier - }{d, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go deleted file mode 100644 index 75a905e2f..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_1_8.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package promhttp - -import ( - "io" - "net/http" -) - -type pusherDelegator struct{ *responseWriterDelegator } - -func (d *pusherDelegator) Push(target string, opts *http.PushOptions) error { - return d.ResponseWriter.(http.Pusher).Push(target, opts) -} - -func init() { - pickDelegator[pusher] = func(d *responseWriterDelegator) delegator { // 16 - return &pusherDelegator{d} - } - pickDelegator[pusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 17 - return struct { - *responseWriterDelegator - http.Pusher - http.CloseNotifier - }{d, &pusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+flusher] = func(d *responseWriterDelegator) delegator { // 18 - return struct { - *responseWriterDelegator - http.Pusher - http.Flusher - }{d, &pusherDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[pusher+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 19 - return struct { - *responseWriterDelegator - http.Pusher - http.Flusher - http.CloseNotifier - }{d, &pusherDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+hijacker] = func(d *responseWriterDelegator) delegator { // 20 - return struct { - *responseWriterDelegator - http.Pusher - http.Hijacker - }{d, &pusherDelegator{d}, &hijackerDelegator{d}} - } - pickDelegator[pusher+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 21 - return struct { - *responseWriterDelegator - http.Pusher - http.Hijacker - http.CloseNotifier - }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 22 - return struct { - *responseWriterDelegator - http.Pusher - http.Hijacker - http.Flusher - }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[pusher+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { //23 - return struct { - *responseWriterDelegator - http.Pusher - http.Hijacker - http.Flusher - http.CloseNotifier - }{d, &pusherDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+readerFrom] = func(d *responseWriterDelegator) delegator { // 24 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - }{d, &pusherDelegator{d}, &readerFromDelegator{d}} - } - pickDelegator[pusher+readerFrom+closeNotifier] = func(d *responseWriterDelegator) delegator { // 25 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.CloseNotifier - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+readerFrom+flusher] = func(d *responseWriterDelegator) delegator { // 26 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Flusher - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[pusher+readerFrom+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 27 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Flusher - http.CloseNotifier - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+readerFrom+hijacker] = func(d *responseWriterDelegator) delegator { // 28 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Hijacker - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}} - } - pickDelegator[pusher+readerFrom+hijacker+closeNotifier] = func(d *responseWriterDelegator) delegator { // 29 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Hijacker - http.CloseNotifier - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &closeNotifierDelegator{d}} - } - pickDelegator[pusher+readerFrom+hijacker+flusher] = func(d *responseWriterDelegator) delegator { // 30 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Hijacker - http.Flusher - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}} - } - pickDelegator[pusher+readerFrom+hijacker+flusher+closeNotifier] = func(d *responseWriterDelegator) delegator { // 31 - return struct { - *responseWriterDelegator - http.Pusher - io.ReaderFrom - http.Hijacker - http.Flusher - http.CloseNotifier - }{d, &pusherDelegator{d}, &readerFromDelegator{d}, &hijackerDelegator{d}, &flusherDelegator{d}, &closeNotifierDelegator{d}} - } -} - -func newDelegator(w http.ResponseWriter, observeWriteHeaderFunc func(int)) delegator { - d := &responseWriterDelegator{ - ResponseWriter: w, - observeWriteHeader: observeWriteHeaderFunc, - } - - id := 0 - if _, ok := w.(http.CloseNotifier); ok { - id += closeNotifier - } - if _, ok := w.(http.Flusher); ok { - id += flusher - } - if _, ok := w.(http.Hijacker); ok { - id += hijacker - } - if _, ok := w.(io.ReaderFrom); ok { - id += readerFrom - } - if _, ok := w.(http.Pusher); ok { - id += pusher - } - - return pickDelegator[id](d) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go deleted file mode 100644 index 8bb9b8b68..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator_pre_1_8.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.8 - -package promhttp - -import ( - "io" - "net/http" -) - -func newDelegator(w http.ResponseWriter, observeWriteHeaderFunc func(int)) delegator { - d := &responseWriterDelegator{ - ResponseWriter: w, - observeWriteHeader: observeWriteHeaderFunc, - } - - id := 0 - if _, ok := w.(http.CloseNotifier); ok { - id += closeNotifier - } - if _, ok := w.(http.Flusher); ok { - id += flusher - } - if _, ok := w.(http.Hijacker); ok { - id += hijacker - } - if _, ok := w.(io.ReaderFrom); ok { - id += readerFrom - } - - return pickDelegator[id](d) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go index 8dc260355..b6dd5a266 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -11,24 +11,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package promhttp provides tooling around HTTP servers and clients. +// Copyright (c) 2013, The Prometheus Authors +// All rights reserved. // -// First, the package allows the creation of http.Handler instances to expose -// Prometheus metrics via HTTP. promhttp.Handler acts on the -// prometheus.DefaultGatherer. With HandlerFor, you can create a handler for a -// custom registry or anything that implements the Gatherer interface. It also -// allows the creation of handlers that act differently on errors or allow to -// log errors. -// -// Second, the package provides tooling to instrument instances of http.Handler -// via middleware. Middleware wrappers follow the naming scheme -// InstrumentHandlerX, where X describes the intended use of the middleware. -// See each function's doc comment for specific details. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +// Package promhttp contains functions to create http.Handler instances to +// expose Prometheus metrics via HTTP. In later versions of this package, it +// will also contain tooling to instrument instances of http.Handler and +// http.RoundTripper. // -// Finally, the package allows for an http.RoundTripper to be instrumented via -// middleware. Middleware wrappers follow the naming scheme -// InstrumentRoundTripperX, where X describes the intended use of the -// middleware. See each function's doc comment for specific details. +// promhttp.Handler acts on the prometheus.DefaultGatherer. With HandlerFor, +// you can create a handler for a custom registry or anything that implements +// the Gatherer interface. It also allows to create handlers that act +// differently on errors or allow to log errors. package promhttp import ( @@ -39,7 +36,6 @@ import ( "net/http" "strings" "sync" - "time" "github.com/prometheus/common/expfmt" @@ -68,51 +64,21 @@ func giveBuf(buf *bytes.Buffer) { bufPool.Put(buf) } -// Handler returns an http.Handler for the prometheus.DefaultGatherer, using -// default HandlerOpts, i.e. it reports the first error as an HTTP error, it has -// no error logging, and it applies compression if requested by the client. -// -// The returned http.Handler is already instrumented using the -// InstrumentMetricHandler function and the prometheus.DefaultRegisterer. If you -// create multiple http.Handlers by separate calls of the Handler function, the -// metrics used for instrumentation will be shared between them, providing -// global scrape counts. +// Handler returns an HTTP handler for the prometheus.DefaultGatherer. The +// Handler uses the default HandlerOpts, i.e. report the first error as an HTTP +// error, no error logging, and compression if requested by the client. // -// This function is meant to cover the bulk of basic use cases. If you are doing -// anything that requires more customization (including using a non-default -// Gatherer, different instrumentation, and non-default HandlerOpts), use the -// HandlerFor function. See there for details. +// If you want to create a Handler for the DefaultGatherer with different +// HandlerOpts, create it with HandlerFor with prometheus.DefaultGatherer and +// your desired HandlerOpts. func Handler() http.Handler { - return InstrumentMetricHandler( - prometheus.DefaultRegisterer, HandlerFor(prometheus.DefaultGatherer, HandlerOpts{}), - ) + return HandlerFor(prometheus.DefaultGatherer, HandlerOpts{}) } -// HandlerFor returns an uninstrumented http.Handler for the provided -// Gatherer. The behavior of the Handler is defined by the provided -// HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom -// Gatherers, with non-default HandlerOpts, and/or with custom (or no) -// instrumentation. Use the InstrumentMetricHandler function to apply the same -// kind of instrumentation as it is used by the Handler function. +// HandlerFor returns an http.Handler for the provided Gatherer. The behavior +// of the Handler is defined by the provided HandlerOpts. func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { - var inFlightSem chan struct{} - if opts.MaxRequestsInFlight > 0 { - inFlightSem = make(chan struct{}, opts.MaxRequestsInFlight) - } - - h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if inFlightSem != nil { - select { - case inFlightSem <- struct{}{}: // All good, carry on. - defer func() { <-inFlightSem }() - default: - http.Error(w, fmt.Sprintf( - "Limit of concurrent requests reached (%d), try again later.", opts.MaxRequestsInFlight, - ), http.StatusServiceUnavailable) - return - } - } - + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mfs, err := reg.Gather() if err != nil { if opts.ErrorLog != nil { @@ -159,7 +125,7 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { closer.Close() } if lastErr != nil && buf.Len() == 0 { - http.Error(w, "No metrics encoded, last error:\n\n"+lastErr.Error(), http.StatusInternalServerError) + http.Error(w, "No metrics encoded, last error:\n\n"+err.Error(), http.StatusInternalServerError) return } header := w.Header() @@ -168,70 +134,9 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler { if encoding != "" { header.Set(contentEncodingHeader, encoding) } - if _, err := w.Write(buf.Bytes()); err != nil && opts.ErrorLog != nil { - opts.ErrorLog.Println("error while sending encoded metrics:", err) - } + w.Write(buf.Bytes()) // TODO(beorn7): Consider streaming serving of metrics. }) - - if opts.Timeout <= 0 { - return h - } - return http.TimeoutHandler(h, opts.Timeout, fmt.Sprintf( - "Exceeded configured timeout of %v.\n", - opts.Timeout, - )) -} - -// InstrumentMetricHandler is usually used with an http.Handler returned by the -// HandlerFor function. It instruments the provided http.Handler with two -// metrics: A counter vector "promhttp_metric_handler_requests_total" to count -// scrapes partitioned by HTTP status code, and a gauge -// "promhttp_metric_handler_requests_in_flight" to track the number of -// simultaneous scrapes. This function idempotently registers collectors for -// both metrics with the provided Registerer. It panics if the registration -// fails. The provided metrics are useful to see how many scrapes hit the -// monitored target (which could be from different Prometheus servers or other -// scrapers), and how often they overlap (which would result in more than one -// scrape in flight at the same time). Note that the scrapes-in-flight gauge -// will contain the scrape by which it is exposed, while the scrape counter will -// only get incremented after the scrape is complete (as only then the status -// code is known). For tracking scrape durations, use the -// "scrape_duration_seconds" gauge created by the Prometheus server upon each -// scrape. -func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) http.Handler { - cnt := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "promhttp_metric_handler_requests_total", - Help: "Total number of scrapes by HTTP status code.", - }, - []string{"code"}, - ) - // Initialize the most likely HTTP status codes. - cnt.WithLabelValues("200") - cnt.WithLabelValues("500") - cnt.WithLabelValues("503") - if err := reg.Register(cnt); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - cnt = are.ExistingCollector.(*prometheus.CounterVec) - } else { - panic(err) - } - } - - gge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "promhttp_metric_handler_requests_in_flight", - Help: "Current number of scrapes being served.", - }) - if err := reg.Register(gge); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - gge = are.ExistingCollector.(prometheus.Gauge) - } else { - panic(err) - } - } - - return InstrumentHandlerCounter(cnt, InstrumentHandlerInFlight(gge, handler)) } // HandlerErrorHandling defines how a Handler serving metrics will handle @@ -275,21 +180,6 @@ type HandlerOpts struct { // If DisableCompression is true, the handler will never compress the // response, even if requested by the client. DisableCompression bool - // The number of concurrent HTTP requests is limited to - // MaxRequestsInFlight. Additional requests are responded to with 503 - // Service Unavailable and a suitable message in the body. If - // MaxRequestsInFlight is 0 or negative, no limit is applied. - MaxRequestsInFlight int - // If handling a request takes longer than Timeout, it is responded to - // with 503 ServiceUnavailable and a suitable Message. No timeout is - // applied if Timeout is 0 or negative. Note that with the current - // implementation, reaching the timeout simply ends the HTTP requests as - // described above (and even that only if sending of the body hasn't - // started yet), while the bulk work of gathering all the metrics keeps - // running in the background (with the eventual result to be thrown - // away). Until the implementation is improved, it is recommended to - // implement a separate timeout in potentially slow Collectors. - Timeout time.Duration } // decorateWriter wraps a writer to handle gzip compression if requested. It diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go deleted file mode 100644 index aeaa0b4d7..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package promhttp - -import ( - "bytes" - "errors" - "log" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/prometheus/client_golang/prometheus" -) - -type errorCollector struct{} - -func (e errorCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- prometheus.NewDesc("invalid_metric", "not helpful", nil, nil) -} - -func (e errorCollector) Collect(ch chan<- prometheus.Metric) { - ch <- prometheus.NewInvalidMetric( - prometheus.NewDesc("invalid_metric", "not helpful", nil, nil), - errors.New("collect error"), - ) -} - -type blockingCollector struct { - CollectStarted, Block chan struct{} -} - -func (b blockingCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- prometheus.NewDesc("dummy_desc", "not helpful", nil, nil) -} - -func (b blockingCollector) Collect(ch chan<- prometheus.Metric) { - select { - case b.CollectStarted <- struct{}{}: - default: - } - // Collects nothing, just waits for a channel receive. - <-b.Block -} - -func TestHandlerErrorHandling(t *testing.T) { - - // Create a registry that collects a MetricFamily with two elements, - // another with one, and reports an error. - reg := prometheus.NewRegistry() - - cnt := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "the_count", - Help: "Ah-ah-ah! Thunder and lightning!", - }) - reg.MustRegister(cnt) - - cntVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - cntVec.WithLabelValues("val1").Inc() - cntVec.WithLabelValues("val2").Inc() - reg.MustRegister(cntVec) - - reg.MustRegister(errorCollector{}) - - logBuf := &bytes.Buffer{} - logger := log.New(logBuf, "", 0) - - writer := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - errorHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: HTTPErrorOnError, - }) - continueHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: ContinueOnError, - }) - panicHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: PanicOnError, - }) - wantMsg := `error gathering metrics: error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantErrorBody := `An error has occurred during metrics gathering: - -error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantOKBody := `# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -# HELP the_count Ah-ah-ah! Thunder and lightning! -# TYPE the_count counter -the_count 0 -` - - errorHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusInternalServerError; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message:\n%s\nwant log mesage:\n%s\n", got, wantMsg) - } - if got := writer.Body.String(); got != wantErrorBody { - t.Errorf("got body:\n%s\nwant body:\n%s\n", got, wantErrorBody) - } - logBuf.Reset() - writer.Body.Reset() - writer.Code = http.StatusOK - - continueHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message %q, want %q", got, wantMsg) - } - if got := writer.Body.String(); got != wantOKBody { - t.Errorf("got body %q, want %q", got, wantOKBody) - } - - defer func() { - if err := recover(); err == nil { - t.Error("expected panic from panicHandler") - } - }() - panicHandler.ServeHTTP(writer, request) -} - -func TestInstrumentMetricHandler(t *testing.T) { - reg := prometheus.NewRegistry() - handler := InstrumentMetricHandler(reg, HandlerFor(reg, HandlerOpts{})) - // Do it again to test idempotency. - InstrumentMetricHandler(reg, HandlerFor(reg, HandlerOpts{})) - writer := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - handler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - - want := "promhttp_metric_handler_requests_in_flight 1\n" - if got := writer.Body.String(); !strings.Contains(got, want) { - t.Errorf("got body %q, does not contain %q", got, want) - } - want = "promhttp_metric_handler_requests_total{code=\"200\"} 0\n" - if got := writer.Body.String(); !strings.Contains(got, want) { - t.Errorf("got body %q, does not contain %q", got, want) - } - - writer.Body.Reset() - handler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - - want = "promhttp_metric_handler_requests_in_flight 1\n" - if got := writer.Body.String(); !strings.Contains(got, want) { - t.Errorf("got body %q, does not contain %q", got, want) - } - want = "promhttp_metric_handler_requests_total{code=\"200\"} 1\n" - if got := writer.Body.String(); !strings.Contains(got, want) { - t.Errorf("got body %q, does not contain %q", got, want) - } -} - -func TestHandlerMaxRequestsInFlight(t *testing.T) { - reg := prometheus.NewRegistry() - handler := HandlerFor(reg, HandlerOpts{MaxRequestsInFlight: 1}) - w1 := httptest.NewRecorder() - w2 := httptest.NewRecorder() - w3 := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - c := blockingCollector{Block: make(chan struct{}), CollectStarted: make(chan struct{}, 1)} - reg.MustRegister(c) - - rq1Done := make(chan struct{}) - go func() { - handler.ServeHTTP(w1, request) - close(rq1Done) - }() - <-c.CollectStarted - - handler.ServeHTTP(w2, request) - - if got, want := w2.Code, http.StatusServiceUnavailable; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got, want := w2.Body.String(), "Limit of concurrent requests reached (1), try again later.\n"; got != want { - t.Errorf("got body %q, want %q", got, want) - } - - close(c.Block) - <-rq1Done - - handler.ServeHTTP(w3, request) - - if got, want := w3.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } -} - -func TestHandlerTimeout(t *testing.T) { - reg := prometheus.NewRegistry() - handler := HandlerFor(reg, HandlerOpts{Timeout: time.Millisecond}) - w := httptest.NewRecorder() - - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - c := blockingCollector{Block: make(chan struct{}), CollectStarted: make(chan struct{}, 1)} - reg.MustRegister(c) - - handler.ServeHTTP(w, request) - - if got, want := w.Code, http.StatusServiceUnavailable; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got, want := w.Body.String(), "Exceeded configured timeout of 1ms.\n"; got != want { - t.Errorf("got body %q, want %q", got, want) - } - - close(c.Block) // To not leak a goroutine. -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go deleted file mode 100644 index 86fd56447..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package promhttp - -import ( - "net/http" - "time" - - "github.com/prometheus/client_golang/prometheus" -) - -// The RoundTripperFunc type is an adapter to allow the use of ordinary -// functions as RoundTrippers. If f is a function with the appropriate -// signature, RountTripperFunc(f) is a RoundTripper that calls f. -type RoundTripperFunc func(req *http.Request) (*http.Response, error) - -// RoundTrip implements the RoundTripper interface. -func (rt RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { - return rt(r) -} - -// InstrumentRoundTripperInFlight is a middleware that wraps the provided -// http.RoundTripper. It sets the provided prometheus.Gauge to the number of -// requests currently handled by the wrapped http.RoundTripper. -// -// See the example for ExampleInstrumentRoundTripperDuration for example usage. -func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripper) RoundTripperFunc { - return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { - gauge.Inc() - defer gauge.Dec() - return next.RoundTrip(r) - }) -} - -// InstrumentRoundTripperCounter is a middleware that wraps the provided -// http.RoundTripper to observe the request result with the provided CounterVec. -// The CounterVec must have zero, one, or two non-const non-curried labels. For -// those, the only allowed label names are "code" and "method". The function -// panics otherwise. Partitioning of the CounterVec happens by HTTP status code -// and/or HTTP method if the respective instance label names are present in the -// CounterVec. For unpartitioned counting, use a CounterVec with zero labels. -// -// If the wrapped RoundTripper panics or returns a non-nil error, the Counter -// is not incremented. -// -// See the example for ExampleInstrumentRoundTripperDuration for example usage. -func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.RoundTripper) RoundTripperFunc { - code, method := checkLabels(counter) - - return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { - resp, err := next.RoundTrip(r) - if err == nil { - counter.With(labels(code, method, r.Method, resp.StatusCode)).Inc() - } - return resp, err - }) -} - -// InstrumentRoundTripperDuration is a middleware that wraps the provided -// http.RoundTripper to observe the request duration with the provided -// ObserverVec. The ObserverVec must have zero, one, or two non-const -// non-curried labels. For those, the only allowed label names are "code" and -// "method". The function panics otherwise. The Observe method of the Observer -// in the ObserverVec is called with the request duration in -// seconds. Partitioning happens by HTTP status code and/or HTTP method if the -// respective instance label names are present in the ObserverVec. For -// unpartitioned observations, use an ObserverVec with zero labels. Note that -// partitioning of Histograms is expensive and should be used judiciously. -// -// If the wrapped RoundTripper panics or returns a non-nil error, no values are -// reported. -// -// Note that this method is only guaranteed to never observe negative durations -// if used with Go1.9+. -func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundTripper) RoundTripperFunc { - code, method := checkLabels(obs) - - return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { - start := time.Now() - resp, err := next.RoundTrip(r) - if err == nil { - obs.With(labels(code, method, r.Method, resp.StatusCode)).Observe(time.Since(start).Seconds()) - } - return resp, err - }) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go deleted file mode 100644 index 0bd80c355..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package promhttp - -import ( - "context" - "crypto/tls" - "net/http" - "net/http/httptrace" - "time" -) - -// InstrumentTrace is used to offer flexibility in instrumenting the available -// httptrace.ClientTrace hook functions. Each function is passed a float64 -// representing the time in seconds since the start of the http request. A user -// may choose to use separately buckets Histograms, or implement custom -// instance labels on a per function basis. -type InstrumentTrace struct { - GotConn func(float64) - PutIdleConn func(float64) - GotFirstResponseByte func(float64) - Got100Continue func(float64) - DNSStart func(float64) - DNSDone func(float64) - ConnectStart func(float64) - ConnectDone func(float64) - TLSHandshakeStart func(float64) - TLSHandshakeDone func(float64) - WroteHeaders func(float64) - Wait100Continue func(float64) - WroteRequest func(float64) -} - -// InstrumentRoundTripperTrace is a middleware that wraps the provided -// RoundTripper and reports times to hook functions provided in the -// InstrumentTrace struct. Hook functions that are not present in the provided -// InstrumentTrace struct are ignored. Times reported to the hook functions are -// time since the start of the request. Only with Go1.9+, those times are -// guaranteed to never be negative. (Earlier Go versions are not using a -// monotonic clock.) Note that partitioning of Histograms is expensive and -// should be used judiciously. -// -// For hook functions that receive an error as an argument, no observations are -// made in the event of a non-nil error value. -// -// See the example for ExampleInstrumentRoundTripperDuration for example usage. -func InstrumentRoundTripperTrace(it *InstrumentTrace, next http.RoundTripper) RoundTripperFunc { - return RoundTripperFunc(func(r *http.Request) (*http.Response, error) { - start := time.Now() - - trace := &httptrace.ClientTrace{ - GotConn: func(_ httptrace.GotConnInfo) { - if it.GotConn != nil { - it.GotConn(time.Since(start).Seconds()) - } - }, - PutIdleConn: func(err error) { - if err != nil { - return - } - if it.PutIdleConn != nil { - it.PutIdleConn(time.Since(start).Seconds()) - } - }, - DNSStart: func(_ httptrace.DNSStartInfo) { - if it.DNSStart != nil { - it.DNSStart(time.Since(start).Seconds()) - } - }, - DNSDone: func(_ httptrace.DNSDoneInfo) { - if it.DNSStart != nil { - it.DNSStart(time.Since(start).Seconds()) - } - }, - ConnectStart: func(_, _ string) { - if it.ConnectStart != nil { - it.ConnectStart(time.Since(start).Seconds()) - } - }, - ConnectDone: func(_, _ string, err error) { - if err != nil { - return - } - if it.ConnectDone != nil { - it.ConnectDone(time.Since(start).Seconds()) - } - }, - GotFirstResponseByte: func() { - if it.GotFirstResponseByte != nil { - it.GotFirstResponseByte(time.Since(start).Seconds()) - } - }, - Got100Continue: func() { - if it.Got100Continue != nil { - it.Got100Continue(time.Since(start).Seconds()) - } - }, - TLSHandshakeStart: func() { - if it.TLSHandshakeStart != nil { - it.TLSHandshakeStart(time.Since(start).Seconds()) - } - }, - TLSHandshakeDone: func(_ tls.ConnectionState, err error) { - if err != nil { - return - } - if it.TLSHandshakeDone != nil { - it.TLSHandshakeDone(time.Since(start).Seconds()) - } - }, - WroteHeaders: func() { - if it.WroteHeaders != nil { - it.WroteHeaders(time.Since(start).Seconds()) - } - }, - Wait100Continue: func() { - if it.Wait100Continue != nil { - it.Wait100Continue(time.Since(start).Seconds()) - } - }, - WroteRequest: func(_ httptrace.WroteRequestInfo) { - if it.WroteRequest != nil { - it.WroteRequest(time.Since(start).Seconds()) - } - }, - } - r = r.WithContext(httptrace.WithClientTrace(context.Background(), trace)) - - return next.RoundTrip(r) - }) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go deleted file mode 100644 index 7e3f5229f..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client_1_8_test.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package promhttp - -import ( - "log" - "net/http" - "testing" - "time" - - "github.com/prometheus/client_golang/prometheus" -) - -func TestClientMiddlewareAPI(t *testing.T) { - client := http.DefaultClient - client.Timeout = 1 * time.Second - - reg := prometheus.NewRegistry() - - inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "client_in_flight_requests", - Help: "A gauge of in-flight requests for the wrapped client.", - }) - - counter := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "client_api_requests_total", - Help: "A counter for requests from the wrapped client.", - }, - []string{"code", "method"}, - ) - - dnsLatencyVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "dns_duration_seconds", - Help: "Trace dns latency histogram.", - Buckets: []float64{.005, .01, .025, .05}, - }, - []string{"event"}, - ) - - tlsLatencyVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "tls_duration_seconds", - Help: "Trace tls latency histogram.", - Buckets: []float64{.05, .1, .25, .5}, - }, - []string{"event"}, - ) - - histVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "request_duration_seconds", - Help: "A histogram of request latencies.", - Buckets: prometheus.DefBuckets, - }, - []string{"method"}, - ) - - reg.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge) - - trace := &InstrumentTrace{ - DNSStart: func(t float64) { - dnsLatencyVec.WithLabelValues("dns_start") - }, - DNSDone: func(t float64) { - dnsLatencyVec.WithLabelValues("dns_done") - }, - TLSHandshakeStart: func(t float64) { - tlsLatencyVec.WithLabelValues("tls_handshake_start") - }, - TLSHandshakeDone: func(t float64) { - tlsLatencyVec.WithLabelValues("tls_handshake_done") - }, - } - - client.Transport = InstrumentRoundTripperInFlight(inFlightGauge, - InstrumentRoundTripperCounter(counter, - InstrumentRoundTripperTrace(trace, - InstrumentRoundTripperDuration(histVec, http.DefaultTransport), - ), - ), - ) - - resp, err := client.Get("http://google.com") - if err != nil { - t.Fatalf("%v", err) - } - defer resp.Body.Close() -} - -func ExampleInstrumentRoundTripperDuration() { - client := http.DefaultClient - client.Timeout = 1 * time.Second - - inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "client_in_flight_requests", - Help: "A gauge of in-flight requests for the wrapped client.", - }) - - counter := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "client_api_requests_total", - Help: "A counter for requests from the wrapped client.", - }, - []string{"code", "method"}, - ) - - // dnsLatencyVec uses custom buckets based on expected dns durations. - // It has an instance label "event", which is set in the - // DNSStart and DNSDonehook functions defined in the - // InstrumentTrace struct below. - dnsLatencyVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "dns_duration_seconds", - Help: "Trace dns latency histogram.", - Buckets: []float64{.005, .01, .025, .05}, - }, - []string{"event"}, - ) - - // tlsLatencyVec uses custom buckets based on expected tls durations. - // It has an instance label "event", which is set in the - // TLSHandshakeStart and TLSHandshakeDone hook functions defined in the - // InstrumentTrace struct below. - tlsLatencyVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "tls_duration_seconds", - Help: "Trace tls latency histogram.", - Buckets: []float64{.05, .1, .25, .5}, - }, - []string{"event"}, - ) - - // histVec has no labels, making it a zero-dimensional ObserverVec. - histVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "request_duration_seconds", - Help: "A histogram of request latencies.", - Buckets: prometheus.DefBuckets, - }, - []string{}, - ) - - // Register all of the metrics in the standard registry. - prometheus.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge) - - // Define functions for the available httptrace.ClientTrace hook - // functions that we want to instrument. - trace := &InstrumentTrace{ - DNSStart: func(t float64) { - dnsLatencyVec.WithLabelValues("dns_start") - }, - DNSDone: func(t float64) { - dnsLatencyVec.WithLabelValues("dns_done") - }, - TLSHandshakeStart: func(t float64) { - tlsLatencyVec.WithLabelValues("tls_handshake_start") - }, - TLSHandshakeDone: func(t float64) { - tlsLatencyVec.WithLabelValues("tls_handshake_done") - }, - } - - // Wrap the default RoundTripper with middleware. - roundTripper := InstrumentRoundTripperInFlight(inFlightGauge, - InstrumentRoundTripperCounter(counter, - InstrumentRoundTripperTrace(trace, - InstrumentRoundTripperDuration(histVec, http.DefaultTransport), - ), - ), - ) - - // Set the RoundTripper on our client. - client.Transport = roundTripper - - resp, err := client.Get("http://google.com") - if err != nil { - log.Printf("error: %v", err) - } - defer resp.Body.Close() -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go deleted file mode 100644 index 9db243805..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package promhttp - -import ( - "errors" - "net/http" - "strconv" - "strings" - "time" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -// magicString is used for the hacky label test in checkLabels. Remove once fixed. -const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa" - -// InstrumentHandlerInFlight is a middleware that wraps the provided -// http.Handler. It sets the provided prometheus.Gauge to the number of -// requests currently handled by the wrapped http.Handler. -// -// See the example for InstrumentHandlerDuration for example usage. -func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - g.Inc() - defer g.Dec() - next.ServeHTTP(w, r) - }) -} - -// InstrumentHandlerDuration is a middleware that wraps the provided -// http.Handler to observe the request duration with the provided ObserverVec. -// The ObserverVec must have zero, one, or two non-const non-curried labels. For -// those, the only allowed label names are "code" and "method". The function -// panics otherwise. The Observe method of the Observer in the ObserverVec is -// called with the request duration in seconds. Partitioning happens by HTTP -// status code and/or HTTP method if the respective instance label names are -// present in the ObserverVec. For unpartitioned observations, use an -// ObserverVec with zero labels. Note that partitioning of Histograms is -// expensive and should be used judiciously. -// -// If the wrapped Handler does not set a status code, a status code of 200 is assumed. -// -// If the wrapped Handler panics, no values are reported. -// -// Note that this method is only guaranteed to never observe negative durations -// if used with Go1.9+. -func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { - code, method := checkLabels(obs) - - if code { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - now := time.Now() - d := newDelegator(w, nil) - next.ServeHTTP(d, r) - - obs.With(labels(code, method, r.Method, d.Status())).Observe(time.Since(now).Seconds()) - }) - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - now := time.Now() - next.ServeHTTP(w, r) - obs.With(labels(code, method, r.Method, 0)).Observe(time.Since(now).Seconds()) - }) -} - -// InstrumentHandlerCounter is a middleware that wraps the provided http.Handler -// to observe the request result with the provided CounterVec. The CounterVec -// must have zero, one, or two non-const non-curried labels. For those, the only -// allowed label names are "code" and "method". The function panics -// otherwise. Partitioning of the CounterVec happens by HTTP status code and/or -// HTTP method if the respective instance label names are present in the -// CounterVec. For unpartitioned counting, use a CounterVec with zero labels. -// -// If the wrapped Handler does not set a status code, a status code of 200 is assumed. -// -// If the wrapped Handler panics, the Counter is not incremented. -// -// See the example for InstrumentHandlerDuration for example usage. -func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc { - code, method := checkLabels(counter) - - if code { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - d := newDelegator(w, nil) - next.ServeHTTP(d, r) - counter.With(labels(code, method, r.Method, d.Status())).Inc() - }) - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r) - counter.With(labels(code, method, r.Method, 0)).Inc() - }) -} - -// InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided -// http.Handler to observe with the provided ObserverVec the request duration -// until the response headers are written. The ObserverVec must have zero, one, -// or two non-const non-curried labels. For those, the only allowed label names -// are "code" and "method". The function panics otherwise. The Observe method of -// the Observer in the ObserverVec is called with the request duration in -// seconds. Partitioning happens by HTTP status code and/or HTTP method if the -// respective instance label names are present in the ObserverVec. For -// unpartitioned observations, use an ObserverVec with zero labels. Note that -// partitioning of Histograms is expensive and should be used judiciously. -// -// If the wrapped Handler panics before calling WriteHeader, no value is -// reported. -// -// Note that this method is only guaranteed to never observe negative durations -// if used with Go1.9+. -// -// See the example for InstrumentHandlerDuration for example usage. -func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { - code, method := checkLabels(obs) - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - now := time.Now() - d := newDelegator(w, func(status int) { - obs.With(labels(code, method, r.Method, status)).Observe(time.Since(now).Seconds()) - }) - next.ServeHTTP(d, r) - }) -} - -// InstrumentHandlerRequestSize is a middleware that wraps the provided -// http.Handler to observe the request size with the provided ObserverVec. The -// ObserverVec must have zero, one, or two non-const non-curried labels. For -// those, the only allowed label names are "code" and "method". The function -// panics otherwise. The Observe method of the Observer in the ObserverVec is -// called with the request size in bytes. Partitioning happens by HTTP status -// code and/or HTTP method if the respective instance label names are present in -// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero -// labels. Note that partitioning of Histograms is expensive and should be used -// judiciously. -// -// If the wrapped Handler does not set a status code, a status code of 200 is assumed. -// -// If the wrapped Handler panics, no values are reported. -// -// See the example for InstrumentHandlerDuration for example usage. -func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler) http.HandlerFunc { - code, method := checkLabels(obs) - - if code { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - d := newDelegator(w, nil) - next.ServeHTTP(d, r) - size := computeApproximateRequestSize(r) - obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(size)) - }) - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r) - size := computeApproximateRequestSize(r) - obs.With(labels(code, method, r.Method, 0)).Observe(float64(size)) - }) -} - -// InstrumentHandlerResponseSize is a middleware that wraps the provided -// http.Handler to observe the response size with the provided ObserverVec. The -// ObserverVec must have zero, one, or two non-const non-curried labels. For -// those, the only allowed label names are "code" and "method". The function -// panics otherwise. The Observe method of the Observer in the ObserverVec is -// called with the response size in bytes. Partitioning happens by HTTP status -// code and/or HTTP method if the respective instance label names are present in -// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero -// labels. Note that partitioning of Histograms is expensive and should be used -// judiciously. -// -// If the wrapped Handler does not set a status code, a status code of 200 is assumed. -// -// If the wrapped Handler panics, no values are reported. -// -// See the example for InstrumentHandlerDuration for example usage. -func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler) http.Handler { - code, method := checkLabels(obs) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - d := newDelegator(w, nil) - next.ServeHTTP(d, r) - obs.With(labels(code, method, r.Method, d.Status())).Observe(float64(d.Written())) - }) -} - -func checkLabels(c prometheus.Collector) (code bool, method bool) { - // TODO(beorn7): Remove this hacky way to check for instance labels - // once Descriptors can have their dimensionality queried. - var ( - desc *prometheus.Desc - m prometheus.Metric - pm dto.Metric - lvs []string - ) - - // Get the Desc from the Collector. - descc := make(chan *prometheus.Desc, 1) - c.Describe(descc) - - select { - case desc = <-descc: - default: - panic("no description provided by collector") - } - select { - case <-descc: - panic("more than one description provided by collector") - default: - } - - close(descc) - - // Create a ConstMetric with the Desc. Since we don't know how many - // variable labels there are, try for as long as it needs. - for err := errors.New("dummy"); err != nil; lvs = append(lvs, magicString) { - m, err = prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, lvs...) - } - - // Write out the metric into a proto message and look at the labels. - // If the value is not the magicString, it is a constLabel, which doesn't interest us. - // If the label is curried, it doesn't interest us. - // In all other cases, only "code" or "method" is allowed. - if err := m.Write(&pm); err != nil { - panic("error checking metric for labels") - } - for _, label := range pm.Label { - name, value := label.GetName(), label.GetValue() - if value != magicString || isLabelCurried(c, name) { - continue - } - switch name { - case "code": - code = true - case "method": - method = true - default: - panic("metric partitioned with non-supported labels") - } - } - return -} - -func isLabelCurried(c prometheus.Collector, label string) bool { - // This is even hackier than the label test above. - // We essentially try to curry again and see if it works. - // But for that, we need to type-convert to the two - // types we use here, ObserverVec or *CounterVec. - switch v := c.(type) { - case *prometheus.CounterVec: - if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil { - return false - } - case prometheus.ObserverVec: - if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil { - return false - } - default: - panic("unsupported metric vec type") - } - return true -} - -// emptyLabels is a one-time allocation for non-partitioned metrics to avoid -// unnecessary allocations on each request. -var emptyLabels = prometheus.Labels{} - -func labels(code, method bool, reqMethod string, status int) prometheus.Labels { - if !(code || method) { - return emptyLabels - } - labels := prometheus.Labels{} - - if code { - labels["code"] = sanitizeCode(status) - } - if method { - labels["method"] = sanitizeMethod(reqMethod) - } - - return labels -} - -func computeApproximateRequestSize(r *http.Request) int { - s := 0 - if r.URL != nil { - s += len(r.URL.String()) - } - - s += len(r.Method) - s += len(r.Proto) - for name, values := range r.Header { - s += len(name) - for _, value := range values { - s += len(value) - } - } - s += len(r.Host) - - // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL. - - if r.ContentLength != -1 { - s += int(r.ContentLength) - } - return s -} - -func sanitizeMethod(m string) string { - switch m { - case "GET", "get": - return "get" - case "PUT", "put": - return "put" - case "HEAD", "head": - return "head" - case "POST", "post": - return "post" - case "DELETE", "delete": - return "delete" - case "CONNECT", "connect": - return "connect" - case "OPTIONS", "options": - return "options" - case "NOTIFY", "notify": - return "notify" - default: - return strings.ToLower(m) - } -} - -// If the wrapped http.Handler has not set a status code, i.e. the value is -// currently 0, santizeCode will return 200, for consistency with behavior in -// the stdlib. -func sanitizeCode(s int) string { - switch s { - case 100: - return "100" - case 101: - return "101" - - case 200, 0: - return "200" - case 201: - return "201" - case 202: - return "202" - case 203: - return "203" - case 204: - return "204" - case 205: - return "205" - case 206: - return "206" - - case 300: - return "300" - case 301: - return "301" - case 302: - return "302" - case 304: - return "304" - case 305: - return "305" - case 307: - return "307" - - case 400: - return "400" - case 401: - return "401" - case 402: - return "402" - case 403: - return "403" - case 404: - return "404" - case 405: - return "405" - case 406: - return "406" - case 407: - return "407" - case 408: - return "408" - case 409: - return "409" - case 410: - return "410" - case 411: - return "411" - case 412: - return "412" - case 413: - return "413" - case 414: - return "414" - case 415: - return "415" - case 416: - return "416" - case 417: - return "417" - case 418: - return "418" - - case 500: - return "500" - case 501: - return "501" - case 502: - return "502" - case 503: - return "503" - case 504: - return "504" - case 505: - return "505" - - case 428: - return "428" - case 429: - return "429" - case 431: - return "431" - case 511: - return "511" - - default: - return strconv.Itoa(s) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go deleted file mode 100644 index 716c6f45e..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server_test.go +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package promhttp - -import ( - "io" - "log" - "net/http" - "net/http/httptest" - "testing" - - "github.com/prometheus/client_golang/prometheus" -) - -func TestLabelCheck(t *testing.T) { - scenarios := map[string]struct { - varLabels []string - constLabels []string - curriedLabels []string - ok bool - }{ - "empty": { - varLabels: []string{}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: true, - }, - "code as single var label": { - varLabels: []string{"code"}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: true, - }, - "method as single var label": { - varLabels: []string{"method"}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: true, - }, - "cade and method as var labels": { - varLabels: []string{"method", "code"}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: true, - }, - "valid case with all labels used": { - varLabels: []string{"code", "method"}, - constLabels: []string{"foo", "bar"}, - curriedLabels: []string{"dings", "bums"}, - ok: true, - }, - "unsupported var label": { - varLabels: []string{"foo"}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: false, - }, - "mixed var labels": { - varLabels: []string{"method", "foo", "code"}, - constLabels: []string{}, - curriedLabels: []string{}, - ok: false, - }, - "unsupported var label but curried": { - varLabels: []string{}, - constLabels: []string{}, - curriedLabels: []string{"foo"}, - ok: true, - }, - "mixed var labels but unsupported curried": { - varLabels: []string{"code", "method"}, - constLabels: []string{}, - curriedLabels: []string{"foo"}, - ok: true, - }, - "supported label as const and curry": { - varLabels: []string{}, - constLabels: []string{"code"}, - curriedLabels: []string{"method"}, - ok: true, - }, - "supported label as const and curry with unsupported as var": { - varLabels: []string{"foo"}, - constLabels: []string{"code"}, - curriedLabels: []string{"method"}, - ok: false, - }, - } - - for name, sc := range scenarios { - t.Run(name, func(t *testing.T) { - constLabels := prometheus.Labels{} - for _, l := range sc.constLabels { - constLabels[l] = "dummy" - } - c := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "c", - Help: "c help", - ConstLabels: constLabels, - }, - append(sc.varLabels, sc.curriedLabels...), - ) - o := prometheus.ObserverVec(prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "c", - Help: "c help", - ConstLabels: constLabels, - }, - append(sc.varLabels, sc.curriedLabels...), - )) - for _, l := range sc.curriedLabels { - c = c.MustCurryWith(prometheus.Labels{l: "dummy"}) - o = o.MustCurryWith(prometheus.Labels{l: "dummy"}) - } - - func() { - defer func() { - if err := recover(); err != nil { - if sc.ok { - t.Error("unexpected panic:", err) - } - } else if !sc.ok { - t.Error("expected panic") - } - }() - InstrumentHandlerCounter(c, nil) - }() - func() { - defer func() { - if err := recover(); err != nil { - if sc.ok { - t.Error("unexpected panic:", err) - } - } else if !sc.ok { - t.Error("expected panic") - } - }() - InstrumentHandlerDuration(o, nil) - }() - if sc.ok { - // Test if wantCode and wantMethod were detected correctly. - var wantCode, wantMethod bool - for _, l := range sc.varLabels { - if l == "code" { - wantCode = true - } - if l == "method" { - wantMethod = true - } - } - gotCode, gotMethod := checkLabels(c) - if gotCode != wantCode { - t.Errorf("wanted code=%t for counter, got code=%t", wantCode, gotCode) - } - if gotMethod != wantMethod { - t.Errorf("wanted method=%t for counter, got method=%t", wantMethod, gotMethod) - } - gotCode, gotMethod = checkLabels(o) - if gotCode != wantCode { - t.Errorf("wanted code=%t for observer, got code=%t", wantCode, gotCode) - } - if gotMethod != wantMethod { - t.Errorf("wanted method=%t for observer, got method=%t", wantMethod, gotMethod) - } - } - }) - } -} - -func TestMiddlewareAPI(t *testing.T) { - reg := prometheus.NewRegistry() - - inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "in_flight_requests", - Help: "A gauge of requests currently being served by the wrapped handler.", - }) - - counter := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "api_requests_total", - Help: "A counter for requests to the wrapped handler.", - }, - []string{"code", "method"}, - ) - - histVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "response_duration_seconds", - Help: "A histogram of request latencies.", - Buckets: prometheus.DefBuckets, - ConstLabels: prometheus.Labels{"handler": "api"}, - }, - []string{"method"}, - ) - - writeHeaderVec := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "write_header_duration_seconds", - Help: "A histogram of time to first write latencies.", - Buckets: prometheus.DefBuckets, - ConstLabels: prometheus.Labels{"handler": "api"}, - }, - []string{}, - ) - - responseSize := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "push_request_size_bytes", - Help: "A histogram of request sizes for requests.", - Buckets: []float64{200, 500, 900, 1500}, - }, - []string{}, - ) - - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("OK")) - }) - - reg.MustRegister(inFlightGauge, counter, histVec, responseSize, writeHeaderVec) - - chain := InstrumentHandlerInFlight(inFlightGauge, - InstrumentHandlerCounter(counter, - InstrumentHandlerDuration(histVec, - InstrumentHandlerTimeToWriteHeader(writeHeaderVec, - InstrumentHandlerResponseSize(responseSize, handler), - ), - ), - ), - ) - - r, _ := http.NewRequest("GET", "www.example.com", nil) - w := httptest.NewRecorder() - chain.ServeHTTP(w, r) -} - -func TestInstrumentTimeToFirstWrite(t *testing.T) { - var i int - dobs := &responseWriterDelegator{ - ResponseWriter: httptest.NewRecorder(), - observeWriteHeader: func(status int) { - i = status - }, - } - d := newDelegator(dobs, nil) - - d.WriteHeader(http.StatusOK) - - if i != http.StatusOK { - t.Fatalf("failed to execute observeWriteHeader") - } -} - -// testResponseWriter is an http.ResponseWriter that also implements -// http.CloseNotifier, http.Flusher, and io.ReaderFrom. -type testResponseWriter struct { - closeNotifyCalled, flushCalled, readFromCalled bool -} - -func (t *testResponseWriter) Header() http.Header { return nil } -func (t *testResponseWriter) Write([]byte) (int, error) { return 0, nil } -func (t *testResponseWriter) WriteHeader(int) {} -func (t *testResponseWriter) CloseNotify() <-chan bool { - t.closeNotifyCalled = true - return nil -} -func (t *testResponseWriter) Flush() { t.flushCalled = true } -func (t *testResponseWriter) ReadFrom(io.Reader) (int64, error) { - t.readFromCalled = true - return 0, nil -} - -// testFlusher is an http.ResponseWriter that also implements http.Flusher. -type testFlusher struct { - flushCalled bool -} - -func (t *testFlusher) Header() http.Header { return nil } -func (t *testFlusher) Write([]byte) (int, error) { return 0, nil } -func (t *testFlusher) WriteHeader(int) {} -func (t *testFlusher) Flush() { t.flushCalled = true } - -func TestInterfaceUpgrade(t *testing.T) { - w := &testResponseWriter{} - d := newDelegator(w, nil) - d.(http.CloseNotifier).CloseNotify() - if !w.closeNotifyCalled { - t.Error("CloseNotify not called") - } - d.(http.Flusher).Flush() - if !w.flushCalled { - t.Error("Flush not called") - } - d.(io.ReaderFrom).ReadFrom(nil) - if !w.readFromCalled { - t.Error("ReadFrom not called") - } - if _, ok := d.(http.Hijacker); ok { - t.Error("delegator unexpectedly implements http.Hijacker") - } - - f := &testFlusher{} - d = newDelegator(f, nil) - if _, ok := d.(http.CloseNotifier); ok { - t.Error("delegator unexpectedly implements http.CloseNotifier") - } - d.(http.Flusher).Flush() - if !w.flushCalled { - t.Error("Flush not called") - } - if _, ok := d.(io.ReaderFrom); ok { - t.Error("delegator unexpectedly implements io.ReaderFrom") - } - if _, ok := d.(http.Hijacker); ok { - t.Error("delegator unexpectedly implements http.Hijacker") - } -} - -func ExampleInstrumentHandlerDuration() { - inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "in_flight_requests", - Help: "A gauge of requests currently being served by the wrapped handler.", - }) - - counter := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "api_requests_total", - Help: "A counter for requests to the wrapped handler.", - }, - []string{"code", "method"}, - ) - - // duration is partitioned by the HTTP method and handler. It uses custom - // buckets based on the expected request duration. - duration := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "request_duration_seconds", - Help: "A histogram of latencies for requests.", - Buckets: []float64{.25, .5, 1, 2.5, 5, 10}, - }, - []string{"handler", "method"}, - ) - - // responseSize has no labels, making it a zero-dimensional - // ObserverVec. - responseSize := prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "response_size_bytes", - Help: "A histogram of response sizes for requests.", - Buckets: []float64{200, 500, 900, 1500}, - }, - []string{}, - ) - - // Create the handlers that will be wrapped by the middleware. - pushHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Push")) - }) - pullHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Pull")) - }) - - // Register all of the metrics in the standard registry. - prometheus.MustRegister(inFlightGauge, counter, duration, responseSize) - - // Instrument the handlers with all the metrics, injecting the "handler" - // label by currying. - pushChain := InstrumentHandlerInFlight(inFlightGauge, - InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "push"}), - InstrumentHandlerCounter(counter, - InstrumentHandlerResponseSize(responseSize, pushHandler), - ), - ), - ) - pullChain := InstrumentHandlerInFlight(inFlightGauge, - InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "pull"}), - InstrumentHandlerCounter(counter, - InstrumentHandlerResponseSize(responseSize, pullHandler), - ), - ), - ) - - http.Handle("/metrics", Handler()) - http.Handle("/push", pushChain) - http.Handle("/pull", pullChain) - - if err := http.ListenAndServe(":3000", nil); err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/deprecated.go b/vendor/github.com/prometheus/client_golang/prometheus/push/deprecated.go deleted file mode 100644 index 3d62b5725..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/deprecated.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2018 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package push - -// This file contains only deprecated code. Remove after v0.9 is released. - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/common/model" - - "github.com/prometheus/client_golang/prometheus" -) - -// FromGatherer triggers a metric collection by the provided Gatherer (which is -// usually implemented by a prometheus.Registry) and pushes all gathered metrics -// to the Pushgateway specified by url, using the provided job name and the -// (optional) further grouping labels (the grouping map may be nil). See the -// Pushgateway documentation for detailed implications of the job and other -// grouping labels. Neither the job name nor any grouping label value may -// contain a "/". The metrics pushed must not contain a job label of their own -// nor any of the grouping labels. -// -// You can use just host:port or ip:port as url, in which case 'http://' is -// added automatically. You can also include the schema in the URL. However, do -// not include the '/metrics/jobs/...' part. -// -// Note that all previously pushed metrics with the same job and other grouping -// labels will be replaced with the metrics pushed by this call. (It uses HTTP -// method 'PUT' to push to the Pushgateway.) -// -// Deprecated: Please use a Pusher created with New instead. -func FromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error { - return push(job, grouping, url, g, "PUT") -} - -// AddFromGatherer works like FromGatherer, but only previously pushed metrics -// with the same name (and the same job and other grouping labels) will be -// replaced. (It uses HTTP method 'POST' to push to the Pushgateway.) -// -// Deprecated: Please use a Pusher created with New instead. -func AddFromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error { - return push(job, grouping, url, g, "POST") -} - -func push(job string, grouping map[string]string, pushURL string, g prometheus.Gatherer, method string) error { - if !strings.Contains(pushURL, "://") { - pushURL = "http://" + pushURL - } - if strings.HasSuffix(pushURL, "/") { - pushURL = pushURL[:len(pushURL)-1] - } - - if strings.Contains(job, "/") { - return fmt.Errorf("job contains '/': %s", job) - } - urlComponents := []string{url.QueryEscape(job)} - for ln, lv := range grouping { - if !model.LabelName(ln).IsValid() { - return fmt.Errorf("grouping label has invalid name: %s", ln) - } - if strings.Contains(lv, "/") { - return fmt.Errorf("value of grouping label %s contains '/': %s", ln, lv) - } - urlComponents = append(urlComponents, ln, lv) - } - pushURL = fmt.Sprintf("%s/metrics/job/%s", pushURL, strings.Join(urlComponents, "/")) - - mfs, err := g.Gather() - if err != nil { - return err - } - buf := &bytes.Buffer{} - enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - // Check for pre-existing grouping labels: - for _, mf := range mfs { - for _, m := range mf.GetMetric() { - for _, l := range m.GetLabel() { - if l.GetName() == "job" { - return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m) - } - if _, ok := grouping[l.GetName()]; ok { - return fmt.Errorf( - "pushed metric %s (%s) already contains grouping label %s", - mf.GetName(), m, l.GetName(), - ) - } - } - } - enc.Encode(mf) - } - req, err := http.NewRequest(method, pushURL, buf) - if err != nil { - return err - } - req.Header.Set(contentTypeHeader, string(expfmt.FmtProtoDelim)) - resp, err := http.DefaultClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != 202 { - body, _ := ioutil.ReadAll(resp.Body) // Ignore any further error as this is for an error message only. - return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, pushURL, body) - } - return nil -} - -// Collectors works like FromGatherer, but it does not use a Gatherer. Instead, -// it collects from the provided collectors directly. It is a convenient way to -// push only a few metrics. -// -// Deprecated: Please use a Pusher created with New instead. -func Collectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error { - return pushCollectors(job, grouping, url, "PUT", collectors...) -} - -// AddCollectors works like AddFromGatherer, but it does not use a Gatherer. -// Instead, it collects from the provided collectors directly. It is a -// convenient way to push only a few metrics. -// -// Deprecated: Please use a Pusher created with New instead. -func AddCollectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error { - return pushCollectors(job, grouping, url, "POST", collectors...) -} - -func pushCollectors(job string, grouping map[string]string, url, method string, collectors ...prometheus.Collector) error { - r := prometheus.NewRegistry() - for _, collector := range collectors { - if err := r.Register(collector); err != nil { - return err - } - } - return push(job, grouping, url, r, method) -} - -// HostnameGroupingKey returns a label map with the only entry -// {instance=""}. This can be conveniently used as the grouping -// parameter if metrics should be pushed with the hostname as label. The -// returned map is created upon each call so that the caller is free to add more -// labels to the map. -// -// Deprecated: Usually, metrics pushed to the Pushgateway should not be -// host-centric. (You would use https://github.com/prometheus/node_exporter in -// that case.) If you have the need to add the hostname to the grouping key, you -// are probably doing something wrong. See -// https://prometheus.io/docs/practices/pushing/ for details. -func HostnameGroupingKey() map[string]string { - hostname, err := os.Hostname() - if err != nil { - return map[string]string{"instance": "unknown"} - } - return map[string]string{"instance": hostname} -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go deleted file mode 100644 index dd22b526a..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/example_add_from_gatherer_test.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package push_test - -import ( - "fmt" - "time" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/push" -) - -var ( - completionTime = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_timestamp_seconds", - Help: "The timestamp of the last completion of a DB backup, successful or not.", - }) - successTime = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_success_timestamp_seconds", - Help: "The timestamp of the last successful completion of a DB backup.", - }) - duration = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_duration_seconds", - Help: "The duration of the last DB backup in seconds.", - }) - records = prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_records_processed", - Help: "The number of records processed in the last DB backup.", - }) -) - -func performBackup() (int, error) { - // Perform the backup and return the number of backed up records and any - // applicable error. - // ... - return 42, nil -} - -func ExamplePusher_Add() { - // We use a registry here to benefit from the consistency checks that - // happen during registration. - registry := prometheus.NewRegistry() - registry.MustRegister(completionTime, duration, records) - // Note that successTime is not registered. - - pusher := push.New("http://pushgateway:9091", "db_backup").Gatherer(registry) - - start := time.Now() - n, err := performBackup() - records.Set(float64(n)) - // Note that time.Since only uses a monotonic clock in Go1.9+. - duration.Set(time.Since(start).Seconds()) - completionTime.SetToCurrentTime() - if err != nil { - fmt.Println("DB backup failed:", err) - } else { - // Add successTime to pusher only in case of success. - // We could as well register it with the registry. - // This example, however, demonstrates that you can - // mix Gatherers and Collectors when handling a Pusher. - pusher.Collector(successTime) - successTime.SetToCurrentTime() - } - // Add is used here rather than Push to not delete a previously pushed - // success timestamp in case of a failure of this backup. - if err := pusher.Add(); err != nil { - fmt.Println("Could not push to Pushgateway:", err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go deleted file mode 100644 index fa5549a9e..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package push_test - -import ( - "fmt" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/push" -) - -func ExamplePusher_Push() { - completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_timestamp_seconds", - Help: "The timestamp of the last successful completion of a DB backup.", - }) - completionTime.SetToCurrentTime() - if err := push.New("http://pushgateway:9091", "db_backup"). - Collector(completionTime). - Grouping("db", "customers"). - Push(); err != nil { - fmt.Println("Could not push completion time to Pushgateway:", err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go deleted file mode 100644 index 02be52c38..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package push provides functions to push metrics to a Pushgateway. It uses a -// builder approach. Create a Pusher with New and then add the various options -// by using its methods, finally calling Add or Push, like this: -// -// // Easy case: -// push.New("http://example.org/metrics", "my_job").Gatherer(myRegistry).Push() -// -// // Complex case: -// push.New("http://example.org/metrics", "my_job"). -// Collector(myCollector1). -// Collector(myCollector2). -// Grouping("zone", "xy"). -// Client(&myHTTPClient). -// BasicAuth("top", "secret"). -// Add() -// -// See the examples section for more detailed examples. -// -// See the documentation of the Pushgateway to understand the meaning of -// the grouping key and the differences between Push and Add: -// https://github.com/prometheus/pushgateway -package push - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/common/model" - - "github.com/prometheus/client_golang/prometheus" -) - -const contentTypeHeader = "Content-Type" - -// Pusher manages a push to the Pushgateway. Use New to create one, configure it -// with its methods, and finally use the Add or Push method to push. -type Pusher struct { - error error - - url, job string - grouping map[string]string - - gatherers prometheus.Gatherers - registerer prometheus.Registerer - - client *http.Client - useBasicAuth bool - username, password string -} - -// New creates a new Pusher to push to the provided URL withe the provided job -// name. You can use just host:port or ip:port as url, in which case “http://” -// is added automatically. Alternatively, include the schema in the -// URL. However, do not include the “/metrics/jobs/…” part. -// -// Note that until https://github.com/prometheus/pushgateway/issues/97 is -// resolved, a “/” character in the job name is prohibited. -func New(url, job string) *Pusher { - var ( - reg = prometheus.NewRegistry() - err error - ) - if !strings.Contains(url, "://") { - url = "http://" + url - } - if strings.HasSuffix(url, "/") { - url = url[:len(url)-1] - } - if strings.Contains(job, "/") { - err = fmt.Errorf("job contains '/': %s", job) - } - - return &Pusher{ - error: err, - url: url, - job: job, - grouping: map[string]string{}, - gatherers: prometheus.Gatherers{reg}, - registerer: reg, - client: &http.Client{}, - } -} - -// Push collects/gathers all metrics from all Collectors and Gatherers added to -// this Pusher. Then, it pushes them to the Pushgateway configured while -// creating this Pusher, using the configured job name and any added grouping -// labels as grouping key. All previously pushed metrics with the same job and -// other grouping labels will be replaced with the metrics pushed by this -// call. (It uses HTTP method “PUT” to push to the Pushgateway.) -// -// Push returns the first error encountered by any method call (including this -// one) in the lifetime of the Pusher. -func (p *Pusher) Push() error { - return p.push("PUT") -} - -// Add works like push, but only previously pushed metrics with the same name -// (and the same job and other grouping labels) will be replaced. (It uses HTTP -// method “POST” to push to the Pushgateway.) -func (p *Pusher) Add() error { - return p.push("POST") -} - -// Gatherer adds a Gatherer to the Pusher, from which metrics will be gathered -// to push them to the Pushgateway. The gathered metrics must not contain a job -// label of their own. -// -// For convenience, this method returns a pointer to the Pusher itself. -func (p *Pusher) Gatherer(g prometheus.Gatherer) *Pusher { - p.gatherers = append(p.gatherers, g) - return p -} - -// Collector adds a Collector to the Pusher, from which metrics will be -// collected to push them to the Pushgateway. The collected metrics must not -// contain a job label of their own. -// -// For convenience, this method returns a pointer to the Pusher itself. -func (p *Pusher) Collector(c prometheus.Collector) *Pusher { - if p.error == nil { - p.error = p.registerer.Register(c) - } - return p -} - -// Grouping adds a label pair to the grouping key of the Pusher, replacing any -// previously added label pair with the same label name. Note that setting any -// labels in the grouping key that are already contained in the metrics to push -// will lead to an error. -// -// For convenience, this method returns a pointer to the Pusher itself. -// -// Note that until https://github.com/prometheus/pushgateway/issues/97 is -// resolved, this method does not allow a “/” character in the label value. -func (p *Pusher) Grouping(name, value string) *Pusher { - if p.error == nil { - if !model.LabelName(name).IsValid() { - p.error = fmt.Errorf("grouping label has invalid name: %s", name) - return p - } - if strings.Contains(value, "/") { - p.error = fmt.Errorf("value of grouping label %s contains '/': %s", name, value) - return p - } - p.grouping[name] = value - } - return p -} - -// Client sets a custom HTTP client for the Pusher. For convenience, this method -// returns a pointer to the Pusher itself. -func (p *Pusher) Client(c *http.Client) *Pusher { - p.client = c - return p -} - -// BasicAuth configures the Pusher to use HTTP Basic Authentication with the -// provided username and password. For convenience, this method returns a -// pointer to the Pusher itself. -func (p *Pusher) BasicAuth(username, password string) *Pusher { - p.useBasicAuth = true - p.username = username - p.password = password - return p -} - -func (p *Pusher) push(method string) error { - if p.error != nil { - return p.error - } - urlComponents := []string{url.QueryEscape(p.job)} - for ln, lv := range p.grouping { - urlComponents = append(urlComponents, ln, lv) - } - pushURL := fmt.Sprintf("%s/metrics/job/%s", p.url, strings.Join(urlComponents, "/")) - - mfs, err := p.gatherers.Gather() - if err != nil { - return err - } - buf := &bytes.Buffer{} - enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - // Check for pre-existing grouping labels: - for _, mf := range mfs { - for _, m := range mf.GetMetric() { - for _, l := range m.GetLabel() { - if l.GetName() == "job" { - return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m) - } - if _, ok := p.grouping[l.GetName()]; ok { - return fmt.Errorf( - "pushed metric %s (%s) already contains grouping label %s", - mf.GetName(), m, l.GetName(), - ) - } - } - } - enc.Encode(mf) - } - req, err := http.NewRequest(method, pushURL, buf) - if err != nil { - return err - } - if p.useBasicAuth { - req.SetBasicAuth(p.username, p.password) - } - req.Header.Set(contentTypeHeader, string(expfmt.FmtProtoDelim)) - resp, err := p.client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != 202 { - body, _ := ioutil.ReadAll(resp.Body) // Ignore any further error as this is for an error message only. - return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, pushURL, body) - } - return nil -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go deleted file mode 100644 index 34ec334bb..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package push - -import ( - "bytes" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/prometheus/common/expfmt" - - "github.com/prometheus/client_golang/prometheus" -) - -func TestPush(t *testing.T) { - - var ( - lastMethod string - lastBody []byte - lastPath string - ) - - // Fake a Pushgateway that always responds with 202. - pgwOK := httptest.NewServer( - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lastMethod = r.Method - var err error - lastBody, err = ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - lastPath = r.URL.EscapedPath() - w.Header().Set("Content-Type", `text/plain; charset=utf-8`) - w.WriteHeader(http.StatusAccepted) - }), - ) - defer pgwOK.Close() - - // Fake a Pushgateway that always responds with 500. - pgwErr := httptest.NewServer( - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "fake error", http.StatusInternalServerError) - }), - ) - defer pgwErr.Close() - - metric1 := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "testname1", - Help: "testhelp1", - }) - metric2 := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "testname2", - Help: "testhelp2", - ConstLabels: prometheus.Labels{"foo": "bar", "dings": "bums"}, - }) - - reg := prometheus.NewRegistry() - reg.MustRegister(metric1) - reg.MustRegister(metric2) - - mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - - buf := &bytes.Buffer{} - enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - - for _, mf := range mfs { - if err := enc.Encode(mf); err != nil { - t.Fatal(err) - } - } - wantBody := buf.Bytes() - - // Push some Collectors, all good. - if err := New(pgwOK.URL, "testjob"). - Collector(metric1). - Collector(metric2). - Push(); err != nil { - t.Fatal(err) - } - if lastMethod != "PUT" { - t.Error("want method PUT for Push, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob" { - t.Error("unexpected path:", lastPath) - } - - // Add some Collectors, with nil grouping, all good. - if err := New(pgwOK.URL, "testjob"). - Collector(metric1). - Collector(metric2). - Add(); err != nil { - t.Fatal(err) - } - if lastMethod != "POST" { - t.Error("want method POST for Add, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob" { - t.Error("unexpected path:", lastPath) - } - - // Push some Collectors with a broken PGW. - if err := New(pgwErr.URL, "testjob"). - Collector(metric1). - Collector(metric2). - Push(); err == nil { - t.Error("push to broken Pushgateway succeeded") - } else { - if got, want := err.Error(), "unexpected status code 500 while pushing to "+pgwErr.URL+"/metrics/job/testjob: fake error\n"; got != want { - t.Errorf("got error %q, want %q", got, want) - } - } - - // Push some Collectors with invalid grouping or job. - if err := New(pgwOK.URL, "testjob"). - Grouping("foo", "bums"). - Collector(metric1). - Collector(metric2). - Push(); err == nil { - t.Error("push with grouping contained in metrics succeeded") - } - if err := New(pgwOK.URL, "test/job"). - Collector(metric1). - Collector(metric2). - Push(); err == nil { - t.Error("push with invalid job value succeeded") - } - if err := New(pgwOK.URL, "testjob"). - Grouping("foobar", "bu/ms"). - Collector(metric1). - Collector(metric2). - Push(); err == nil { - t.Error("push with invalid grouping succeeded") - } - if err := New(pgwOK.URL, "testjob"). - Grouping("foo-bar", "bums"). - Collector(metric1). - Collector(metric2). - Push(); err == nil { - t.Error("push with invalid grouping succeeded") - } - - // Push registry, all good. - if err := New(pgwOK.URL, "testjob"). - Gatherer(reg). - Push(); err != nil { - t.Fatal(err) - } - if lastMethod != "PUT" { - t.Error("want method PUT for Push, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - - // Add registry, all good. - if err := New(pgwOK.URL, "testjob"). - Grouping("a", "x"). - Grouping("b", "y"). - Gatherer(reg). - Add(); err != nil { - t.Fatal(err) - } - if lastMethod != "POST" { - t.Error("want method POST for Add, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob/a/x/b/y" && lastPath != "/metrics/job/testjob/b/y/a/x" { - t.Error("unexpected path:", lastPath) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go index bee370364..32a3986b0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go @@ -18,10 +18,8 @@ import ( "errors" "fmt" "os" - "runtime" "sort" "sync" - "unicode/utf8" "github.com/golang/protobuf/proto" @@ -37,13 +35,13 @@ const ( // DefaultRegisterer and DefaultGatherer are the implementations of the // Registerer and Gatherer interface a number of convenience functions in this // package act on. Initially, both variables point to the same Registry, which -// has a process collector (currently on Linux only, see NewProcessCollector) -// and a Go collector (see NewGoCollector) already registered. This approach to -// keep default instances as global state mirrors the approach of other packages -// in the Go standard library. Note that there are caveats. Change the variables -// with caution and only if you understand the consequences. Users who want to -// avoid global state altogether should not use the convenience functions and -// act on custom instances instead. +// has a process collector (see NewProcessCollector) and a Go collector (see +// NewGoCollector) already registered. This approach to keep default instances +// as global state mirrors the approach of other packages in the Go standard +// library. Note that there are caveats. Change the variables with caution and +// only if you understand the consequences. Users who want to avoid global state +// altogether should not use the convenience function and act on custom +// instances instead. var ( defaultRegistry = NewRegistry() DefaultRegisterer Registerer = defaultRegistry @@ -82,7 +80,7 @@ func NewPedanticRegistry() *Registry { // Registerer is the interface for the part of a registry in charge of // registering and unregistering. Users of custom registries should use -// Registerer as type for registration purposes (rather than the Registry type +// Registerer as type for registration purposes (rather then the Registry type // directly). In that way, they are free to use custom Registerer implementation // (e.g. for testing purposes). type Registerer interface { @@ -154,6 +152,38 @@ func MustRegister(cs ...Collector) { DefaultRegisterer.MustRegister(cs...) } +// RegisterOrGet registers the provided Collector with the DefaultRegisterer and +// returns the Collector, unless an equal Collector was registered before, in +// which case that Collector is returned. +// +// Deprecated: RegisterOrGet is merely a convenience function for the +// implementation as described in the documentation for +// AlreadyRegisteredError. As the use case is relatively rare, this function +// will be removed in a future version of this package to clean up the +// namespace. +func RegisterOrGet(c Collector) (Collector, error) { + if err := Register(c); err != nil { + if are, ok := err.(AlreadyRegisteredError); ok { + return are.ExistingCollector, nil + } + return nil, err + } + return c, nil +} + +// MustRegisterOrGet behaves like RegisterOrGet but panics instead of returning +// an error. +// +// Deprecated: This is deprecated for the same reason RegisterOrGet is. See +// there for details. +func MustRegisterOrGet(c Collector) Collector { + c, err := RegisterOrGet(c) + if err != nil { + panic(err) + } + return c +} + // Unregister removes the registration of the provided Collector from the // DefaultRegisterer. // @@ -171,6 +201,25 @@ func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error) { return gf() } +// SetMetricFamilyInjectionHook replaces the DefaultGatherer with one that +// gathers from the previous DefaultGatherers but then merges the MetricFamily +// protobufs returned from the provided hook function with the MetricFamily +// protobufs returned from the original DefaultGatherer. +// +// Deprecated: This function manipulates the DefaultGatherer variable. Consider +// the implications, i.e. don't do this concurrently with any uses of the +// DefaultGatherer. In the rare cases where you need to inject MetricFamily +// protobufs directly, it is recommended to use a custom Registry and combine it +// with a custom Gatherer using the Gatherers type (see +// there). SetMetricFamilyInjectionHook only exists for compatibility reasons +// with previous versions of this package. +func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily) { + DefaultGatherer = Gatherers{ + DefaultGatherer, + GathererFunc(func() ([]*dto.MetricFamily, error) { return hook(), nil }), + } +} + // AlreadyRegisteredError is returned by the Register method if the Collector to // be registered has already been registered before, or a different Collector // that collects the same metrics has been registered before. Registration fails @@ -203,13 +252,6 @@ func (errs MultiError) Error() string { return buf.String() } -// Append appends the provided error if it is not nil. -func (errs *MultiError) Append(err error) { - if err != nil { - *errs = append(*errs, err) - } -} - // MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only // contained error as error if len(errs is 1). In all other cases, it returns // the MultiError directly. This is helpful for returning a MultiError in a way @@ -252,7 +294,7 @@ func (r *Registry) Register(c Collector) error { }() r.mtx.Lock() defer r.mtx.Unlock() - // Conduct various tests... + // Coduct various tests... for desc := range descChan { // Is the descriptor valid at all? @@ -376,12 +418,22 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { ) r.mtx.RLock() - goroutineBudget := len(r.collectorsByID) metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName)) - collectors := make(chan Collector, len(r.collectorsByID)) + + // Scatter. + // (Collectors could be complex and slow, so we call them all at once.) + wg.Add(len(r.collectorsByID)) + go func() { + wg.Wait() + close(metricChan) + }() for _, collector := range r.collectorsByID { - collectors <- collector + go func(collector Collector) { + defer wg.Done() + collector.Collect(metricChan) + }(collector) } + // In case pedantic checks are enabled, we have to copy the map before // giving up the RLock. if r.pedanticChecksEnabled { @@ -390,174 +442,127 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { registeredDescIDs[id] = struct{}{} } } - r.mtx.RUnlock() - wg.Add(goroutineBudget) - - collectWorker := func() { - for { - select { - case collector := <-collectors: - collector.Collect(metricChan) - wg.Done() - default: - return - } - } - } - - // Start the first worker now to make sure at least one is running. - go collectWorker() - goroutineBudget-- - - // Close the metricChan once all collectors are collected. - go func() { - wg.Wait() - close(metricChan) - }() + r.mtx.RUnlock() // Drain metricChan in case of premature return. defer func() { - for range metricChan { + for _ = range metricChan { } }() -collectLoop: - for { - select { - case metric, ok := <-metricChan: - if !ok { - // metricChan is closed, we are done. - break collectLoop - } - errs.Append(processMetric( - metric, metricFamiliesByName, - metricHashes, dimHashes, - registeredDescIDs, + // Gather. + for metric := range metricChan { + // This could be done concurrently, too, but it required locking + // of metricFamiliesByName (and of metricHashes if checks are + // enabled). Most likely not worth it. + desc := metric.Desc() + dtoMetric := &dto.Metric{} + if err := metric.Write(dtoMetric); err != nil { + errs = append(errs, fmt.Errorf( + "error collecting metric %v: %s", desc, err, )) - default: - if goroutineBudget <= 0 || len(collectors) == 0 { - // All collectors are aleady being worked on or - // we have already as many goroutines started as - // there are collectors. Just process metrics - // from now on. - for metric := range metricChan { - errs.Append(processMetric( - metric, metricFamiliesByName, - metricHashes, dimHashes, - registeredDescIDs, + continue + } + metricFamily, ok := metricFamiliesByName[desc.fqName] + if ok { + if metricFamily.GetHelp() != desc.help { + errs = append(errs, fmt.Errorf( + "collected metric %s %s has help %q but should have %q", + desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(), + )) + continue + } + // TODO(beorn7): Simplify switch once Desc has type. + switch metricFamily.GetType() { + case dto.MetricType_COUNTER: + if dtoMetric.Counter == nil { + errs = append(errs, fmt.Errorf( + "collected metric %s %s should be a Counter", + desc.fqName, dtoMetric, + )) + continue + } + case dto.MetricType_GAUGE: + if dtoMetric.Gauge == nil { + errs = append(errs, fmt.Errorf( + "collected metric %s %s should be a Gauge", + desc.fqName, dtoMetric, + )) + continue + } + case dto.MetricType_SUMMARY: + if dtoMetric.Summary == nil { + errs = append(errs, fmt.Errorf( + "collected metric %s %s should be a Summary", + desc.fqName, dtoMetric, + )) + continue + } + case dto.MetricType_UNTYPED: + if dtoMetric.Untyped == nil { + errs = append(errs, fmt.Errorf( + "collected metric %s %s should be Untyped", + desc.fqName, dtoMetric, + )) + continue + } + case dto.MetricType_HISTOGRAM: + if dtoMetric.Histogram == nil { + errs = append(errs, fmt.Errorf( + "collected metric %s %s should be a Histogram", + desc.fqName, dtoMetric, )) + continue } - break collectLoop + default: + panic("encountered MetricFamily with invalid type") } - // Start more workers. - go collectWorker() - goroutineBudget-- - runtime.Gosched() + } else { + metricFamily = &dto.MetricFamily{} + metricFamily.Name = proto.String(desc.fqName) + metricFamily.Help = proto.String(desc.help) + // TODO(beorn7): Simplify switch once Desc has type. + switch { + case dtoMetric.Gauge != nil: + metricFamily.Type = dto.MetricType_GAUGE.Enum() + case dtoMetric.Counter != nil: + metricFamily.Type = dto.MetricType_COUNTER.Enum() + case dtoMetric.Summary != nil: + metricFamily.Type = dto.MetricType_SUMMARY.Enum() + case dtoMetric.Untyped != nil: + metricFamily.Type = dto.MetricType_UNTYPED.Enum() + case dtoMetric.Histogram != nil: + metricFamily.Type = dto.MetricType_HISTOGRAM.Enum() + default: + errs = append(errs, fmt.Errorf( + "empty metric collected: %s", dtoMetric, + )) + continue + } + metricFamiliesByName[desc.fqName] = metricFamily } - } - return normalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() -} - -// processMetric is an internal helper method only used by the Gather method. -func processMetric( - metric Metric, - metricFamiliesByName map[string]*dto.MetricFamily, - metricHashes map[uint64]struct{}, - dimHashes map[string]uint64, - registeredDescIDs map[uint64]struct{}, -) error { - desc := metric.Desc() - dtoMetric := &dto.Metric{} - if err := metric.Write(dtoMetric); err != nil { - return fmt.Errorf("error collecting metric %v: %s", desc, err) - } - metricFamily, ok := metricFamiliesByName[desc.fqName] - if ok { - if metricFamily.GetHelp() != desc.help { - return fmt.Errorf( - "collected metric %s %s has help %q but should have %q", - desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(), - ) + if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes, dimHashes); err != nil { + errs = append(errs, err) + continue } - // TODO(beorn7): Simplify switch once Desc has type. - switch metricFamily.GetType() { - case dto.MetricType_COUNTER: - if dtoMetric.Counter == nil { - return fmt.Errorf( - "collected metric %s %s should be a Counter", - desc.fqName, dtoMetric, - ) - } - case dto.MetricType_GAUGE: - if dtoMetric.Gauge == nil { - return fmt.Errorf( - "collected metric %s %s should be a Gauge", - desc.fqName, dtoMetric, - ) + if r.pedanticChecksEnabled { + // Is the desc registered at all? + if _, exist := registeredDescIDs[desc.id]; !exist { + errs = append(errs, fmt.Errorf( + "collected metric %s %s with unregistered descriptor %s", + metricFamily.GetName(), dtoMetric, desc, + )) + continue } - case dto.MetricType_SUMMARY: - if dtoMetric.Summary == nil { - return fmt.Errorf( - "collected metric %s %s should be a Summary", - desc.fqName, dtoMetric, - ) + if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil { + errs = append(errs, err) + continue } - case dto.MetricType_UNTYPED: - if dtoMetric.Untyped == nil { - return fmt.Errorf( - "collected metric %s %s should be Untyped", - desc.fqName, dtoMetric, - ) - } - case dto.MetricType_HISTOGRAM: - if dtoMetric.Histogram == nil { - return fmt.Errorf( - "collected metric %s %s should be a Histogram", - desc.fqName, dtoMetric, - ) - } - default: - panic("encountered MetricFamily with invalid type") - } - } else { - metricFamily = &dto.MetricFamily{} - metricFamily.Name = proto.String(desc.fqName) - metricFamily.Help = proto.String(desc.help) - // TODO(beorn7): Simplify switch once Desc has type. - switch { - case dtoMetric.Gauge != nil: - metricFamily.Type = dto.MetricType_GAUGE.Enum() - case dtoMetric.Counter != nil: - metricFamily.Type = dto.MetricType_COUNTER.Enum() - case dtoMetric.Summary != nil: - metricFamily.Type = dto.MetricType_SUMMARY.Enum() - case dtoMetric.Untyped != nil: - metricFamily.Type = dto.MetricType_UNTYPED.Enum() - case dtoMetric.Histogram != nil: - metricFamily.Type = dto.MetricType_HISTOGRAM.Enum() - default: - return fmt.Errorf("empty metric collected: %s", dtoMetric) - } - metricFamiliesByName[desc.fqName] = metricFamily - } - if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes, dimHashes); err != nil { - return err - } - if registeredDescIDs != nil { - // Is the desc registered at all? - if _, exist := registeredDescIDs[desc.id]; !exist { - return fmt.Errorf( - "collected metric %s %s with unregistered descriptor %s", - metricFamily.GetName(), dtoMetric, desc, - ) - } - if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil { - return err } + metricFamily.Metric = append(metricFamily.Metric, dtoMetric) } - metricFamily.Metric = append(metricFamily.Metric, dtoMetric) - return nil + return normalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap() } // Gatherers is a slice of Gatherer instances that implements the Gatherer @@ -678,7 +683,7 @@ func (s metricSorter) Less(i, j int) bool { return s[i].GetTimestampMs() < s[j].GetTimestampMs() } -// normalizeMetricFamilies returns a MetricFamily slice with empty +// normalizeMetricFamilies returns a MetricFamily slice whith empty // MetricFamilies pruned and the remaining MetricFamilies sorted by name within // the slice, with the contained Metrics sorted within each MetricFamily. func normalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily { @@ -701,7 +706,7 @@ func normalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) // checkMetricConsistency checks if the provided Metric is consistent with the // provided MetricFamily. It also hashed the Metric labels and the MetricFamily -// name. If the resulting hash is already in the provided metricHashes, an error +// name. If the resulting hash is alread in the provided metricHashes, an error // is returned. If not, it is added to metricHashes. The provided dimHashes maps // MetricFamily names to their dimHash (hashed sorted label names). If dimHashes // doesn't yet contain a hash for the provided MetricFamily, it is @@ -725,12 +730,6 @@ func checkMetricConsistency( ) } - for _, labelPair := range dtoMetric.GetLabel() { - if !utf8.ValidString(*labelPair.Value) { - return fmt.Errorf("collected metric's label %s is not utf8: %#v", *labelPair.Name, *labelPair.Value) - } - } - // Is the metric unique (i.e. no other metric with the same name and the same label values)? h := hashNew() h = hashAdd(h, metricFamily.GetName()) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go deleted file mode 100644 index d136bba1e..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go +++ /dev/null @@ -1,590 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Copyright (c) 2013, The Prometheus Authors -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. - -package prometheus_test - -import ( - "bytes" - "net/http" - "net/http/httptest" - "testing" - - dto "github.com/prometheus/client_model/go" - - "github.com/golang/protobuf/proto" - "github.com/prometheus/common/expfmt" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -func testHandler(t testing.TB) { - - metricVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - - metricVec.WithLabelValues("val1").Inc() - metricVec.WithLabelValues("val2").Inc() - - externalMetricFamily := &dto.MetricFamily{ - Name: proto.String("externalname"), - Help: proto.String("externaldocstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("externalconstname"), - Value: proto.String("externalconstvalue"), - }, - { - Name: proto.String("externallabelname"), - Value: proto.String("externalval1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - externalBuf := &bytes.Buffer{} - enc := expfmt.NewEncoder(externalBuf, expfmt.FmtProtoDelim) - if err := enc.Encode(externalMetricFamily); err != nil { - t.Fatal(err) - } - externalMetricFamilyAsBytes := externalBuf.Bytes() - externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring -# TYPE externalname counter -externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 -`) - externalMetricFamilyAsProtoText := []byte(`name: "externalname" -help: "externaldocstring" -type: COUNTER -metric: < - label: < - name: "externalconstname" - value: "externalconstvalue" - > - label: < - name: "externallabelname" - value: "externalval1" - > - counter: < - value: 1 - > -> - -`) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) - - expectedMetricFamily := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - buf := &bytes.Buffer{} - enc = expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - if err := enc.Encode(expectedMetricFamily); err != nil { - t.Fatal(err) - } - expectedMetricFamilyAsBytes := buf.Bytes() - expectedMetricFamilyAsText := []byte(`# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -`) - expectedMetricFamilyAsProtoText := []byte(`name: "name" -help: "docstring" -type: COUNTER -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val1" - > - counter: < - value: 1 - > -> -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val2" - > - counter: < - value: 1 - > -> - -`) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithSameName := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithInvalidLabelValue := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("\xFF"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyInvalidLabelValueAsText := []byte(`An error has occurred during metrics gathering: - -collected metric's label constname is not utf8: "\xff" -`) - - type output struct { - headers map[string]string - body []byte - } - - var scenarios = []struct { - headers map[string]string - out output - collector prometheus.Collector - externalMF []*dto.MetricFamily - }{ - { // 0 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 1 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/quark;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 2 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 3 - headers: map[string]string{ - "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: []byte{}, - }, - }, - { // 4 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 5 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: expectedMetricFamilyAsBytes, - }, - collector: metricVec, - }, - { // 6 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: externalMetricFamilyAsText, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 7 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: externalMetricFamilyAsBytes, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 8 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 9 - headers: map[string]string{ - "Accept": "text/plain", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 10 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 11 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsText, - expectedMetricFamilyAsText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 12 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 13 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoText, - expectedMetricFamilyAsProtoText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 14 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 15 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyMergedWithExternalAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithSameName, - }, - }, - { // 16 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; charset=utf-8`, - }, - body: expectedMetricFamilyInvalidLabelValueAsText, - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithInvalidLabelValue, - }, - }, - } - for i, scenario := range scenarios { - registry := prometheus.NewPedanticRegistry() - gatherer := prometheus.Gatherer(registry) - if scenario.externalMF != nil { - gatherer = prometheus.Gatherers{ - registry, - prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { - return scenario.externalMF, nil - }), - } - } - - if scenario.collector != nil { - registry.Register(scenario.collector) - } - writer := httptest.NewRecorder() - handler := prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})) - request, _ := http.NewRequest("GET", "/", nil) - for key, value := range scenario.headers { - request.Header.Add(key, value) - } - handler(writer, request) - - for key, value := range scenario.out.headers { - if writer.HeaderMap.Get(key) != value { - t.Errorf( - "%d. expected %q for header %q, got %q", - i, value, key, writer.Header().Get(key), - ) - } - } - - if !bytes.Equal(scenario.out.body, writer.Body.Bytes()) { - t.Errorf( - "%d. expected body:\n%s\ngot body:\n%s\n", - i, scenario.out.body, writer.Body.Bytes(), - ) - } - } -} - -func TestHandler(t *testing.T) { - testHandler(t) -} - -func BenchmarkHandler(b *testing.B) { - for i := 0; i < b.N; i++ { - testHandler(b) - } -} - -func TestRegisterWithOrGet(t *testing.T) { - // Replace the default registerer just to be sure. This is bad, but this - // whole test will go away once RegisterOrGet is removed. - oldRegisterer := prometheus.DefaultRegisterer - defer func() { - prometheus.DefaultRegisterer = oldRegisterer - }() - prometheus.DefaultRegisterer = prometheus.NewRegistry() - original := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - equalButNotSame := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - var err error - if err = prometheus.Register(original); err != nil { - t.Fatal(err) - } - if err = prometheus.Register(equalButNotSame); err == nil { - t.Fatal("expected error when registringe equal collector") - } - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - if are.ExistingCollector != original { - t.Error("expected original collector but got something else") - } - if are.ExistingCollector == equalButNotSame { - t.Error("expected original callector but got new one") - } - } else { - t.Error("unexpected error:", err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index f7dc85b96..bce05bf9a 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -36,10 +36,7 @@ const quantileLabel = "quantile" // // A typical use-case is the observation of request latencies. By default, a // Summary provides the median, the 90th and the 99th percentile of the latency -// as rank estimations. However, the default behavior will change in the -// upcoming v0.10 of the library. There will be no rank estiamtions at all by -// default. For a sane transition, it is recommended to set the desired rank -// estimations explicitly. +// as rank estimations. // // Note that the rank estimations cannot be aggregated in a meaningful way with // the Prometheus query language (i.e. you cannot average or add them). If you @@ -57,9 +54,6 @@ type Summary interface { } // DefObjectives are the default Summary quantile values. -// -// Deprecated: DefObjectives will not be used as the default objectives in -// v0.10 of the library. The default Summary will have no quantiles then. var ( DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001} @@ -81,10 +75,8 @@ const ( ) // SummaryOpts bundles the options for creating a Summary metric. It is -// mandatory to set Name and Help to a non-empty string. While all other fields -// are optional and can safely be left at their zero value, it is recommended to -// explicitly set the Objectives field to the desired value as the default value -// will change in the upcoming v0.10 of the library. +// mandatory to set Name and Help to a non-empty string. All other fields are +// optional and can safely be left at their zero value. type SummaryOpts struct { // Namespace, Subsystem, and Name are components of the fully-qualified // name of the Summary (created by joining these components with @@ -101,28 +93,29 @@ type SummaryOpts struct { // string. Help string - // ConstLabels are used to attach fixed labels to this metric. Metrics - // with the same fully-qualified name must have the same label names in - // their ConstLabels. + // ConstLabels are used to attach fixed labels to this + // Summary. Summaries with the same fully-qualified name must have the + // same label names in their ConstLabels. + // + // Note that in most cases, labels have a value that varies during the + // lifetime of a process. Those labels are usually managed with a + // SummaryVec. ConstLabels serve only special purposes. One is for the + // special case where the value of a label does not change during the + // lifetime of a process, e.g. if the revision of the running binary is + // put into a label. Another, more advanced purpose is if more than one + // Collector needs to collect Summaries with the same fully-qualified + // name. In that case, those Summaries must differ in the values of + // their ConstLabels. See the Collector examples. // - // ConstLabels are only used rarely. In particular, do not use them to - // attach the same labels to all your metrics. Those use cases are - // better covered by target labels set by the scraping Prometheus - // server, or by one specific metric (e.g. a build_info or a - // machine_role metric). See also - // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels + // If the value of a label never changes (not even between binaries), + // that label most likely should not be a label at all (but part of the + // metric name). ConstLabels Labels // Objectives defines the quantile rank estimates with their respective - // absolute error. If Objectives[q] = e, then the value reported for q - // will be the φ-quantile value for some φ between q-e and q+e. The - // default value is DefObjectives. It is used if Objectives is left at - // its zero value (i.e. nil). To create a Summary without Objectives, - // set it to an empty map (i.e. map[float64]float64{}). - // - // Deprecated: Note that the current value of DefObjectives is - // deprecated. It will be replaced by an empty map in v0.10 of the - // library. Please explicitly set Objectives to the desired value. + // absolute error. If Objectives[q] = e, then the value reported + // for q will be the φ-quantile value for some φ between q-e and q+e. + // The default value is DefObjectives. Objectives map[float64]float64 // MaxAge defines the duration for which an observation stays relevant @@ -190,7 +183,7 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary { } } - if opts.Objectives == nil { + if len(opts.Objectives) == 0 { opts.Objectives = DefObjectives } @@ -397,11 +390,12 @@ func (s quantSort) Less(i, j int) bool { // (e.g. HTTP request latencies, partitioned by status code and method). Create // instances with NewSummaryVec. type SummaryVec struct { - *metricVec + *MetricVec } // NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and -// partitioned by the given label names. +// partitioned by the given label names. At least one label name must be +// provided. func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec { desc := NewDesc( BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), @@ -410,116 +404,47 @@ func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec { opts.ConstLabels, ) return &SummaryVec{ - metricVec: newMetricVec(desc, func(lvs ...string) Metric { + MetricVec: newMetricVec(desc, func(lvs ...string) Metric { return newSummary(desc, opts, lvs...) }), } } -// GetMetricWithLabelValues returns the Summary for the given slice of label -// values (same order as the VariableLabels in Desc). If that combination of -// label values is accessed for the first time, a new Summary is created. -// -// It is possible to call this method without using the returned Summary to only -// create the new Summary but leave it at its starting value, a Summary without -// any observations. -// -// Keeping the Summary for later use is possible (and should be considered if -// performance is critical), but keep in mind that Reset, DeleteLabelValues and -// Delete can be used to delete the Summary from the SummaryVec. In that case, -// the Summary will still exist, but it will not be exported anymore, even if a -// Summary with the same label values is created later. See also the CounterVec -// example. -// -// An error is returned if the number of label values is not the same as the -// number of VariableLabels in Desc (minus any curried labels). -// -// Note that for more than one label value, this method is prone to mistakes -// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as -// an alternative to avoid that type of mistake. For higher label numbers, the -// latter has a much more readable (albeit more verbose) syntax, but it comes -// with a performance overhead (for creating and processing the Labels map). -// See also the GaugeVec example. -func (v *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) { - metric, err := v.metricVec.getMetricWithLabelValues(lvs...) +// GetMetricWithLabelValues replaces the method of the same name in +// MetricVec. The difference is that this method returns a Summary and not a +// Metric so that no type conversion is required. +func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error) { + metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) if metric != nil { - return metric.(Observer), err + return metric.(Summary), err } return nil, err } -// GetMetricWith returns the Summary for the given Labels map (the label names -// must match those of the VariableLabels in Desc). If that label map is -// accessed for the first time, a new Summary is created. Implications of -// creating a Summary without using it and keeping the Summary for later use are -// the same as for GetMetricWithLabelValues. -// -// An error is returned if the number and names of the Labels are inconsistent -// with those of the VariableLabels in Desc (minus any curried labels). -// -// This method is used for the same purpose as -// GetMetricWithLabelValues(...string). See there for pros and cons of the two -// methods. -func (v *SummaryVec) GetMetricWith(labels Labels) (Observer, error) { - metric, err := v.metricVec.getMetricWith(labels) +// GetMetricWith replaces the method of the same name in MetricVec. The +// difference is that this method returns a Summary and not a Metric so that no +// type conversion is required. +func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error) { + metric, err := m.MetricVec.GetMetricWith(labels) if metric != nil { - return metric.(Observer), err + return metric.(Summary), err } return nil, err } // WithLabelValues works as GetMetricWithLabelValues, but panics where -// GetMetricWithLabelValues would have returned an error. Not returning an -// error allows shortcuts like +// GetMetricWithLabelValues would have returned an error. By not returning an +// error, WithLabelValues allows shortcuts like // myVec.WithLabelValues("404", "GET").Observe(42.21) -func (v *SummaryVec) WithLabelValues(lvs ...string) Observer { - s, err := v.GetMetricWithLabelValues(lvs...) - if err != nil { - panic(err) - } - return s +func (m *SummaryVec) WithLabelValues(lvs ...string) Summary { + return m.MetricVec.WithLabelValues(lvs...).(Summary) } // With works as GetMetricWith, but panics where GetMetricWithLabels would have -// returned an error. Not returning an error allows shortcuts like -// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21) -func (v *SummaryVec) With(labels Labels) Observer { - s, err := v.GetMetricWith(labels) - if err != nil { - panic(err) - } - return s -} - -// CurryWith returns a vector curried with the provided labels, i.e. the -// returned vector has those labels pre-set for all labeled operations performed -// on it. The cardinality of the curried vector is reduced accordingly. The -// order of the remaining labels stays the same (just with the curried labels -// taken out of the sequence – which is relevant for the -// (GetMetric)WithLabelValues methods). It is possible to curry a curried -// vector, but only with labels not yet used for currying before. -// -// The metrics contained in the SummaryVec are shared between the curried and -// uncurried vectors. They are just accessed differently. Curried and uncurried -// vectors behave identically in terms of collection. Only one must be -// registered with a given registry (usually the uncurried version). The Reset -// method deletes all metrics, even if called on a curried vector. -func (v *SummaryVec) CurryWith(labels Labels) (ObserverVec, error) { - vec, err := v.curryWith(labels) - if vec != nil { - return &SummaryVec{vec}, err - } - return nil, err -} - -// MustCurryWith works as CurryWith but panics where CurryWith would have -// returned an error. -func (v *SummaryVec) MustCurryWith(labels Labels) ObserverVec { - vec, err := v.CurryWith(labels) - if err != nil { - panic(err) - } - return vec +// returned an error. By not returning an error, With allows shortcuts like +// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21) +func (m *SummaryVec) With(labels Labels) Summary { + return m.MetricVec.With(labels).(Summary) } type constSummary struct { @@ -580,8 +505,8 @@ func NewConstSummary( quantiles map[float64]float64, labelValues ...string, ) (Metric, error) { - if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil { - return nil, err + if len(desc.variableLabels) != len(labelValues) { + return nil, errInconsistentCardinality } return &constSummary{ desc: desc, diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go deleted file mode 100644 index b162ed946..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sort" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestSummaryWithDefaultObjectives(t *testing.T) { - reg := NewRegistry() - summaryWithDefaultObjectives := NewSummary(SummaryOpts{ - Name: "default_objectives", - Help: "Test help.", - }) - if err := reg.Register(summaryWithDefaultObjectives); err != nil { - t.Error(err) - } - - m := &dto.Metric{} - if err := summaryWithDefaultObjectives.Write(m); err != nil { - t.Error(err) - } - if len(m.GetSummary().Quantile) != len(DefObjectives) { - t.Error("expected default objectives in summary") - } -} - -func TestSummaryWithoutObjectives(t *testing.T) { - reg := NewRegistry() - summaryWithEmptyObjectives := NewSummary(SummaryOpts{ - Name: "empty_objectives", - Help: "Test help.", - Objectives: map[float64]float64{}, - }) - if err := reg.Register(summaryWithEmptyObjectives); err != nil { - t.Error(err) - } - - m := &dto.Metric{} - if err := summaryWithEmptyObjectives.Write(m); err != nil { - t.Error(err) - } - if len(m.GetSummary().Quantile) != 0 { - t.Error("expected no objectives in summary") - } -} - -func benchmarkSummaryObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryObserve1(b *testing.B) { - benchmarkSummaryObserve(1, b) -} - -func BenchmarkSummaryObserve2(b *testing.B) { - benchmarkSummaryObserve(2, b) -} - -func BenchmarkSummaryObserve4(b *testing.B) { - benchmarkSummaryObserve(4, b) -} - -func BenchmarkSummaryObserve8(b *testing.B) { - benchmarkSummaryObserve(8, b) -} - -func benchmarkSummaryWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryWrite1(b *testing.B) { - benchmarkSummaryWrite(1, b) -} - -func BenchmarkSummaryWrite2(b *testing.B) { - benchmarkSummaryWrite(2, b) -} - -func BenchmarkSummaryWrite4(b *testing.B) { - benchmarkSummaryWrite(4, b) -} - -func BenchmarkSummaryWrite8(b *testing.B) { - benchmarkSummaryWrite(8, b) -} - -func TestSummaryConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Summary.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - for i, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[i].Quantile - gotV := *m.Summary.Quantile[i].Value - min, max := getBounds(allVars, wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f, want %f", gotQ, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummaryVec( - SummaryOpts{ - Name: "test_summary", - Help: "helpless", - Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sum.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := sum.WithLabelValues(string('A' + i)) - s.(Summary).Write(m) - if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) - } - if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) - } - for j, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[j].Quantile - gotV := *m.Summary.Quantile[j].Value - min, max := getBounds(allVars[i], wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryDecay(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - // More because it depends on timing than because it is particularly long... - } - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - MaxAge: 100 * time.Millisecond, - Objectives: map[float64]float64{0.1: 0.001}, - AgeBuckets: 10, - }) - - m := &dto.Metric{} - i := 0 - tick := time.NewTicker(time.Millisecond) - for range tick.C { - i++ - sum.Observe(float64(i)) - if i%10 == 0 { - sum.Write(m) - if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { - t.Errorf("%d. got %f, want %f", i, got, want) - } - m.Reset() - } - if i >= 1000 { - break - } - } - tick.Stop() - // Wait for MaxAge without observations and make sure quantiles are NaN. - time.Sleep(100 * time.Millisecond) - sum.Write(m) - if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { - t.Errorf("got %f, want NaN after expiration", got) - } -} - -func getBounds(vars []float64, q, ε float64) (min, max float64) { - // TODO(beorn7): This currently tolerates an error of up to 2*ε. The - // error must be at most ε, but for some reason, it's sometimes slightly - // higher. That's a bug. - n := float64(len(vars)) - lower := int((q - 2*ε) * n) - upper := int(math.Ceil((q + 2*ε) * n)) - min = vars[0] - if lower > 1 { - min = vars[lower-1] - } - max = vars[len(vars)-1] - if upper < len(vars) { - max = vars[upper-1] - } - return -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer.go b/vendor/github.com/prometheus/client_golang/prometheus/timer.go deleted file mode 100644 index b8fc5f18c..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/timer.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import "time" - -// Timer is a helper type to time functions. Use NewTimer to create new -// instances. -type Timer struct { - begin time.Time - observer Observer -} - -// NewTimer creates a new Timer. The provided Observer is used to observe a -// duration in seconds. Timer is usually used to time a function call in the -// following way: -// func TimeMe() { -// timer := NewTimer(myHistogram) -// defer timer.ObserveDuration() -// // Do actual work. -// } -func NewTimer(o Observer) *Timer { - return &Timer{ - begin: time.Now(), - observer: o, - } -} - -// ObserveDuration records the duration passed since the Timer was created with -// NewTimer. It calls the Observe method of the Observer provided during -// construction with the duration in seconds as an argument. ObserveDuration is -// usually called with a defer statement. -// -// Note that this method is only guaranteed to never observe negative durations -// if used with Go1.9+. -func (t *Timer) ObserveDuration() { - if t.observer != nil { - t.observer.Observe(time.Since(t.begin).Seconds()) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go b/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go deleted file mode 100644 index 294902068..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/timer_test.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestTimerObserve(t *testing.T) { - var ( - his = NewHistogram(HistogramOpts{Name: "test_histogram"}) - sum = NewSummary(SummaryOpts{Name: "test_summary"}) - gauge = NewGauge(GaugeOpts{Name: "test_gauge"}) - ) - - func() { - hisTimer := NewTimer(his) - sumTimer := NewTimer(sum) - gaugeTimer := NewTimer(ObserverFunc(gauge.Set)) - defer hisTimer.ObserveDuration() - defer sumTimer.ObserveDuration() - defer gaugeTimer.ObserveDuration() - }() - - m := &dto.Metric{} - his.Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for histogram, got %d", want, got) - } - m.Reset() - sum.Write(m) - if want, got := uint64(1), m.GetSummary().GetSampleCount(); want != got { - t.Errorf("want %d observations for summary, got %d", want, got) - } - m.Reset() - gauge.Write(m) - if got := m.GetGauge().GetValue(); got <= 0 { - t.Errorf("want value > 0 for gauge, got %f", got) - } -} - -func TestTimerEmpty(t *testing.T) { - emptyTimer := NewTimer(nil) - emptyTimer.ObserveDuration() - // Do nothing, just demonstrate it works without panic. -} - -func TestTimerConditionalTiming(t *testing.T) { - var ( - his = NewHistogram(HistogramOpts{ - Name: "test_histogram", - }) - timeMe = true - m = &dto.Metric{} - ) - - timedFunc := func() { - timer := NewTimer(ObserverFunc(func(v float64) { - if timeMe { - his.Observe(v) - } - })) - defer timer.ObserveDuration() - } - - timedFunc() // This will time. - his.Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for histogram, got %d", want, got) - } - - timeMe = false - timedFunc() // This will not time again. - m.Reset() - his.Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for histogram, got %d", want, got) - } -} - -func TestTimerByOutcome(t *testing.T) { - var ( - his = NewHistogramVec( - HistogramOpts{Name: "test_histogram"}, - []string{"outcome"}, - ) - outcome = "foo" - m = &dto.Metric{} - ) - - timedFunc := func() { - timer := NewTimer(ObserverFunc(func(v float64) { - his.WithLabelValues(outcome).Observe(v) - })) - defer timer.ObserveDuration() - - if outcome == "foo" { - outcome = "bar" - return - } - outcome = "foo" - } - - timedFunc() - his.WithLabelValues("foo").(Histogram).Write(m) - if want, got := uint64(0), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'foo' histogram, got %d", want, got) - } - m.Reset() - his.WithLabelValues("bar").(Histogram).Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'bar' histogram, got %d", want, got) - } - - timedFunc() - m.Reset() - his.WithLabelValues("foo").(Histogram).Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'foo' histogram, got %d", want, got) - } - m.Reset() - his.WithLabelValues("bar").(Histogram).Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'bar' histogram, got %d", want, got) - } - - timedFunc() - m.Reset() - his.WithLabelValues("foo").(Histogram).Write(m) - if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'foo' histogram, got %d", want, got) - } - m.Reset() - his.WithLabelValues("bar").(Histogram).Write(m) - if want, got := uint64(2), m.GetHistogram().GetSampleCount(); want != got { - t.Errorf("want %d observations for 'bar' histogram, got %d", want, got) - } - -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go index 0f9ce63f4..5faf7e6e3 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go @@ -13,12 +13,108 @@ package prometheus +// Untyped is a Metric that represents a single numerical value that can +// arbitrarily go up and down. +// +// An Untyped metric works the same as a Gauge. The only difference is that to +// no type information is implied. +// +// To create Untyped instances, use NewUntyped. +type Untyped interface { + Metric + Collector + + // Set sets the Untyped metric to an arbitrary value. + Set(float64) + // Inc increments the Untyped metric by 1. + Inc() + // Dec decrements the Untyped metric by 1. + Dec() + // Add adds the given value to the Untyped metric. (The value can be + // negative, resulting in a decrease.) + Add(float64) + // Sub subtracts the given value from the Untyped metric. (The value can + // be negative, resulting in an increase.) + Sub(float64) +} + // UntypedOpts is an alias for Opts. See there for doc comments. type UntypedOpts Opts -// UntypedFunc works like GaugeFunc but the collected metric is of type -// "Untyped". UntypedFunc is useful to mirror an external metric of unknown -// type. +// NewUntyped creates a new Untyped metric from the provided UntypedOpts. +func NewUntyped(opts UntypedOpts) Untyped { + return newValue(NewDesc( + BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), + opts.Help, + nil, + opts.ConstLabels, + ), UntypedValue, 0) +} + +// UntypedVec is a Collector that bundles a set of Untyped metrics that all +// share the same Desc, but have different values for their variable +// labels. This is used if you want to count the same thing partitioned by +// various dimensions. Create instances with NewUntypedVec. +type UntypedVec struct { + *MetricVec +} + +// NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and +// partitioned by the given label names. At least one label name must be +// provided. +func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec { + desc := NewDesc( + BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), + opts.Help, + labelNames, + opts.ConstLabels, + ) + return &UntypedVec{ + MetricVec: newMetricVec(desc, func(lvs ...string) Metric { + return newValue(desc, UntypedValue, 0, lvs...) + }), + } +} + +// GetMetricWithLabelValues replaces the method of the same name in +// MetricVec. The difference is that this method returns an Untyped and not a +// Metric so that no type conversion is required. +func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error) { + metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...) + if metric != nil { + return metric.(Untyped), err + } + return nil, err +} + +// GetMetricWith replaces the method of the same name in MetricVec. The +// difference is that this method returns an Untyped and not a Metric so that no +// type conversion is required. +func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error) { + metric, err := m.MetricVec.GetMetricWith(labels) + if metric != nil { + return metric.(Untyped), err + } + return nil, err +} + +// WithLabelValues works as GetMetricWithLabelValues, but panics where +// GetMetricWithLabelValues would have returned an error. By not returning an +// error, WithLabelValues allows shortcuts like +// myVec.WithLabelValues("404", "GET").Add(42) +func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped { + return m.MetricVec.WithLabelValues(lvs...).(Untyped) +} + +// With works as GetMetricWith, but panics where GetMetricWithLabels would have +// returned an error. By not returning an error, With allows shortcuts like +// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) +func (m *UntypedVec) With(labels Labels) Untyped { + return m.MetricVec.With(labels).(Untyped) +} + +// UntypedFunc is an Untyped whose value is determined at collect time by +// calling a provided function. // // To create UntypedFunc instances, use NewUntypedFunc. type UntypedFunc interface { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go index 543b57c27..a944c3775 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/value.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go @@ -14,8 +14,11 @@ package prometheus import ( + "errors" "fmt" + "math" "sort" + "sync/atomic" dto "github.com/prometheus/client_model/go" @@ -33,6 +36,77 @@ const ( UntypedValue ) +var errInconsistentCardinality = errors.New("inconsistent label cardinality") + +// value is a generic metric for simple values. It implements Metric, Collector, +// Counter, Gauge, and Untyped. Its effective type is determined by +// ValueType. This is a low-level building block used by the library to back the +// implementations of Counter, Gauge, and Untyped. +type value struct { + // valBits containst the bits of the represented float64 value. It has + // to go first in the struct to guarantee alignment for atomic + // operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG + valBits uint64 + + selfCollector + + desc *Desc + valType ValueType + labelPairs []*dto.LabelPair +} + +// newValue returns a newly allocated value with the given Desc, ValueType, +// sample value and label values. It panics if the number of label +// values is different from the number of variable labels in Desc. +func newValue(desc *Desc, valueType ValueType, val float64, labelValues ...string) *value { + if len(labelValues) != len(desc.variableLabels) { + panic(errInconsistentCardinality) + } + result := &value{ + desc: desc, + valType: valueType, + valBits: math.Float64bits(val), + labelPairs: makeLabelPairs(desc, labelValues), + } + result.init(result) + return result +} + +func (v *value) Desc() *Desc { + return v.desc +} + +func (v *value) Set(val float64) { + atomic.StoreUint64(&v.valBits, math.Float64bits(val)) +} + +func (v *value) Inc() { + v.Add(1) +} + +func (v *value) Dec() { + v.Add(-1) +} + +func (v *value) Add(val float64) { + for { + oldBits := atomic.LoadUint64(&v.valBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + val) + if atomic.CompareAndSwapUint64(&v.valBits, oldBits, newBits) { + return + } + } +} + +func (v *value) Sub(val float64) { + v.Add(val * -1) +} + +func (v *value) Write(out *dto.Metric) error { + val := math.Float64frombits(atomic.LoadUint64(&v.valBits)) + return populateMetric(v.valType, val, v.labelPairs, out) +} + // valueFunc is a generic metric for simple values retrieved on collect time // from a function. It implements Metric and Collector. Its effective type is // determined by ValueType. This is a low-level building block used by the @@ -79,8 +153,8 @@ func (v *valueFunc) Write(out *dto.Metric) error { // the Collect method. NewConstMetric returns an error if the length of // labelValues is not consistent with the variable labels in Desc. func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) { - if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil { - return nil, err + if len(desc.variableLabels) != len(labelValues) { + return nil, errInconsistentCardinality } return &constMetric{ desc: desc, diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value_test.go b/vendor/github.com/prometheus/client_golang/prometheus/value_test.go deleted file mode 100644 index eed517e7b..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/value_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package prometheus - -import ( - "fmt" - "testing" -) - -func TestNewConstMetricInvalidLabelValues(t *testing.T) { - testCases := []struct { - desc string - labels Labels - }{ - { - desc: "non utf8 label value", - labels: Labels{"a": "\xFF"}, - }, - { - desc: "not enough label values", - labels: Labels{}, - }, - { - desc: "too many label values", - labels: Labels{"a": "1", "b": "2"}, - }, - } - - for _, test := range testCases { - metricDesc := NewDesc( - "sample_value", - "sample value", - []string{"a"}, - Labels{}, - ) - - expectPanic(t, func() { - MustNewConstMetric(metricDesc, CounterValue, 0.3, "\xFF") - }, fmt.Sprintf("WithLabelValues: expected panic because: %s", test.desc)) - - if _, err := NewConstMetric(metricDesc, CounterValue, 0.3, "\xFF"); err == nil { - t.Errorf("NewConstMetric: expected error because: %s", test.desc) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec.go b/vendor/github.com/prometheus/client_golang/prometheus/vec.go index cea158249..7f3eef9a4 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/vec.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/vec.go @@ -20,253 +20,200 @@ import ( "github.com/prometheus/common/model" ) -// metricVec is a Collector to bundle metrics of the same name that differ in -// their label values. metricVec is not used directly (and therefore -// unexported). It is used as a building block for implementations of vectors of -// a given metric type, like GaugeVec, CounterVec, SummaryVec, and HistogramVec. -// It also handles label currying. It uses basicMetricVec internally. -type metricVec struct { - *metricMap - - curry []curriedLabelValue - - // hashAdd and hashAddByte can be replaced for testing collision handling. - hashAdd func(h uint64, s string) uint64 +// MetricVec is a Collector to bundle metrics of the same name that +// differ in their label values. MetricVec is usually not used directly but as a +// building block for implementations of vectors of a given metric +// type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already +// provided in this package. +type MetricVec struct { + mtx sync.RWMutex // Protects the children. + children map[uint64][]metricWithLabelValues + desc *Desc + + newMetric func(labelValues ...string) Metric + hashAdd func(h uint64, s string) uint64 // replace hash function for testing collision handling hashAddByte func(h uint64, b byte) uint64 } -// newMetricVec returns an initialized metricVec. -func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec { - return &metricVec{ - metricMap: &metricMap{ - metrics: map[uint64][]metricWithLabelValues{}, - desc: desc, - newMetric: newMetric, - }, +// newMetricVec returns an initialized MetricVec. The concrete value is +// returned for embedding into another struct. +func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *MetricVec { + return &MetricVec{ + children: map[uint64][]metricWithLabelValues{}, + desc: desc, + newMetric: newMetric, hashAdd: hashAdd, hashAddByte: hashAddByte, } } -// DeleteLabelValues removes the metric where the variable labels are the same -// as those passed in as labels (same order as the VariableLabels in Desc). It -// returns true if a metric was deleted. -// -// It is not an error if the number of label values is not the same as the -// number of VariableLabels in Desc. However, such inconsistent label count can -// never match an actual metric, so the method will always return false in that -// case. -// -// Note that for more than one label value, this method is prone to mistakes -// caused by an incorrect order of arguments. Consider Delete(Labels) as an -// alternative to avoid that type of mistake. For higher label numbers, the -// latter has a much more readable (albeit more verbose) syntax, but it comes -// with a performance overhead (for creating and processing the Labels map). -// See also the CounterVec example. -func (m *metricVec) DeleteLabelValues(lvs ...string) bool { - h, err := m.hashLabelValues(lvs) - if err != nil { - return false - } - - return m.metricMap.deleteByHashWithLabelValues(h, lvs, m.curry) +// metricWithLabelValues provides the metric and its label values for +// disambiguation on hash collision. +type metricWithLabelValues struct { + values []string + metric Metric } -// Delete deletes the metric where the variable labels are the same as those -// passed in as labels. It returns true if a metric was deleted. -// -// It is not an error if the number and names of the Labels are inconsistent -// with those of the VariableLabels in Desc. However, such inconsistent Labels -// can never match an actual metric, so the method will always return false in -// that case. -// -// This method is used for the same purpose as DeleteLabelValues(...string). See -// there for pros and cons of the two methods. -func (m *metricVec) Delete(labels Labels) bool { - h, err := m.hashLabels(labels) - if err != nil { - return false - } - - return m.metricMap.deleteByHashWithLabels(h, labels, m.curry) +// Describe implements Collector. The length of the returned slice +// is always one. +func (m *MetricVec) Describe(ch chan<- *Desc) { + ch <- m.desc } -func (m *metricVec) curryWith(labels Labels) (*metricVec, error) { - var ( - newCurry []curriedLabelValue - oldCurry = m.curry - iCurry int - ) - for i, label := range m.desc.variableLabels { - val, ok := labels[label] - if iCurry < len(oldCurry) && oldCurry[iCurry].index == i { - if ok { - return nil, fmt.Errorf("label name %q is already curried", label) - } - newCurry = append(newCurry, oldCurry[iCurry]) - iCurry++ - } else { - if !ok { - continue // Label stays uncurried. - } - newCurry = append(newCurry, curriedLabelValue{i, val}) +// Collect implements Collector. +func (m *MetricVec) Collect(ch chan<- Metric) { + m.mtx.RLock() + defer m.mtx.RUnlock() + + for _, metrics := range m.children { + for _, metric := range metrics { + ch <- metric.metric } } - if l := len(oldCurry) + len(labels) - len(newCurry); l > 0 { - return nil, fmt.Errorf("%d unknown label(s) found during currying", l) - } - - return &metricVec{ - metricMap: m.metricMap, - curry: newCurry, - hashAdd: m.hashAdd, - hashAddByte: m.hashAddByte, - }, nil } -func (m *metricVec) getMetricWithLabelValues(lvs ...string) (Metric, error) { +// GetMetricWithLabelValues returns the Metric for the given slice of label +// values (same order as the VariableLabels in Desc). If that combination of +// label values is accessed for the first time, a new Metric is created. +// +// It is possible to call this method without using the returned Metric to only +// create the new Metric but leave it at its start value (e.g. a Summary or +// Histogram without any observations). See also the SummaryVec example. +// +// Keeping the Metric for later use is possible (and should be considered if +// performance is critical), but keep in mind that Reset, DeleteLabelValues and +// Delete can be used to delete the Metric from the MetricVec. In that case, the +// Metric will still exist, but it will not be exported anymore, even if a +// Metric with the same label values is created later. See also the CounterVec +// example. +// +// An error is returned if the number of label values is not the same as the +// number of VariableLabels in Desc. +// +// Note that for more than one label value, this method is prone to mistakes +// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as +// an alternative to avoid that type of mistake. For higher label numbers, the +// latter has a much more readable (albeit more verbose) syntax, but it comes +// with a performance overhead (for creating and processing the Labels map). +// See also the GaugeVec example. +func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) { h, err := m.hashLabelValues(lvs) if err != nil { return nil, err } - return m.metricMap.getOrCreateMetricWithLabelValues(h, lvs, m.curry), nil + return m.getOrCreateMetricWithLabelValues(h, lvs), nil } -func (m *metricVec) getMetricWith(labels Labels) (Metric, error) { +// GetMetricWith returns the Metric for the given Labels map (the label names +// must match those of the VariableLabels in Desc). If that label map is +// accessed for the first time, a new Metric is created. Implications of +// creating a Metric without using it and keeping the Metric for later use are +// the same as for GetMetricWithLabelValues. +// +// An error is returned if the number and names of the Labels are inconsistent +// with those of the VariableLabels in Desc. +// +// This method is used for the same purpose as +// GetMetricWithLabelValues(...string). See there for pros and cons of the two +// methods. +func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) { h, err := m.hashLabels(labels) if err != nil { return nil, err } - return m.metricMap.getOrCreateMetricWithLabels(h, labels, m.curry), nil + return m.getOrCreateMetricWithLabels(h, labels), nil } -func (m *metricVec) hashLabelValues(vals []string) (uint64, error) { - if err := validateLabelValues(vals, len(m.desc.variableLabels)-len(m.curry)); err != nil { - return 0, err - } - - var ( - h = hashNew() - curry = m.curry - iVals, iCurry int - ) - for i := 0; i < len(m.desc.variableLabels); i++ { - if iCurry < len(curry) && curry[iCurry].index == i { - h = m.hashAdd(h, curry[iCurry].value) - iCurry++ - } else { - h = m.hashAdd(h, vals[iVals]) - iVals++ - } - h = m.hashAddByte(h, model.SeparatorByte) +// WithLabelValues works as GetMetricWithLabelValues, but panics if an error +// occurs. The method allows neat syntax like: +// httpReqs.WithLabelValues("404", "POST").Inc() +func (m *MetricVec) WithLabelValues(lvs ...string) Metric { + metric, err := m.GetMetricWithLabelValues(lvs...) + if err != nil { + panic(err) } - return h, nil + return metric } -func (m *metricVec) hashLabels(labels Labels) (uint64, error) { - if err := validateValuesInLabels(labels, len(m.desc.variableLabels)-len(m.curry)); err != nil { - return 0, err - } - - var ( - h = hashNew() - curry = m.curry - iCurry int - ) - for i, label := range m.desc.variableLabels { - val, ok := labels[label] - if iCurry < len(curry) && curry[iCurry].index == i { - if ok { - return 0, fmt.Errorf("label name %q is already curried", label) - } - h = m.hashAdd(h, curry[iCurry].value) - iCurry++ - } else { - if !ok { - return 0, fmt.Errorf("label name %q missing in label map", label) - } - h = m.hashAdd(h, val) - } - h = m.hashAddByte(h, model.SeparatorByte) +// With works as GetMetricWith, but panics if an error occurs. The method allows +// neat syntax like: +// httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc() +func (m *MetricVec) With(labels Labels) Metric { + metric, err := m.GetMetricWith(labels) + if err != nil { + panic(err) } - return h, nil -} - -// metricWithLabelValues provides the metric and its label values for -// disambiguation on hash collision. -type metricWithLabelValues struct { - values []string - metric Metric -} - -// curriedLabelValue sets the curried value for a label at the given index. -type curriedLabelValue struct { - index int - value string -} - -// metricMap is a helper for metricVec and shared between differently curried -// metricVecs. -type metricMap struct { - mtx sync.RWMutex // Protects metrics. - metrics map[uint64][]metricWithLabelValues - desc *Desc - newMetric func(labelValues ...string) Metric -} - -// Describe implements Collector. It will send exactly one Desc to the provided -// channel. -func (m *metricMap) Describe(ch chan<- *Desc) { - ch <- m.desc + return metric } -// Collect implements Collector. -func (m *metricMap) Collect(ch chan<- Metric) { - m.mtx.RLock() - defer m.mtx.RUnlock() +// DeleteLabelValues removes the metric where the variable labels are the same +// as those passed in as labels (same order as the VariableLabels in Desc). It +// returns true if a metric was deleted. +// +// It is not an error if the number of label values is not the same as the +// number of VariableLabels in Desc. However, such inconsistent label count can +// never match an actual Metric, so the method will always return false in that +// case. +// +// Note that for more than one label value, this method is prone to mistakes +// caused by an incorrect order of arguments. Consider Delete(Labels) as an +// alternative to avoid that type of mistake. For higher label numbers, the +// latter has a much more readable (albeit more verbose) syntax, but it comes +// with a performance overhead (for creating and processing the Labels map). +// See also the CounterVec example. +func (m *MetricVec) DeleteLabelValues(lvs ...string) bool { + m.mtx.Lock() + defer m.mtx.Unlock() - for _, metrics := range m.metrics { - for _, metric := range metrics { - ch <- metric.metric - } + h, err := m.hashLabelValues(lvs) + if err != nil { + return false } + return m.deleteByHashWithLabelValues(h, lvs) } -// Reset deletes all metrics in this vector. -func (m *metricMap) Reset() { +// Delete deletes the metric where the variable labels are the same as those +// passed in as labels. It returns true if a metric was deleted. +// +// It is not an error if the number and names of the Labels are inconsistent +// with those of the VariableLabels in the Desc of the MetricVec. However, such +// inconsistent Labels can never match an actual Metric, so the method will +// always return false in that case. +// +// This method is used for the same purpose as DeleteLabelValues(...string). See +// there for pros and cons of the two methods. +func (m *MetricVec) Delete(labels Labels) bool { m.mtx.Lock() defer m.mtx.Unlock() - for h := range m.metrics { - delete(m.metrics, h) + h, err := m.hashLabels(labels) + if err != nil { + return false } + + return m.deleteByHashWithLabels(h, labels) } // deleteByHashWithLabelValues removes the metric from the hash bucket h. If // there are multiple matches in the bucket, use lvs to select a metric and // remove only that metric. -func (m *metricMap) deleteByHashWithLabelValues( - h uint64, lvs []string, curry []curriedLabelValue, -) bool { - m.mtx.Lock() - defer m.mtx.Unlock() - - metrics, ok := m.metrics[h] +func (m *MetricVec) deleteByHashWithLabelValues(h uint64, lvs []string) bool { + metrics, ok := m.children[h] if !ok { return false } - i := findMetricWithLabelValues(metrics, lvs, curry) + i := m.findMetricWithLabelValues(metrics, lvs) if i >= len(metrics) { return false } if len(metrics) > 1 { - m.metrics[h] = append(metrics[:i], metrics[i+1:]...) + m.children[h] = append(metrics[:i], metrics[i+1:]...) } else { - delete(m.metrics, h) + delete(m.children, h) } return true } @@ -274,35 +221,69 @@ func (m *metricMap) deleteByHashWithLabelValues( // deleteByHashWithLabels removes the metric from the hash bucket h. If there // are multiple matches in the bucket, use lvs to select a metric and remove // only that metric. -func (m *metricMap) deleteByHashWithLabels( - h uint64, labels Labels, curry []curriedLabelValue, -) bool { - metrics, ok := m.metrics[h] +func (m *MetricVec) deleteByHashWithLabels(h uint64, labels Labels) bool { + metrics, ok := m.children[h] if !ok { return false } - i := findMetricWithLabels(m.desc, metrics, labels, curry) + i := m.findMetricWithLabels(metrics, labels) if i >= len(metrics) { return false } if len(metrics) > 1 { - m.metrics[h] = append(metrics[:i], metrics[i+1:]...) + m.children[h] = append(metrics[:i], metrics[i+1:]...) } else { - delete(m.metrics, h) + delete(m.children, h) } return true } +// Reset deletes all metrics in this vector. +func (m *MetricVec) Reset() { + m.mtx.Lock() + defer m.mtx.Unlock() + + for h := range m.children { + delete(m.children, h) + } +} + +func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) { + if len(vals) != len(m.desc.variableLabels) { + return 0, errInconsistentCardinality + } + h := hashNew() + for _, val := range vals { + h = m.hashAdd(h, val) + h = m.hashAddByte(h, model.SeparatorByte) + } + return h, nil +} + +func (m *MetricVec) hashLabels(labels Labels) (uint64, error) { + if len(labels) != len(m.desc.variableLabels) { + return 0, errInconsistentCardinality + } + h := hashNew() + for _, label := range m.desc.variableLabels { + val, ok := labels[label] + if !ok { + return 0, fmt.Errorf("label name %q missing in label map", label) + } + h = m.hashAdd(h, val) + h = m.hashAddByte(h, model.SeparatorByte) + } + return h, nil +} + // getOrCreateMetricWithLabelValues retrieves the metric by hash and label value // or creates it and returns the new one. // // This function holds the mutex. -func (m *metricMap) getOrCreateMetricWithLabelValues( - hash uint64, lvs []string, curry []curriedLabelValue, -) Metric { +func (m *MetricVec) getOrCreateMetricWithLabelValues(hash uint64, lvs []string) Metric { m.mtx.RLock() - metric, ok := m.getMetricWithHashAndLabelValues(hash, lvs, curry) + metric, ok := m.getMetricWithLabelValues(hash, lvs) m.mtx.RUnlock() if ok { return metric @@ -310,11 +291,13 @@ func (m *metricMap) getOrCreateMetricWithLabelValues( m.mtx.Lock() defer m.mtx.Unlock() - metric, ok = m.getMetricWithHashAndLabelValues(hash, lvs, curry) + metric, ok = m.getMetricWithLabelValues(hash, lvs) if !ok { - inlinedLVs := inlineLabelValues(lvs, curry) - metric = m.newMetric(inlinedLVs...) - m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: inlinedLVs, metric: metric}) + // Copy to avoid allocation in case wo don't go down this code path. + copiedLVs := make([]string, len(lvs)) + copy(copiedLVs, lvs) + metric = m.newMetric(copiedLVs...) + m.children[hash] = append(m.children[hash], metricWithLabelValues{values: copiedLVs, metric: metric}) } return metric } @@ -323,11 +306,9 @@ func (m *metricMap) getOrCreateMetricWithLabelValues( // or creates it and returns the new one. // // This function holds the mutex. -func (m *metricMap) getOrCreateMetricWithLabels( - hash uint64, labels Labels, curry []curriedLabelValue, -) Metric { +func (m *MetricVec) getOrCreateMetricWithLabels(hash uint64, labels Labels) Metric { m.mtx.RLock() - metric, ok := m.getMetricWithHashAndLabels(hash, labels, curry) + metric, ok := m.getMetricWithLabels(hash, labels) m.mtx.RUnlock() if ok { return metric @@ -335,37 +316,33 @@ func (m *metricMap) getOrCreateMetricWithLabels( m.mtx.Lock() defer m.mtx.Unlock() - metric, ok = m.getMetricWithHashAndLabels(hash, labels, curry) + metric, ok = m.getMetricWithLabels(hash, labels) if !ok { - lvs := extractLabelValues(m.desc, labels, curry) + lvs := m.extractLabelValues(labels) metric = m.newMetric(lvs...) - m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: lvs, metric: metric}) + m.children[hash] = append(m.children[hash], metricWithLabelValues{values: lvs, metric: metric}) } return metric } -// getMetricWithHashAndLabelValues gets a metric while handling possible -// collisions in the hash space. Must be called while holding the read mutex. -func (m *metricMap) getMetricWithHashAndLabelValues( - h uint64, lvs []string, curry []curriedLabelValue, -) (Metric, bool) { - metrics, ok := m.metrics[h] +// getMetricWithLabelValues gets a metric while handling possible collisions in +// the hash space. Must be called while holding read mutex. +func (m *MetricVec) getMetricWithLabelValues(h uint64, lvs []string) (Metric, bool) { + metrics, ok := m.children[h] if ok { - if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) { + if i := m.findMetricWithLabelValues(metrics, lvs); i < len(metrics) { return metrics[i].metric, true } } return nil, false } -// getMetricWithHashAndLabels gets a metric while handling possible collisions in +// getMetricWithLabels gets a metric while handling possible collisions in // the hash space. Must be called while holding read mutex. -func (m *metricMap) getMetricWithHashAndLabels( - h uint64, labels Labels, curry []curriedLabelValue, -) (Metric, bool) { - metrics, ok := m.metrics[h] +func (m *MetricVec) getMetricWithLabels(h uint64, labels Labels) (Metric, bool) { + metrics, ok := m.children[h] if ok { - if i := findMetricWithLabels(m.desc, metrics, labels, curry); i < len(metrics) { + if i := m.findMetricWithLabels(metrics, labels); i < len(metrics) { return metrics[i].metric, true } } @@ -374,11 +351,9 @@ func (m *metricMap) getMetricWithHashAndLabels( // findMetricWithLabelValues returns the index of the matching metric or // len(metrics) if not found. -func findMetricWithLabelValues( - metrics []metricWithLabelValues, lvs []string, curry []curriedLabelValue, -) int { +func (m *MetricVec) findMetricWithLabelValues(metrics []metricWithLabelValues, lvs []string) int { for i, metric := range metrics { - if matchLabelValues(metric.values, lvs, curry) { + if m.matchLabelValues(metric.values, lvs) { return i } } @@ -387,51 +362,32 @@ func findMetricWithLabelValues( // findMetricWithLabels returns the index of the matching metric or len(metrics) // if not found. -func findMetricWithLabels( - desc *Desc, metrics []metricWithLabelValues, labels Labels, curry []curriedLabelValue, -) int { +func (m *MetricVec) findMetricWithLabels(metrics []metricWithLabelValues, labels Labels) int { for i, metric := range metrics { - if matchLabels(desc, metric.values, labels, curry) { + if m.matchLabels(metric.values, labels) { return i } } return len(metrics) } -func matchLabelValues(values []string, lvs []string, curry []curriedLabelValue) bool { - if len(values) != len(lvs)+len(curry) { +func (m *MetricVec) matchLabelValues(values []string, lvs []string) bool { + if len(values) != len(lvs) { return false } - var iLVs, iCurry int for i, v := range values { - if iCurry < len(curry) && curry[iCurry].index == i { - if v != curry[iCurry].value { - return false - } - iCurry++ - continue - } - if v != lvs[iLVs] { + if v != lvs[i] { return false } - iLVs++ } return true } -func matchLabels(desc *Desc, values []string, labels Labels, curry []curriedLabelValue) bool { - if len(values) != len(labels)+len(curry) { +func (m *MetricVec) matchLabels(values []string, labels Labels) bool { + if len(labels) != len(values) { return false } - iCurry := 0 - for i, k := range desc.variableLabels { - if iCurry < len(curry) && curry[iCurry].index == i { - if values[i] != curry[iCurry].value { - return false - } - iCurry++ - continue - } + for i, k := range m.desc.variableLabels { if values[i] != labels[k] { return false } @@ -439,31 +395,10 @@ func matchLabels(desc *Desc, values []string, labels Labels, curry []curriedLabe return true } -func extractLabelValues(desc *Desc, labels Labels, curry []curriedLabelValue) []string { - labelValues := make([]string, len(labels)+len(curry)) - iCurry := 0 - for i, k := range desc.variableLabels { - if iCurry < len(curry) && curry[iCurry].index == i { - labelValues[i] = curry[iCurry].value - iCurry++ - continue - } +func (m *MetricVec) extractLabelValues(labels Labels) []string { + labelValues := make([]string, len(labels)) + for i, k := range m.desc.variableLabels { labelValues[i] = labels[k] } return labelValues } - -func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string { - labelValues := make([]string, len(lvs)+len(curry)) - var iCurry, iLVs int - for i := range labelValues { - if iCurry < len(curry) && curry[iCurry].index == i { - labelValues[i] = curry[iCurry].value - iCurry++ - continue - } - labelValues[i] = lvs[iLVs] - iLVs++ - } - return labelValues -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go deleted file mode 100644 index bd18a9f4e..000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "fmt" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestDelete(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDelete(t, vec) -} - -func TestDeleteWithCollisions(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDelete(t, vec) -} - -func testDelete(t *testing.T, vec *GaugeVec) { - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestDeleteLabelValues(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDeleteLabelValues(t, vec) -} - -func TestDeleteLabelValuesWithCollisions(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDeleteLabelValues(t, vec) -} - -func testDeleteLabelValues(t *testing.T, vec *GaugeVec) { - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - vec.With(Labels{"l1": "v1", "l2": "v3"}).(Gauge).Set(42) // Add junk data for collision. - if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v3"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Gauge).Set(42) - // Delete out of order. - if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestMetricVec(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testMetricVec(t, vec) -} - -func TestMetricVecWithCollisions(t *testing.T) { - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testMetricVec(t, vec) -} - -func testMetricVec(t *testing.T, vec *GaugeVec) { - vec.Reset() // Actually test Reset now! - - var pair [2]string - // Keep track of metrics. - expected := map[[2]string]int{} - - for i := 0; i < 1000; i++ { - pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples. - expected[pair]++ - vec.WithLabelValues(pair[0], pair[1]).Inc() - - expected[[2]string{"v1", "v2"}]++ - vec.WithLabelValues("v1", "v2").(Gauge).Inc() - } - - var total int - for _, metrics := range vec.metricMap.metrics { - for _, metric := range metrics { - total++ - copy(pair[:], metric.values) - - var metricOut dto.Metric - if err := metric.metric.Write(&metricOut); err != nil { - t.Fatal(err) - } - actual := *metricOut.Gauge.Value - - var actualPair [2]string - for i, label := range metricOut.Label { - actualPair[i] = *label.Value - } - - // Test output pair against metric.values to ensure we've selected - // the right one. We check this to ensure the below check means - // anything at all. - if actualPair != pair { - t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair) - } - - if actual != float64(expected[pair]) { - t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) - } - } - } - - if total != len(expected) { - t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected)) - } - - vec.Reset() - - if len(vec.metricMap.metrics) > 0 { - t.Fatalf("reset failed") - } -} - -func TestCounterVecEndToEndWithCollision(t *testing.T) { - vec := NewCounterVec( - CounterOpts{ - Name: "test", - Help: "helpless", - }, - []string{"labelname"}, - ) - vec.WithLabelValues("77kepQFQ8Kl").Inc() - vec.WithLabelValues("!0IC=VloaY").Add(2) - - m := &dto.Metric{} - if err := vec.WithLabelValues("77kepQFQ8Kl").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "77kepQFQ8Kl"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 1.; got != want { - t.Errorf("got value %f, want %f", got, want) - } - m.Reset() - if err := vec.WithLabelValues("!0IC=VloaY").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "!0IC=VloaY"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 2.; got != want { - t.Errorf("got value %f, want %f", got, want) - } -} - -func TestCurryVec(t *testing.T) { - vec := NewCounterVec( - CounterOpts{ - Name: "test", - Help: "helpless", - }, - []string{"one", "two", "three"}, - ) - testCurryVec(t, vec) -} - -func TestCurryVecWithCollisions(t *testing.T) { - vec := NewCounterVec( - CounterOpts{ - Name: "test", - Help: "helpless", - }, - []string{"one", "two", "three"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testCurryVec(t, vec) -} - -func testCurryVec(t *testing.T, vec *CounterVec) { - - assertMetrics := func(t *testing.T) { - n := 0 - for _, m := range vec.metricMap.metrics { - n += len(m) - } - if n != 2 { - t.Error("expected two metrics, got", n) - } - m := &dto.Metric{} - c1, err := vec.GetMetricWithLabelValues("1", "2", "3") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } - c1.Write(m) - if want, got := 1., m.GetCounter().GetValue(); want != got { - t.Errorf("want %f as counter value, got %f", want, got) - } - m.Reset() - c2, err := vec.GetMetricWithLabelValues("11", "22", "33") - if err != nil { - t.Fatal("unexpected error getting metric:", err) - } - c2.Write(m) - if want, got := 1., m.GetCounter().GetValue(); want != got { - t.Errorf("want %f as counter value, got %f", want, got) - } - } - - assertNoMetric := func(t *testing.T) { - if n := len(vec.metricMap.metrics); n != 0 { - t.Error("expected no metrics, got", n) - } - } - - t.Run("zero labels", func(t *testing.T) { - c1 := vec.MustCurryWith(nil) - c2 := vec.MustCurryWith(nil) - c1.WithLabelValues("1", "2", "3").Inc() - c2.With(Labels{"one": "11", "two": "22", "three": "33"}).Inc() - assertMetrics(t) - if !c1.Delete(Labels{"one": "1", "two": "2", "three": "3"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("11", "22", "33") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("first label", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"one": "1"}) - c2 := vec.MustCurryWith(Labels{"one": "11"}) - c1.WithLabelValues("2", "3").Inc() - c2.With(Labels{"two": "22", "three": "33"}).Inc() - assertMetrics(t) - if c1.Delete(Labels{"two": "22", "three": "33"}) { - t.Error("deletion unexpectedly succeeded") - } - if c2.DeleteLabelValues("2", "3") { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"two": "2", "three": "3"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("22", "33") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("middle label", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"two": "2"}) - c2 := vec.MustCurryWith(Labels{"two": "22"}) - c1.WithLabelValues("1", "3").Inc() - c2.With(Labels{"one": "11", "three": "33"}).Inc() - assertMetrics(t) - if c1.Delete(Labels{"one": "11", "three": "33"}) { - t.Error("deletion unexpectedly succeeded") - } - if c2.DeleteLabelValues("1", "3") { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"one": "1", "three": "3"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("11", "33") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("last label", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"three": "3"}) - c2 := vec.MustCurryWith(Labels{"three": "33"}) - c1.WithLabelValues("1", "2").Inc() - c2.With(Labels{"one": "11", "two": "22"}).Inc() - assertMetrics(t) - if c1.Delete(Labels{"two": "22", "one": "11"}) { - t.Error("deletion unexpectedly succeeded") - } - if c2.DeleteLabelValues("1", "2") { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"two": "2", "one": "1"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("11", "22") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("two labels", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"three": "3", "one": "1"}) - c2 := vec.MustCurryWith(Labels{"three": "33", "one": "11"}) - c1.WithLabelValues("2").Inc() - c2.With(Labels{"two": "22"}).Inc() - assertMetrics(t) - if c1.Delete(Labels{"two": "22"}) { - t.Error("deletion unexpectedly succeeded") - } - if c2.DeleteLabelValues("2") { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"two": "2"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("22") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("all labels", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"three": "3", "two": "2", "one": "1"}) - c2 := vec.MustCurryWith(Labels{"three": "33", "one": "11", "two": "22"}) - c1.WithLabelValues().Inc() - c2.With(nil).Inc() - assertMetrics(t) - if !c1.Delete(Labels{}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues() { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("double curry", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"three": "3"}).MustCurryWith(Labels{"one": "1"}) - c2 := vec.MustCurryWith(Labels{"three": "33"}).MustCurryWith(Labels{"one": "11"}) - c1.WithLabelValues("2").Inc() - c2.With(Labels{"two": "22"}).Inc() - assertMetrics(t) - if c1.Delete(Labels{"two": "22"}) { - t.Error("deletion unexpectedly succeeded") - } - if c2.DeleteLabelValues("2") { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"two": "2"}) { - t.Error("deletion failed") - } - if !c2.DeleteLabelValues("22") { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("use already curried label", func(t *testing.T) { - c1 := vec.MustCurryWith(Labels{"three": "3"}) - if _, err := c1.GetMetricWithLabelValues("1", "2", "3"); err == nil { - t.Error("expected error when using already curried label") - } - if _, err := c1.GetMetricWith(Labels{"one": "1", "two": "2", "three": "3"}); err == nil { - t.Error("expected error when using already curried label") - } - assertNoMetric(t) - c1.WithLabelValues("1", "2").Inc() - if c1.Delete(Labels{"one": "1", "two": "2", "three": "3"}) { - t.Error("deletion unexpectedly succeeded") - } - if !c1.Delete(Labels{"one": "1", "two": "2"}) { - t.Error("deletion failed") - } - assertNoMetric(t) - }) - t.Run("curry already curried label", func(t *testing.T) { - if _, err := vec.MustCurryWith(Labels{"three": "3"}).CurryWith(Labels{"three": "33"}); err == nil { - t.Error("currying unexpectedly succeeded") - } else if err.Error() != `label name "three" is already curried` { - t.Error("currying returned unexpected error:", err) - } - - }) - t.Run("unknown label", func(t *testing.T) { - if _, err := vec.CurryWith(Labels{"foo": "bar"}); err == nil { - t.Error("currying unexpectedly succeeded") - } else if err.Error() != "1 unknown label(s) found during currying" { - t.Error("currying returned unexpected error:", err) - } - }) -} - -func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) { - benchmarkMetricVecWithLabelValues(b, map[string][]string{ - "l1": {"onevalue"}, - "l2": {"twovalue"}, - }) -} - -func BenchmarkMetricVecWithLabelValues2Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 10) -} - -func BenchmarkMetricVecWithLabelValues4Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 4, 10) -} - -func BenchmarkMetricVecWithLabelValues2Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys1000ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 1000) -} - -func benchmarkMetricVecWithLabelValuesCardinality(b *testing.B, nkeys, nvalues int) { - labels := map[string][]string{} - - for i := 0; i < nkeys; i++ { - var ( - k = fmt.Sprintf("key-%v", i) - vs = make([]string, 0, nvalues) - ) - for j := 0; j < nvalues; j++ { - vs = append(vs, fmt.Sprintf("value-%v", j)) - } - labels[k] = vs - } - - benchmarkMetricVecWithLabelValues(b, labels) -} - -func benchmarkMetricVecWithLabelValues(b *testing.B, labels map[string][]string) { - var keys []string - for k := range labels { // Map order dependent, who cares though. - keys = append(keys, k) - } - - values := make([]string, len(labels)) // Value cache for permutations. - vec := NewGaugeVec( - GaugeOpts{ - Name: "test", - Help: "helpless", - }, - keys, - ) - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - // Varies input across provide map entries based on key size. - for j, k := range keys { - candidates := labels[k] - values[j] = candidates[i%len(candidates)] - } - - vec.WithLabelValues(values...) - } -} diff --git a/vendor/github.com/prometheus/client_model/.gitignore b/vendor/github.com/prometheus/client_model/.gitignore deleted file mode 100644 index 2f7896d1d..000000000 --- a/vendor/github.com/prometheus/client_model/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target/ diff --git a/vendor/github.com/prometheus/client_model/CONTRIBUTING.md b/vendor/github.com/prometheus/client_model/CONTRIBUTING.md deleted file mode 100644 index 40503edbf..000000000 --- a/vendor/github.com/prometheus/client_model/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contributing - -Prometheus uses GitHub to manage reviews of pull requests. - -* If you have a trivial fix or improvement, go ahead and create a pull request, - addressing (with `@...`) the maintainer of this repository (see - [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request. - -* If you plan to do something more involved, first discuss your ideas - on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). - This will avoid unnecessary work and surely give you and us a good deal - of inspiration. - -* Relevant coding style guidelines are the [Go Code Review - Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) - and the _Formatting and style_ section of Peter Bourgon's [Go: Best - Practices for Production - Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). diff --git a/vendor/github.com/prometheus/client_model/MAINTAINERS.md b/vendor/github.com/prometheus/client_model/MAINTAINERS.md deleted file mode 100644 index 3ede55fe1..000000000 --- a/vendor/github.com/prometheus/client_model/MAINTAINERS.md +++ /dev/null @@ -1 +0,0 @@ -* Björn Rabenstein diff --git a/vendor/github.com/prometheus/client_model/Makefile b/vendor/github.com/prometheus/client_model/Makefile deleted file mode 100644 index e147c69da..000000000 --- a/vendor/github.com/prometheus/client_model/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -# Copyright 2013 Prometheus Team -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at - -# http://www.apache.org/licenses/LICENSE-2.0 - -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -KEY_ID ?= _DEFINE_ME_ - -all: cpp go java python ruby - -SUFFIXES: - -cpp: cpp/metrics.pb.cc cpp/metrics.pb.h - -cpp/metrics.pb.cc: metrics.proto - protoc $< --cpp_out=cpp/ - -cpp/metrics.pb.h: metrics.proto - protoc $< --cpp_out=cpp/ - -go: go/metrics.pb.go - -go/metrics.pb.go: metrics.proto - protoc $< --go_out=go/ - -java: src/main/java/io/prometheus/client/Metrics.java pom.xml - mvn clean compile package - -src/main/java/io/prometheus/client/Metrics.java: metrics.proto - protoc $< --java_out=src/main/java - -python: python/prometheus/client/model/metrics_pb2.py - -python/prometheus/client/model/metrics_pb2.py: metrics.proto - mkdir -p python/prometheus/client/model - protoc $< --python_out=python/prometheus/client/model - -ruby: - $(MAKE) -C ruby build - -clean: - -rm -rf cpp/* - -rm -rf go/* - -rm -rf java/* - -rm -rf python/* - -$(MAKE) -C ruby clean - -mvn clean - -maven-deploy-snapshot: java - mvn clean deploy -Dgpg.keyname=$(KEY_ID) -DperformRelease=true - -maven-deploy-release: java - mvn clean release:clean release:prepare release:perform -Dgpg.keyname=$(KEY_ID) -DperformRelease=true - -.PHONY: all clean cpp go java maven-deploy-snapshot maven-deploy-release python ruby diff --git a/vendor/github.com/prometheus/client_model/README.md b/vendor/github.com/prometheus/client_model/README.md deleted file mode 100644 index a710042db..000000000 --- a/vendor/github.com/prometheus/client_model/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Background -Under most circumstances, manually downloading this repository should never -be required. - -# Prerequisites -# Base -* [Google Protocol Buffers](https://developers.google.com/protocol-buffers) - -## Java -* [Apache Maven](http://maven.apache.org) -* [Prometheus Maven Repository](https://github.com/prometheus/io.prometheus-maven-repository) checked out into ../io.prometheus-maven-repository - -## Go -* [Go](http://golang.org) -* [goprotobuf](https://code.google.com/p/goprotobuf) - -## Ruby -* [Ruby](https://www.ruby-lang.org) -* [bundler](https://rubygems.org/gems/bundler) - -# Building - $ make - -# Getting Started - * The Go source code is periodically indexed: [Go Protocol Buffer Model](http://godoc.org/github.com/prometheus/client_model/go). - * All of the core developers are accessible via the [Prometheus Developers Mailinglist](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). diff --git a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc deleted file mode 100644 index 1ff893b83..000000000 --- a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc +++ /dev/null @@ -1,3380 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: metrics.proto - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include "metrics.pb.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace io { -namespace prometheus { -namespace client { - -namespace { - -const ::google::protobuf::Descriptor* LabelPair_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - LabelPair_reflection_ = NULL; -const ::google::protobuf::Descriptor* Gauge_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Gauge_reflection_ = NULL; -const ::google::protobuf::Descriptor* Counter_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Counter_reflection_ = NULL; -const ::google::protobuf::Descriptor* Quantile_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Quantile_reflection_ = NULL; -const ::google::protobuf::Descriptor* Summary_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Summary_reflection_ = NULL; -const ::google::protobuf::Descriptor* Untyped_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Untyped_reflection_ = NULL; -const ::google::protobuf::Descriptor* Histogram_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Histogram_reflection_ = NULL; -const ::google::protobuf::Descriptor* Bucket_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Bucket_reflection_ = NULL; -const ::google::protobuf::Descriptor* Metric_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - Metric_reflection_ = NULL; -const ::google::protobuf::Descriptor* MetricFamily_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - MetricFamily_reflection_ = NULL; -const ::google::protobuf::EnumDescriptor* MetricType_descriptor_ = NULL; - -} // namespace - - -void protobuf_AssignDesc_metrics_2eproto() { - protobuf_AddDesc_metrics_2eproto(); - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( - "metrics.proto"); - GOOGLE_CHECK(file != NULL); - LabelPair_descriptor_ = file->message_type(0); - static const int LabelPair_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, value_), - }; - LabelPair_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - LabelPair_descriptor_, - LabelPair::default_instance_, - LabelPair_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(LabelPair)); - Gauge_descriptor_ = file->message_type(1); - static const int Gauge_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, value_), - }; - Gauge_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Gauge_descriptor_, - Gauge::default_instance_, - Gauge_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Gauge)); - Counter_descriptor_ = file->message_type(2); - static const int Counter_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, value_), - }; - Counter_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Counter_descriptor_, - Counter::default_instance_, - Counter_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Counter)); - Quantile_descriptor_ = file->message_type(3); - static const int Quantile_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, quantile_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, value_), - }; - Quantile_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Quantile_descriptor_, - Quantile::default_instance_, - Quantile_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Quantile)); - Summary_descriptor_ = file->message_type(4); - static const int Summary_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_count_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_sum_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, quantile_), - }; - Summary_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Summary_descriptor_, - Summary::default_instance_, - Summary_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Summary)); - Untyped_descriptor_ = file->message_type(5); - static const int Untyped_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, value_), - }; - Untyped_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Untyped_descriptor_, - Untyped::default_instance_, - Untyped_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Untyped)); - Histogram_descriptor_ = file->message_type(6); - static const int Histogram_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_count_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_sum_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, bucket_), - }; - Histogram_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Histogram_descriptor_, - Histogram::default_instance_, - Histogram_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Histogram)); - Bucket_descriptor_ = file->message_type(7); - static const int Bucket_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, cumulative_count_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, upper_bound_), - }; - Bucket_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Bucket_descriptor_, - Bucket::default_instance_, - Bucket_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Bucket)); - Metric_descriptor_ = file->message_type(8); - static const int Metric_offsets_[7] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, label_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, gauge_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, counter_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, summary_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, untyped_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, histogram_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, timestamp_ms_), - }; - Metric_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - Metric_descriptor_, - Metric::default_instance_, - Metric_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(Metric)); - MetricFamily_descriptor_ = file->message_type(9); - static const int MetricFamily_offsets_[4] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, help_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, metric_), - }; - MetricFamily_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - MetricFamily_descriptor_, - MetricFamily::default_instance_, - MetricFamily_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(MetricFamily)); - MetricType_descriptor_ = file->enum_type(0); -} - -namespace { - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); -inline void protobuf_AssignDescriptorsOnce() { - ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, - &protobuf_AssignDesc_metrics_2eproto); -} - -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - LabelPair_descriptor_, &LabelPair::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Gauge_descriptor_, &Gauge::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Counter_descriptor_, &Counter::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Quantile_descriptor_, &Quantile::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Summary_descriptor_, &Summary::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Untyped_descriptor_, &Untyped::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Histogram_descriptor_, &Histogram::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Bucket_descriptor_, &Bucket::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - Metric_descriptor_, &Metric::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - MetricFamily_descriptor_, &MetricFamily::default_instance()); -} - -} // namespace - -void protobuf_ShutdownFile_metrics_2eproto() { - delete LabelPair::default_instance_; - delete LabelPair_reflection_; - delete Gauge::default_instance_; - delete Gauge_reflection_; - delete Counter::default_instance_; - delete Counter_reflection_; - delete Quantile::default_instance_; - delete Quantile_reflection_; - delete Summary::default_instance_; - delete Summary_reflection_; - delete Untyped::default_instance_; - delete Untyped_reflection_; - delete Histogram::default_instance_; - delete Histogram_reflection_; - delete Bucket::default_instance_; - delete Bucket_reflection_; - delete Metric::default_instance_; - delete Metric_reflection_; - delete MetricFamily::default_instance_; - delete MetricFamily_reflection_; -} - -void protobuf_AddDesc_metrics_2eproto() { - static bool already_here = false; - if (already_here) return; - already_here = true; - GOOGLE_PROTOBUF_VERIFY_VERSION; - - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - "\n\rmetrics.proto\022\024io.prometheus.client\"(\n" - "\tLabelPair\022\014\n\004name\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\"" - "\026\n\005Gauge\022\r\n\005value\030\001 \001(\001\"\030\n\007Counter\022\r\n\005va" - "lue\030\001 \001(\001\"+\n\010Quantile\022\020\n\010quantile\030\001 \001(\001\022" - "\r\n\005value\030\002 \001(\001\"e\n\007Summary\022\024\n\014sample_coun" - "t\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\0220\n\010quantile\030" - "\003 \003(\0132\036.io.prometheus.client.Quantile\"\030\n" - "\007Untyped\022\r\n\005value\030\001 \001(\001\"c\n\tHistogram\022\024\n\014" - "sample_count\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\022," - "\n\006bucket\030\003 \003(\0132\034.io.prometheus.client.Bu" - "cket\"7\n\006Bucket\022\030\n\020cumulative_count\030\001 \001(\004" - "\022\023\n\013upper_bound\030\002 \001(\001\"\276\002\n\006Metric\022.\n\005labe" - "l\030\001 \003(\0132\037.io.prometheus.client.LabelPair" - "\022*\n\005gauge\030\002 \001(\0132\033.io.prometheus.client.G" - "auge\022.\n\007counter\030\003 \001(\0132\035.io.prometheus.cl" - "ient.Counter\022.\n\007summary\030\004 \001(\0132\035.io.prome" - "theus.client.Summary\022.\n\007untyped\030\005 \001(\0132\035." - "io.prometheus.client.Untyped\0222\n\thistogra" - "m\030\007 \001(\0132\037.io.prometheus.client.Histogram" - "\022\024\n\014timestamp_ms\030\006 \001(\003\"\210\001\n\014MetricFamily\022" - "\014\n\004name\030\001 \001(\t\022\014\n\004help\030\002 \001(\t\022.\n\004type\030\003 \001(" - "\0162 .io.prometheus.client.MetricType\022,\n\006m" - "etric\030\004 \003(\0132\034.io.prometheus.client.Metri" - "c*M\n\nMetricType\022\013\n\007COUNTER\020\000\022\t\n\005GAUGE\020\001\022" - "\013\n\007SUMMARY\020\002\022\013\n\007UNTYPED\020\003\022\r\n\tHISTOGRAM\020\004" - "B\026\n\024io.prometheus.client", 1024); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "metrics.proto", &protobuf_RegisterTypes); - LabelPair::default_instance_ = new LabelPair(); - Gauge::default_instance_ = new Gauge(); - Counter::default_instance_ = new Counter(); - Quantile::default_instance_ = new Quantile(); - Summary::default_instance_ = new Summary(); - Untyped::default_instance_ = new Untyped(); - Histogram::default_instance_ = new Histogram(); - Bucket::default_instance_ = new Bucket(); - Metric::default_instance_ = new Metric(); - MetricFamily::default_instance_ = new MetricFamily(); - LabelPair::default_instance_->InitAsDefaultInstance(); - Gauge::default_instance_->InitAsDefaultInstance(); - Counter::default_instance_->InitAsDefaultInstance(); - Quantile::default_instance_->InitAsDefaultInstance(); - Summary::default_instance_->InitAsDefaultInstance(); - Untyped::default_instance_->InitAsDefaultInstance(); - Histogram::default_instance_->InitAsDefaultInstance(); - Bucket::default_instance_->InitAsDefaultInstance(); - Metric::default_instance_->InitAsDefaultInstance(); - MetricFamily::default_instance_->InitAsDefaultInstance(); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_metrics_2eproto); -} - -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_metrics_2eproto { - StaticDescriptorInitializer_metrics_2eproto() { - protobuf_AddDesc_metrics_2eproto(); - } -} static_descriptor_initializer_metrics_2eproto_; -const ::google::protobuf::EnumDescriptor* MetricType_descriptor() { - protobuf_AssignDescriptorsOnce(); - return MetricType_descriptor_; -} -bool MetricType_IsValid(int value) { - switch(value) { - case 0: - case 1: - case 2: - case 3: - case 4: - return true; - default: - return false; - } -} - - -// =================================================================== - -#ifndef _MSC_VER -const int LabelPair::kNameFieldNumber; -const int LabelPair::kValueFieldNumber; -#endif // !_MSC_VER - -LabelPair::LabelPair() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.LabelPair) -} - -void LabelPair::InitAsDefaultInstance() { -} - -LabelPair::LabelPair(const LabelPair& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.LabelPair) -} - -void LabelPair::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -LabelPair::~LabelPair() { - // @@protoc_insertion_point(destructor:io.prometheus.client.LabelPair) - SharedDtor(); -} - -void LabelPair::SharedDtor() { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete name_; - } - if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete value_; - } - if (this != default_instance_) { - } -} - -void LabelPair::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* LabelPair::descriptor() { - protobuf_AssignDescriptorsOnce(); - return LabelPair_descriptor_; -} - -const LabelPair& LabelPair::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -LabelPair* LabelPair::default_instance_ = NULL; - -LabelPair* LabelPair::New() const { - return new LabelPair; -} - -void LabelPair::Clear() { - if (_has_bits_[0 / 32] & 3) { - if (has_name()) { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_->clear(); - } - } - if (has_value()) { - if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool LabelPair::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.LabelPair) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "name"); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_value; - break; - } - - // optional string value = 2; - case 2: { - if (tag == 18) { - parse_value: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->value().data(), this->value().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "value"); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.LabelPair) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.LabelPair) - return false; -#undef DO_ -} - -void LabelPair::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.LabelPair) - // optional string name = 1; - if (has_name()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // optional string value = 2; - if (has_value()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->value().data(), this->value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "value"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.LabelPair) -} - -::google::protobuf::uint8* LabelPair::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.LabelPair) - // optional string name = 1; - if (has_name()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string value = 2; - if (has_value()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->value().data(), this->value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "value"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.LabelPair) - return target; -} - -int LabelPair::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional string value = 2; - if (has_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->value()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void LabelPair::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const LabelPair* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void LabelPair::MergeFrom(const LabelPair& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_name()) { - set_name(from.name()); - } - if (from.has_value()) { - set_value(from.value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void LabelPair::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void LabelPair::CopyFrom(const LabelPair& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool LabelPair::IsInitialized() const { - - return true; -} - -void LabelPair::Swap(LabelPair* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(value_, other->value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata LabelPair::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = LabelPair_descriptor_; - metadata.reflection = LabelPair_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Gauge::kValueFieldNumber; -#endif // !_MSC_VER - -Gauge::Gauge() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Gauge) -} - -void Gauge::InitAsDefaultInstance() { -} - -Gauge::Gauge(const Gauge& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Gauge) -} - -void Gauge::SharedCtor() { - _cached_size_ = 0; - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Gauge::~Gauge() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Gauge) - SharedDtor(); -} - -void Gauge::SharedDtor() { - if (this != default_instance_) { - } -} - -void Gauge::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Gauge::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Gauge_descriptor_; -} - -const Gauge& Gauge::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Gauge* Gauge::default_instance_ = NULL; - -Gauge* Gauge::New() const { - return new Gauge; -} - -void Gauge::Clear() { - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Gauge::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Gauge) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional double value = 1; - case 1: { - if (tag == 9) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &value_))); - set_has_value(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Gauge) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Gauge) - return false; -#undef DO_ -} - -void Gauge::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Gauge) - // optional double value = 1; - if (has_value()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Gauge) -} - -::google::protobuf::uint8* Gauge::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Gauge) - // optional double value = 1; - if (has_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Gauge) - return target; -} - -int Gauge::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional double value = 1; - if (has_value()) { - total_size += 1 + 8; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Gauge::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Gauge* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Gauge::MergeFrom(const Gauge& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_value()) { - set_value(from.value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Gauge::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Gauge::CopyFrom(const Gauge& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Gauge::IsInitialized() const { - - return true; -} - -void Gauge::Swap(Gauge* other) { - if (other != this) { - std::swap(value_, other->value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Gauge::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Gauge_descriptor_; - metadata.reflection = Gauge_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Counter::kValueFieldNumber; -#endif // !_MSC_VER - -Counter::Counter() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Counter) -} - -void Counter::InitAsDefaultInstance() { -} - -Counter::Counter(const Counter& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Counter) -} - -void Counter::SharedCtor() { - _cached_size_ = 0; - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Counter::~Counter() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Counter) - SharedDtor(); -} - -void Counter::SharedDtor() { - if (this != default_instance_) { - } -} - -void Counter::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Counter::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Counter_descriptor_; -} - -const Counter& Counter::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Counter* Counter::default_instance_ = NULL; - -Counter* Counter::New() const { - return new Counter; -} - -void Counter::Clear() { - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Counter::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Counter) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional double value = 1; - case 1: { - if (tag == 9) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &value_))); - set_has_value(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Counter) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Counter) - return false; -#undef DO_ -} - -void Counter::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Counter) - // optional double value = 1; - if (has_value()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Counter) -} - -::google::protobuf::uint8* Counter::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Counter) - // optional double value = 1; - if (has_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Counter) - return target; -} - -int Counter::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional double value = 1; - if (has_value()) { - total_size += 1 + 8; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Counter::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Counter* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Counter::MergeFrom(const Counter& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_value()) { - set_value(from.value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Counter::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Counter::CopyFrom(const Counter& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Counter::IsInitialized() const { - - return true; -} - -void Counter::Swap(Counter* other) { - if (other != this) { - std::swap(value_, other->value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Counter::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Counter_descriptor_; - metadata.reflection = Counter_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Quantile::kQuantileFieldNumber; -const int Quantile::kValueFieldNumber; -#endif // !_MSC_VER - -Quantile::Quantile() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Quantile) -} - -void Quantile::InitAsDefaultInstance() { -} - -Quantile::Quantile(const Quantile& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Quantile) -} - -void Quantile::SharedCtor() { - _cached_size_ = 0; - quantile_ = 0; - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Quantile::~Quantile() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Quantile) - SharedDtor(); -} - -void Quantile::SharedDtor() { - if (this != default_instance_) { - } -} - -void Quantile::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Quantile::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Quantile_descriptor_; -} - -const Quantile& Quantile::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Quantile* Quantile::default_instance_ = NULL; - -Quantile* Quantile::New() const { - return new Quantile; -} - -void Quantile::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(quantile_, value_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Quantile::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Quantile) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional double quantile = 1; - case 1: { - if (tag == 9) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &quantile_))); - set_has_quantile(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(17)) goto parse_value; - break; - } - - // optional double value = 2; - case 2: { - if (tag == 17) { - parse_value: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &value_))); - set_has_value(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Quantile) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Quantile) - return false; -#undef DO_ -} - -void Quantile::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Quantile) - // optional double quantile = 1; - if (has_quantile()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->quantile(), output); - } - - // optional double value = 2; - if (has_value()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Quantile) -} - -::google::protobuf::uint8* Quantile::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Quantile) - // optional double quantile = 1; - if (has_quantile()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->quantile(), target); - } - - // optional double value = 2; - if (has_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Quantile) - return target; -} - -int Quantile::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional double quantile = 1; - if (has_quantile()) { - total_size += 1 + 8; - } - - // optional double value = 2; - if (has_value()) { - total_size += 1 + 8; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Quantile::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Quantile* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Quantile::MergeFrom(const Quantile& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_quantile()) { - set_quantile(from.quantile()); - } - if (from.has_value()) { - set_value(from.value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Quantile::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Quantile::CopyFrom(const Quantile& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Quantile::IsInitialized() const { - - return true; -} - -void Quantile::Swap(Quantile* other) { - if (other != this) { - std::swap(quantile_, other->quantile_); - std::swap(value_, other->value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Quantile::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Quantile_descriptor_; - metadata.reflection = Quantile_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Summary::kSampleCountFieldNumber; -const int Summary::kSampleSumFieldNumber; -const int Summary::kQuantileFieldNumber; -#endif // !_MSC_VER - -Summary::Summary() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Summary) -} - -void Summary::InitAsDefaultInstance() { -} - -Summary::Summary(const Summary& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Summary) -} - -void Summary::SharedCtor() { - _cached_size_ = 0; - sample_count_ = GOOGLE_ULONGLONG(0); - sample_sum_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Summary::~Summary() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Summary) - SharedDtor(); -} - -void Summary::SharedDtor() { - if (this != default_instance_) { - } -} - -void Summary::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Summary::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Summary_descriptor_; -} - -const Summary& Summary::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Summary* Summary::default_instance_ = NULL; - -Summary* Summary::New() const { - return new Summary; -} - -void Summary::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(sample_count_, sample_sum_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - quantile_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Summary::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Summary) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional uint64 sample_count = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sample_count_))); - set_has_sample_count(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(17)) goto parse_sample_sum; - break; - } - - // optional double sample_sum = 2; - case 2: { - if (tag == 17) { - parse_sample_sum: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &sample_sum_))); - set_has_sample_sum(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_quantile; - break; - } - - // repeated .io.prometheus.client.Quantile quantile = 3; - case 3: { - if (tag == 26) { - parse_quantile: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_quantile())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_quantile; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Summary) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Summary) - return false; -#undef DO_ -} - -void Summary::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Summary) - // optional uint64 sample_count = 1; - if (has_sample_count()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output); - } - - // repeated .io.prometheus.client.Quantile quantile = 3; - for (int i = 0; i < this->quantile_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->quantile(i), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Summary) -} - -::google::protobuf::uint8* Summary::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Summary) - // optional uint64 sample_count = 1; - if (has_sample_count()) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target); - } - - // repeated .io.prometheus.client.Quantile quantile = 3; - for (int i = 0; i < this->quantile_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->quantile(i), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Summary) - return target; -} - -int Summary::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional uint64 sample_count = 1; - if (has_sample_count()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sample_count()); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - total_size += 1 + 8; - } - - } - // repeated .io.prometheus.client.Quantile quantile = 3; - total_size += 1 * this->quantile_size(); - for (int i = 0; i < this->quantile_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->quantile(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Summary::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Summary* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Summary::MergeFrom(const Summary& from) { - GOOGLE_CHECK_NE(&from, this); - quantile_.MergeFrom(from.quantile_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sample_count()) { - set_sample_count(from.sample_count()); - } - if (from.has_sample_sum()) { - set_sample_sum(from.sample_sum()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Summary::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Summary::CopyFrom(const Summary& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Summary::IsInitialized() const { - - return true; -} - -void Summary::Swap(Summary* other) { - if (other != this) { - std::swap(sample_count_, other->sample_count_); - std::swap(sample_sum_, other->sample_sum_); - quantile_.Swap(&other->quantile_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Summary::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Summary_descriptor_; - metadata.reflection = Summary_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Untyped::kValueFieldNumber; -#endif // !_MSC_VER - -Untyped::Untyped() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Untyped) -} - -void Untyped::InitAsDefaultInstance() { -} - -Untyped::Untyped(const Untyped& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Untyped) -} - -void Untyped::SharedCtor() { - _cached_size_ = 0; - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Untyped::~Untyped() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Untyped) - SharedDtor(); -} - -void Untyped::SharedDtor() { - if (this != default_instance_) { - } -} - -void Untyped::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Untyped::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Untyped_descriptor_; -} - -const Untyped& Untyped::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Untyped* Untyped::default_instance_ = NULL; - -Untyped* Untyped::New() const { - return new Untyped; -} - -void Untyped::Clear() { - value_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Untyped::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Untyped) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional double value = 1; - case 1: { - if (tag == 9) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &value_))); - set_has_value(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Untyped) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Untyped) - return false; -#undef DO_ -} - -void Untyped::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Untyped) - // optional double value = 1; - if (has_value()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Untyped) -} - -::google::protobuf::uint8* Untyped::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Untyped) - // optional double value = 1; - if (has_value()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Untyped) - return target; -} - -int Untyped::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional double value = 1; - if (has_value()) { - total_size += 1 + 8; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Untyped::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Untyped* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Untyped::MergeFrom(const Untyped& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_value()) { - set_value(from.value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Untyped::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Untyped::CopyFrom(const Untyped& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Untyped::IsInitialized() const { - - return true; -} - -void Untyped::Swap(Untyped* other) { - if (other != this) { - std::swap(value_, other->value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Untyped::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Untyped_descriptor_; - metadata.reflection = Untyped_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Histogram::kSampleCountFieldNumber; -const int Histogram::kSampleSumFieldNumber; -const int Histogram::kBucketFieldNumber; -#endif // !_MSC_VER - -Histogram::Histogram() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Histogram) -} - -void Histogram::InitAsDefaultInstance() { -} - -Histogram::Histogram(const Histogram& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Histogram) -} - -void Histogram::SharedCtor() { - _cached_size_ = 0; - sample_count_ = GOOGLE_ULONGLONG(0); - sample_sum_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Histogram::~Histogram() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Histogram) - SharedDtor(); -} - -void Histogram::SharedDtor() { - if (this != default_instance_) { - } -} - -void Histogram::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Histogram::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Histogram_descriptor_; -} - -const Histogram& Histogram::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Histogram* Histogram::default_instance_ = NULL; - -Histogram* Histogram::New() const { - return new Histogram; -} - -void Histogram::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(sample_count_, sample_sum_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - bucket_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Histogram::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Histogram) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional uint64 sample_count = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &sample_count_))); - set_has_sample_count(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(17)) goto parse_sample_sum; - break; - } - - // optional double sample_sum = 2; - case 2: { - if (tag == 17) { - parse_sample_sum: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &sample_sum_))); - set_has_sample_sum(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_bucket; - break; - } - - // repeated .io.prometheus.client.Bucket bucket = 3; - case 3: { - if (tag == 26) { - parse_bucket: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_bucket())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_bucket; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Histogram) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Histogram) - return false; -#undef DO_ -} - -void Histogram::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Histogram) - // optional uint64 sample_count = 1; - if (has_sample_count()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output); - } - - // repeated .io.prometheus.client.Bucket bucket = 3; - for (int i = 0; i < this->bucket_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->bucket(i), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Histogram) -} - -::google::protobuf::uint8* Histogram::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Histogram) - // optional uint64 sample_count = 1; - if (has_sample_count()) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target); - } - - // repeated .io.prometheus.client.Bucket bucket = 3; - for (int i = 0; i < this->bucket_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->bucket(i), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Histogram) - return target; -} - -int Histogram::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional uint64 sample_count = 1; - if (has_sample_count()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->sample_count()); - } - - // optional double sample_sum = 2; - if (has_sample_sum()) { - total_size += 1 + 8; - } - - } - // repeated .io.prometheus.client.Bucket bucket = 3; - total_size += 1 * this->bucket_size(); - for (int i = 0; i < this->bucket_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->bucket(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Histogram::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Histogram* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Histogram::MergeFrom(const Histogram& from) { - GOOGLE_CHECK_NE(&from, this); - bucket_.MergeFrom(from.bucket_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_sample_count()) { - set_sample_count(from.sample_count()); - } - if (from.has_sample_sum()) { - set_sample_sum(from.sample_sum()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Histogram::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Histogram::CopyFrom(const Histogram& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Histogram::IsInitialized() const { - - return true; -} - -void Histogram::Swap(Histogram* other) { - if (other != this) { - std::swap(sample_count_, other->sample_count_); - std::swap(sample_sum_, other->sample_sum_); - bucket_.Swap(&other->bucket_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Histogram::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Histogram_descriptor_; - metadata.reflection = Histogram_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Bucket::kCumulativeCountFieldNumber; -const int Bucket::kUpperBoundFieldNumber; -#endif // !_MSC_VER - -Bucket::Bucket() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Bucket) -} - -void Bucket::InitAsDefaultInstance() { -} - -Bucket::Bucket(const Bucket& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Bucket) -} - -void Bucket::SharedCtor() { - _cached_size_ = 0; - cumulative_count_ = GOOGLE_ULONGLONG(0); - upper_bound_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Bucket::~Bucket() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Bucket) - SharedDtor(); -} - -void Bucket::SharedDtor() { - if (this != default_instance_) { - } -} - -void Bucket::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Bucket::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Bucket_descriptor_; -} - -const Bucket& Bucket::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Bucket* Bucket::default_instance_ = NULL; - -Bucket* Bucket::New() const { - return new Bucket; -} - -void Bucket::Clear() { -#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ - &reinterpret_cast(16)->f) - \ - reinterpret_cast(16)) - -#define ZR_(first, last) do { \ - size_t f = OFFSET_OF_FIELD_(first); \ - size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ - ::memset(&first, 0, n); \ - } while (0) - - ZR_(cumulative_count_, upper_bound_); - -#undef OFFSET_OF_FIELD_ -#undef ZR_ - - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Bucket::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Bucket) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional uint64 cumulative_count = 1; - case 1: { - if (tag == 8) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &cumulative_count_))); - set_has_cumulative_count(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(17)) goto parse_upper_bound; - break; - } - - // optional double upper_bound = 2; - case 2: { - if (tag == 17) { - parse_upper_bound: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &upper_bound_))); - set_has_upper_bound(); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Bucket) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Bucket) - return false; -#undef DO_ -} - -void Bucket::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Bucket) - // optional uint64 cumulative_count = 1; - if (has_cumulative_count()) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->cumulative_count(), output); - } - - // optional double upper_bound = 2; - if (has_upper_bound()) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->upper_bound(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Bucket) -} - -::google::protobuf::uint8* Bucket::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Bucket) - // optional uint64 cumulative_count = 1; - if (has_cumulative_count()) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->cumulative_count(), target); - } - - // optional double upper_bound = 2; - if (has_upper_bound()) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->upper_bound(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Bucket) - return target; -} - -int Bucket::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional uint64 cumulative_count = 1; - if (has_cumulative_count()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->cumulative_count()); - } - - // optional double upper_bound = 2; - if (has_upper_bound()) { - total_size += 1 + 8; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Bucket::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Bucket* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Bucket::MergeFrom(const Bucket& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_cumulative_count()) { - set_cumulative_count(from.cumulative_count()); - } - if (from.has_upper_bound()) { - set_upper_bound(from.upper_bound()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Bucket::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Bucket::CopyFrom(const Bucket& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Bucket::IsInitialized() const { - - return true; -} - -void Bucket::Swap(Bucket* other) { - if (other != this) { - std::swap(cumulative_count_, other->cumulative_count_); - std::swap(upper_bound_, other->upper_bound_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Bucket::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Bucket_descriptor_; - metadata.reflection = Bucket_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int Metric::kLabelFieldNumber; -const int Metric::kGaugeFieldNumber; -const int Metric::kCounterFieldNumber; -const int Metric::kSummaryFieldNumber; -const int Metric::kUntypedFieldNumber; -const int Metric::kHistogramFieldNumber; -const int Metric::kTimestampMsFieldNumber; -#endif // !_MSC_VER - -Metric::Metric() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.Metric) -} - -void Metric::InitAsDefaultInstance() { - gauge_ = const_cast< ::io::prometheus::client::Gauge*>(&::io::prometheus::client::Gauge::default_instance()); - counter_ = const_cast< ::io::prometheus::client::Counter*>(&::io::prometheus::client::Counter::default_instance()); - summary_ = const_cast< ::io::prometheus::client::Summary*>(&::io::prometheus::client::Summary::default_instance()); - untyped_ = const_cast< ::io::prometheus::client::Untyped*>(&::io::prometheus::client::Untyped::default_instance()); - histogram_ = const_cast< ::io::prometheus::client::Histogram*>(&::io::prometheus::client::Histogram::default_instance()); -} - -Metric::Metric(const Metric& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Metric) -} - -void Metric::SharedCtor() { - _cached_size_ = 0; - gauge_ = NULL; - counter_ = NULL; - summary_ = NULL; - untyped_ = NULL; - histogram_ = NULL; - timestamp_ms_ = GOOGLE_LONGLONG(0); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -Metric::~Metric() { - // @@protoc_insertion_point(destructor:io.prometheus.client.Metric) - SharedDtor(); -} - -void Metric::SharedDtor() { - if (this != default_instance_) { - delete gauge_; - delete counter_; - delete summary_; - delete untyped_; - delete histogram_; - } -} - -void Metric::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* Metric::descriptor() { - protobuf_AssignDescriptorsOnce(); - return Metric_descriptor_; -} - -const Metric& Metric::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -Metric* Metric::default_instance_ = NULL; - -Metric* Metric::New() const { - return new Metric; -} - -void Metric::Clear() { - if (_has_bits_[0 / 32] & 126) { - if (has_gauge()) { - if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear(); - } - if (has_counter()) { - if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear(); - } - if (has_summary()) { - if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear(); - } - if (has_untyped()) { - if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear(); - } - if (has_histogram()) { - if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear(); - } - timestamp_ms_ = GOOGLE_LONGLONG(0); - } - label_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool Metric::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.Metric) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .io.prometheus.client.LabelPair label = 1; - case 1: { - if (tag == 10) { - parse_label: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_label())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(10)) goto parse_label; - if (input->ExpectTag(18)) goto parse_gauge; - break; - } - - // optional .io.prometheus.client.Gauge gauge = 2; - case 2: { - if (tag == 18) { - parse_gauge: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_gauge())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_counter; - break; - } - - // optional .io.prometheus.client.Counter counter = 3; - case 3: { - if (tag == 26) { - parse_counter: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_counter())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(34)) goto parse_summary; - break; - } - - // optional .io.prometheus.client.Summary summary = 4; - case 4: { - if (tag == 34) { - parse_summary: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_summary())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(42)) goto parse_untyped; - break; - } - - // optional .io.prometheus.client.Untyped untyped = 5; - case 5: { - if (tag == 42) { - parse_untyped: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_untyped())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(48)) goto parse_timestamp_ms; - break; - } - - // optional int64 timestamp_ms = 6; - case 6: { - if (tag == 48) { - parse_timestamp_ms: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( - input, ×tamp_ms_))); - set_has_timestamp_ms(); - } else { - goto handle_unusual; - } - if (input->ExpectTag(58)) goto parse_histogram; - break; - } - - // optional .io.prometheus.client.Histogram histogram = 7; - case 7: { - if (tag == 58) { - parse_histogram: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_histogram())); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.Metric) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.Metric) - return false; -#undef DO_ -} - -void Metric::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.Metric) - // repeated .io.prometheus.client.LabelPair label = 1; - for (int i = 0; i < this->label_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, this->label(i), output); - } - - // optional .io.prometheus.client.Gauge gauge = 2; - if (has_gauge()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->gauge(), output); - } - - // optional .io.prometheus.client.Counter counter = 3; - if (has_counter()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->counter(), output); - } - - // optional .io.prometheus.client.Summary summary = 4; - if (has_summary()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->summary(), output); - } - - // optional .io.prometheus.client.Untyped untyped = 5; - if (has_untyped()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->untyped(), output); - } - - // optional int64 timestamp_ms = 6; - if (has_timestamp_ms()) { - ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->timestamp_ms(), output); - } - - // optional .io.prometheus.client.Histogram histogram = 7; - if (has_histogram()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, this->histogram(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.Metric) -} - -::google::protobuf::uint8* Metric::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Metric) - // repeated .io.prometheus.client.LabelPair label = 1; - for (int i = 0; i < this->label_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 1, this->label(i), target); - } - - // optional .io.prometheus.client.Gauge gauge = 2; - if (has_gauge()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, this->gauge(), target); - } - - // optional .io.prometheus.client.Counter counter = 3; - if (has_counter()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->counter(), target); - } - - // optional .io.prometheus.client.Summary summary = 4; - if (has_summary()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 4, this->summary(), target); - } - - // optional .io.prometheus.client.Untyped untyped = 5; - if (has_untyped()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 5, this->untyped(), target); - } - - // optional int64 timestamp_ms = 6; - if (has_timestamp_ms()) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->timestamp_ms(), target); - } - - // optional .io.prometheus.client.Histogram histogram = 7; - if (has_histogram()) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 7, this->histogram(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Metric) - return target; -} - -int Metric::ByteSize() const { - int total_size = 0; - - if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { - // optional .io.prometheus.client.Gauge gauge = 2; - if (has_gauge()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->gauge()); - } - - // optional .io.prometheus.client.Counter counter = 3; - if (has_counter()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->counter()); - } - - // optional .io.prometheus.client.Summary summary = 4; - if (has_summary()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->summary()); - } - - // optional .io.prometheus.client.Untyped untyped = 5; - if (has_untyped()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->untyped()); - } - - // optional .io.prometheus.client.Histogram histogram = 7; - if (has_histogram()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->histogram()); - } - - // optional int64 timestamp_ms = 6; - if (has_timestamp_ms()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int64Size( - this->timestamp_ms()); - } - - } - // repeated .io.prometheus.client.LabelPair label = 1; - total_size += 1 * this->label_size(); - for (int i = 0; i < this->label_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->label(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void Metric::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const Metric* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void Metric::MergeFrom(const Metric& from) { - GOOGLE_CHECK_NE(&from, this); - label_.MergeFrom(from.label_); - if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) { - if (from.has_gauge()) { - mutable_gauge()->::io::prometheus::client::Gauge::MergeFrom(from.gauge()); - } - if (from.has_counter()) { - mutable_counter()->::io::prometheus::client::Counter::MergeFrom(from.counter()); - } - if (from.has_summary()) { - mutable_summary()->::io::prometheus::client::Summary::MergeFrom(from.summary()); - } - if (from.has_untyped()) { - mutable_untyped()->::io::prometheus::client::Untyped::MergeFrom(from.untyped()); - } - if (from.has_histogram()) { - mutable_histogram()->::io::prometheus::client::Histogram::MergeFrom(from.histogram()); - } - if (from.has_timestamp_ms()) { - set_timestamp_ms(from.timestamp_ms()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void Metric::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Metric::CopyFrom(const Metric& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Metric::IsInitialized() const { - - return true; -} - -void Metric::Swap(Metric* other) { - if (other != this) { - label_.Swap(&other->label_); - std::swap(gauge_, other->gauge_); - std::swap(counter_, other->counter_); - std::swap(summary_, other->summary_); - std::swap(untyped_, other->untyped_); - std::swap(histogram_, other->histogram_); - std::swap(timestamp_ms_, other->timestamp_ms_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata Metric::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = Metric_descriptor_; - metadata.reflection = Metric_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int MetricFamily::kNameFieldNumber; -const int MetricFamily::kHelpFieldNumber; -const int MetricFamily::kTypeFieldNumber; -const int MetricFamily::kMetricFieldNumber; -#endif // !_MSC_VER - -MetricFamily::MetricFamily() - : ::google::protobuf::Message() { - SharedCtor(); - // @@protoc_insertion_point(constructor:io.prometheus.client.MetricFamily) -} - -void MetricFamily::InitAsDefaultInstance() { -} - -MetricFamily::MetricFamily(const MetricFamily& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); - // @@protoc_insertion_point(copy_constructor:io.prometheus.client.MetricFamily) -} - -void MetricFamily::SharedCtor() { - ::google::protobuf::internal::GetEmptyString(); - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - type_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MetricFamily::~MetricFamily() { - // @@protoc_insertion_point(destructor:io.prometheus.client.MetricFamily) - SharedDtor(); -} - -void MetricFamily::SharedDtor() { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete name_; - } - if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete help_; - } - if (this != default_instance_) { - } -} - -void MetricFamily::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* MetricFamily::descriptor() { - protobuf_AssignDescriptorsOnce(); - return MetricFamily_descriptor_; -} - -const MetricFamily& MetricFamily::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); - return *default_instance_; -} - -MetricFamily* MetricFamily::default_instance_ = NULL; - -MetricFamily* MetricFamily::New() const { - return new MetricFamily; -} - -void MetricFamily::Clear() { - if (_has_bits_[0 / 32] & 7) { - if (has_name()) { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_->clear(); - } - } - if (has_help()) { - if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_->clear(); - } - } - type_ = 0; - } - metric_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool MetricFamily::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:io.prometheus.client.MetricFamily) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "name"); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_help; - break; - } - - // optional string help = 2; - case 2: { - if (tag == 18) { - parse_help: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_help())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->help().data(), this->help().length(), - ::google::protobuf::internal::WireFormat::PARSE, - "help"); - } else { - goto handle_unusual; - } - if (input->ExpectTag(24)) goto parse_type; - break; - } - - // optional .io.prometheus.client.MetricType type = 3; - case 3: { - if (tag == 24) { - parse_type: - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::io::prometheus::client::MetricType_IsValid(value)) { - set_type(static_cast< ::io::prometheus::client::MetricType >(value)); - } else { - mutable_unknown_fields()->AddVarint(3, value); - } - } else { - goto handle_unusual; - } - if (input->ExpectTag(34)) goto parse_metric; - break; - } - - // repeated .io.prometheus.client.Metric metric = 4; - case 4: { - if (tag == 34) { - parse_metric: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_metric())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(34)) goto parse_metric; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:io.prometheus.client.MetricFamily) - return true; -failure: - // @@protoc_insertion_point(parse_failure:io.prometheus.client.MetricFamily) - return false; -#undef DO_ -} - -void MetricFamily::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:io.prometheus.client.MetricFamily) - // optional string name = 1; - if (has_name()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // optional string help = 2; - if (has_help()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->help().data(), this->help().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "help"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->help(), output); - } - - // optional .io.prometheus.client.MetricType type = 3; - if (has_type()) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 3, this->type(), output); - } - - // repeated .io.prometheus.client.Metric metric = 4; - for (int i = 0; i < this->metric_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->metric(i), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:io.prometheus.client.MetricFamily) -} - -::google::protobuf::uint8* MetricFamily::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.MetricFamily) - // optional string name = 1; - if (has_name()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string help = 2; - if (has_help()) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->help().data(), this->help().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "help"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->help(), target); - } - - // optional .io.prometheus.client.MetricType type = 3; - if (has_type()) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 3, this->type(), target); - } - - // repeated .io.prometheus.client.Metric metric = 4; - for (int i = 0; i < this->metric_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 4, this->metric(i), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.MetricFamily) - return target; -} - -int MetricFamily::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional string help = 2; - if (has_help()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->help()); - } - - // optional .io.prometheus.client.MetricType type = 3; - if (has_type()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); - } - - } - // repeated .io.prometheus.client.Metric metric = 4; - total_size += 1 * this->metric_size(); - for (int i = 0; i < this->metric_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->metric(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MetricFamily::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const MetricFamily* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void MetricFamily::MergeFrom(const MetricFamily& from) { - GOOGLE_CHECK_NE(&from, this); - metric_.MergeFrom(from.metric_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from.has_name()) { - set_name(from.name()); - } - if (from.has_help()) { - set_help(from.help()); - } - if (from.has_type()) { - set_type(from.type()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void MetricFamily::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void MetricFamily::CopyFrom(const MetricFamily& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MetricFamily::IsInitialized() const { - - return true; -} - -void MetricFamily::Swap(MetricFamily* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(help_, other->help_); - std::swap(type_, other->type_); - metric_.Swap(&other->metric_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata MetricFamily::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = MetricFamily_descriptor_; - metadata.reflection = MetricFamily_reflection_; - return metadata; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace client -} // namespace prometheus -} // namespace io - -// @@protoc_insertion_point(global_scope) diff --git a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h deleted file mode 100644 index 206ba3704..000000000 --- a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h +++ /dev/null @@ -1,2072 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: metrics.proto - -#ifndef PROTOBUF_metrics_2eproto__INCLUDED -#define PROTOBUF_metrics_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 2006000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace io { -namespace prometheus { -namespace client { - -// Internal implementation detail -- do not call these. -void protobuf_AddDesc_metrics_2eproto(); -void protobuf_AssignDesc_metrics_2eproto(); -void protobuf_ShutdownFile_metrics_2eproto(); - -class LabelPair; -class Gauge; -class Counter; -class Quantile; -class Summary; -class Untyped; -class Histogram; -class Bucket; -class Metric; -class MetricFamily; - -enum MetricType { - COUNTER = 0, - GAUGE = 1, - SUMMARY = 2, - UNTYPED = 3, - HISTOGRAM = 4 -}; -bool MetricType_IsValid(int value); -const MetricType MetricType_MIN = COUNTER; -const MetricType MetricType_MAX = HISTOGRAM; -const int MetricType_ARRAYSIZE = MetricType_MAX + 1; - -const ::google::protobuf::EnumDescriptor* MetricType_descriptor(); -inline const ::std::string& MetricType_Name(MetricType value) { - return ::google::protobuf::internal::NameOfEnum( - MetricType_descriptor(), value); -} -inline bool MetricType_Parse( - const ::std::string& name, MetricType* value) { - return ::google::protobuf::internal::ParseNamedEnum( - MetricType_descriptor(), name, value); -} -// =================================================================== - -class LabelPair : public ::google::protobuf::Message { - public: - LabelPair(); - virtual ~LabelPair(); - - LabelPair(const LabelPair& from); - - inline LabelPair& operator=(const LabelPair& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const LabelPair& default_instance(); - - void Swap(LabelPair* other); - - // implements Message ---------------------------------------------- - - LabelPair* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const LabelPair& from); - void MergeFrom(const LabelPair& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - inline ::std::string* release_name(); - inline void set_allocated_name(::std::string* name); - - // optional string value = 2; - inline bool has_value() const; - inline void clear_value(); - static const int kValueFieldNumber = 2; - inline const ::std::string& value() const; - inline void set_value(const ::std::string& value); - inline void set_value(const char* value); - inline void set_value(const char* value, size_t size); - inline ::std::string* mutable_value(); - inline ::std::string* release_value(); - inline void set_allocated_value(::std::string* value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair) - private: - inline void set_has_name(); - inline void clear_has_name(); - inline void set_has_value(); - inline void clear_has_value(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* name_; - ::std::string* value_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static LabelPair* default_instance_; -}; -// ------------------------------------------------------------------- - -class Gauge : public ::google::protobuf::Message { - public: - Gauge(); - virtual ~Gauge(); - - Gauge(const Gauge& from); - - inline Gauge& operator=(const Gauge& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Gauge& default_instance(); - - void Swap(Gauge* other); - - // implements Message ---------------------------------------------- - - Gauge* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Gauge& from); - void MergeFrom(const Gauge& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional double value = 1; - inline bool has_value() const; - inline void clear_value(); - static const int kValueFieldNumber = 1; - inline double value() const; - inline void set_value(double value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge) - private: - inline void set_has_value(); - inline void clear_has_value(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - double value_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Gauge* default_instance_; -}; -// ------------------------------------------------------------------- - -class Counter : public ::google::protobuf::Message { - public: - Counter(); - virtual ~Counter(); - - Counter(const Counter& from); - - inline Counter& operator=(const Counter& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Counter& default_instance(); - - void Swap(Counter* other); - - // implements Message ---------------------------------------------- - - Counter* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Counter& from); - void MergeFrom(const Counter& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional double value = 1; - inline bool has_value() const; - inline void clear_value(); - static const int kValueFieldNumber = 1; - inline double value() const; - inline void set_value(double value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Counter) - private: - inline void set_has_value(); - inline void clear_has_value(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - double value_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Counter* default_instance_; -}; -// ------------------------------------------------------------------- - -class Quantile : public ::google::protobuf::Message { - public: - Quantile(); - virtual ~Quantile(); - - Quantile(const Quantile& from); - - inline Quantile& operator=(const Quantile& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Quantile& default_instance(); - - void Swap(Quantile* other); - - // implements Message ---------------------------------------------- - - Quantile* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Quantile& from); - void MergeFrom(const Quantile& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional double quantile = 1; - inline bool has_quantile() const; - inline void clear_quantile(); - static const int kQuantileFieldNumber = 1; - inline double quantile() const; - inline void set_quantile(double value); - - // optional double value = 2; - inline bool has_value() const; - inline void clear_value(); - static const int kValueFieldNumber = 2; - inline double value() const; - inline void set_value(double value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile) - private: - inline void set_has_quantile(); - inline void clear_has_quantile(); - inline void set_has_value(); - inline void clear_has_value(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - double quantile_; - double value_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Quantile* default_instance_; -}; -// ------------------------------------------------------------------- - -class Summary : public ::google::protobuf::Message { - public: - Summary(); - virtual ~Summary(); - - Summary(const Summary& from); - - inline Summary& operator=(const Summary& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Summary& default_instance(); - - void Swap(Summary* other); - - // implements Message ---------------------------------------------- - - Summary* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Summary& from); - void MergeFrom(const Summary& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional uint64 sample_count = 1; - inline bool has_sample_count() const; - inline void clear_sample_count(); - static const int kSampleCountFieldNumber = 1; - inline ::google::protobuf::uint64 sample_count() const; - inline void set_sample_count(::google::protobuf::uint64 value); - - // optional double sample_sum = 2; - inline bool has_sample_sum() const; - inline void clear_sample_sum(); - static const int kSampleSumFieldNumber = 2; - inline double sample_sum() const; - inline void set_sample_sum(double value); - - // repeated .io.prometheus.client.Quantile quantile = 3; - inline int quantile_size() const; - inline void clear_quantile(); - static const int kQuantileFieldNumber = 3; - inline const ::io::prometheus::client::Quantile& quantile(int index) const; - inline ::io::prometheus::client::Quantile* mutable_quantile(int index); - inline ::io::prometheus::client::Quantile* add_quantile(); - inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >& - quantile() const; - inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >* - mutable_quantile(); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Summary) - private: - inline void set_has_sample_count(); - inline void clear_has_sample_count(); - inline void set_has_sample_sum(); - inline void clear_has_sample_sum(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sample_count_; - double sample_sum_; - ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile > quantile_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Summary* default_instance_; -}; -// ------------------------------------------------------------------- - -class Untyped : public ::google::protobuf::Message { - public: - Untyped(); - virtual ~Untyped(); - - Untyped(const Untyped& from); - - inline Untyped& operator=(const Untyped& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Untyped& default_instance(); - - void Swap(Untyped* other); - - // implements Message ---------------------------------------------- - - Untyped* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Untyped& from); - void MergeFrom(const Untyped& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional double value = 1; - inline bool has_value() const; - inline void clear_value(); - static const int kValueFieldNumber = 1; - inline double value() const; - inline void set_value(double value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped) - private: - inline void set_has_value(); - inline void clear_has_value(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - double value_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Untyped* default_instance_; -}; -// ------------------------------------------------------------------- - -class Histogram : public ::google::protobuf::Message { - public: - Histogram(); - virtual ~Histogram(); - - Histogram(const Histogram& from); - - inline Histogram& operator=(const Histogram& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Histogram& default_instance(); - - void Swap(Histogram* other); - - // implements Message ---------------------------------------------- - - Histogram* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Histogram& from); - void MergeFrom(const Histogram& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional uint64 sample_count = 1; - inline bool has_sample_count() const; - inline void clear_sample_count(); - static const int kSampleCountFieldNumber = 1; - inline ::google::protobuf::uint64 sample_count() const; - inline void set_sample_count(::google::protobuf::uint64 value); - - // optional double sample_sum = 2; - inline bool has_sample_sum() const; - inline void clear_sample_sum(); - static const int kSampleSumFieldNumber = 2; - inline double sample_sum() const; - inline void set_sample_sum(double value); - - // repeated .io.prometheus.client.Bucket bucket = 3; - inline int bucket_size() const; - inline void clear_bucket(); - static const int kBucketFieldNumber = 3; - inline const ::io::prometheus::client::Bucket& bucket(int index) const; - inline ::io::prometheus::client::Bucket* mutable_bucket(int index); - inline ::io::prometheus::client::Bucket* add_bucket(); - inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >& - bucket() const; - inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >* - mutable_bucket(); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram) - private: - inline void set_has_sample_count(); - inline void clear_has_sample_count(); - inline void set_has_sample_sum(); - inline void clear_has_sample_sum(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 sample_count_; - double sample_sum_; - ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket > bucket_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Histogram* default_instance_; -}; -// ------------------------------------------------------------------- - -class Bucket : public ::google::protobuf::Message { - public: - Bucket(); - virtual ~Bucket(); - - Bucket(const Bucket& from); - - inline Bucket& operator=(const Bucket& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Bucket& default_instance(); - - void Swap(Bucket* other); - - // implements Message ---------------------------------------------- - - Bucket* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Bucket& from); - void MergeFrom(const Bucket& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional uint64 cumulative_count = 1; - inline bool has_cumulative_count() const; - inline void clear_cumulative_count(); - static const int kCumulativeCountFieldNumber = 1; - inline ::google::protobuf::uint64 cumulative_count() const; - inline void set_cumulative_count(::google::protobuf::uint64 value); - - // optional double upper_bound = 2; - inline bool has_upper_bound() const; - inline void clear_upper_bound(); - static const int kUpperBoundFieldNumber = 2; - inline double upper_bound() const; - inline void set_upper_bound(double value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket) - private: - inline void set_has_cumulative_count(); - inline void clear_has_cumulative_count(); - inline void set_has_upper_bound(); - inline void clear_has_upper_bound(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::uint64 cumulative_count_; - double upper_bound_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Bucket* default_instance_; -}; -// ------------------------------------------------------------------- - -class Metric : public ::google::protobuf::Message { - public: - Metric(); - virtual ~Metric(); - - Metric(const Metric& from); - - inline Metric& operator=(const Metric& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const Metric& default_instance(); - - void Swap(Metric* other); - - // implements Message ---------------------------------------------- - - Metric* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const Metric& from); - void MergeFrom(const Metric& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .io.prometheus.client.LabelPair label = 1; - inline int label_size() const; - inline void clear_label(); - static const int kLabelFieldNumber = 1; - inline const ::io::prometheus::client::LabelPair& label(int index) const; - inline ::io::prometheus::client::LabelPair* mutable_label(int index); - inline ::io::prometheus::client::LabelPair* add_label(); - inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >& - label() const; - inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >* - mutable_label(); - - // optional .io.prometheus.client.Gauge gauge = 2; - inline bool has_gauge() const; - inline void clear_gauge(); - static const int kGaugeFieldNumber = 2; - inline const ::io::prometheus::client::Gauge& gauge() const; - inline ::io::prometheus::client::Gauge* mutable_gauge(); - inline ::io::prometheus::client::Gauge* release_gauge(); - inline void set_allocated_gauge(::io::prometheus::client::Gauge* gauge); - - // optional .io.prometheus.client.Counter counter = 3; - inline bool has_counter() const; - inline void clear_counter(); - static const int kCounterFieldNumber = 3; - inline const ::io::prometheus::client::Counter& counter() const; - inline ::io::prometheus::client::Counter* mutable_counter(); - inline ::io::prometheus::client::Counter* release_counter(); - inline void set_allocated_counter(::io::prometheus::client::Counter* counter); - - // optional .io.prometheus.client.Summary summary = 4; - inline bool has_summary() const; - inline void clear_summary(); - static const int kSummaryFieldNumber = 4; - inline const ::io::prometheus::client::Summary& summary() const; - inline ::io::prometheus::client::Summary* mutable_summary(); - inline ::io::prometheus::client::Summary* release_summary(); - inline void set_allocated_summary(::io::prometheus::client::Summary* summary); - - // optional .io.prometheus.client.Untyped untyped = 5; - inline bool has_untyped() const; - inline void clear_untyped(); - static const int kUntypedFieldNumber = 5; - inline const ::io::prometheus::client::Untyped& untyped() const; - inline ::io::prometheus::client::Untyped* mutable_untyped(); - inline ::io::prometheus::client::Untyped* release_untyped(); - inline void set_allocated_untyped(::io::prometheus::client::Untyped* untyped); - - // optional .io.prometheus.client.Histogram histogram = 7; - inline bool has_histogram() const; - inline void clear_histogram(); - static const int kHistogramFieldNumber = 7; - inline const ::io::prometheus::client::Histogram& histogram() const; - inline ::io::prometheus::client::Histogram* mutable_histogram(); - inline ::io::prometheus::client::Histogram* release_histogram(); - inline void set_allocated_histogram(::io::prometheus::client::Histogram* histogram); - - // optional int64 timestamp_ms = 6; - inline bool has_timestamp_ms() const; - inline void clear_timestamp_ms(); - static const int kTimestampMsFieldNumber = 6; - inline ::google::protobuf::int64 timestamp_ms() const; - inline void set_timestamp_ms(::google::protobuf::int64 value); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.Metric) - private: - inline void set_has_gauge(); - inline void clear_has_gauge(); - inline void set_has_counter(); - inline void clear_has_counter(); - inline void set_has_summary(); - inline void clear_has_summary(); - inline void set_has_untyped(); - inline void clear_has_untyped(); - inline void set_has_histogram(); - inline void clear_has_histogram(); - inline void set_has_timestamp_ms(); - inline void clear_has_timestamp_ms(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair > label_; - ::io::prometheus::client::Gauge* gauge_; - ::io::prometheus::client::Counter* counter_; - ::io::prometheus::client::Summary* summary_; - ::io::prometheus::client::Untyped* untyped_; - ::io::prometheus::client::Histogram* histogram_; - ::google::protobuf::int64 timestamp_ms_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static Metric* default_instance_; -}; -// ------------------------------------------------------------------- - -class MetricFamily : public ::google::protobuf::Message { - public: - MetricFamily(); - virtual ~MetricFamily(); - - MetricFamily(const MetricFamily& from); - - inline MetricFamily& operator=(const MetricFamily& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const MetricFamily& default_instance(); - - void Swap(MetricFamily* other); - - // implements Message ---------------------------------------------- - - MetricFamily* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const MetricFamily& from); - void MergeFrom(const MetricFamily& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - inline ::std::string* release_name(); - inline void set_allocated_name(::std::string* name); - - // optional string help = 2; - inline bool has_help() const; - inline void clear_help(); - static const int kHelpFieldNumber = 2; - inline const ::std::string& help() const; - inline void set_help(const ::std::string& value); - inline void set_help(const char* value); - inline void set_help(const char* value, size_t size); - inline ::std::string* mutable_help(); - inline ::std::string* release_help(); - inline void set_allocated_help(::std::string* help); - - // optional .io.prometheus.client.MetricType type = 3; - inline bool has_type() const; - inline void clear_type(); - static const int kTypeFieldNumber = 3; - inline ::io::prometheus::client::MetricType type() const; - inline void set_type(::io::prometheus::client::MetricType value); - - // repeated .io.prometheus.client.Metric metric = 4; - inline int metric_size() const; - inline void clear_metric(); - static const int kMetricFieldNumber = 4; - inline const ::io::prometheus::client::Metric& metric(int index) const; - inline ::io::prometheus::client::Metric* mutable_metric(int index); - inline ::io::prometheus::client::Metric* add_metric(); - inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >& - metric() const; - inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >* - mutable_metric(); - - // @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily) - private: - inline void set_has_name(); - inline void clear_has_name(); - inline void set_has_help(); - inline void clear_has_help(); - inline void set_has_type(); - inline void clear_has_type(); - - ::google::protobuf::UnknownFieldSet _unknown_fields_; - - ::google::protobuf::uint32 _has_bits_[1]; - mutable int _cached_size_; - ::std::string* name_; - ::std::string* help_; - ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric > metric_; - int type_; - friend void protobuf_AddDesc_metrics_2eproto(); - friend void protobuf_AssignDesc_metrics_2eproto(); - friend void protobuf_ShutdownFile_metrics_2eproto(); - - void InitAsDefaultInstance(); - static MetricFamily* default_instance_; -}; -// =================================================================== - - -// =================================================================== - -// LabelPair - -// optional string name = 1; -inline bool LabelPair::has_name() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void LabelPair::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void LabelPair::clear_has_name() { - _has_bits_[0] &= ~0x00000001u; -} -inline void LabelPair::clear_name() { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_->clear(); - } - clear_has_name(); -} -inline const ::std::string& LabelPair::name() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.name) - return *name_; -} -inline void LabelPair::set_name(const ::std::string& value) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(value); - // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.name) -} -inline void LabelPair::set_name(const char* value) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(value); - // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.name) -} -inline void LabelPair::set_name(const char* value, size_t size) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.name) -} -inline ::std::string* LabelPair::mutable_name() { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.name) - return name_; -} -inline ::std::string* LabelPair::release_name() { - clear_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = name_; - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void LabelPair::set_allocated_name(::std::string* name) { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete name_; - } - if (name) { - set_has_name(); - name_ = name; - } else { - clear_has_name(); - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.name) -} - -// optional string value = 2; -inline bool LabelPair::has_value() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void LabelPair::set_has_value() { - _has_bits_[0] |= 0x00000002u; -} -inline void LabelPair::clear_has_value() { - _has_bits_[0] &= ~0x00000002u; -} -inline void LabelPair::clear_value() { - if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_->clear(); - } - clear_has_value(); -} -inline const ::std::string& LabelPair::value() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.value) - return *value_; -} -inline void LabelPair::set_value(const ::std::string& value) { - set_has_value(); - if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_ = new ::std::string; - } - value_->assign(value); - // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.value) -} -inline void LabelPair::set_value(const char* value) { - set_has_value(); - if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_ = new ::std::string; - } - value_->assign(value); - // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.value) -} -inline void LabelPair::set_value(const char* value, size_t size) { - set_has_value(); - if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_ = new ::std::string; - } - value_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.value) -} -inline ::std::string* LabelPair::mutable_value() { - set_has_value(); - if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - value_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.value) - return value_; -} -inline ::std::string* LabelPair::release_value() { - clear_has_value(); - if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = value_; - value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void LabelPair::set_allocated_value(::std::string* value) { - if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete value_; - } - if (value) { - set_has_value(); - value_ = value; - } else { - clear_has_value(); - value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.value) -} - -// ------------------------------------------------------------------- - -// Gauge - -// optional double value = 1; -inline bool Gauge::has_value() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Gauge::set_has_value() { - _has_bits_[0] |= 0x00000001u; -} -inline void Gauge::clear_has_value() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Gauge::clear_value() { - value_ = 0; - clear_has_value(); -} -inline double Gauge::value() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Gauge.value) - return value_; -} -inline void Gauge::set_value(double value) { - set_has_value(); - value_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Gauge.value) -} - -// ------------------------------------------------------------------- - -// Counter - -// optional double value = 1; -inline bool Counter::has_value() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Counter::set_has_value() { - _has_bits_[0] |= 0x00000001u; -} -inline void Counter::clear_has_value() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Counter::clear_value() { - value_ = 0; - clear_has_value(); -} -inline double Counter::value() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Counter.value) - return value_; -} -inline void Counter::set_value(double value) { - set_has_value(); - value_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Counter.value) -} - -// ------------------------------------------------------------------- - -// Quantile - -// optional double quantile = 1; -inline bool Quantile::has_quantile() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Quantile::set_has_quantile() { - _has_bits_[0] |= 0x00000001u; -} -inline void Quantile::clear_has_quantile() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Quantile::clear_quantile() { - quantile_ = 0; - clear_has_quantile(); -} -inline double Quantile::quantile() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.quantile) - return quantile_; -} -inline void Quantile::set_quantile(double value) { - set_has_quantile(); - quantile_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.quantile) -} - -// optional double value = 2; -inline bool Quantile::has_value() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Quantile::set_has_value() { - _has_bits_[0] |= 0x00000002u; -} -inline void Quantile::clear_has_value() { - _has_bits_[0] &= ~0x00000002u; -} -inline void Quantile::clear_value() { - value_ = 0; - clear_has_value(); -} -inline double Quantile::value() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.value) - return value_; -} -inline void Quantile::set_value(double value) { - set_has_value(); - value_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.value) -} - -// ------------------------------------------------------------------- - -// Summary - -// optional uint64 sample_count = 1; -inline bool Summary::has_sample_count() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Summary::set_has_sample_count() { - _has_bits_[0] |= 0x00000001u; -} -inline void Summary::clear_has_sample_count() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Summary::clear_sample_count() { - sample_count_ = GOOGLE_ULONGLONG(0); - clear_has_sample_count(); -} -inline ::google::protobuf::uint64 Summary::sample_count() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_count) - return sample_count_; -} -inline void Summary::set_sample_count(::google::protobuf::uint64 value) { - set_has_sample_count(); - sample_count_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_count) -} - -// optional double sample_sum = 2; -inline bool Summary::has_sample_sum() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Summary::set_has_sample_sum() { - _has_bits_[0] |= 0x00000002u; -} -inline void Summary::clear_has_sample_sum() { - _has_bits_[0] &= ~0x00000002u; -} -inline void Summary::clear_sample_sum() { - sample_sum_ = 0; - clear_has_sample_sum(); -} -inline double Summary::sample_sum() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_sum) - return sample_sum_; -} -inline void Summary::set_sample_sum(double value) { - set_has_sample_sum(); - sample_sum_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_sum) -} - -// repeated .io.prometheus.client.Quantile quantile = 3; -inline int Summary::quantile_size() const { - return quantile_.size(); -} -inline void Summary::clear_quantile() { - quantile_.Clear(); -} -inline const ::io::prometheus::client::Quantile& Summary::quantile(int index) const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.quantile) - return quantile_.Get(index); -} -inline ::io::prometheus::client::Quantile* Summary::mutable_quantile(int index) { - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Summary.quantile) - return quantile_.Mutable(index); -} -inline ::io::prometheus::client::Quantile* Summary::add_quantile() { - // @@protoc_insertion_point(field_add:io.prometheus.client.Summary.quantile) - return quantile_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >& -Summary::quantile() const { - // @@protoc_insertion_point(field_list:io.prometheus.client.Summary.quantile) - return quantile_; -} -inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >* -Summary::mutable_quantile() { - // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Summary.quantile) - return &quantile_; -} - -// ------------------------------------------------------------------- - -// Untyped - -// optional double value = 1; -inline bool Untyped::has_value() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Untyped::set_has_value() { - _has_bits_[0] |= 0x00000001u; -} -inline void Untyped::clear_has_value() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Untyped::clear_value() { - value_ = 0; - clear_has_value(); -} -inline double Untyped::value() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Untyped.value) - return value_; -} -inline void Untyped::set_value(double value) { - set_has_value(); - value_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Untyped.value) -} - -// ------------------------------------------------------------------- - -// Histogram - -// optional uint64 sample_count = 1; -inline bool Histogram::has_sample_count() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Histogram::set_has_sample_count() { - _has_bits_[0] |= 0x00000001u; -} -inline void Histogram::clear_has_sample_count() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Histogram::clear_sample_count() { - sample_count_ = GOOGLE_ULONGLONG(0); - clear_has_sample_count(); -} -inline ::google::protobuf::uint64 Histogram::sample_count() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_count) - return sample_count_; -} -inline void Histogram::set_sample_count(::google::protobuf::uint64 value) { - set_has_sample_count(); - sample_count_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_count) -} - -// optional double sample_sum = 2; -inline bool Histogram::has_sample_sum() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Histogram::set_has_sample_sum() { - _has_bits_[0] |= 0x00000002u; -} -inline void Histogram::clear_has_sample_sum() { - _has_bits_[0] &= ~0x00000002u; -} -inline void Histogram::clear_sample_sum() { - sample_sum_ = 0; - clear_has_sample_sum(); -} -inline double Histogram::sample_sum() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_sum) - return sample_sum_; -} -inline void Histogram::set_sample_sum(double value) { - set_has_sample_sum(); - sample_sum_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_sum) -} - -// repeated .io.prometheus.client.Bucket bucket = 3; -inline int Histogram::bucket_size() const { - return bucket_.size(); -} -inline void Histogram::clear_bucket() { - bucket_.Clear(); -} -inline const ::io::prometheus::client::Bucket& Histogram::bucket(int index) const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.bucket) - return bucket_.Get(index); -} -inline ::io::prometheus::client::Bucket* Histogram::mutable_bucket(int index) { - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Histogram.bucket) - return bucket_.Mutable(index); -} -inline ::io::prometheus::client::Bucket* Histogram::add_bucket() { - // @@protoc_insertion_point(field_add:io.prometheus.client.Histogram.bucket) - return bucket_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >& -Histogram::bucket() const { - // @@protoc_insertion_point(field_list:io.prometheus.client.Histogram.bucket) - return bucket_; -} -inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >* -Histogram::mutable_bucket() { - // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Histogram.bucket) - return &bucket_; -} - -// ------------------------------------------------------------------- - -// Bucket - -// optional uint64 cumulative_count = 1; -inline bool Bucket::has_cumulative_count() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Bucket::set_has_cumulative_count() { - _has_bits_[0] |= 0x00000001u; -} -inline void Bucket::clear_has_cumulative_count() { - _has_bits_[0] &= ~0x00000001u; -} -inline void Bucket::clear_cumulative_count() { - cumulative_count_ = GOOGLE_ULONGLONG(0); - clear_has_cumulative_count(); -} -inline ::google::protobuf::uint64 Bucket::cumulative_count() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.cumulative_count) - return cumulative_count_; -} -inline void Bucket::set_cumulative_count(::google::protobuf::uint64 value) { - set_has_cumulative_count(); - cumulative_count_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.cumulative_count) -} - -// optional double upper_bound = 2; -inline bool Bucket::has_upper_bound() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Bucket::set_has_upper_bound() { - _has_bits_[0] |= 0x00000002u; -} -inline void Bucket::clear_has_upper_bound() { - _has_bits_[0] &= ~0x00000002u; -} -inline void Bucket::clear_upper_bound() { - upper_bound_ = 0; - clear_has_upper_bound(); -} -inline double Bucket::upper_bound() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.upper_bound) - return upper_bound_; -} -inline void Bucket::set_upper_bound(double value) { - set_has_upper_bound(); - upper_bound_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.upper_bound) -} - -// ------------------------------------------------------------------- - -// Metric - -// repeated .io.prometheus.client.LabelPair label = 1; -inline int Metric::label_size() const { - return label_.size(); -} -inline void Metric::clear_label() { - label_.Clear(); -} -inline const ::io::prometheus::client::LabelPair& Metric::label(int index) const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.label) - return label_.Get(index); -} -inline ::io::prometheus::client::LabelPair* Metric::mutable_label(int index) { - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.label) - return label_.Mutable(index); -} -inline ::io::prometheus::client::LabelPair* Metric::add_label() { - // @@protoc_insertion_point(field_add:io.prometheus.client.Metric.label) - return label_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >& -Metric::label() const { - // @@protoc_insertion_point(field_list:io.prometheus.client.Metric.label) - return label_; -} -inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >* -Metric::mutable_label() { - // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Metric.label) - return &label_; -} - -// optional .io.prometheus.client.Gauge gauge = 2; -inline bool Metric::has_gauge() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Metric::set_has_gauge() { - _has_bits_[0] |= 0x00000002u; -} -inline void Metric::clear_has_gauge() { - _has_bits_[0] &= ~0x00000002u; -} -inline void Metric::clear_gauge() { - if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear(); - clear_has_gauge(); -} -inline const ::io::prometheus::client::Gauge& Metric::gauge() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.gauge) - return gauge_ != NULL ? *gauge_ : *default_instance_->gauge_; -} -inline ::io::prometheus::client::Gauge* Metric::mutable_gauge() { - set_has_gauge(); - if (gauge_ == NULL) gauge_ = new ::io::prometheus::client::Gauge; - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.gauge) - return gauge_; -} -inline ::io::prometheus::client::Gauge* Metric::release_gauge() { - clear_has_gauge(); - ::io::prometheus::client::Gauge* temp = gauge_; - gauge_ = NULL; - return temp; -} -inline void Metric::set_allocated_gauge(::io::prometheus::client::Gauge* gauge) { - delete gauge_; - gauge_ = gauge; - if (gauge) { - set_has_gauge(); - } else { - clear_has_gauge(); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.gauge) -} - -// optional .io.prometheus.client.Counter counter = 3; -inline bool Metric::has_counter() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void Metric::set_has_counter() { - _has_bits_[0] |= 0x00000004u; -} -inline void Metric::clear_has_counter() { - _has_bits_[0] &= ~0x00000004u; -} -inline void Metric::clear_counter() { - if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear(); - clear_has_counter(); -} -inline const ::io::prometheus::client::Counter& Metric::counter() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.counter) - return counter_ != NULL ? *counter_ : *default_instance_->counter_; -} -inline ::io::prometheus::client::Counter* Metric::mutable_counter() { - set_has_counter(); - if (counter_ == NULL) counter_ = new ::io::prometheus::client::Counter; - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.counter) - return counter_; -} -inline ::io::prometheus::client::Counter* Metric::release_counter() { - clear_has_counter(); - ::io::prometheus::client::Counter* temp = counter_; - counter_ = NULL; - return temp; -} -inline void Metric::set_allocated_counter(::io::prometheus::client::Counter* counter) { - delete counter_; - counter_ = counter; - if (counter) { - set_has_counter(); - } else { - clear_has_counter(); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.counter) -} - -// optional .io.prometheus.client.Summary summary = 4; -inline bool Metric::has_summary() const { - return (_has_bits_[0] & 0x00000008u) != 0; -} -inline void Metric::set_has_summary() { - _has_bits_[0] |= 0x00000008u; -} -inline void Metric::clear_has_summary() { - _has_bits_[0] &= ~0x00000008u; -} -inline void Metric::clear_summary() { - if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear(); - clear_has_summary(); -} -inline const ::io::prometheus::client::Summary& Metric::summary() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.summary) - return summary_ != NULL ? *summary_ : *default_instance_->summary_; -} -inline ::io::prometheus::client::Summary* Metric::mutable_summary() { - set_has_summary(); - if (summary_ == NULL) summary_ = new ::io::prometheus::client::Summary; - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.summary) - return summary_; -} -inline ::io::prometheus::client::Summary* Metric::release_summary() { - clear_has_summary(); - ::io::prometheus::client::Summary* temp = summary_; - summary_ = NULL; - return temp; -} -inline void Metric::set_allocated_summary(::io::prometheus::client::Summary* summary) { - delete summary_; - summary_ = summary; - if (summary) { - set_has_summary(); - } else { - clear_has_summary(); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.summary) -} - -// optional .io.prometheus.client.Untyped untyped = 5; -inline bool Metric::has_untyped() const { - return (_has_bits_[0] & 0x00000010u) != 0; -} -inline void Metric::set_has_untyped() { - _has_bits_[0] |= 0x00000010u; -} -inline void Metric::clear_has_untyped() { - _has_bits_[0] &= ~0x00000010u; -} -inline void Metric::clear_untyped() { - if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear(); - clear_has_untyped(); -} -inline const ::io::prometheus::client::Untyped& Metric::untyped() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.untyped) - return untyped_ != NULL ? *untyped_ : *default_instance_->untyped_; -} -inline ::io::prometheus::client::Untyped* Metric::mutable_untyped() { - set_has_untyped(); - if (untyped_ == NULL) untyped_ = new ::io::prometheus::client::Untyped; - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.untyped) - return untyped_; -} -inline ::io::prometheus::client::Untyped* Metric::release_untyped() { - clear_has_untyped(); - ::io::prometheus::client::Untyped* temp = untyped_; - untyped_ = NULL; - return temp; -} -inline void Metric::set_allocated_untyped(::io::prometheus::client::Untyped* untyped) { - delete untyped_; - untyped_ = untyped; - if (untyped) { - set_has_untyped(); - } else { - clear_has_untyped(); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.untyped) -} - -// optional .io.prometheus.client.Histogram histogram = 7; -inline bool Metric::has_histogram() const { - return (_has_bits_[0] & 0x00000020u) != 0; -} -inline void Metric::set_has_histogram() { - _has_bits_[0] |= 0x00000020u; -} -inline void Metric::clear_has_histogram() { - _has_bits_[0] &= ~0x00000020u; -} -inline void Metric::clear_histogram() { - if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear(); - clear_has_histogram(); -} -inline const ::io::prometheus::client::Histogram& Metric::histogram() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.histogram) - return histogram_ != NULL ? *histogram_ : *default_instance_->histogram_; -} -inline ::io::prometheus::client::Histogram* Metric::mutable_histogram() { - set_has_histogram(); - if (histogram_ == NULL) histogram_ = new ::io::prometheus::client::Histogram; - // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.histogram) - return histogram_; -} -inline ::io::prometheus::client::Histogram* Metric::release_histogram() { - clear_has_histogram(); - ::io::prometheus::client::Histogram* temp = histogram_; - histogram_ = NULL; - return temp; -} -inline void Metric::set_allocated_histogram(::io::prometheus::client::Histogram* histogram) { - delete histogram_; - histogram_ = histogram; - if (histogram) { - set_has_histogram(); - } else { - clear_has_histogram(); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.histogram) -} - -// optional int64 timestamp_ms = 6; -inline bool Metric::has_timestamp_ms() const { - return (_has_bits_[0] & 0x00000040u) != 0; -} -inline void Metric::set_has_timestamp_ms() { - _has_bits_[0] |= 0x00000040u; -} -inline void Metric::clear_has_timestamp_ms() { - _has_bits_[0] &= ~0x00000040u; -} -inline void Metric::clear_timestamp_ms() { - timestamp_ms_ = GOOGLE_LONGLONG(0); - clear_has_timestamp_ms(); -} -inline ::google::protobuf::int64 Metric::timestamp_ms() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.timestamp_ms) - return timestamp_ms_; -} -inline void Metric::set_timestamp_ms(::google::protobuf::int64 value) { - set_has_timestamp_ms(); - timestamp_ms_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.Metric.timestamp_ms) -} - -// ------------------------------------------------------------------- - -// MetricFamily - -// optional string name = 1; -inline bool MetricFamily::has_name() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void MetricFamily::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void MetricFamily::clear_has_name() { - _has_bits_[0] &= ~0x00000001u; -} -inline void MetricFamily::clear_name() { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_->clear(); - } - clear_has_name(); -} -inline const ::std::string& MetricFamily::name() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.name) - return *name_; -} -inline void MetricFamily::set_name(const ::std::string& value) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(value); - // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.name) -} -inline void MetricFamily::set_name(const char* value) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(value); - // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.name) -} -inline void MetricFamily::set_name(const char* value, size_t size) { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.name) -} -inline ::std::string* MetricFamily::mutable_name() { - set_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - name_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.name) - return name_; -} -inline ::std::string* MetricFamily::release_name() { - clear_has_name(); - if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = name_; - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void MetricFamily::set_allocated_name(::std::string* name) { - if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete name_; - } - if (name) { - set_has_name(); - name_ = name; - } else { - clear_has_name(); - name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.name) -} - -// optional string help = 2; -inline bool MetricFamily::has_help() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void MetricFamily::set_has_help() { - _has_bits_[0] |= 0x00000002u; -} -inline void MetricFamily::clear_has_help() { - _has_bits_[0] &= ~0x00000002u; -} -inline void MetricFamily::clear_help() { - if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_->clear(); - } - clear_has_help(); -} -inline const ::std::string& MetricFamily::help() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.help) - return *help_; -} -inline void MetricFamily::set_help(const ::std::string& value) { - set_has_help(); - if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_ = new ::std::string; - } - help_->assign(value); - // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.help) -} -inline void MetricFamily::set_help(const char* value) { - set_has_help(); - if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_ = new ::std::string; - } - help_->assign(value); - // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.help) -} -inline void MetricFamily::set_help(const char* value, size_t size) { - set_has_help(); - if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_ = new ::std::string; - } - help_->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.help) -} -inline ::std::string* MetricFamily::mutable_help() { - set_has_help(); - if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - help_ = new ::std::string; - } - // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.help) - return help_; -} -inline ::std::string* MetricFamily::release_help() { - clear_has_help(); - if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - return NULL; - } else { - ::std::string* temp = help_; - help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - return temp; - } -} -inline void MetricFamily::set_allocated_help(::std::string* help) { - if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { - delete help_; - } - if (help) { - set_has_help(); - help_ = help; - } else { - clear_has_help(); - help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.help) -} - -// optional .io.prometheus.client.MetricType type = 3; -inline bool MetricFamily::has_type() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void MetricFamily::set_has_type() { - _has_bits_[0] |= 0x00000004u; -} -inline void MetricFamily::clear_has_type() { - _has_bits_[0] &= ~0x00000004u; -} -inline void MetricFamily::clear_type() { - type_ = 0; - clear_has_type(); -} -inline ::io::prometheus::client::MetricType MetricFamily::type() const { - // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.type) - return static_cast< ::io::prometheus::client::MetricType >(type_); -} -inline void MetricFamily::set_type(::io::prometheus::client::MetricType value) { - assert(::io::prometheus::client::MetricType_IsValid(value)); - set_has_type(); - type_ = value; - // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.type) -} - -// repeated .io.prometheus.client.Metric metric = 4; -inline int MetricFamily::metric_size() const { - return metric_.size(); -} -inline void MetricFamily::clear_metric() { - metric_.Clear(); -} -inline const ::io::prometheus::client::Metric& MetricFamily::metric(int index) const { - // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.metric) - return metric_.Get(index); -} -inline ::io::prometheus::client::Metric* MetricFamily::mutable_metric(int index) { - // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.metric) - return metric_.Mutable(index); -} -inline ::io::prometheus::client::Metric* MetricFamily::add_metric() { - // @@protoc_insertion_point(field_add:io.prometheus.client.MetricFamily.metric) - return metric_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >& -MetricFamily::metric() const { - // @@protoc_insertion_point(field_list:io.prometheus.client.MetricFamily.metric) - return metric_; -} -inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >* -MetricFamily::mutable_metric() { - // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.MetricFamily.metric) - return &metric_; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace client -} // namespace prometheus -} // namespace io - -#ifndef SWIG -namespace google { -namespace protobuf { - -template <> struct is_proto_enum< ::io::prometheus::client::MetricType> : ::google::protobuf::internal::true_type {}; -template <> -inline const EnumDescriptor* GetEnumDescriptor< ::io::prometheus::client::MetricType>() { - return ::io::prometheus::client::MetricType_descriptor(); -} - -} // namespace google -} // namespace protobuf -#endif // SWIG - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_metrics_2eproto__INCLUDED diff --git a/vendor/github.com/prometheus/client_model/metrics.proto b/vendor/github.com/prometheus/client_model/metrics.proto deleted file mode 100644 index 0b84af920..000000000 --- a/vendor/github.com/prometheus/client_model/metrics.proto +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 Prometheus Team -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package io.prometheus.client; -option java_package = "io.prometheus.client"; - -message LabelPair { - optional string name = 1; - optional string value = 2; -} - -enum MetricType { - COUNTER = 0; - GAUGE = 1; - SUMMARY = 2; - UNTYPED = 3; - HISTOGRAM = 4; -} - -message Gauge { - optional double value = 1; -} - -message Counter { - optional double value = 1; -} - -message Quantile { - optional double quantile = 1; - optional double value = 2; -} - -message Summary { - optional uint64 sample_count = 1; - optional double sample_sum = 2; - repeated Quantile quantile = 3; -} - -message Untyped { - optional double value = 1; -} - -message Histogram { - optional uint64 sample_count = 1; - optional double sample_sum = 2; - repeated Bucket bucket = 3; // Ordered in increasing order of upper_bound, +Inf bucket is optional. -} - -message Bucket { - optional uint64 cumulative_count = 1; // Cumulative in increasing order. - optional double upper_bound = 2; // Inclusive. -} - -message Metric { - repeated LabelPair label = 1; - optional Gauge gauge = 2; - optional Counter counter = 3; - optional Summary summary = 4; - optional Untyped untyped = 5; - optional Histogram histogram = 7; - optional int64 timestamp_ms = 6; -} - -message MetricFamily { - optional string name = 1; - optional string help = 2; - optional MetricType type = 3; - repeated Metric metric = 4; -} diff --git a/vendor/github.com/prometheus/client_model/pom.xml b/vendor/github.com/prometheus/client_model/pom.xml deleted file mode 100644 index 4d34c9015..000000000 --- a/vendor/github.com/prometheus/client_model/pom.xml +++ /dev/null @@ -1,130 +0,0 @@ - - - 4.0.0 - - io.prometheus.client - model - 0.0.3-SNAPSHOT - - - org.sonatype.oss - oss-parent - 7 - - - Prometheus Client Data Model - http://github.com/prometheus/client_model - - Prometheus Client Data Model: Generated Protocol Buffer Assets - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - scm:git:git@github.com:prometheus/client_model.git - scm:git:git@github.com:prometheus/client_model.git - git@github.com:prometheus/client_model.git - - - - - mtp - Matt T. Proud - matt.proud@gmail.com - - - - - - com.google.protobuf - protobuf-java - 2.5.0 - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - UTF-8 - UTF-8 - true - - - - generate-javadoc-site-report - site - - javadoc - - - - attach-javadocs - - jar - - - - - - maven-compiler-plugin - - 1.6 - 1.6 - - 3.1 - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - - - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - diff --git a/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py b/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py deleted file mode 100644 index 617c0ced0..000000000 --- a/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ - # Copyright 2013 Prometheus Team - # Licensed under the Apache License, Version 2.0 (the "License"); - # you may not use this file except in compliance with the License. - # You may obtain a copy of the License at - - # http://www.apache.org/licenses/LICENSE-2.0 - - # Unless required by applicable law or agreed to in writing, software - # distributed under the License is distributed on an "AS IS" BASIS, - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - # See the License for the specific language governing permissions and - # limitations under the License. diff --git a/vendor/github.com/prometheus/client_model/ruby/.gitignore b/vendor/github.com/prometheus/client_model/ruby/.gitignore deleted file mode 100644 index 8442a4709..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.gem -.bundle -Gemfile.lock -pkg -vendor/bundle diff --git a/vendor/github.com/prometheus/client_model/ruby/Gemfile b/vendor/github.com/prometheus/client_model/ruby/Gemfile deleted file mode 100644 index 1ff638cdc..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/Gemfile +++ /dev/null @@ -1,4 +0,0 @@ -source 'https://rubygems.org' - -# Specify your gem's dependencies in prometheus-client-model.gemspec -gemspec diff --git a/vendor/github.com/prometheus/client_model/ruby/Makefile b/vendor/github.com/prometheus/client_model/ruby/Makefile deleted file mode 100644 index 09d544bf0..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -VENDOR_BUNDLE = vendor/bundle - -build: $(VENDOR_BUNDLE)/.bundled - BEEFCAKE_NAMESPACE=Prometheus::Client protoc --beefcake_out lib/prometheus/client/model -I .. ../metrics.proto - -$(VENDOR_BUNDLE): - mkdir -p $@ - -$(VENDOR_BUNDLE)/.bundled: $(VENDOR_BUNDLE) Gemfile - bundle install --quiet --path $< - @touch $@ - -clean: - -rm -f lib/prometheus/client/model/metrics.pb.rb - -rm -rf $(VENDOR_BUNDLE) - -.PHONY: build clean diff --git a/vendor/github.com/prometheus/client_model/ruby/README.md b/vendor/github.com/prometheus/client_model/ruby/README.md deleted file mode 100644 index c45fcc7a9..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Prometheus Ruby client model - -Data model artifacts for the [Prometheus Ruby client][1]. - -## Installation - - gem install prometheus-client-model - -## Usage - -Build the artifacts from the protobuf specification: - - make build - -While this Gem's main purpose is to define the Prometheus data types for the -[client][1], it's possible to use it without the client to decode a stream of -delimited protobuf messages: - -```ruby -require 'open-uri' -require 'prometheus/client/model' - -CONTENT_TYPE = 'application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited' - -stream = open('http://localhost:9090/metrics', 'Accept' => CONTENT_TYPE).read -while family = Prometheus::Client::MetricFamily.read_delimited(stream) - puts family -end -``` - -[1]: https://github.com/prometheus/client_ruby diff --git a/vendor/github.com/prometheus/client_model/ruby/Rakefile b/vendor/github.com/prometheus/client_model/ruby/Rakefile deleted file mode 100644 index 29955274e..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/Rakefile +++ /dev/null @@ -1 +0,0 @@ -require "bundler/gem_tasks" diff --git a/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec b/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec deleted file mode 100644 index 438ba127e..000000000 --- a/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec +++ /dev/null @@ -1,22 +0,0 @@ -# coding: utf-8 -lib = File.expand_path('../lib', __FILE__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'prometheus/client/model/version' - -Gem::Specification.new do |spec| - spec.name = 'prometheus-client-model' - spec.version = Prometheus::Client::Model::VERSION - spec.authors = ['Tobias Schmidt'] - spec.email = ['tobidt@gmail.com'] - spec.summary = 'Data model artifacts for the Prometheus Ruby client' - spec.homepage = 'https://github.com/prometheus/client_model/tree/master/ruby' - spec.license = 'Apache 2.0' - - spec.files = %w[README.md LICENSE] + Dir.glob('{lib/**/*}') - spec.require_paths = ['lib'] - - spec.add_dependency 'beefcake', '>= 0.4.0' - - spec.add_development_dependency 'bundler', '~> 1.3' - spec.add_development_dependency 'rake' -end diff --git a/vendor/github.com/prometheus/client_model/setup.py b/vendor/github.com/prometheus/client_model/setup.py deleted file mode 100644 index 67b9f20e3..000000000 --- a/vendor/github.com/prometheus/client_model/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/python - -from setuptools import setup - -setup( - name = 'prometheus_client_model', - version = '0.0.1', - author = 'Matt T. Proud', - author_email = 'matt.proud@gmail.com', - description = 'Data model artifacts for the Prometheus client.', - license = 'Apache License 2.0', - url = 'http://github.com/prometheus/client_model', - packages = ['prometheus', 'prometheus/client', 'prometheus/client/model'], - package_dir = {'': 'python'}, - requires = ['protobuf(==2.4.1)'], - platforms = 'Platform Independent', - classifiers = ['Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Intended Audience :: System Administrators', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: OS Independent', - 'Topic :: Software Development :: Testing', - 'Topic :: System :: Monitoring']) diff --git a/vendor/github.com/prometheus/common/.travis.yml b/vendor/github.com/prometheus/common/.travis.yml deleted file mode 100644 index 2fe8e9ad7..000000000 --- a/vendor/github.com/prometheus/common/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -sudo: false - -language: go -go: - - 1.7.5 - - tip diff --git a/vendor/github.com/prometheus/common/CONTRIBUTING.md b/vendor/github.com/prometheus/common/CONTRIBUTING.md deleted file mode 100644 index 40503edbf..000000000 --- a/vendor/github.com/prometheus/common/CONTRIBUTING.md +++ /dev/null @@ -1,18 +0,0 @@ -# Contributing - -Prometheus uses GitHub to manage reviews of pull requests. - -* If you have a trivial fix or improvement, go ahead and create a pull request, - addressing (with `@...`) the maintainer of this repository (see - [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request. - -* If you plan to do something more involved, first discuss your ideas - on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). - This will avoid unnecessary work and surely give you and us a good deal - of inspiration. - -* Relevant coding style guidelines are the [Go Code Review - Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) - and the _Formatting and style_ section of Peter Bourgon's [Go: Best - Practices for Production - Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). diff --git a/vendor/github.com/prometheus/common/MAINTAINERS.md b/vendor/github.com/prometheus/common/MAINTAINERS.md deleted file mode 100644 index 1b3152161..000000000 --- a/vendor/github.com/prometheus/common/MAINTAINERS.md +++ /dev/null @@ -1 +0,0 @@ -* Fabian Reinartz diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md deleted file mode 100644 index 11a584945..000000000 --- a/vendor/github.com/prometheus/common/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Common -[![Build Status](https://travis-ci.org/prometheus/common.svg)](https://travis-ci.org/prometheus/common) - -This repository contains Go libraries that are shared across Prometheus -components and libraries. - -* **config**: Common configuration structures -* **expfmt**: Decoding and encoding for the exposition format -* **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus) -* **model**: Shared data structures -* **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context` -* **version**: Version informations and metric diff --git a/vendor/github.com/prometheus/common/config/config.go b/vendor/github.com/prometheus/common/config/config.go deleted file mode 100644 index 9195c34bf..000000000 --- a/vendor/github.com/prometheus/common/config/config.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "fmt" - "strings" -) - -func checkOverflow(m map[string]interface{}, ctx string) error { - if len(m) > 0 { - var keys []string - for k := range m { - keys = append(keys, k) - } - return fmt.Errorf("unknown fields in %s: %s", ctx, strings.Join(keys, ", ")) - } - return nil -} - -// Secret special type for storing secrets. -type Secret string - -// MarshalYAML implements the yaml.Marshaler interface for Secrets. -func (s Secret) MarshalYAML() (interface{}, error) { - if s != "" { - return "", nil - } - return nil, nil -} - -//UnmarshalYAML implements the yaml.Unmarshaler interface for Secrets. -func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error { - type plain Secret - return unmarshal((*plain)(s)) -} diff --git a/vendor/github.com/prometheus/common/config/http_config.go b/vendor/github.com/prometheus/common/config/http_config.go deleted file mode 100644 index ea231bf8d..000000000 --- a/vendor/github.com/prometheus/common/config/http_config.go +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "gopkg.in/yaml.v2" -) - -// BasicAuth contains basic HTTP authentication credentials. -type BasicAuth struct { - Username string `yaml:"username"` - Password Secret `yaml:"password"` - - // Catches all undefined fields and must be empty after parsing. - XXX map[string]interface{} `yaml:",inline"` -} - -// URL is a custom URL type that allows validation at configuration load time. -type URL struct { - *url.URL -} - -// UnmarshalYAML implements the yaml.Unmarshaler interface for URLs. -func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - if err := unmarshal(&s); err != nil { - return err - } - - urlp, err := url.Parse(s) - if err != nil { - return err - } - u.URL = urlp - return nil -} - -// MarshalYAML implements the yaml.Marshaler interface for URLs. -func (u URL) MarshalYAML() (interface{}, error) { - if u.URL != nil { - return u.String(), nil - } - return nil, nil -} - -// HTTPClientConfig configures an HTTP client. -type HTTPClientConfig struct { - // The HTTP basic authentication credentials for the targets. - BasicAuth *BasicAuth `yaml:"basic_auth,omitempty"` - // The bearer token for the targets. - BearerToken Secret `yaml:"bearer_token,omitempty"` - // The bearer token file for the targets. - BearerTokenFile string `yaml:"bearer_token_file,omitempty"` - // HTTP proxy server to use to connect to the targets. - ProxyURL URL `yaml:"proxy_url,omitempty"` - // TLSConfig to use to connect to the targets. - TLSConfig TLSConfig `yaml:"tls_config,omitempty"` - - // Catches all undefined fields and must be empty after parsing. - XXX map[string]interface{} `yaml:",inline"` -} - -// Validate validates the HTTPClientConfig to check only one of BearerToken, -// BasicAuth and BearerTokenFile is configured. -func (c *HTTPClientConfig) Validate() error { - if len(c.BearerToken) > 0 && len(c.BearerTokenFile) > 0 { - return fmt.Errorf("at most one of bearer_token & bearer_token_file must be configured") - } - if c.BasicAuth != nil && (len(c.BearerToken) > 0 || len(c.BearerTokenFile) > 0) { - return fmt.Errorf("at most one of basic_auth, bearer_token & bearer_token_file must be configured") - } - return nil -} - -// UnmarshalYAML implements the yaml.Unmarshaler interface -func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { - type plain HTTPClientConfig - err := unmarshal((*plain)(c)) - if err != nil { - return err - } - err = c.Validate() - if err != nil { - return c.Validate() - } - return checkOverflow(c.XXX, "http_client_config") -} - -// UnmarshalYAML implements the yaml.Unmarshaler interface. -func (a *BasicAuth) UnmarshalYAML(unmarshal func(interface{}) error) error { - type plain BasicAuth - err := unmarshal((*plain)(a)) - if err != nil { - return err - } - return checkOverflow(a.XXX, "basic_auth") -} - -// NewHTTPClientFromConfig returns a new HTTP client configured for the -// given config.HTTPClientConfig. -func NewHTTPClientFromConfig(cfg *HTTPClientConfig) (*http.Client, error) { - tlsConfig, err := NewTLSConfig(&cfg.TLSConfig) - if err != nil { - return nil, err - } - - // It's the caller's job to handle timeouts - var rt http.RoundTripper = &http.Transport{ - Proxy: http.ProxyURL(cfg.ProxyURL.URL), - DisableKeepAlives: true, - TLSClientConfig: tlsConfig, - } - - // If a bearer token is provided, create a round tripper that will set the - // Authorization header correctly on each request. - bearerToken := cfg.BearerToken - if len(bearerToken) == 0 && len(cfg.BearerTokenFile) > 0 { - b, err := ioutil.ReadFile(cfg.BearerTokenFile) - if err != nil { - return nil, fmt.Errorf("unable to read bearer token file %s: %s", cfg.BearerTokenFile, err) - } - bearerToken = Secret(strings.TrimSpace(string(b))) - } - - if len(bearerToken) > 0 { - rt = NewBearerAuthRoundTripper(bearerToken, rt) - } - - if cfg.BasicAuth != nil { - rt = NewBasicAuthRoundTripper(cfg.BasicAuth.Username, Secret(cfg.BasicAuth.Password), rt) - } - - // Return a new client with the configured round tripper. - return &http.Client{Transport: rt}, nil -} - -type bearerAuthRoundTripper struct { - bearerToken Secret - rt http.RoundTripper -} - -type basicAuthRoundTripper struct { - username string - password Secret - rt http.RoundTripper -} - -// NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a request unless it has -// already been set. -func NewBasicAuthRoundTripper(username string, password Secret, rt http.RoundTripper) http.RoundTripper { - return &basicAuthRoundTripper{username, password, rt} -} - -func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - if len(req.Header.Get("Authorization")) == 0 { - req = cloneRequest(req) - req.Header.Set("Authorization", "Bearer "+string(rt.bearerToken)) - } - - return rt.rt.RoundTrip(req) -} - -// NewBearerAuthRoundTripper adds the provided bearer token to a request unless the authorization -// header has already been set. -func NewBearerAuthRoundTripper(bearer Secret, rt http.RoundTripper) http.RoundTripper { - return &bearerAuthRoundTripper{bearer, rt} -} - -func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - if len(req.Header.Get("Authorization")) != 0 { - return rt.RoundTrip(req) - } - req = cloneRequest(req) - req.SetBasicAuth(rt.username, string(rt.password)) - return rt.rt.RoundTrip(req) -} - -// cloneRequest returns a clone of the provided *http.Request. -// The clone is a shallow copy of the struct and its Header map. -func cloneRequest(r *http.Request) *http.Request { - // Shallow copy of the struct. - r2 := new(http.Request) - *r2 = *r - // Deep copy of the Header. - r2.Header = make(http.Header) - for k, s := range r.Header { - r2.Header[k] = s - } - return r2 -} - -// NewTLSConfig creates a new tls.Config from the given config.TLSConfig. -func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { - tlsConfig := &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify} - - // If a CA cert is provided then let's read it in so we can validate the - // scrape target's certificate properly. - if len(cfg.CAFile) > 0 { - caCertPool := x509.NewCertPool() - // Load CA cert. - caCert, err := ioutil.ReadFile(cfg.CAFile) - if err != nil { - return nil, fmt.Errorf("unable to use specified CA cert %s: %s", cfg.CAFile, err) - } - caCertPool.AppendCertsFromPEM(caCert) - tlsConfig.RootCAs = caCertPool - } - - if len(cfg.ServerName) > 0 { - tlsConfig.ServerName = cfg.ServerName - } - - // If a client cert & key is provided then configure TLS config accordingly. - if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 { - return nil, fmt.Errorf("client cert file %q specified without client key file", cfg.CertFile) - } else if len(cfg.KeyFile) > 0 && len(cfg.CertFile) == 0 { - return nil, fmt.Errorf("client key file %q specified without client cert file", cfg.KeyFile) - } else if len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 { - cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile) - if err != nil { - return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", cfg.CertFile, cfg.KeyFile, err) - } - tlsConfig.Certificates = []tls.Certificate{cert} - } - tlsConfig.BuildNameToCertificate() - - return tlsConfig, nil -} - -// TLSConfig configures the options for TLS connections. -type TLSConfig struct { - // The CA cert to use for the targets. - CAFile string `yaml:"ca_file,omitempty"` - // The client cert file for the targets. - CertFile string `yaml:"cert_file,omitempty"` - // The client key file for the targets. - KeyFile string `yaml:"key_file,omitempty"` - // Used to verify the hostname for the targets. - ServerName string `yaml:"server_name,omitempty"` - // Disable target certificate validation. - InsecureSkipVerify bool `yaml:"insecure_skip_verify"` - - // Catches all undefined fields and must be empty after parsing. - XXX map[string]interface{} `yaml:",inline"` -} - -// UnmarshalYAML implements the yaml.Unmarshaler interface. -func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { - type plain TLSConfig - if err := unmarshal((*plain)(c)); err != nil { - return err - } - return checkOverflow(c.XXX, "TLS config") -} - -func (c HTTPClientConfig) String() string { - b, err := yaml.Marshal(c) - if err != nil { - return fmt.Sprintf("", err) - } - return string(b) -} diff --git a/vendor/github.com/prometheus/common/config/http_config_test.go b/vendor/github.com/prometheus/common/config/http_config_test.go deleted file mode 100644 index 4b13e101b..000000000 --- a/vendor/github.com/prometheus/common/config/http_config_test.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "io/ioutil" - "net/http" - "net/url" - "strings" - "testing" - - yaml "gopkg.in/yaml.v2" -) - -var invalidHTTPClientConfigs = []struct { - httpClientConfigFile string - errMsg string -}{ - { - httpClientConfigFile: "testdata/http.conf.bearer-token-and-file-set.bad.yml", - errMsg: "at most one of bearer_token & bearer_token_file must be configured", - }, - { - httpClientConfigFile: "testdata/http.conf.empty.bad.yml", - errMsg: "at most one of basic_auth, bearer_token & bearer_token_file must be configured", - }, -} - -func TestAuthRoundTrippers(t *testing.T) { - - cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml") - if err != nil { - t.Errorf("Error loading HTTP client config: %v", err) - } - - tlsConfig, err := NewTLSConfig(&cfg.TLSConfig) - if err != nil { - t.Errorf("Error creating new TLS config: %v", err) - } - - rt := &http.Transport{ - Proxy: http.ProxyURL(cfg.ProxyURL.URL), - DisableKeepAlives: true, - TLSClientConfig: tlsConfig, - } - req := new(http.Request) - - bearerAuthRoundTripper := NewBearerAuthRoundTripper("mysecret", rt) - bearerAuthRoundTripper.RoundTrip(req) - - basicAuthRoundTripper := NewBasicAuthRoundTripper("username", "password", rt) - basicAuthRoundTripper.RoundTrip(req) -} - -func TestHideHTTPClientConfigSecrets(t *testing.T) { - c, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml") - if err != nil { - t.Errorf("Error parsing %s: %s", "testdata/http.conf.good.yml", err) - } - - // String method must not reveal authentication credentials. - s := c.String() - if strings.Contains(s, "mysecret") { - t.Fatal("http client config's String method reveals authentication credentials.") - } -} - -func mustParseURL(u string) *URL { - parsed, err := url.Parse(u) - if err != nil { - panic(err) - } - return &URL{URL: parsed} -} - -func TestNewClientFromConfig(t *testing.T) { - cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml") - if err != nil { - t.Errorf("Error loading HTTP client config: %v", err) - } - _, err = NewHTTPClientFromConfig(cfg) - if err != nil { - t.Errorf("Error creating new client from config: %v", err) - } -} - -func TestNewClientFromInvalidConfig(t *testing.T) { - cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.invalid-bearer-token-file.bad.yml") - if err != nil { - t.Errorf("Error loading HTTP client config: %v", err) - } - _, err = NewHTTPClientFromConfig(cfg) - if err == nil { - t.Error("Expected error creating new client from invalid config but got none") - } - if !strings.Contains(err.Error(), "unable to read bearer token file file: open file: no such file or directory") { - t.Errorf("Expected error with config but got: %s", err.Error()) - } -} - -func TestValidateHTTPConfig(t *testing.T) { - cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml") - if err != nil { - t.Errorf("Error loading HTTP client config: %v", err) - } - err = cfg.Validate() - if err != nil { - t.Fatalf("Error validating %s: %s", "testdata/http.conf.good.yml", err) - } -} - -func TestInvalidHTTPConfigs(t *testing.T) { - for _, ee := range invalidHTTPClientConfigs { - _, _, err := LoadHTTPConfigFile(ee.httpClientConfigFile) - if err == nil { - t.Error("Expected error with config but got none") - continue - } - if !strings.Contains(err.Error(), ee.errMsg) { - t.Errorf("Expected error for invalid HTTP client configuration to contain %q but got: %s", ee.errMsg, err) - } - } -} - -// LoadHTTPConfig parses the YAML input s into a HTTPClientConfig. -func LoadHTTPConfig(s string) (*HTTPClientConfig, error) { - cfg := &HTTPClientConfig{} - err := yaml.Unmarshal([]byte(s), cfg) - if err != nil { - return nil, err - } - return cfg, nil -} - -// LoadHTTPConfigFile parses the given YAML file into a HTTPClientConfig. -func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error) { - content, err := ioutil.ReadFile(filename) - if err != nil { - return nil, nil, err - } - cfg, err := LoadHTTPConfig(string(content)) - if err != nil { - return nil, nil, err - } - return cfg, content, nil -} diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml deleted file mode 100644 index c613bacb0..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml +++ /dev/null @@ -1,5 +0,0 @@ -basic_auth: - username: username - password: "mysecret" -bearer_token: mysecret -bearer_token_file: file diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml deleted file mode 100644 index ea2811f7c..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml +++ /dev/null @@ -1,4 +0,0 @@ -basic_auth: - username: username - password: mysecret -bearer_token_file: file diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml deleted file mode 100644 index 46ca63908..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml +++ /dev/null @@ -1,4 +0,0 @@ -basic_auth: - username: username - password: "mysecret" -proxy_url: "http://remote.host" diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml deleted file mode 100644 index 4b1349bf4..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml +++ /dev/null @@ -1 +0,0 @@ -bearer_token_file: file diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml deleted file mode 100644 index 7dfdc1ead..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml +++ /dev/null @@ -1 +0,0 @@ -cert_file: somefile diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.empty.good.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.empty.good.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml deleted file mode 100644 index d054383f1..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml +++ /dev/null @@ -1 +0,0 @@ -insecure_skip_verify: true diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml deleted file mode 100644 index 12cbaac3b..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml +++ /dev/null @@ -1 +0,0 @@ -something_invalid: true diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml deleted file mode 100644 index cec045e89..000000000 --- a/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml +++ /dev/null @@ -1 +0,0 @@ -key_file: somefile diff --git a/vendor/github.com/prometheus/common/config/tls_config_test.go b/vendor/github.com/prometheus/common/config/tls_config_test.go deleted file mode 100644 index e2bd68edb..000000000 --- a/vendor/github.com/prometheus/common/config/tls_config_test.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package config - -import ( - "crypto/tls" - "io/ioutil" - "reflect" - "strings" - "testing" - - "gopkg.in/yaml.v2" -) - -// LoadTLSConfig parses the given YAML file into a tls.Config. -func LoadTLSConfig(filename string) (*tls.Config, error) { - content, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - cfg := &TLSConfig{} - if err = yaml.Unmarshal(content, cfg); err != nil { - return nil, err - } - return NewTLSConfig(cfg) -} - -var expectedTLSConfigs = []struct { - filename string - config *tls.Config -}{ - { - filename: "tls_config.empty.good.yml", - config: &tls.Config{}, - }, { - filename: "tls_config.insecure.good.yml", - config: &tls.Config{InsecureSkipVerify: true}, - }, -} - -func TestValidTLSConfig(t *testing.T) { - for _, cfg := range expectedTLSConfigs { - cfg.config.BuildNameToCertificate() - got, err := LoadTLSConfig("testdata/" + cfg.filename) - if err != nil { - t.Errorf("Error parsing %s: %s", cfg.filename, err) - } - if !reflect.DeepEqual(*got, *cfg.config) { - t.Fatalf("%v: unexpected config result: \n\n%v\n expected\n\n%v", cfg.filename, got, cfg.config) - } - } -} - -var expectedTLSConfigErrors = []struct { - filename string - errMsg string -}{ - { - filename: "tls_config.invalid_field.bad.yml", - errMsg: "unknown fields in", - }, { - filename: "tls_config.cert_no_key.bad.yml", - errMsg: "specified without client key file", - }, { - filename: "tls_config.key_no_cert.bad.yml", - errMsg: "specified without client cert file", - }, -} - -func TestBadTLSConfigs(t *testing.T) { - for _, ee := range expectedTLSConfigErrors { - _, err := LoadTLSConfig("testdata/" + ee.filename) - if err == nil { - t.Errorf("Expected error parsing %s but got none", ee.filename) - continue - } - if !strings.Contains(err.Error(), ee.errMsg) { - t.Errorf("Expected error for %s to contain %q but got: %s", ee.filename, ee.errMsg, err) - } - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/bench_test.go b/vendor/github.com/prometheus/common/expfmt/bench_test.go deleted file mode 100644 index e539bfc13..000000000 --- a/vendor/github.com/prometheus/common/expfmt/bench_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "testing" - - "github.com/matttproud/golang_protobuf_extensions/pbutil" - - dto "github.com/prometheus/client_model/go" -) - -var parser TextParser - -// Benchmarks to show how much penalty text format parsing actually inflicts. -// -// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. -// -// BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op -// BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op -// BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op -// BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op -// BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op -// -// CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. -// Without compression, it needs ~7x longer, but with compression (the more relevant scenario), -// the difference becomes less relevant, only ~4x. -// -// The test data contains 248 samples. - -// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric -// family DTOs. -func BenchmarkParseText(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape -// into metric family DTOs. -func BenchmarkParseTextGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - if _, err := parser.TextToMetricFamilies(in); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into -// metric family DTOs. Note that this does not build a map of metric families -// (as the text version does), because it is not required for Prometheus -// ingestion either. (However, it is required for the text-format parsing, as -// the metric family might be sprinkled all over the text, while the -// protobuf-format guarantees bundling at one place.) -func BenchmarkParseProto(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped -// protobuf format. -func BenchmarkParseProtoGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed -// metric family DTOs into a map. This is not happening during Prometheus -// ingestion. It is just here to measure the overhead of that map creation and -// separate it from the overhead of the text format parsing. -func BenchmarkParseProtoMap(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - families := map[string]*dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family := &dto.MetricFamily{} - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - families[family.GetName()] = family - } - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index a7a42d5ef..c092723e8 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -164,9 +164,9 @@ func (sd *SampleDecoder) Decode(s *model.Vector) error { } // ExtractSamples builds a slice of samples from the provided metric -// families. If an error occurs during sample extraction, it continues to +// families. If an error occurrs during sample extraction, it continues to // extract from the remaining metric families. The returned error is the last -// error that has occured. +// error that has occurred. func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) { var ( all model.Vector diff --git a/vendor/github.com/prometheus/common/expfmt/decode_test.go b/vendor/github.com/prometheus/common/expfmt/decode_test.go deleted file mode 100644 index 82c1130c9..000000000 --- a/vendor/github.com/prometheus/common/expfmt/decode_test.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "io" - "net/http" - "reflect" - "sort" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/common/model" -) - -func TestTextDecoder(t *testing.T) { - var ( - ts = model.Now() - in = ` -# Only a quite simple scenario with two metric families. -# More complicated tests of the parser itself can be found in the text package. -# TYPE mf2 counter -mf2 3 -mf1{label="value1"} -3.14 123456 -mf1{label="value2"} 42 -mf2 4 -` - out = model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value1", - }, - Value: -3.14, - Timestamp: 123456, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value2", - }, - Value: 42, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 3, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 4, - Timestamp: ts, - }, - } - ) - - dec := &SampleDecoder{ - Dec: &textDecoder{r: strings.NewReader(in)}, - Opts: &DecodeOptions{ - Timestamp: ts, - }, - } - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(out) - if !reflect.DeepEqual(all, out) { - t.Fatalf("output does not match") - } -} - -func TestProtoDecoder(t *testing.T) { - - var testTime = model.Now() - - scenarios := []struct { - in string - expected model.Vector - fail bool - }{ - { - in: "", - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_!abel_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - fail: true, - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - }, - Value: 84, - Timestamp: testTime, - }, - }, - }, - { - in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.99", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.999", - }, - Value: -84, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - "quantile": "0.5", - }, - Value: 10, - Timestamp: testTime, - }, - }, - }, - { - in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "100", - }, - Value: 123, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "120", - }, - Value: 412, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "144", - }, - Value: 592, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "172.8", - }, - Value: 1524, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "+Inf", - }, - Value: 2693, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_sum", - }, - Value: 1756047.3, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_count", - }, - Value: 2693, - Timestamp: testTime, - }, - }, - }, - { - // The metric type is unset in this protobuf, which needs to be handled - // correctly by the decoder. - in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - }, - Value: 1, - Timestamp: testTime, - }, - }, - }, - } - - for i, scenario := range scenarios { - dec := &SampleDecoder{ - Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, - Opts: &DecodeOptions{ - Timestamp: testTime, - }, - } - - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if scenario.fail { - if err == nil { - t.Fatal("Expected error but got none") - } - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(scenario.expected) - if !reflect.DeepEqual(all, scenario.expected) { - t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) - } - } -} - -func testDiscriminatorHTTPHeader(t testing.TB) { - var scenarios = []struct { - input map[string]string - output Format - err error - }{ - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, - output: FmtProtoDelim, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, - output: FmtUnknown, - }, - } - - for i, scenario := range scenarios { - var header http.Header - - if len(scenario.input) > 0 { - header = http.Header{} - } - - for key, value := range scenario.input { - header.Add(key, value) - } - - actual := ResponseFormat(header) - - if scenario.output != actual { - t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) - } - } -} - -func TestDiscriminatorHTTPHeader(t *testing.T) { - testDiscriminatorHTTPHeader(t) -} - -func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - testDiscriminatorHTTPHeader(b) - } -} - -func TestExtractSamples(t *testing.T) { - var ( - goodMetricFamily1 = &dto.MetricFamily{ - Name: proto.String("foo"), - Help: proto.String("Help for foo."), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(4711), - }, - }, - }, - } - goodMetricFamily2 = &dto.MetricFamily{ - Name: proto.String("bar"), - Help: proto.String("Help for bar."), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14), - }, - }, - }, - } - badMetricFamily = &dto.MetricFamily{ - Name: proto.String("bad"), - Help: proto.String("Help for bad."), - Type: dto.MetricType(42).Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Gauge: &dto.Gauge{ - Value: proto.Float64(2.7), - }, - }, - }, - } - - opts = &DecodeOptions{ - Timestamp: 42, - } - ) - - got, err := ExtractSamples(opts, goodMetricFamily1, goodMetricFamily2) - if err != nil { - t.Error("Unexpected error from ExtractSamples:", err) - } - want := model.Vector{ - &model.Sample{Metric: model.Metric{model.MetricNameLabel: "foo"}, Value: 4711, Timestamp: 42}, - &model.Sample{Metric: model.Metric{model.MetricNameLabel: "bar"}, Value: 3.14, Timestamp: 42}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want) - } - - got, err = ExtractSamples(opts, goodMetricFamily1, badMetricFamily, goodMetricFamily2) - if err == nil { - t.Error("Expected error from ExtractSamples") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 371ac7503..c71bcb981 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -26,7 +26,7 @@ const ( // The Content-Type values for the different wire protocols. FmtUnknown Format = `` - FmtText Format = `text/plain; version=` + TextVersion + FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` FmtProtoText Format = ProtoFmt + ` encoding=text` FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 deleted file mode 100644 index 139597f9c..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 deleted file mode 100644 index 2ae870679..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 +++ /dev/null @@ -1,6 +0,0 @@ - -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 deleted file mode 100644 index 5c351db36..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 +++ /dev/null @@ -1,12 +0,0 @@ - -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 deleted file mode 100644 index 0b3c345aa..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 +++ /dev/null @@ -1,22 +0,0 @@ - -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 deleted file mode 100644 index bde0a387a..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 +++ /dev/null @@ -1,10 +0,0 @@ - -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 deleted file mode 100644 index 4c67f9a19..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 +++ /dev/null @@ -1 +0,0 @@ -bla 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 deleted file mode 100644 index b853478ee..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 +++ /dev/null @@ -1 +0,0 @@ -metric{label="\t"} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 deleted file mode 100644 index b5fe5f5a6..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} 3.14 2 3 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 deleted file mode 100644 index 57c7fbc0b..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} blubb diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 deleted file mode 100644 index 0a9df79a1..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 +++ /dev/null @@ -1,3 +0,0 @@ - -# HELP metric one -# HELP metric two diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 deleted file mode 100644 index 5bc742781..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric counter -# TYPE metric untyped diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 deleted file mode 100644 index a9a24265b..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 +++ /dev/null @@ -1,3 +0,0 @@ - -metric 4.12 -# TYPE metric counter diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 deleted file mode 100644 index 7e95ca8f4..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 +++ /dev/null @@ -1,2 +0,0 @@ - -# TYPE metric bla diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 deleted file mode 100644 index 7825f8887..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 +++ /dev/null @@ -1,2 +0,0 @@ - -# TYPE met-ric diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 deleted file mode 100644 index 8f35cae0c..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 +++ /dev/null @@ -1 +0,0 @@ -@invalidmetric{label="bla"} 3.14 2 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 deleted file mode 100644 index 7ca2cc268..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 +++ /dev/null @@ -1 +0,0 @@ -{label="bla"} 3.14 2 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 deleted file mode 100644 index 7a6ccc0dd..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 deleted file mode 100644 index 726d0017c..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 +++ /dev/null @@ -1,3 +0,0 @@ - -metric{label="new -line"} 3.14 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 deleted file mode 100644 index 6aa9e3081..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 +++ /dev/null @@ -1 +0,0 @@ -metric{@="bla"} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 deleted file mode 100644 index d112cb902..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 +++ /dev/null @@ -1 +0,0 @@ -metric{__name__="bla"} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 deleted file mode 100644 index b34554a8d..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 +++ /dev/null @@ -1 +0,0 @@ -metric{label+="bla"} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 deleted file mode 100644 index c4d7df3d1..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 +++ /dev/null @@ -1 +0,0 @@ -metric{label=bla} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 deleted file mode 100644 index 97eafc4a6..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 +++ /dev/null @@ -1,3 +0,0 @@ - -# TYPE metric summary -metric{quantile="bla"} 3.14 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 deleted file mode 100644 index fc706496b..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"+} 3.14 \ No newline at end of file diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 deleted file mode 100644 index 57b4879c0..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 +++ /dev/null @@ -1 +0,0 @@ -metric{label="bla"} 3.14 2.72 diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal deleted file mode 100644 index be1e6a369..000000000 --- a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal +++ /dev/null @@ -1 +0,0 @@ -m{} 0 diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/json2 b/vendor/github.com/prometheus/common/expfmt/testdata/json2 deleted file mode 100644 index b914c9386..000000000 --- a/vendor/github.com/prometheus/common/expfmt/testdata/json2 +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "baseLabels": { - "__name__": "rpc_calls_total", - "job": "batch_job" - }, - "docstring": "RPC calls.", - "metric": { - "type": "counter", - "value": [ - { - "labels": { - "service": "zed" - }, - "value": 25 - }, - { - "labels": { - "service": "bar" - }, - "value": 24 - } - ] - } - }, - { - "baseLabels": { - "__name__": "rpc_latency_microseconds" - }, - "docstring": "RPC latency.", - "metric": { - "type": "histogram", - "value": [ - { - "labels": { - "service": "foo" - }, - "value": { - "0.010000": 15, - "0.990000": 17 - } - } - ] - } - } -] diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad b/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad deleted file mode 100644 index cc6ac97c5..000000000 --- a/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "baseLabels": { - "__name__": "rpc_calls_total", - "job": "batch_job" - }, - "docstring": "RPC calls.", - "metric": { - "type": "counter", - "value": [ - { - "labels": { - "servic|e": "zed" - }, - "value": 25 - }, - { - "labels": { - "service": "bar" - }, - "value": 24 - } - ] - } - }, - { - "baseLabels": { - "__name__": "rpc_latency_microseconds" - }, - "docstring": "RPC latency.", - "metric": { - "type": "histogram", - "value": [ - { - "labels": { - "service": "foo" - }, - "value": { - "0.010000": 15, - "0.990000": 17 - } - } - ] - } - } -] diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf deleted file mode 100644 index b2d018a7c..000000000 Binary files a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf and /dev/null differ diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz deleted file mode 100644 index 7622adb1c..000000000 Binary files a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz and /dev/null differ diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/text b/vendor/github.com/prometheus/common/expfmt/testdata/text deleted file mode 100644 index f3d8c3784..000000000 --- a/vendor/github.com/prometheus/common/expfmt/testdata/text +++ /dev/null @@ -1,322 +0,0 @@ -# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. -# TYPE http_request_duration_microseconds summary -http_request_duration_microseconds{handler="/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/"} 0 -http_request_duration_microseconds_count{handler="/"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/alerts"} 0 -http_request_duration_microseconds_count{handler="/alerts"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/metrics"} 0 -http_request_duration_microseconds_count{handler="/api/metrics"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query"} 0 -http_request_duration_microseconds_count{handler="/api/query"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query_range"} 0 -http_request_duration_microseconds_count{handler="/api/query_range"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/targets"} 0 -http_request_duration_microseconds_count{handler="/api/targets"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/consoles/"} 0 -http_request_duration_microseconds_count{handler="/consoles/"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/graph"} 0 -http_request_duration_microseconds_count{handler="/graph"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/heap"} 0 -http_request_duration_microseconds_count{handler="/heap"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/static/"} 0 -http_request_duration_microseconds_count{handler="/static/"} 0 -http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 1307.275 -http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 1858.632 -http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 3087.384 -http_request_duration_microseconds_sum{handler="prometheus"} 179886.5000000001 -http_request_duration_microseconds_count{handler="prometheus"} 119 -# HELP http_request_size_bytes The HTTP request sizes in bytes. -# TYPE http_request_size_bytes summary -http_request_size_bytes{handler="/",quantile="0.5"} 0 -http_request_size_bytes{handler="/",quantile="0.9"} 0 -http_request_size_bytes{handler="/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/"} 0 -http_request_size_bytes_count{handler="/"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/alerts"} 0 -http_request_size_bytes_count{handler="/alerts"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/metrics"} 0 -http_request_size_bytes_count{handler="/api/metrics"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query"} 0 -http_request_size_bytes_count{handler="/api/query"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query_range"} 0 -http_request_size_bytes_count{handler="/api/query_range"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/targets"} 0 -http_request_size_bytes_count{handler="/api/targets"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/consoles/"} 0 -http_request_size_bytes_count{handler="/consoles/"} 0 -http_request_size_bytes{handler="/graph",quantile="0.5"} 0 -http_request_size_bytes{handler="/graph",quantile="0.9"} 0 -http_request_size_bytes{handler="/graph",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/graph"} 0 -http_request_size_bytes_count{handler="/graph"} 0 -http_request_size_bytes{handler="/heap",quantile="0.5"} 0 -http_request_size_bytes{handler="/heap",quantile="0.9"} 0 -http_request_size_bytes{handler="/heap",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/heap"} 0 -http_request_size_bytes_count{handler="/heap"} 0 -http_request_size_bytes{handler="/static/",quantile="0.5"} 0 -http_request_size_bytes{handler="/static/",quantile="0.9"} 0 -http_request_size_bytes{handler="/static/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/static/"} 0 -http_request_size_bytes_count{handler="/static/"} 0 -http_request_size_bytes{handler="prometheus",quantile="0.5"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.9"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.99"} 291 -http_request_size_bytes_sum{handler="prometheus"} 34488 -http_request_size_bytes_count{handler="prometheus"} 119 -# HELP http_requests_total Total number of HTTP requests made. -# TYPE http_requests_total counter -http_requests_total{code="200",handler="prometheus",method="get"} 119 -# HELP http_response_size_bytes The HTTP response sizes in bytes. -# TYPE http_response_size_bytes summary -http_response_size_bytes{handler="/",quantile="0.5"} 0 -http_response_size_bytes{handler="/",quantile="0.9"} 0 -http_response_size_bytes{handler="/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/"} 0 -http_response_size_bytes_count{handler="/"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/alerts"} 0 -http_response_size_bytes_count{handler="/alerts"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/metrics"} 0 -http_response_size_bytes_count{handler="/api/metrics"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query"} 0 -http_response_size_bytes_count{handler="/api/query"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query_range"} 0 -http_response_size_bytes_count{handler="/api/query_range"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/targets"} 0 -http_response_size_bytes_count{handler="/api/targets"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/consoles/"} 0 -http_response_size_bytes_count{handler="/consoles/"} 0 -http_response_size_bytes{handler="/graph",quantile="0.5"} 0 -http_response_size_bytes{handler="/graph",quantile="0.9"} 0 -http_response_size_bytes{handler="/graph",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/graph"} 0 -http_response_size_bytes_count{handler="/graph"} 0 -http_response_size_bytes{handler="/heap",quantile="0.5"} 0 -http_response_size_bytes{handler="/heap",quantile="0.9"} 0 -http_response_size_bytes{handler="/heap",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/heap"} 0 -http_response_size_bytes_count{handler="/heap"} 0 -http_response_size_bytes{handler="/static/",quantile="0.5"} 0 -http_response_size_bytes{handler="/static/",quantile="0.9"} 0 -http_response_size_bytes{handler="/static/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/static/"} 0 -http_response_size_bytes_count{handler="/static/"} 0 -http_response_size_bytes{handler="prometheus",quantile="0.5"} 2049 -http_response_size_bytes{handler="prometheus",quantile="0.9"} 2058 -http_response_size_bytes{handler="prometheus",quantile="0.99"} 2064 -http_response_size_bytes_sum{handler="prometheus"} 247001 -http_response_size_bytes_count{handler="prometheus"} 119 -# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. -# TYPE process_cpu_seconds_total counter -process_cpu_seconds_total 0.55 -# HELP go_goroutines Number of goroutines that currently exist. -# TYPE go_goroutines gauge -go_goroutines 70 -# HELP process_max_fds Maximum number of open file descriptors. -# TYPE process_max_fds gauge -process_max_fds 8192 -# HELP process_open_fds Number of open file descriptors. -# TYPE process_open_fds gauge -process_open_fds 29 -# HELP process_resident_memory_bytes Resident memory size in bytes. -# TYPE process_resident_memory_bytes gauge -process_resident_memory_bytes 5.3870592e+07 -# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. -# TYPE process_start_time_seconds gauge -process_start_time_seconds 1.42236894836e+09 -# HELP process_virtual_memory_bytes Virtual memory size in bytes. -# TYPE process_virtual_memory_bytes gauge -process_virtual_memory_bytes 5.41478912e+08 -# HELP prometheus_dns_sd_lookup_failures_total The number of DNS-SD lookup failures. -# TYPE prometheus_dns_sd_lookup_failures_total counter -prometheus_dns_sd_lookup_failures_total 0 -# HELP prometheus_dns_sd_lookups_total The number of DNS-SD lookups. -# TYPE prometheus_dns_sd_lookups_total counter -prometheus_dns_sd_lookups_total 7 -# HELP prometheus_evaluator_duration_milliseconds The duration for all evaluations to execute. -# TYPE prometheus_evaluator_duration_milliseconds summary -prometheus_evaluator_duration_milliseconds{quantile="0.01"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.05"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.5"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.9"} 1 -prometheus_evaluator_duration_milliseconds{quantile="0.99"} 1 -prometheus_evaluator_duration_milliseconds_sum 12 -prometheus_evaluator_duration_milliseconds_count 23 -# HELP prometheus_local_storage_checkpoint_duration_milliseconds The duration (in milliseconds) it took to checkpoint in-memory metrics and head chunks. -# TYPE prometheus_local_storage_checkpoint_duration_milliseconds gauge -prometheus_local_storage_checkpoint_duration_milliseconds 0 -# HELP prometheus_local_storage_chunk_ops_total The total number of chunk operations by their type. -# TYPE prometheus_local_storage_chunk_ops_total counter -prometheus_local_storage_chunk_ops_total{type="create"} 598 -prometheus_local_storage_chunk_ops_total{type="persist"} 174 -prometheus_local_storage_chunk_ops_total{type="pin"} 920 -prometheus_local_storage_chunk_ops_total{type="transcode"} 415 -prometheus_local_storage_chunk_ops_total{type="unpin"} 920 -# HELP prometheus_local_storage_indexing_batch_latency_milliseconds Quantiles for batch indexing latencies in milliseconds. -# TYPE prometheus_local_storage_indexing_batch_latency_milliseconds summary -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.5"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.9"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.99"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_sum 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_count 1 -# HELP prometheus_local_storage_indexing_batch_sizes Quantiles for indexing batch sizes (number of metrics per batch). -# TYPE prometheus_local_storage_indexing_batch_sizes summary -prometheus_local_storage_indexing_batch_sizes{quantile="0.5"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.9"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.99"} 2 -prometheus_local_storage_indexing_batch_sizes_sum 2 -prometheus_local_storage_indexing_batch_sizes_count 1 -# HELP prometheus_local_storage_indexing_queue_capacity The capacity of the indexing queue. -# TYPE prometheus_local_storage_indexing_queue_capacity gauge -prometheus_local_storage_indexing_queue_capacity 16384 -# HELP prometheus_local_storage_indexing_queue_length The number of metrics waiting to be indexed. -# TYPE prometheus_local_storage_indexing_queue_length gauge -prometheus_local_storage_indexing_queue_length 0 -# HELP prometheus_local_storage_ingested_samples_total The total number of samples ingested. -# TYPE prometheus_local_storage_ingested_samples_total counter -prometheus_local_storage_ingested_samples_total 30473 -# HELP prometheus_local_storage_invalid_preload_requests_total The total number of preload requests referring to a non-existent series. This is an indication of outdated label indexes. -# TYPE prometheus_local_storage_invalid_preload_requests_total counter -prometheus_local_storage_invalid_preload_requests_total 0 -# HELP prometheus_local_storage_memory_chunkdescs The current number of chunk descriptors in memory. -# TYPE prometheus_local_storage_memory_chunkdescs gauge -prometheus_local_storage_memory_chunkdescs 1059 -# HELP prometheus_local_storage_memory_chunks The current number of chunks in memory, excluding cloned chunks (i.e. chunks without a descriptor). -# TYPE prometheus_local_storage_memory_chunks gauge -prometheus_local_storage_memory_chunks 1020 -# HELP prometheus_local_storage_memory_series The current number of series in memory. -# TYPE prometheus_local_storage_memory_series gauge -prometheus_local_storage_memory_series 424 -# HELP prometheus_local_storage_persist_latency_microseconds A summary of latencies for persisting each chunk. -# TYPE prometheus_local_storage_persist_latency_microseconds summary -prometheus_local_storage_persist_latency_microseconds{quantile="0.5"} 30.377 -prometheus_local_storage_persist_latency_microseconds{quantile="0.9"} 203.539 -prometheus_local_storage_persist_latency_microseconds{quantile="0.99"} 2626.463 -prometheus_local_storage_persist_latency_microseconds_sum 20424.415 -prometheus_local_storage_persist_latency_microseconds_count 174 -# HELP prometheus_local_storage_persist_queue_capacity The total capacity of the persist queue. -# TYPE prometheus_local_storage_persist_queue_capacity gauge -prometheus_local_storage_persist_queue_capacity 1024 -# HELP prometheus_local_storage_persist_queue_length The current number of chunks waiting in the persist queue. -# TYPE prometheus_local_storage_persist_queue_length gauge -prometheus_local_storage_persist_queue_length 0 -# HELP prometheus_local_storage_series_ops_total The total number of series operations by their type. -# TYPE prometheus_local_storage_series_ops_total counter -prometheus_local_storage_series_ops_total{type="create"} 2 -prometheus_local_storage_series_ops_total{type="maintenance_in_memory"} 11 -# HELP prometheus_notifications_latency_milliseconds Latency quantiles for sending alert notifications (not including dropped notifications). -# TYPE prometheus_notifications_latency_milliseconds summary -prometheus_notifications_latency_milliseconds{quantile="0.5"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.9"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.99"} 0 -prometheus_notifications_latency_milliseconds_sum 0 -prometheus_notifications_latency_milliseconds_count 0 -# HELP prometheus_notifications_queue_capacity The capacity of the alert notifications queue. -# TYPE prometheus_notifications_queue_capacity gauge -prometheus_notifications_queue_capacity 100 -# HELP prometheus_notifications_queue_length The number of alert notifications in the queue. -# TYPE prometheus_notifications_queue_length gauge -prometheus_notifications_queue_length 0 -# HELP prometheus_rule_evaluation_duration_milliseconds The duration for a rule to execute. -# TYPE prometheus_rule_evaluation_duration_milliseconds summary -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.99"} 2 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="alerting"} 12 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="alerting"} 115 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.99"} 3 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="recording"} 15 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="recording"} 115 -# HELP prometheus_rule_evaluation_failures_total The total number of rule evaluation failures. -# TYPE prometheus_rule_evaluation_failures_total counter -prometheus_rule_evaluation_failures_total 0 -# HELP prometheus_samples_queue_capacity Capacity of the queue for unwritten samples. -# TYPE prometheus_samples_queue_capacity gauge -prometheus_samples_queue_capacity 4096 -# HELP prometheus_samples_queue_length Current number of items in the queue for unwritten samples. Each item comprises all samples exposed by one target as one metric family (i.e. metrics of the same name). -# TYPE prometheus_samples_queue_length gauge -prometheus_samples_queue_length 0 -# HELP prometheus_target_interval_length_seconds Actual intervals between scrapes. -# TYPE prometheus_target_interval_length_seconds summary -prometheus_target_interval_length_seconds{interval="15s",quantile="0.01"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.05"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.5"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.9"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15 -prometheus_target_interval_length_seconds_sum{interval="15s"} 175 -prometheus_target_interval_length_seconds_count{interval="15s"} 12 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.01"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.05"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.5"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.9"} 1 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.99"} 1 -prometheus_target_interval_length_seconds_sum{interval="1s"} 55 -prometheus_target_interval_length_seconds_count{interval="1s"} 117 diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/text.gz b/vendor/github.com/prometheus/common/expfmt/testdata/text.gz deleted file mode 100644 index b7658c84d..000000000 Binary files a/vendor/github.com/prometheus/common/expfmt/testdata/text.gz and /dev/null differ diff --git a/vendor/github.com/prometheus/common/expfmt/text_create_test.go b/vendor/github.com/prometheus/common/expfmt/text_create_test.go deleted file mode 100644 index e4cc5d803..000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_create_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" -) - -func testCreate(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - out string - }{ - // 0: Counter, NaN as value, timestamp given. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - out: `# HELP name two-line\n doc str\\ing -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name{labelname="val2",basename="basevalue"} 0.23 1234567890 -`, - }, - // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. - { - in: &dto.MetricFamily{ - Name: proto.String("gauge_name"), - Help: proto.String("gauge\ndoc\nstr\"ing"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("val with\nnew line"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("val with \\backslash and \"quotes\""), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("Björn"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("佖佥"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14E42), - }, - }, - }, - }, - out: `# HELP gauge_name gauge\ndoc\nstr"ing -# TYPE gauge_name gauge -gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf -gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 -`, - }, - // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. - { - in: &dto.MetricFamily{ - Name: proto.String("untyped_name"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(-1.23e-45), - }, - }, - }, - }, - out: `# TYPE untyped_name untyped -untyped_name -Inf -untyped_name{name_1="value 1"} -1.23e-45 -`, - }, - // 3: Summary. - { - in: &dto.MetricFamily{ - Name: proto.String("summary_name"), - Help: proto.String("summary docstring"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(-3.4567), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(-1.23), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(.2342354), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(0), - }, - }, - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("value 2"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(4711), - SampleSum: proto.Float64(2010.1971), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(1), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(2), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - out: `# HELP summary_name summary docstring -# TYPE summary_name summary -summary_name{quantile="0.5"} -1.23 -summary_name{quantile="0.9"} 0.2342354 -summary_name{quantile="0.99"} 0 -summary_name_sum -3.4567 -summary_name_count 42 -summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 -summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 -summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 -summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 -summary_name_count{name_1="value 1",name_2="value 2"} 4711 -`, - }, - // 4: Histogram - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 5: Histogram with missing +Inf bucket. - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 6: No metric type, should result in default type Counter. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - out: `# HELP name doc string -# TYPE name counter -name -Inf -`, - }, - } - - for i, scenario := range scenarios { - out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) - n, err := MetricFamilyToText(out, scenario.in) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), n; expected != got { - t.Errorf( - "%d. expected %d bytes written, got %d", - i, expected, got, - ) - } - if expected, got := scenario.out, out.String(); expected != got { - t.Errorf( - "%d. expected out=%q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreate(t *testing.T) { - testCreate(t) -} - -func BenchmarkCreate(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreate(b) - } -} - -func testCreateError(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - err string - }{ - // 0: No metric. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{}, - }, - err: "MetricFamily has no metrics", - }, - // 1: No metric name. - { - in: &dto.MetricFamily{ - Help: proto.String("doc string"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "MetricFamily has no name", - }, - // 2: Wrong type. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "expected counter in metric", - }, - } - - for i, scenario := range scenarios { - var out bytes.Buffer - _, err := MetricFamilyToText(&out, scenario.in) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreateError(t *testing.T) { - testCreateError(t) -} - -func BenchmarkCreateError(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreateError(b) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 54bcfde29..b86290afa 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -556,8 +556,8 @@ func (p *TextParser) readTokenUntilWhitespace() { // byte considered is the byte already read (now in p.currentByte). The first // newline byte encountered is still copied into p.currentByte, but not into // p.currentToken. If recognizeEscapeSequence is true, two escape sequences are -// recognized: '\\' tranlates into '\', and '\n' into a line-feed character. All -// other escape sequences are invalid and cause an error. +// recognized: '\\' translates into '\', and '\n' into a line-feed character. +// All other escape sequences are invalid and cause an error. func (p *TextParser) readTokenUntilNewline(recognizeEscapeSequence bool) { p.currentToken.Reset() escaped := false diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go b/vendor/github.com/prometheus/common/expfmt/text_parse_test.go deleted file mode 100644 index 76c951185..000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go +++ /dev/null @@ -1,593 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func testTextParse(t testing.TB) { - var scenarios = []struct { - in string - out []*dto.MetricFamily - }{ - // 0: Empty lines as input. - { - in: ` - -`, - out: []*dto.MetricFamily{}, - }, - // 1: Minimal case. - { - in: ` -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("minimal_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(1.234), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-3e3), - }, - TimestampMs: proto.Int64(103948), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("no_labels"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - // 2: Counters & gauges, docstrings, various whitespace, escape sequences. - { - in: ` -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("base\"v\\al\nue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("name2"), - Help: proto.String("doc str\"ing 2"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue2"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - TimestampMs: proto.Int64(54321), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - }, - }, - // 3: The evil summary, mixed with other types and funny comments. - { - in: ` -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("fake_sum"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(2001), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("decoy"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-1), - }, - TimestampMs: proto.Int64(-2), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("my_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(4711), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(110), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(140), - }, - }, - }, - TimestampMs: proto.Int64(2), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(5), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(-12.34), - Value: proto.Float64(math.NaN()), - }, - }, - }, - TimestampMs: proto.Int64(5), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val2"), - }, - }, - Summary: &dto.Summary{ - SampleSum: proto.Float64(8), - }, - TimestampMs: proto.Int64(15), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val3"), - }, - }, - Summary: &dto.Summary{ - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.2), - Value: proto.Float64(4711), - }, - }, - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(20), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.3), - Value: proto.Float64(-1.2), - }, - }, - }, - }, - }, - }, - }, - }, - // 4: The histogram. - { - in: ` -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - out: []*dto.MetricFamily{ - { - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - }, - }, - } - - for i, scenario := range scenarios { - out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), len(out); expected != got { - t.Errorf( - "%d. expected %d MetricFamilies, got %d", - i, expected, got, - ) - } - for _, expected := range scenario.out { - got, ok := out[expected.GetName()] - if !ok { - t.Errorf( - "%d. expected MetricFamily %q, found none", - i, expected.GetName(), - ) - continue - } - if expected.String() != got.String() { - t.Errorf( - "%d. expected MetricFamily %s, got %s", - i, expected, got, - ) - } - } - } -} - -func TestTextParse(t *testing.T) { - testTextParse(t) -} - -func BenchmarkTextParse(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParse(b) - } -} - -func testTextParseError(t testing.TB) { - var scenarios = []struct { - in string - err string - }{ - // 0: No new-line at end of input. - { - in: ` -bla 3.14 -blubber 42`, - err: "text format parsing error in line 3: unexpected end of input stream", - }, - // 1: Invalid escape sequence in label value. - { - in: `metric{label="\t"} 3.14`, - err: "text format parsing error in line 1: invalid escape sequence", - }, - // 2: Newline in label value. - { - in: ` -metric{label="new -line"} 3.14 -`, - err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, - }, - // 3: - { - in: `metric{@="bla"} 3.14`, - err: "text format parsing error in line 1: invalid label name for metric", - }, - // 4: - { - in: `metric{__name__="bla"} 3.14`, - err: `text format parsing error in line 1: label name "__name__" is reserved`, - }, - // 5: - { - in: `metric{label+="bla"} 3.14`, - err: "text format parsing error in line 1: expected '=' after label name", - }, - // 6: - { - in: `metric{label=bla} 3.14`, - err: "text format parsing error in line 1: expected '\"' at start of label value", - }, - // 7: - { - in: ` -# TYPE metric summary -metric{quantile="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'quantile' label", - }, - // 8: - { - in: `metric{label="bla"+} 3.14`, - err: "text format parsing error in line 1: unexpected end of label value", - }, - // 9: - { - in: `metric{label="bla"} 3.14 2.72 -`, - err: "text format parsing error in line 1: expected integer as timestamp", - }, - // 10: - { - in: `metric{label="bla"} 3.14 2 3 -`, - err: "text format parsing error in line 1: spurious string after timestamp", - }, - // 11: - { - in: `metric{label="bla"} blubb -`, - err: "text format parsing error in line 1: expected float as value", - }, - // 12: - { - in: ` -# HELP metric one -# HELP metric two -`, - err: "text format parsing error in line 3: second HELP line for metric name", - }, - // 13: - { - in: ` -# TYPE metric counter -# TYPE metric untyped -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -metric 4.12 -# TYPE metric counter -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -# TYPE metric bla -`, - err: "text format parsing error in line 2: unknown metric type", - }, - // 15: - { - in: ` -# TYPE met-ric -`, - err: "text format parsing error in line 2: invalid metric name in comment", - }, - // 16: - { - in: `@invalidmetric{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 17: - { - in: `{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 18: - { - in: ` -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'le' label", - }, - // 19: Invalid UTF-8 in label value. - { - in: "metric{l=\"\xbd\"} 3.14\n", - err: "text format parsing error in line 1: invalid label value \"\\xbd\"", - }, - } - - for i, scenario := range scenarios { - _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestTextParseError(t *testing.T) { - testTextParseError(t) -} - -func BenchmarkParseError(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParseError(b) - } -} diff --git a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go deleted file mode 100644 index 41d328f1d..000000000 --- a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package goautoneg - -import ( - "testing" -) - -var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - -func TestParseAccept(t *testing.T) { - alternatives := []string{"text/html", "image/png"} - content_type := Negotiate(chrome, alternatives) - if content_type != "image/png" { - t.Errorf("got %s expected image/png", content_type) - } - - alternatives = []string{"text/html", "text/plain", "text/n3"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/html" { - t.Errorf("got %s expected text/html", content_type) - } - - alternatives = []string{"text/n3", "text/plain"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/plain" { - t.Errorf("got %s expected text/plain", content_type) - } - - alternatives = []string{"text/n3", "application/rdf+xml"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/n3" { - t.Errorf("got %s expected text/n3", content_type) - } -} diff --git a/vendor/github.com/prometheus/common/log/eventlog_formatter.go b/vendor/github.com/prometheus/common/log/eventlog_formatter.go deleted file mode 100644 index bcf68e6f2..000000000 --- a/vendor/github.com/prometheus/common/log/eventlog_formatter.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build windows - -package log - -import ( - "fmt" - "os" - - "golang.org/x/sys/windows/svc/eventlog" - - "github.com/sirupsen/logrus" -) - -func init() { - setEventlogFormatter = func(l logger, name string, debugAsInfo bool) error { - if name == "" { - return fmt.Errorf("missing name parameter") - } - - fmter, err := newEventlogger(name, debugAsInfo, l.entry.Logger.Formatter) - if err != nil { - fmt.Fprintf(os.Stderr, "error creating eventlog formatter: %v\n", err) - l.Errorf("can't connect logger to eventlog: %v", err) - return err - } - l.entry.Logger.Formatter = fmter - return nil - } -} - -type eventlogger struct { - log *eventlog.Log - debugAsInfo bool - wrap logrus.Formatter -} - -func newEventlogger(name string, debugAsInfo bool, fmter logrus.Formatter) (*eventlogger, error) { - logHandle, err := eventlog.Open(name) - if err != nil { - return nil, err - } - return &eventlogger{log: logHandle, debugAsInfo: debugAsInfo, wrap: fmter}, nil -} - -func (s *eventlogger) Format(e *logrus.Entry) ([]byte, error) { - data, err := s.wrap.Format(e) - if err != nil { - fmt.Fprintf(os.Stderr, "eventlogger: can't format entry: %v\n", err) - return data, err - } - - switch e.Level { - case logrus.PanicLevel: - fallthrough - case logrus.FatalLevel: - fallthrough - case logrus.ErrorLevel: - err = s.log.Error(102, e.Message) - case logrus.WarnLevel: - err = s.log.Warning(101, e.Message) - case logrus.InfoLevel: - err = s.log.Info(100, e.Message) - case logrus.DebugLevel: - if s.debugAsInfo { - err = s.log.Info(100, e.Message) - } - default: - err = s.log.Info(100, e.Message) - } - - if err != nil { - fmt.Fprintf(os.Stderr, "eventlogger: can't send log to eventlog: %v\n", err) - } - - return data, err -} diff --git a/vendor/github.com/prometheus/common/log/log.go b/vendor/github.com/prometheus/common/log/log.go deleted file mode 100644 index 108830255..000000000 --- a/vendor/github.com/prometheus/common/log/log.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "fmt" - "io" - "io/ioutil" - "log" - "net/url" - "os" - "runtime" - "strconv" - "strings" - - "github.com/sirupsen/logrus" - "gopkg.in/alecthomas/kingpin.v2" -) - -// setSyslogFormatter is nil if the target architecture does not support syslog. -var setSyslogFormatter func(logger, string, string) error - -// setEventlogFormatter is nil if the target OS does not support Eventlog (i.e., is not Windows). -var setEventlogFormatter func(logger, string, bool) error - -func setJSONFormatter() { - origLogger.Formatter = &logrus.JSONFormatter{} -} - -type loggerSettings struct { - level string - format string -} - -func (s *loggerSettings) apply(ctx *kingpin.ParseContext) error { - err := baseLogger.SetLevel(s.level) - if err != nil { - return err - } - err = baseLogger.SetFormat(s.format) - return err -} - -// AddFlags adds the flags used by this package to the Kingpin application. -// To use the default Kingpin application, call AddFlags(kingpin.CommandLine) -func AddFlags(a *kingpin.Application) { - s := loggerSettings{} - a.Flag("log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal]"). - Default(origLogger.Level.String()). - StringVar(&s.level) - defaultFormat := url.URL{Scheme: "logger", Opaque: "stderr"} - a.Flag("log.format", `Set the log target and format. Example: "logger:syslog?appname=bob&local=7" or "logger:stdout?json=true"`). - Default(defaultFormat.String()). - StringVar(&s.format) - a.Action(s.apply) -} - -// Logger is the interface for loggers used in the Prometheus components. -type Logger interface { - Debug(...interface{}) - Debugln(...interface{}) - Debugf(string, ...interface{}) - - Info(...interface{}) - Infoln(...interface{}) - Infof(string, ...interface{}) - - Warn(...interface{}) - Warnln(...interface{}) - Warnf(string, ...interface{}) - - Error(...interface{}) - Errorln(...interface{}) - Errorf(string, ...interface{}) - - Fatal(...interface{}) - Fatalln(...interface{}) - Fatalf(string, ...interface{}) - - With(key string, value interface{}) Logger - - SetFormat(string) error - SetLevel(string) error -} - -type logger struct { - entry *logrus.Entry -} - -func (l logger) With(key string, value interface{}) Logger { - return logger{l.entry.WithField(key, value)} -} - -// Debug logs a message at level Debug on the standard logger. -func (l logger) Debug(args ...interface{}) { - l.sourced().Debug(args...) -} - -// Debug logs a message at level Debug on the standard logger. -func (l logger) Debugln(args ...interface{}) { - l.sourced().Debugln(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func (l logger) Debugf(format string, args ...interface{}) { - l.sourced().Debugf(format, args...) -} - -// Info logs a message at level Info on the standard logger. -func (l logger) Info(args ...interface{}) { - l.sourced().Info(args...) -} - -// Info logs a message at level Info on the standard logger. -func (l logger) Infoln(args ...interface{}) { - l.sourced().Infoln(args...) -} - -// Infof logs a message at level Info on the standard logger. -func (l logger) Infof(format string, args ...interface{}) { - l.sourced().Infof(format, args...) -} - -// Warn logs a message at level Warn on the standard logger. -func (l logger) Warn(args ...interface{}) { - l.sourced().Warn(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func (l logger) Warnln(args ...interface{}) { - l.sourced().Warnln(args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func (l logger) Warnf(format string, args ...interface{}) { - l.sourced().Warnf(format, args...) -} - -// Error logs a message at level Error on the standard logger. -func (l logger) Error(args ...interface{}) { - l.sourced().Error(args...) -} - -// Error logs a message at level Error on the standard logger. -func (l logger) Errorln(args ...interface{}) { - l.sourced().Errorln(args...) -} - -// Errorf logs a message at level Error on the standard logger. -func (l logger) Errorf(format string, args ...interface{}) { - l.sourced().Errorf(format, args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func (l logger) Fatal(args ...interface{}) { - l.sourced().Fatal(args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func (l logger) Fatalln(args ...interface{}) { - l.sourced().Fatalln(args...) -} - -// Fatalf logs a message at level Fatal on the standard logger. -func (l logger) Fatalf(format string, args ...interface{}) { - l.sourced().Fatalf(format, args...) -} - -func (l logger) SetLevel(level string) error { - lvl, err := logrus.ParseLevel(level) - if err != nil { - return err - } - - l.entry.Logger.Level = lvl - return nil -} - -func (l logger) SetFormat(format string) error { - u, err := url.Parse(format) - if err != nil { - return err - } - if u.Scheme != "logger" { - return fmt.Errorf("invalid scheme %s", u.Scheme) - } - jsonq := u.Query().Get("json") - if jsonq == "true" { - setJSONFormatter() - } - - switch u.Opaque { - case "syslog": - if setSyslogFormatter == nil { - return fmt.Errorf("system does not support syslog") - } - appname := u.Query().Get("appname") - facility := u.Query().Get("local") - return setSyslogFormatter(l, appname, facility) - case "eventlog": - if setEventlogFormatter == nil { - return fmt.Errorf("system does not support eventlog") - } - name := u.Query().Get("name") - debugAsInfo := false - debugAsInfoRaw := u.Query().Get("debugAsInfo") - if parsedDebugAsInfo, err := strconv.ParseBool(debugAsInfoRaw); err == nil { - debugAsInfo = parsedDebugAsInfo - } - return setEventlogFormatter(l, name, debugAsInfo) - case "stdout": - l.entry.Logger.Out = os.Stdout - case "stderr": - l.entry.Logger.Out = os.Stderr - default: - return fmt.Errorf("unsupported logger %q", u.Opaque) - } - return nil -} - -// sourced adds a source field to the logger that contains -// the file name and line where the logging happened. -func (l logger) sourced() *logrus.Entry { - _, file, line, ok := runtime.Caller(2) - if !ok { - file = "" - line = 1 - } else { - slash := strings.LastIndex(file, "/") - file = file[slash+1:] - } - return l.entry.WithField("source", fmt.Sprintf("%s:%d", file, line)) -} - -var origLogger = logrus.New() -var baseLogger = logger{entry: logrus.NewEntry(origLogger)} - -// Base returns the default Logger logging to -func Base() Logger { - return baseLogger -} - -// NewLogger returns a new Logger logging to out. -func NewLogger(w io.Writer) Logger { - l := logrus.New() - l.Out = w - return logger{entry: logrus.NewEntry(l)} -} - -// NewNopLogger returns a logger that discards all log messages. -func NewNopLogger() Logger { - l := logrus.New() - l.Out = ioutil.Discard - return logger{entry: logrus.NewEntry(l)} -} - -// With adds a field to the logger. -func With(key string, value interface{}) Logger { - return baseLogger.With(key, value) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - baseLogger.sourced().Debug(args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - baseLogger.sourced().Debugln(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - baseLogger.sourced().Debugf(format, args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - baseLogger.sourced().Info(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - baseLogger.sourced().Infoln(args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - baseLogger.sourced().Infof(format, args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - baseLogger.sourced().Warn(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - baseLogger.sourced().Warnln(args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - baseLogger.sourced().Warnf(format, args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - baseLogger.sourced().Error(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - baseLogger.sourced().Errorln(args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - baseLogger.sourced().Errorf(format, args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func Fatal(args ...interface{}) { - baseLogger.sourced().Fatal(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger. -func Fatalln(args ...interface{}) { - baseLogger.sourced().Fatalln(args...) -} - -// Fatalf logs a message at level Fatal on the standard logger. -func Fatalf(format string, args ...interface{}) { - baseLogger.sourced().Fatalf(format, args...) -} - -// AddHook adds hook to Prometheus' original logger. -func AddHook(hook logrus.Hook) { - origLogger.Hooks.Add(hook) -} - -type errorLogWriter struct{} - -func (errorLogWriter) Write(b []byte) (int, error) { - baseLogger.sourced().Error(string(b)) - return len(b), nil -} - -// NewErrorLogger returns a log.Logger that is meant to be used -// in the ErrorLog field of an http.Server to log HTTP server errors. -func NewErrorLogger() *log.Logger { - return log.New(&errorLogWriter{}, "", 0) -} diff --git a/vendor/github.com/prometheus/common/log/log_test.go b/vendor/github.com/prometheus/common/log/log_test.go deleted file mode 100644 index f63b4417f..000000000 --- a/vendor/github.com/prometheus/common/log/log_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "bytes" - "regexp" - "testing" - - "github.com/sirupsen/logrus" -) - -func TestFileLineLogging(t *testing.T) { - var buf bytes.Buffer - origLogger.Out = &buf - origLogger.Formatter = &logrus.TextFormatter{ - DisableColors: true, - } - - // The default logging level should be "info". - Debug("This debug-level line should not show up in the output.") - Infof("This %s-level line should show up in the output.", "info") - - re := `^time=".*" level=info msg="This info-level line should show up in the output." source="log_test.go:33"\n$` - if !regexp.MustCompile(re).Match(buf.Bytes()) { - t.Fatalf("%q did not match expected regex %q", buf.String(), re) - } -} diff --git a/vendor/github.com/prometheus/common/log/syslog_formatter.go b/vendor/github.com/prometheus/common/log/syslog_formatter.go deleted file mode 100644 index f882f2f84..000000000 --- a/vendor/github.com/prometheus/common/log/syslog_formatter.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !windows,!nacl,!plan9 - -package log - -import ( - "fmt" - "log/syslog" - "os" - - "github.com/sirupsen/logrus" -) - -var _ logrus.Formatter = (*syslogger)(nil) - -func init() { - setSyslogFormatter = func(l logger, appname, local string) error { - if appname == "" { - return fmt.Errorf("missing appname parameter") - } - if local == "" { - return fmt.Errorf("missing local parameter") - } - - fmter, err := newSyslogger(appname, local, l.entry.Logger.Formatter) - if err != nil { - fmt.Fprintf(os.Stderr, "error creating syslog formatter: %v\n", err) - l.entry.Errorf("can't connect logger to syslog: %v", err) - return err - } - l.entry.Logger.Formatter = fmter - return nil - } -} - -var prefixTag []byte - -type syslogger struct { - wrap logrus.Formatter - out *syslog.Writer -} - -func newSyslogger(appname string, facility string, fmter logrus.Formatter) (*syslogger, error) { - priority, err := getFacility(facility) - if err != nil { - return nil, err - } - out, err := syslog.New(priority, appname) - _, isJSON := fmter.(*logrus.JSONFormatter) - if isJSON { - // add cee tag to json formatted syslogs - prefixTag = []byte("@cee:") - } - return &syslogger{ - out: out, - wrap: fmter, - }, err -} - -func getFacility(facility string) (syslog.Priority, error) { - switch facility { - case "0": - return syslog.LOG_LOCAL0, nil - case "1": - return syslog.LOG_LOCAL1, nil - case "2": - return syslog.LOG_LOCAL2, nil - case "3": - return syslog.LOG_LOCAL3, nil - case "4": - return syslog.LOG_LOCAL4, nil - case "5": - return syslog.LOG_LOCAL5, nil - case "6": - return syslog.LOG_LOCAL6, nil - case "7": - return syslog.LOG_LOCAL7, nil - } - return syslog.LOG_LOCAL0, fmt.Errorf("invalid local(%s) for syslog", facility) -} - -func (s *syslogger) Format(e *logrus.Entry) ([]byte, error) { - data, err := s.wrap.Format(e) - if err != nil { - fmt.Fprintf(os.Stderr, "syslogger: can't format entry: %v\n", err) - return data, err - } - // only append tag to data sent to syslog (line), not to what - // is returned - line := string(append(prefixTag, data...)) - - switch e.Level { - case logrus.PanicLevel: - err = s.out.Crit(line) - case logrus.FatalLevel: - err = s.out.Crit(line) - case logrus.ErrorLevel: - err = s.out.Err(line) - case logrus.WarnLevel: - err = s.out.Warning(line) - case logrus.InfoLevel: - err = s.out.Info(line) - case logrus.DebugLevel: - err = s.out.Debug(line) - default: - err = s.out.Notice(line) - } - - if err != nil { - fmt.Fprintf(os.Stderr, "syslogger: can't send log to syslog: %v\n", err) - } - - return data, err -} diff --git a/vendor/github.com/prometheus/common/log/syslog_formatter_test.go b/vendor/github.com/prometheus/common/log/syslog_formatter_test.go deleted file mode 100644 index b7e68848f..000000000 --- a/vendor/github.com/prometheus/common/log/syslog_formatter_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !windows,!nacl,!plan9 - -package log - -import ( - "errors" - "log/syslog" - "testing" -) - -func TestGetFacility(t *testing.T) { - testCases := []struct { - facility string - expectedPriority syslog.Priority - expectedErr error - }{ - {"0", syslog.LOG_LOCAL0, nil}, - {"1", syslog.LOG_LOCAL1, nil}, - {"2", syslog.LOG_LOCAL2, nil}, - {"3", syslog.LOG_LOCAL3, nil}, - {"4", syslog.LOG_LOCAL4, nil}, - {"5", syslog.LOG_LOCAL5, nil}, - {"6", syslog.LOG_LOCAL6, nil}, - {"7", syslog.LOG_LOCAL7, nil}, - {"8", syslog.LOG_LOCAL0, errors.New("invalid local(8) for syslog")}, - } - for _, tc := range testCases { - priority, err := getFacility(tc.facility) - if err != tc.expectedErr { - if err.Error() != tc.expectedErr.Error() { - t.Errorf("want %s, got %s", tc.expectedErr.Error(), err.Error()) - } - } - - if priority != tc.expectedPriority { - t.Errorf("want %q, got %q", tc.expectedPriority, priority) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/alert_test.go b/vendor/github.com/prometheus/common/model/alert_test.go deleted file mode 100644 index 9692bca21..000000000 --- a/vendor/github.com/prometheus/common/model/alert_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "strings" - "testing" - "time" -) - -func TestAlertValidate(t *testing.T) { - ts := time.Now() - - var cases = []struct { - alert *Alert - err string - }{ - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - }, - err: "start time missing", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts, - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts.Add(1 * time.Minute), - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts.Add(-1 * time.Minute), - }, - err: "start time must be before end time", - }, - { - alert: &Alert{ - StartsAt: ts, - }, - err: "at least one label pair required", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b", "!bad": "label"}, - StartsAt: ts, - }, - err: "invalid label set: invalid name", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b", "bad": "\xfflabel"}, - StartsAt: ts, - }, - err: "invalid label set: invalid value", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - Annotations: LabelSet{"!bad": "label"}, - StartsAt: ts, - }, - err: "invalid annotations: invalid name", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - Annotations: LabelSet{"bad": "\xfflabel"}, - StartsAt: ts, - }, - err: "invalid annotations: invalid value", - }, - } - - for i, c := range cases { - err := c.alert.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/labels_test.go b/vendor/github.com/prometheus/common/model/labels_test.go deleted file mode 100644 index e8df28ffa..000000000 --- a/vendor/github.com/prometheus/common/model/labels_test.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "sort" - "testing" -) - -func testLabelNames(t testing.TB) { - var scenarios = []struct { - in LabelNames - out LabelNames - }{ - { - in: LabelNames{"ZZZ", "zzz"}, - out: LabelNames{"ZZZ", "zzz"}, - }, - { - in: LabelNames{"aaa", "AAA"}, - out: LabelNames{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelNames(t *testing.T) { - testLabelNames(t) -} - -func BenchmarkLabelNames(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelNames(b) - } -} - -func testLabelValues(t testing.TB) { - var scenarios = []struct { - in LabelValues - out LabelValues - }{ - { - in: LabelValues{"ZZZ", "zzz"}, - out: LabelValues{"ZZZ", "zzz"}, - }, - { - in: LabelValues{"aaa", "AAA"}, - out: LabelValues{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelValues(t *testing.T) { - testLabelValues(t) -} - -func BenchmarkLabelValues(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelValues(b) - } -} - -func TestLabelNameIsValid(t *testing.T) { - var scenarios = []struct { - ln LabelName - valid bool - }{ - { - ln: "Avalid_23name", - valid: true, - }, - { - ln: "_Avalid_23name", - valid: true, - }, - { - ln: "1valid_23name", - valid: false, - }, - { - ln: "avalid_23name", - valid: true, - }, - { - ln: "Ava:lid_23name", - valid: false, - }, - { - ln: "a lid_23name", - valid: false, - }, - { - ln: ":leading_colon", - valid: false, - }, - { - ln: "colon:in:the:middle", - valid: false, - }, - } - - for _, s := range scenarios { - if s.ln.IsValid() != s.valid { - t.Errorf("Expected %v for %q using IsValid method", s.valid, s.ln) - } - if LabelNameRE.MatchString(string(s.ln)) != s.valid { - t.Errorf("Expected %v for %q using regexp match", s.valid, s.ln) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/metric_test.go b/vendor/github.com/prometheus/common/model/metric_test.go deleted file mode 100644 index 06f9de525..000000000 --- a/vendor/github.com/prometheus/common/model/metric_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import "testing" - -func testMetric(t testing.TB) { - var scenarios = []struct { - input LabelSet - fingerprint Fingerprint - fastFingerprint Fingerprint - }{ - { - input: LabelSet{}, - fingerprint: 14695981039346656037, - fastFingerprint: 14695981039346656037, - }, - { - input: LabelSet{ - "first_name": "electro", - "occupation": "robot", - "manufacturer": "westinghouse", - }, - fingerprint: 5911716720268894962, - fastFingerprint: 11310079640881077873, - }, - { - input: LabelSet{ - "x": "y", - }, - fingerprint: 8241431561484471700, - fastFingerprint: 13948396922932177635, - }, - { - input: LabelSet{ - "a": "bb", - "b": "c", - }, - fingerprint: 3016285359649981711, - fastFingerprint: 3198632812309449502, - }, - { - input: LabelSet{ - "a": "b", - "bb": "c", - }, - fingerprint: 7122421792099404749, - fastFingerprint: 5774953389407657638, - }, - } - - for i, scenario := range scenarios { - input := Metric(scenario.input) - - if scenario.fingerprint != input.Fingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) - } - if scenario.fastFingerprint != input.FastFingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) - } - } -} - -func TestMetric(t *testing.T) { - testMetric(t) -} - -func BenchmarkMetric(b *testing.B) { - for i := 0; i < b.N; i++ { - testMetric(b) - } -} - -func TestMetricNameIsValid(t *testing.T) { - var scenarios = []struct { - mn LabelValue - valid bool - }{ - { - mn: "Avalid_23name", - valid: true, - }, - { - mn: "_Avalid_23name", - valid: true, - }, - { - mn: "1valid_23name", - valid: false, - }, - { - mn: "avalid_23name", - valid: true, - }, - { - mn: "Ava:lid_23name", - valid: true, - }, - { - mn: "a lid_23name", - valid: false, - }, - { - mn: ":leading_colon", - valid: true, - }, - { - mn: "colon:in:the:middle", - valid: true, - }, - } - - for _, s := range scenarios { - if IsValidMetricName(s.mn) != s.valid { - t.Errorf("Expected %v for %q using IsValidMetricName function", s.valid, s.mn) - } - if MetricNameRE.MatchString(string(s.mn)) != s.valid { - t.Errorf("Expected %v for %q using regexp matching", s.valid, s.mn) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/signature_test.go b/vendor/github.com/prometheus/common/model/signature_test.go deleted file mode 100644 index d59c8a8c3..000000000 --- a/vendor/github.com/prometheus/common/model/signature_test.go +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "runtime" - "sync" - "testing" -) - -func TestLabelsToSignature(t *testing.T) { - var scenarios = []struct { - in map[string]string - out uint64 - }{ - { - in: map[string]string{}, - out: 14695981039346656037, - }, - { - in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := LabelsToSignature(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFastFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 12952432476264840823, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFastFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureForLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels LabelNames - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{}, - labels: LabelNames{"empty"}, - out: 7187873163539638612, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"empty"}, - out: 7187873163539638612, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 14695981039346656037, - }, - } - - for i, scenario := range scenarios { - actual := SignatureForLabels(scenario.in, scenario.labels...) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureWithoutLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels map[LabelName]struct{} - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: map[LabelName]struct{}{"foo": struct{}{}}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := SignatureWithoutLabels(scenario.in, scenario.labels) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { - for i := 0; i < b.N; i++ { - if a := LabelsToSignature(l); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, l, a) - } - } -} - -func BenchmarkLabelToSignatureScalar(b *testing.B) { - benchmarkLabelToSignature(b, nil, 14695981039346656037) -} - -func BenchmarkLabelToSignatureSingle(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkLabelToSignatureDouble(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkLabelToSignatureTriple(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFingerprintScalar(b *testing.B) { - benchmarkMetricToFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFingerprintSingle(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkMetricToFingerprintDouble(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkMetricToFingerprintTriple(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { - benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) -} - -func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) -} - -func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) -} - -func BenchmarkEmptyLabelSignature(b *testing.B) { - input := []map[string]string{nil, {}} - - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - - alloc := ms.Alloc - - for _, labels := range input { - LabelsToSignature(labels) - } - - runtime.ReadMemStats(&ms) - - if got := ms.Alloc; alloc != got { - b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") - } -} - -func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - for i := 0; i < concLevel; i++ { - go func() { - start.Wait() - for j := b.N / concLevel; j >= 0; j-- { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } - end.Done() - }() - } - b.ResetTimer() - start.Done() - end.Wait() -} - -func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) -} - -func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) -} - -func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) -} - -func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) -} diff --git a/vendor/github.com/prometheus/common/model/silence.go b/vendor/github.com/prometheus/common/model/silence.go index 7538e2997..bb99889d2 100644 --- a/vendor/github.com/prometheus/common/model/silence.go +++ b/vendor/github.com/prometheus/common/model/silence.go @@ -59,8 +59,8 @@ func (m *Matcher) Validate() error { return nil } -// Silence defines the representation of a silence definiton -// in the Prometheus eco-system. +// Silence defines the representation of a silence definition in the Prometheus +// eco-system. type Silence struct { ID uint64 `json:"id,omitempty"` diff --git a/vendor/github.com/prometheus/common/model/silence_test.go b/vendor/github.com/prometheus/common/model/silence_test.go deleted file mode 100644 index 8eaaf0744..000000000 --- a/vendor/github.com/prometheus/common/model/silence_test.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "strings" - "testing" - "time" -) - -func TestMatcherValidate(t *testing.T) { - var cases = []struct { - matcher *Matcher - err string - }{ - { - matcher: &Matcher{ - Name: "name", - Value: "value", - }, - }, - { - matcher: &Matcher{ - Name: "name", - Value: "value", - IsRegex: true, - }, - }, - { - matcher: &Matcher{ - Name: "name!", - Value: "value", - }, - err: "invalid name", - }, - { - matcher: &Matcher{ - Name: "", - Value: "value", - }, - err: "invalid name", - }, - { - matcher: &Matcher{ - Name: "name", - Value: "value\xff", - }, - err: "invalid value", - }, - { - matcher: &Matcher{ - Name: "name", - Value: "", - }, - err: "invalid value", - }, - } - - for i, c := range cases { - err := c.matcher.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} - -func TestSilenceValidate(t *testing.T) { - ts := time.Now() - - var cases = []struct { - sil *Silence - err string - }{ - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - {Name: "name", Value: "value"}, - {Name: "name", Value: "value"}, - {Name: "name", Value: "value", IsRegex: true}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts.Add(-1 * time.Minute), - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "start time must be before end time", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "end time missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "start time missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "!name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "invalid matcher", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - }, - err: "comment missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "creation timestamp missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - Comment: "comment", - }, - err: "creator information missing", - }, - } - - for i, c := range cases { - err := c.sil.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/time_test.go b/vendor/github.com/prometheus/common/model/time_test.go deleted file mode 100644 index 3efdd65ff..000000000 --- a/vendor/github.com/prometheus/common/model/time_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "testing" - "time" -) - -func TestComparators(t *testing.T) { - t1a := TimeFromUnix(0) - t1b := TimeFromUnix(0) - t2 := TimeFromUnix(2*second - 1) - - if !t1a.Equal(t1b) { - t.Fatalf("Expected %s to be equal to %s", t1a, t1b) - } - if t1a.Equal(t2) { - t.Fatalf("Expected %s to not be equal to %s", t1a, t2) - } - - if !t1a.Before(t2) { - t.Fatalf("Expected %s to be before %s", t1a, t2) - } - if t1a.Before(t1b) { - t.Fatalf("Expected %s to not be before %s", t1a, t1b) - } - - if !t2.After(t1a) { - t.Fatalf("Expected %s to be after %s", t2, t1a) - } - if t1b.After(t1a) { - t.Fatalf("Expected %s to not be after %s", t1b, t1a) - } -} - -func TestTimeConversions(t *testing.T) { - unixSecs := int64(1136239445) - unixNsecs := int64(123456789) - unixNano := unixSecs*1e9 + unixNsecs - - t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) - t2 := time.Unix(unixSecs, unixNsecs) - - ts := TimeFromUnixNano(unixNano) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - // Test available precision. - ts = TimeFromUnixNano(t2.UnixNano()) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - if ts.UnixNano() != unixNano-unixNano%nanosPerTick { - t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) - } -} - -func TestDuration(t *testing.T) { - duration := time.Second + time.Minute + time.Hour - goTime := time.Unix(1136239445, 0) - - ts := TimeFromUnix(goTime.Unix()) - if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { - t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) - } - - earlier := ts.Add(-duration) - delta := ts.Sub(earlier) - if delta != duration { - t.Fatalf("Expected %s to be equal to %s", delta, duration) - } -} - -func TestParseDuration(t *testing.T) { - var cases = []struct { - in string - out time.Duration - }{ - { - in: "0s", - out: 0, - }, { - in: "324ms", - out: 324 * time.Millisecond, - }, { - in: "3s", - out: 3 * time.Second, - }, { - in: "5m", - out: 5 * time.Minute, - }, { - in: "1h", - out: time.Hour, - }, { - in: "4d", - out: 4 * 24 * time.Hour, - }, { - in: "3w", - out: 3 * 7 * 24 * time.Hour, - }, { - in: "10y", - out: 10 * 365 * 24 * time.Hour, - }, - } - - for _, c := range cases { - d, err := ParseDuration(c.in) - if err != nil { - t.Errorf("Unexpected error on input %q", c.in) - } - if time.Duration(d) != c.out { - t.Errorf("Expected %v but got %v", c.out, d) - } - if d.String() != c.in { - t.Errorf("Expected duration string %q but got %q", c.in, d.String()) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go index c9ed3ffd8..c9d8fb1a2 100644 --- a/vendor/github.com/prometheus/common/model/value.go +++ b/vendor/github.com/prometheus/common/model/value.go @@ -100,7 +100,7 @@ func (s *SamplePair) UnmarshalJSON(b []byte) error { } // Equal returns true if this SamplePair and o have equal Values and equal -// Timestamps. The sematics of Value equality is defined by SampleValue.Equal. +// Timestamps. The semantics of Value equality is defined by SampleValue.Equal. func (s *SamplePair) Equal(o *SamplePair) bool { return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp)) } @@ -117,7 +117,7 @@ type Sample struct { } // Equal compares first the metrics, then the timestamp, then the value. The -// sematics of value equality is defined by SampleValue.Equal. +// semantics of value equality is defined by SampleValue.Equal. func (s *Sample) Equal(o *Sample) bool { if s == o { return true diff --git a/vendor/github.com/prometheus/common/model/value_test.go b/vendor/github.com/prometheus/common/model/value_test.go deleted file mode 100644 index b97dcf84c..000000000 --- a/vendor/github.com/prometheus/common/model/value_test.go +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "encoding/json" - "math" - "reflect" - "sort" - "testing" -) - -func TestEqualValues(t *testing.T) { - tests := map[string]struct { - in1, in2 SampleValue - want bool - }{ - "equal floats": { - in1: 3.14, - in2: 3.14, - want: true, - }, - "unequal floats": { - in1: 3.14, - in2: 3.1415, - want: false, - }, - "positive inifinities": { - in1: SampleValue(math.Inf(+1)), - in2: SampleValue(math.Inf(+1)), - want: true, - }, - "negative inifinities": { - in1: SampleValue(math.Inf(-1)), - in2: SampleValue(math.Inf(-1)), - want: true, - }, - "different inifinities": { - in1: SampleValue(math.Inf(+1)), - in2: SampleValue(math.Inf(-1)), - want: false, - }, - "number and infinity": { - in1: 42, - in2: SampleValue(math.Inf(+1)), - want: false, - }, - "number and NaN": { - in1: 42, - in2: SampleValue(math.NaN()), - want: false, - }, - "NaNs": { - in1: SampleValue(math.NaN()), - in2: SampleValue(math.NaN()), - want: true, // !!! - }, - } - - for name, test := range tests { - got := test.in1.Equal(test.in2) - if got != test.want { - t.Errorf("Comparing %s, %f and %f: got %t, want %t", name, test.in1, test.in2, got, test.want) - } - } -} - -func TestEqualSamples(t *testing.T) { - testSample := &Sample{} - - tests := map[string]struct { - in1, in2 *Sample - want bool - }{ - "equal pointers": { - in1: testSample, - in2: testSample, - want: true, - }, - "different metrics": { - in1: &Sample{Metric: Metric{"foo": "bar"}}, - in2: &Sample{Metric: Metric{"foo": "biz"}}, - want: false, - }, - "different timestamp": { - in1: &Sample{Timestamp: 0}, - in2: &Sample{Timestamp: 1}, - want: false, - }, - "different value": { - in1: &Sample{Value: 0}, - in2: &Sample{Value: 1}, - want: false, - }, - "equal samples": { - in1: &Sample{ - Metric: Metric{"foo": "bar"}, - Timestamp: 0, - Value: 1, - }, - in2: &Sample{ - Metric: Metric{"foo": "bar"}, - Timestamp: 0, - Value: 1, - }, - want: true, - }, - } - - for name, test := range tests { - got := test.in1.Equal(test.in2) - if got != test.want { - t.Errorf("Comparing %s, %v and %v: got %t, want %t", name, test.in1, test.in2, got, test.want) - } - } - -} - -func TestSamplePairJSON(t *testing.T) { - input := []struct { - plain string - value SamplePair - }{ - { - plain: `[1234.567,"123.1"]`, - value: SamplePair{ - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sp SamplePair - err = json.Unmarshal(b, &sp) - if err != nil { - t.Error(err) - continue - } - - if sp != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sp) - } - } -} - -func TestSampleJSON(t *testing.T) { - input := []struct { - plain string - value Sample - }{ - { - plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, - value: Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Sample - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(sv, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorJSON(t *testing.T) { - input := []struct { - plain string - value Vector - }{ - { - plain: `[]`, - value: Vector{}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, - value: Vector{&Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, - value: Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - &Sample{ - Metric: Metric{ - "foo": "bar", - }, - Value: SampleValue(math.Inf(1)), - Timestamp: 1234, - }, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var vec Vector - err = json.Unmarshal(b, &vec) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(vec, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, vec) - } - } -} - -func TestScalarJSON(t *testing.T) { - input := []struct { - plain string - value Scalar - }{ - { - plain: `[123.456,"456"]`, - value: Scalar{ - Timestamp: 123456, - Value: 456, - }, - }, - { - plain: `[123123.456,"+Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(1)), - }, - }, - { - plain: `[123123.456,"-Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(-1)), - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Scalar - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestStringJSON(t *testing.T) { - input := []struct { - plain string - value String - }{ - { - plain: `[123.456,"test"]`, - value: String{ - Timestamp: 123456, - Value: "test", - }, - }, - { - plain: `[123123.456,"台北"]`, - value: String{ - Timestamp: 123123456, - Value: "台北", - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv String - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorSort(t *testing.T) { - input := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - } - - expected := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - } - - sort.Sort(input) - - for i, actual := range input { - actualFp := actual.Metric.Fingerprint() - expectedFp := expected[i].Metric.Fingerprint() - - if actualFp != expectedFp { - t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) - } - - if actual.Timestamp != expected[i].Timestamp { - t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) - } - } -} diff --git a/vendor/github.com/prometheus/common/promlog/flag/flag.go b/vendor/github.com/prometheus/common/promlog/flag/flag.go deleted file mode 100644 index b9d361e43..000000000 --- a/vendor/github.com/prometheus/common/promlog/flag/flag.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package flag - -import ( - "github.com/prometheus/common/promlog" - kingpin "gopkg.in/alecthomas/kingpin.v2" -) - -// LevelFlagName is the canonical flag name to configure the allowed log level -// within Prometheus projects. -const LevelFlagName = "log.level" - -// LevelFlagHelp is the help description for the log.level flag. -const LevelFlagHelp = "Only log messages with the given severity or above. One of: [debug, info, warn, error]" - -// AddFlags adds the flags used by this package to the Kingpin application. -// To use the default Kingpin application, call AddFlags(kingpin.CommandLine) -func AddFlags(a *kingpin.Application, logLevel *promlog.AllowedLevel) { - a.Flag(LevelFlagName, LevelFlagHelp). - Default("info").SetValue(logLevel) -} diff --git a/vendor/github.com/prometheus/common/promlog/log.go b/vendor/github.com/prometheus/common/promlog/log.go deleted file mode 100644 index cf8307ad2..000000000 --- a/vendor/github.com/prometheus/common/promlog/log.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package promlog defines standardised ways to initialize Go kit loggers -// across Prometheus components. -// It should typically only ever be imported by main packages. -package promlog - -import ( - "os" - - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" - "github.com/pkg/errors" -) - -// AllowedLevel is a settable identifier for the minimum level a log entry -// must be have. -type AllowedLevel struct { - s string - o level.Option -} - -func (l *AllowedLevel) String() string { - return l.s -} - -// Set updates the value of the allowed level. -func (l *AllowedLevel) Set(s string) error { - switch s { - case "debug": - l.o = level.AllowDebug() - case "info": - l.o = level.AllowInfo() - case "warn": - l.o = level.AllowWarn() - case "error": - l.o = level.AllowError() - default: - return errors.Errorf("unrecognized log level %q", s) - } - l.s = s - return nil -} - -// New returns a new leveled oklog logger in the logfmt format. Each logged line will be annotated -// with a timestamp. The output always goes to stderr. -func New(al AllowedLevel) log.Logger { - l := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - l = level.NewFilter(l, al.o) - l = log.With(l, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) - return l -} diff --git a/vendor/github.com/prometheus/common/route/route.go b/vendor/github.com/prometheus/common/route/route.go deleted file mode 100644 index bb4688173..000000000 --- a/vendor/github.com/prometheus/common/route/route.go +++ /dev/null @@ -1,100 +0,0 @@ -package route - -import ( - "net/http" - - "github.com/julienschmidt/httprouter" - "golang.org/x/net/context" -) - -type param string - -// Param returns param p for the context. -func Param(ctx context.Context, p string) string { - return ctx.Value(param(p)).(string) -} - -// WithParam returns a new context with param p set to v. -func WithParam(ctx context.Context, p, v string) context.Context { - return context.WithValue(ctx, param(p), v) -} - -// Router wraps httprouter.Router and adds support for prefixed sub-routers -// and per-request context injections. -type Router struct { - rtr *httprouter.Router - prefix string -} - -// New returns a new Router. -func New() *Router { - return &Router{ - rtr: httprouter.New(), - } -} - -// WithPrefix returns a router that prefixes all registered routes with prefix. -func (r *Router) WithPrefix(prefix string) *Router { - return &Router{rtr: r.rtr, prefix: r.prefix + prefix} -} - -// handle turns a HandlerFunc into an httprouter.Handle. -func (r *Router) handle(h http.HandlerFunc) httprouter.Handle { - return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - - for _, p := range params { - ctx = context.WithValue(ctx, param(p.Key), p.Value) - } - h(w, req.WithContext(ctx)) - } -} - -// Get registers a new GET route. -func (r *Router) Get(path string, h http.HandlerFunc) { - r.rtr.GET(r.prefix+path, r.handle(h)) -} - -// Options registers a new OPTIONS route. -func (r *Router) Options(path string, h http.HandlerFunc) { - r.rtr.OPTIONS(r.prefix+path, r.handle(h)) -} - -// Del registers a new DELETE route. -func (r *Router) Del(path string, h http.HandlerFunc) { - r.rtr.DELETE(r.prefix+path, r.handle(h)) -} - -// Put registers a new PUT route. -func (r *Router) Put(path string, h http.HandlerFunc) { - r.rtr.PUT(r.prefix+path, r.handle(h)) -} - -// Post registers a new POST route. -func (r *Router) Post(path string, h http.HandlerFunc) { - r.rtr.POST(r.prefix+path, r.handle(h)) -} - -// Redirect takes an absolute path and sends an internal HTTP redirect for it, -// prefixed by the router's path prefix. Note that this method does not include -// functionality for handling relative paths or full URL redirects. -func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) { - http.Redirect(w, req, r.prefix+path, code) -} - -// ServeHTTP implements http.Handler. -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - r.rtr.ServeHTTP(w, req) -} - -// FileServe returns a new http.HandlerFunc that serves files from dir. -// Using routes must provide the *filepath parameter. -func FileServe(dir string) http.HandlerFunc { - fs := http.FileServer(http.Dir(dir)) - - return func(w http.ResponseWriter, r *http.Request) { - r.URL.Path = Param(r.Context(), "filepath") - fs.ServeHTTP(w, r) - } -} diff --git a/vendor/github.com/prometheus/common/route/route_test.go b/vendor/github.com/prometheus/common/route/route_test.go deleted file mode 100644 index a9bb20996..000000000 --- a/vendor/github.com/prometheus/common/route/route_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package route - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestRedirect(t *testing.T) { - router := New().WithPrefix("/test/prefix") - w := httptest.NewRecorder() - r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil) - if err != nil { - t.Fatalf("Error building test request: %s", err) - } - - router.Redirect(w, r, "/some/endpoint", http.StatusFound) - if w.Code != http.StatusFound { - t.Fatalf("Unexpected redirect status code: got %d, want %d", w.Code, http.StatusFound) - } - - want := "/test/prefix/some/endpoint" - got := w.Header()["Location"][0] - if want != got { - t.Fatalf("Unexpected redirect location: got %s, want %s", got, want) - } -} - -func TestContext(t *testing.T) { - router := New() - router.Get("/test/:foo/", func(w http.ResponseWriter, r *http.Request) { - want := "bar" - got := Param(r.Context(), "foo") - if want != got { - t.Fatalf("Unexpected context value: want %q, got %q", want, got) - } - }) - - r, err := http.NewRequest("GET", "http://localhost:9090/test/bar/", nil) - if err != nil { - t.Fatalf("Error building test request: %s", err) - } - router.ServeHTTP(nil, r) -} diff --git a/vendor/github.com/prometheus/common/version/info.go b/vendor/github.com/prometheus/common/version/info.go deleted file mode 100644 index 84489a510..000000000 --- a/vendor/github.com/prometheus/common/version/info.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package version - -import ( - "bytes" - "fmt" - "runtime" - "strings" - "text/template" - - "github.com/prometheus/client_golang/prometheus" -) - -// Build information. Populated at build-time. -var ( - Version string - Revision string - Branch string - BuildUser string - BuildDate string - GoVersion = runtime.Version() -) - -// NewCollector returns a collector which exports metrics about current version information. -func NewCollector(program string) *prometheus.GaugeVec { - buildInfo := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: program, - Name: "build_info", - Help: fmt.Sprintf( - "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.", - program, - ), - }, - []string{"version", "revision", "branch", "goversion"}, - ) - buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1) - return buildInfo -} - -// versionInfoTmpl contains the template used by Info. -var versionInfoTmpl = ` -{{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}}) - build user: {{.buildUser}} - build date: {{.buildDate}} - go version: {{.goVersion}} -` - -// Print returns version information. -func Print(program string) string { - m := map[string]string{ - "program": program, - "version": Version, - "revision": Revision, - "branch": Branch, - "buildUser": BuildUser, - "buildDate": BuildDate, - "goVersion": GoVersion, - } - t := template.Must(template.New("version").Parse(versionInfoTmpl)) - - var buf bytes.Buffer - if err := t.ExecuteTemplate(&buf, "version", m); err != nil { - panic(err) - } - return strings.TrimSpace(buf.String()) -} - -// Info returns version, branch and revision information. -func Info() string { - return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, Revision) -} - -// BuildContext returns goVersion, buildUser and buildDate information. -func BuildContext() string { - return fmt.Sprintf("(go=%s, user=%s, date=%s)", GoVersion, BuildUser, BuildDate) -} diff --git a/vendor/github.com/prometheus/procfs/.gitignore b/vendor/github.com/prometheus/procfs/.gitignore new file mode 100644 index 000000000..25e3659ab --- /dev/null +++ b/vendor/github.com/prometheus/procfs/.gitignore @@ -0,0 +1 @@ +/fixtures/ diff --git a/vendor/github.com/prometheus/procfs/.travis.yml b/vendor/github.com/prometheus/procfs/.travis.yml index 0dc42122b..5416cf8a2 100644 --- a/vendor/github.com/prometheus/procfs/.travis.yml +++ b/vendor/github.com/prometheus/procfs/.travis.yml @@ -3,7 +3,13 @@ sudo: false language: go go: +- 1.7.x +- 1.8.x - 1.9.x +- 1.10.x - 1.x go_import_path: github.com/prometheus/procfs + +script: +- make style check_license vet test staticcheck diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile index dd48afdcd..5c8f72625 100644 --- a/vendor/github.com/prometheus/procfs/Makefile +++ b/vendor/github.com/prometheus/procfs/Makefile @@ -1,18 +1,71 @@ -ci: fmt lint test +# Copyright 2018 The Prometheus Authors +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -fmt: - ! gofmt -l *.go | read nothing - go vet +# Ensure GOBIN is not set during build so that promu is installed to the correct path +unexport GOBIN -lint: - go get github.com/golang/lint/golint - golint *.go +GO ?= go +GOFMT ?= $(GO)fmt +FIRST_GOPATH := $(firstword $(subst :, ,$(shell $(GO) env GOPATH))) +STATICCHECK := $(FIRST_GOPATH)/bin/staticcheck +pkgs = $(shell $(GO) list ./... | grep -v /vendor/) -test: sysfs/fixtures/.unpacked - go test -v ./... +PREFIX ?= $(shell pwd) +BIN_DIR ?= $(shell pwd) -sysfs/fixtures/.unpacked: sysfs/fixtures.ttar - ./ttar -C sysfs -x -f sysfs/fixtures.ttar +ifdef DEBUG + bindata_flags = -debug +endif + +STATICCHECK_IGNORE = + +all: format staticcheck build test + +style: + @echo ">> checking code style" + @! $(GOFMT) -d $(shell find . -path ./vendor -prune -o -name '*.go' -print) | grep '^' + +check_license: + @echo ">> checking license header" + @./scripts/check_license.sh + +test: fixtures/.unpacked sysfs/fixtures/.unpacked + @echo ">> running all tests" + @$(GO) test -race $(shell $(GO) list ./... | grep -v /vendor/ | grep -v examples) + +format: + @echo ">> formatting code" + @$(GO) fmt $(pkgs) + +vet: + @echo ">> vetting code" + @$(GO) vet $(pkgs) + +staticcheck: $(STATICCHECK) + @echo ">> running staticcheck" + @$(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" $(pkgs) + +%/.unpacked: %.ttar + ./ttar -C $(dir $*) -x -f $*.ttar touch $@ -.PHONY: fmt lint test ci +$(FIRST_GOPATH)/bin/staticcheck: + @GOOS= GOARCH= $(GO) get -u honnef.co/go/tools/cmd/staticcheck + +.PHONY: all style check_license format test vet staticcheck + +# Declaring the binaries at their default locations as PHONY targets is a hack +# to ensure the latest version is downloaded on every make execution. +# If this is not desired, copy/symlink these binaries to a different path and +# set the respective environment variables. +.PHONY: $(GOPATH)/bin/staticcheck diff --git a/vendor/github.com/prometheus/procfs/bcache/bcache.go b/vendor/github.com/prometheus/procfs/bcache/bcache.go deleted file mode 100644 index 1db178cec..000000000 --- a/vendor/github.com/prometheus/procfs/bcache/bcache.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package bcache provides access to statistics exposed by the bcache (Linux -// block cache). -package bcache - -// Stats contains bcache runtime statistics, parsed from /sys/fs/bcache/. -// -// The names and meanings of each statistic were taken from bcache.txt and -// files in drivers/md/bcache in the Linux kernel source. Counters are uint64 -// (in-kernel counters are mostly unsigned long). -type Stats struct { - // The name of the bcache used to source these statistics. - Name string - Bcache BcacheStats - Bdevs []BdevStats - Caches []CacheStats -} - -// BcacheStats contains statistics tied to a bcache ID. -type BcacheStats struct { - AverageKeySize uint64 - BtreeCacheSize uint64 - CacheAvailablePercent uint64 - Congested uint64 - RootUsagePercent uint64 - TreeDepth uint64 - Internal InternalStats - FiveMin PeriodStats - Total PeriodStats -} - -// BdevStats contains statistics for one backing device. -type BdevStats struct { - Name string - DirtyData uint64 - FiveMin PeriodStats - Total PeriodStats -} - -// CacheStats contains statistics for one cache device. -type CacheStats struct { - Name string - IOErrors uint64 - MetadataWritten uint64 - Written uint64 - Priority PriorityStats -} - -// PriorityStats contains statistics from the priority_stats file. -type PriorityStats struct { - UnusedPercent uint64 - MetadataPercent uint64 -} - -// InternalStats contains internal bcache statistics. -type InternalStats struct { - ActiveJournalEntries uint64 - BtreeNodes uint64 - BtreeReadAverageDurationNanoSeconds uint64 - CacheReadRaces uint64 -} - -// PeriodStats contains statistics for a time period (5 min or total). -type PeriodStats struct { - Bypassed uint64 - CacheBypassHits uint64 - CacheBypassMisses uint64 - CacheHits uint64 - CacheMissCollisions uint64 - CacheMisses uint64 - CacheReadaheads uint64 -} diff --git a/vendor/github.com/prometheus/procfs/bcache/get.go b/vendor/github.com/prometheus/procfs/bcache/get.go deleted file mode 100644 index b6d97de15..000000000 --- a/vendor/github.com/prometheus/procfs/bcache/get.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package bcache - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strconv" - "strings" -) - -// ParsePseudoFloat parses the peculiar format produced by bcache's bch_hprint. -func parsePseudoFloat(str string) (float64, error) { - ss := strings.Split(str, ".") - - intPart, err := strconv.ParseFloat(ss[0], 64) - if err != nil { - return 0, err - } - - if len(ss) == 1 { - // Pure integers are fine. - return intPart, nil - } - fracPart, err := strconv.ParseFloat(ss[1], 64) - if err != nil { - return 0, err - } - // fracPart is a number between 0 and 1023 divided by 100; it is off - // by a small amount. Unexpected bumps in time lines may occur because - // for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux - // v4.12-rc3). - - // Restore the proper order: - fracPart = fracPart / 10.24 - return intPart + fracPart, nil -} - -// Dehumanize converts a human-readable byte slice into a uint64. -func dehumanize(hbytes []byte) (uint64, error) { - ll := len(hbytes) - if ll == 0 { - return 0, fmt.Errorf("zero-length reply") - } - lastByte := hbytes[ll-1] - mul := float64(1) - var ( - mant float64 - err error - ) - // If lastByte is beyond the range of ASCII digits, it must be a - // multiplier. - if lastByte > 57 { - // Remove multiplier from slice. - hbytes = hbytes[:len(hbytes)-1] - - const ( - _ = 1 << (10 * iota) - KiB - MiB - GiB - TiB - PiB - EiB - ZiB - YiB - ) - - multipliers := map[rune]float64{ - // Source for conversion rules: - // linux-kernel/drivers/md/bcache/util.c:bch_hprint() - 'k': KiB, - 'M': MiB, - 'G': GiB, - 'T': TiB, - 'P': PiB, - 'E': EiB, - 'Z': ZiB, - 'Y': YiB, - } - mul = multipliers[rune(lastByte)] - mant, err = parsePseudoFloat(string(hbytes)) - if err != nil { - return 0, err - } - } else { - // Not humanized by bch_hprint - mant, err = strconv.ParseFloat(string(hbytes), 64) - if err != nil { - return 0, err - } - } - res := uint64(mant * mul) - return res, nil -} - -type parser struct { - uuidPath string - subDir string - currentDir string - err error -} - -func (p *parser) setSubDir(pathElements ...string) { - p.subDir = path.Join(pathElements...) - p.currentDir = path.Join(p.uuidPath, p.subDir) -} - -func (p *parser) readValue(fileName string) uint64 { - if p.err != nil { - return 0 - } - path := path.Join(p.currentDir, fileName) - byt, err := ioutil.ReadFile(path) - if err != nil { - p.err = fmt.Errorf("failed to read: %s", path) - return 0 - } - // Remove trailing newline. - byt = byt[:len(byt)-1] - res, err := dehumanize(byt) - p.err = err - return res -} - -// ParsePriorityStats parses lines from the priority_stats file. -func parsePriorityStats(line string, ps *PriorityStats) error { - var ( - value uint64 - err error - ) - switch { - case strings.HasPrefix(line, "Unused:"): - fields := strings.Fields(line) - rawValue := fields[len(fields)-1] - valueStr := strings.TrimSuffix(rawValue, "%") - value, err = strconv.ParseUint(valueStr, 10, 64) - if err != nil { - return err - } - ps.UnusedPercent = value - case strings.HasPrefix(line, "Metadata:"): - fields := strings.Fields(line) - rawValue := fields[len(fields)-1] - valueStr := strings.TrimSuffix(rawValue, "%") - value, err = strconv.ParseUint(valueStr, 10, 64) - if err != nil { - return err - } - ps.MetadataPercent = value - } - return nil -} - -func (p *parser) getPriorityStats() PriorityStats { - var res PriorityStats - - if p.err != nil { - return res - } - - path := path.Join(p.currentDir, "priority_stats") - - file, err := os.Open(path) - if err != nil { - p.err = fmt.Errorf("failed to read: %s", path) - return res - } - defer file.Close() - - scanner := bufio.NewScanner(file) - for scanner.Scan() { - err = parsePriorityStats(scanner.Text(), &res) - if err != nil { - p.err = fmt.Errorf("failed to parse: %s (%s)", path, err) - return res - } - } - if err := scanner.Err(); err != nil { - p.err = fmt.Errorf("failed to parse: %s (%s)", path, err) - return res - } - return res -} - -// GetStats collects from sysfs files data tied to one bcache ID. -func GetStats(uuidPath string) (*Stats, error) { - var bs Stats - - par := parser{uuidPath: uuidPath} - - // bcache stats - - // dir - par.setSubDir("") - bs.Bcache.AverageKeySize = par.readValue("average_key_size") - bs.Bcache.BtreeCacheSize = par.readValue("btree_cache_size") - bs.Bcache.CacheAvailablePercent = par.readValue("cache_available_percent") - bs.Bcache.Congested = par.readValue("congested") - bs.Bcache.RootUsagePercent = par.readValue("root_usage_percent") - bs.Bcache.TreeDepth = par.readValue("tree_depth") - - // bcache stats (internal) - - // dir /internal - par.setSubDir("internal") - bs.Bcache.Internal.ActiveJournalEntries = par.readValue("active_journal_entries") - bs.Bcache.Internal.BtreeNodes = par.readValue("btree_nodes") - bs.Bcache.Internal.BtreeReadAverageDurationNanoSeconds = par.readValue("btree_read_average_duration_us") - bs.Bcache.Internal.CacheReadRaces = par.readValue("cache_read_races") - - // bcache stats (period) - - // dir /stats_five_minute - par.setSubDir("stats_five_minute") - bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed") - bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits") - - bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed") - bs.Bcache.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits") - bs.Bcache.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses") - bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits") - bs.Bcache.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions") - bs.Bcache.FiveMin.CacheMisses = par.readValue("cache_misses") - bs.Bcache.FiveMin.CacheReadaheads = par.readValue("cache_readaheads") - - // dir /stats_total - par.setSubDir("stats_total") - bs.Bcache.Total.Bypassed = par.readValue("bypassed") - bs.Bcache.Total.CacheHits = par.readValue("cache_hits") - - bs.Bcache.Total.Bypassed = par.readValue("bypassed") - bs.Bcache.Total.CacheBypassHits = par.readValue("cache_bypass_hits") - bs.Bcache.Total.CacheBypassMisses = par.readValue("cache_bypass_misses") - bs.Bcache.Total.CacheHits = par.readValue("cache_hits") - bs.Bcache.Total.CacheMissCollisions = par.readValue("cache_miss_collisions") - bs.Bcache.Total.CacheMisses = par.readValue("cache_misses") - bs.Bcache.Total.CacheReadaheads = par.readValue("cache_readaheads") - - if par.err != nil { - return nil, par.err - } - - // bdev stats - - reg := path.Join(uuidPath, "bdev[0-9]*") - bdevDirs, err := filepath.Glob(reg) - if err != nil { - return nil, err - } - - bs.Bdevs = make([]BdevStats, len(bdevDirs)) - - for ii, bdevDir := range bdevDirs { - var bds = &bs.Bdevs[ii] - - bds.Name = filepath.Base(bdevDir) - - par.setSubDir(bds.Name) - bds.DirtyData = par.readValue("dirty_data") - - // dir //stats_five_minute - par.setSubDir(bds.Name, "stats_five_minute") - bds.FiveMin.Bypassed = par.readValue("bypassed") - bds.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits") - bds.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses") - bds.FiveMin.CacheHits = par.readValue("cache_hits") - bds.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions") - bds.FiveMin.CacheMisses = par.readValue("cache_misses") - bds.FiveMin.CacheReadaheads = par.readValue("cache_readaheads") - - // dir //stats_total - par.setSubDir("stats_total") - bds.Total.Bypassed = par.readValue("bypassed") - bds.Total.CacheBypassHits = par.readValue("cache_bypass_hits") - bds.Total.CacheBypassMisses = par.readValue("cache_bypass_misses") - bds.Total.CacheHits = par.readValue("cache_hits") - bds.Total.CacheMissCollisions = par.readValue("cache_miss_collisions") - bds.Total.CacheMisses = par.readValue("cache_misses") - bds.Total.CacheReadaheads = par.readValue("cache_readaheads") - } - - if par.err != nil { - return nil, par.err - } - - // cache stats - - reg = path.Join(uuidPath, "cache[0-9]*") - cacheDirs, err := filepath.Glob(reg) - if err != nil { - return nil, err - } - bs.Caches = make([]CacheStats, len(cacheDirs)) - - for ii, cacheDir := range cacheDirs { - var cs = &bs.Caches[ii] - cs.Name = filepath.Base(cacheDir) - - // dir is / - par.setSubDir(cs.Name) - cs.IOErrors = par.readValue("io_errors") - cs.MetadataWritten = par.readValue("metadata_written") - cs.Written = par.readValue("written") - - ps := par.getPriorityStats() - cs.Priority = ps - } - - if par.err != nil { - return nil, par.err - } - - return &bs, nil -} diff --git a/vendor/github.com/prometheus/procfs/bcache/get_test.go b/vendor/github.com/prometheus/procfs/bcache/get_test.go deleted file mode 100644 index 1d41a5ad3..000000000 --- a/vendor/github.com/prometheus/procfs/bcache/get_test.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package bcache - -import ( - "math" - "testing" -) - -func TestDehumanizeTests(t *testing.T) { - dehumanizeTests := []struct { - in []byte - out uint64 - invalid bool - }{ - { - in: []byte("542k"), - out: 555008, - }, - { - in: []byte("322M"), - out: 337641472, - }, - { - in: []byte("1.1k"), - out: 1124, - }, - { - in: []byte("1.9k"), - out: 1924, - }, - { - in: []byte("1.10k"), - out: 2024, - }, - { - in: []byte(""), - out: 0, - invalid: true, - }, - } - for _, tst := range dehumanizeTests { - got, err := dehumanize(tst.in) - if tst.invalid && err == nil { - t.Error("expected an error, but none occurred") - } - if !tst.invalid && err != nil { - t.Errorf("unexpected error: %v", err) - } - if got != tst.out { - t.Errorf("dehumanize: '%s', want %d, got %d", tst.in, tst.out, got) - } - } -} - -func TestParsePseudoFloatTests(t *testing.T) { - parsePseudoFloatTests := []struct { - in string - out float64 - }{ - { - in: "1.1", - out: float64(1.097656), - }, - { - in: "1.9", - out: float64(1.878906), - }, - { - in: "1.10", - out: float64(1.976562), - }, - } - for _, tst := range parsePseudoFloatTests { - got, err := parsePseudoFloat(tst.in) - if err != nil || math.Abs(got-tst.out) > 0.0001 { - t.Errorf("parsePseudoFloat: %s, want %f, got %f", tst.in, tst.out, got) - } - } -} - -func TestPriorityStats(t *testing.T) { - var want = PriorityStats{ - UnusedPercent: 99, - MetadataPercent: 5, - } - var ( - in string - gotErr error - got PriorityStats - ) - in = "Metadata: 5%" - gotErr = parsePriorityStats(in, &got) - if gotErr != nil || got.MetadataPercent != want.MetadataPercent { - t.Errorf("parsePriorityStats: '%s', want %d, got %d", in, want.MetadataPercent, got.MetadataPercent) - } - - in = "Unused: 99%" - gotErr = parsePriorityStats(in, &got) - if gotErr != nil || got.UnusedPercent != want.UnusedPercent { - t.Errorf("parsePriorityStats: '%s', want %d, got %d", in, want.UnusedPercent, got.UnusedPercent) - } -} diff --git a/vendor/github.com/prometheus/procfs/buddyinfo_test.go b/vendor/github.com/prometheus/procfs/buddyinfo_test.go deleted file mode 100644 index bcf9355ca..000000000 --- a/vendor/github.com/prometheus/procfs/buddyinfo_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package procfs - -import ( - "strings" - "testing" -) - -func TestBuddyInfo(t *testing.T) { - buddyInfo, err := FS("fixtures/buddyinfo/valid").NewBuddyInfo() - if err != nil { - t.Fatal(err) - } - - if want, got := "DMA", buddyInfo[0].Zone; want != got { - t.Errorf("want Node 0, Zone %s, got %s", want, got) - } - - if want, got := "Normal", buddyInfo[2].Zone; want != got { - t.Errorf("want Node 0, Zone %s, got %s", want, got) - } - - if want, got := 4381.0, buddyInfo[2].Sizes[0]; want != got { - t.Errorf("want Node 0, Zone Normal %f, got %f", want, got) - } - - if want, got := 572.0, buddyInfo[1].Sizes[1]; want != got { - t.Errorf("want Node 0, Zone DMA32 %f, got %f", want, got) - } -} - -func TestBuddyInfoShort(t *testing.T) { - _, err := FS("fixtures/buddyinfo/short").NewBuddyInfo() - if err == nil { - t.Errorf("expected error, but none occurred") - } - - if want, got := "invalid number of fields when parsing buddyinfo", err.Error(); want != got { - t.Errorf("wrong error returned, wanted %q, got %q", want, got) - } -} - -func TestBuddyInfoSizeMismatch(t *testing.T) { - _, err := FS("fixtures/buddyinfo/sizemismatch").NewBuddyInfo() - if err == nil { - t.Errorf("expected error, but none occurred") - } - - if want, got := "mismatch in number of buddyinfo buckets", err.Error(); !strings.HasPrefix(got, want) { - t.Errorf("wrong error returned, wanted prefix %q, got %q", want, got) - } -} diff --git a/vendor/github.com/prometheus/procfs/fixtures.ttar b/vendor/github.com/prometheus/procfs/fixtures.ttar new file mode 100644 index 000000000..3ee8291e8 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/fixtures.ttar @@ -0,0 +1,446 @@ +# Archive created by ttar -c -f fixtures.ttar fixtures/ +Directory: fixtures +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/cmdline +Lines: 1 +vimNULLBYTEtest.goNULLBYTE+10NULLBYTEEOF +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/comm +Lines: 1 +vim +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/exe +SymlinkTo: /usr/bin/vim +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/fd +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/0 +SymlinkTo: ../../symlinktargets/abc +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/1 +SymlinkTo: ../../symlinktargets/def +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/10 +SymlinkTo: ../../symlinktargets/xyz +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/2 +SymlinkTo: ../../symlinktargets/ghi +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/3 +SymlinkTo: ../../symlinktargets/uvw +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/io +Lines: 7 +rchar: 750339 +wchar: 818609 +syscr: 7405 +syscw: 5245 +read_bytes: 1024 +write_bytes: 2048 +cancelled_write_bytes: -1024 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/limits +Lines: 17 +Limit Soft Limit Hard Limit Units +Max cpu time unlimited unlimited seconds +Max file size unlimited unlimited bytes +Max data size unlimited unlimited bytes +Max stack size 8388608 unlimited bytes +Max core file size 0 unlimited bytes +Max resident set unlimited unlimited bytes +Max processes 62898 62898 processes +Max open files 2048 4096 files +Max locked memory 65536 65536 bytes +Max address space 8589934592 unlimited bytes +Max file locks unlimited unlimited locks +Max pending signals 62898 62898 signals +Max msgqueue size 819200 819200 bytes +Max nice priority 0 0 +Max realtime priority 0 0 +Max realtime timeout unlimited unlimited us +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/mountstats +Lines: 19 +device rootfs mounted on / with fstype rootfs +device sysfs mounted on /sys with fstype sysfs +device proc mounted on /proc with fstype proc +device /dev/sda1 mounted on / with fstype ext4 +device 192.168.1.1:/srv/test mounted on /mnt/nfs/test with fstype nfs4 statvers=1.1 + opts: rw,vers=4.0,rsize=1048576,wsize=1048576,namlen=255,acregmin=3,acregmax=60,acdirmin=30,acdirmax=60,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none + age: 13968 + caps: caps=0xfff7,wtmult=512,dtsize=32768,bsize=0,namlen=255 + nfsv4: bm0=0xfdffafff,bm1=0xf9be3e,bm2=0x0,acl=0x0,pnfs=not configured + sec: flavor=1,pseudoflavor=1 + events: 52 226 0 0 1 13 398 0 0 331 0 47 0 0 77 0 0 77 0 0 0 0 0 0 0 0 0 + bytes: 1207640230 0 0 0 1210214218 0 295483 0 + RPC iostats version: 1.0 p/v: 100003/4 (nfs) + xprt: tcp 832 0 1 0 11 6428 6428 0 12154 0 24 26 5726 + per-op statistics + NULL: 0 0 0 0 0 0 0 0 + READ: 1298 1298 0 207680 1210292152 6 79386 79407 + WRITE: 0 0 0 0 0 0 0 0 + +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/net +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/net/dev +Lines: 4 +Inter-| Receive | Transmit + face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed + lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + eth0: 438 5 0 0 0 0 0 0 648 8 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/ns +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/ns/mnt +SymlinkTo: mnt:[4026531840] +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/ns/net +SymlinkTo: net:[4026531993] +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/stat +Lines: 1 +26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26232 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/cmdline +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/comm +Lines: 1 +ata_sff +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26232/fd +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/0 +SymlinkTo: ../../symlinktargets/abc +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/1 +SymlinkTo: ../../symlinktargets/def +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/2 +SymlinkTo: ../../symlinktargets/ghi +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/3 +SymlinkTo: ../../symlinktargets/uvw +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/4 +SymlinkTo: ../../symlinktargets/xyz +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/limits +Lines: 17 +Limit Soft Limit Hard Limit Units +Max cpu time unlimited unlimited seconds +Max file size unlimited unlimited bytes +Max data size unlimited unlimited bytes +Max stack size 8388608 unlimited bytes +Max core file size 0 unlimited bytes +Max resident set unlimited unlimited bytes +Max processes 29436 29436 processes +Max open files 1024 4096 files +Max locked memory 65536 65536 bytes +Max address space unlimited unlimited bytes +Max file locks unlimited unlimited locks +Max pending signals 29436 29436 signals +Max msgqueue size 819200 819200 bytes +Max nice priority 0 0 +Max realtime priority 0 0 +Max realtime timeout unlimited unlimited us +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/stat +Lines: 1 +33 (ata_sff) S 2 0 0 0 -1 69238880 0 0 0 0 0 0 0 0 0 -20 1 0 5 0 0 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 18446744073709551615 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26233 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26233/cmdline +Lines: 1 +com.github.uiautomatorNULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTEEOF +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/584 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/584/stat +Lines: 2 +1020 ((a b ) ( c d) ) R 28378 1020 28378 34842 1020 4218880 286 0 0 0 0 0 0 0 20 0 1 0 10839175 10395648 155 18446744073709551615 4194304 4238788 140736466511168 140736466511168 140609271124624 0 0 0 0 0 0 0 17 5 0 0 0 0 0 6336016 6337300 25579520 140736466515030 140736466515061 140736466515061 140736466518002 0 +#!/bin/cat /proc/self/stat +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/short +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/short/buddyinfo +Lines: 3 +Node 0, zone +Node 0, zone +Node 0, zone +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/sizemismatch +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/sizemismatch/buddyinfo +Lines: 3 +Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 +Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 0 +Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/valid +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/valid/buddyinfo +Lines: 3 +Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 +Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 +Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/fs +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/fs/xfs +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/fs/xfs/stat +Lines: 23 +extent_alloc 92447 97589 92448 93751 +abt 0 0 0 0 +blk_map 1767055 188820 184891 92447 92448 2140766 0 +bmbt 0 0 0 0 +dir 185039 92447 92444 136422 +trans 706 944304 0 +ig 185045 58807 0 126238 0 33637 22 +log 2883 113448 9 17360 739 +push_ail 945014 0 134260 15483 0 3940 464 159985 0 40 +xstrat 92447 0 +rw 107739 94045 +attr 4 0 0 0 +icluster 8677 7849 135802 +vnodes 92601 0 0 0 92444 92444 92444 0 +buf 2666287 7122 2659202 3599 2 7085 0 10297 7085 +abtb2 184941 1277345 13257 13278 0 0 0 0 0 0 0 0 0 0 2746147 +abtc2 345295 2416764 172637 172658 0 0 0 0 0 0 0 0 0 0 21406023 +bmbt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +ibt2 343004 1358467 0 0 0 0 0 0 0 0 0 0 0 0 0 +fibt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +qm 0 0 0 0 0 0 0 0 +xpc 399724544 92823103 86219234 +debug 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/mdstat +Lines: 26 +Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] +md3 : active raid6 sda1[8] sdh1[7] sdg1[6] sdf1[5] sde1[11] sdd1[3] sdc1[10] sdb1[9] + 5853468288 blocks super 1.2 level 6, 64k chunk, algorithm 2 [8/8] [UUUUUUUU] + +md127 : active raid1 sdi2[0] sdj2[1] + 312319552 blocks [2/2] [UU] + +md0 : active raid1 sdk[2](S) sdi1[0] sdj1[1] + 248896 blocks [2/2] [UU] + +md4 : inactive raid1 sda3[0] sdb3[1] + 4883648 blocks [2/2] [UU] + +md6 : active raid1 sdb2[2] sda2[0] + 195310144 blocks [2/1] [U_] + [=>...................] recovery = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec + +md8 : active raid1 sdb1[1] sda1[0] + 195310144 blocks [2/2] [UU] + [=>...................] resync = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec + +md7 : active raid6 sdb1[0] sde1[3] sdd1[2] sdc1[1] + 7813735424 blocks super 1.2 level 6, 512k chunk, algorithm 2 [4/3] [U_UU] + bitmap: 0/30 pages [0KB], 65536KB chunk + +unused devices: +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/net +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/dev +Lines: 6 +Inter-| Receive | Transmit + face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed +vethf345468: 648 8 0 0 0 0 0 0 438 5 0 0 0 0 0 0 + lo: 1664039048 1566805 0 0 0 0 0 0 1664039048 1566805 0 0 0 0 0 0 +docker0: 2568 38 0 0 0 0 0 0 438 5 0 0 0 0 0 0 + eth0: 874354587 1036395 0 0 0 0 0 0 563352563 732147 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/ip_vs +Lines: 21 +IP Virtual Server version 1.2.1 (size=4096) +Prot LocalAddress:Port Scheduler Flags + -> RemoteAddress:Port Forward Weight ActiveConn InActConn +TCP C0A80016:0CEA wlc + -> C0A85216:0CEA Tunnel 100 248 2 + -> C0A85318:0CEA Tunnel 100 248 2 + -> C0A85315:0CEA Tunnel 100 248 1 +TCP C0A80039:0CEA wlc + -> C0A85416:0CEA Tunnel 0 0 0 + -> C0A85215:0CEA Tunnel 100 1499 0 + -> C0A83215:0CEA Tunnel 100 1498 0 +TCP C0A80037:0CEA wlc + -> C0A8321A:0CEA Tunnel 0 0 0 + -> C0A83120:0CEA Tunnel 100 0 0 +TCP [2620:0000:0000:0000:0000:0000:0000:0001]:0050 sh + -> [2620:0000:0000:0000:0000:0000:0000:0002]:0050 Route 1 0 0 + -> [2620:0000:0000:0000:0000:0000:0000:0003]:0050 Route 1 0 0 + -> [2620:0000:0000:0000:0000:0000:0000:0004]:0050 Route 1 1 1 +FWM 10001000 wlc + -> C0A8321A:0CEA Route 0 0 1 + -> C0A83215:0CEA Route 0 0 2 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/ip_vs_stats +Lines: 6 + Total Incoming Outgoing Incoming Outgoing + Conns Packets Packets Bytes Bytes + 16AA370 E33656E5 0 51D8C8883AB3 0 + + Conns/s Pkts/s Pkts/s Bytes/s Bytes/s + 4 1FB3C 0 1282A8F 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/net/rpc +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/rpc/nfs +Lines: 5 +net 18628 0 18628 6 +rpc 4329785 0 4338291 +proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 +proc3 22 1 4084749 29200 94754 32580 186 47747 7981 8639 0 6356 0 6962 0 7958 0 0 241 4 4 2 39 +proc4 61 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/rpc/nfsd +Lines: 11 +rc 0 6 18622 +fh 0 0 0 0 0 +io 157286400 0 +th 8 0 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 +ra 32 0 0 0 0 0 0 0 0 0 0 0 +net 18628 0 18628 6 +rpc 18628 0 0 0 0 +proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 +proc3 22 2 112 0 2719 111 0 0 0 0 0 0 0 0 0 0 0 27 216 0 2 1 0 +proc4 2 2 10853 +proc4ops 72 0 0 0 1098 2 0 0 0 0 8179 5896 0 0 0 0 5900 0 0 2 0 2 0 9609 0 2 150 1272 0 0 0 1236 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/xfrm_stat +Lines: 28 +XfrmInError 1 +XfrmInBufferError 2 +XfrmInHdrError 4 +XfrmInNoStates 3 +XfrmInStateProtoError 40 +XfrmInStateModeError 100 +XfrmInStateSeqError 6000 +XfrmInStateExpired 4 +XfrmInStateMismatch 23451 +XfrmInStateInvalid 55555 +XfrmInTmplMismatch 51 +XfrmInNoPols 65432 +XfrmInPolBlock 100 +XfrmInPolError 10000 +XfrmOutError 1000000 +XfrmOutBundleGenError 43321 +XfrmOutBundleCheckError 555 +XfrmOutNoStates 869 +XfrmOutStateProtoError 4542 +XfrmOutStateModeError 4 +XfrmOutStateSeqError 543 +XfrmOutStateExpired 565 +XfrmOutPolBlock 43456 +XfrmOutPolDead 7656 +XfrmOutPolError 1454 +XfrmFwdHdrError 6654 +XfrmOutStateInvalid 28765 +XfrmAcquireError 24532 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/self +SymlinkTo: 26231 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/stat +Lines: 16 +cpu 301854 612 111922 8979004 3552 2 3944 0 0 0 +cpu0 44490 19 21045 1087069 220 1 3410 0 0 0 +cpu1 47869 23 16474 1110787 591 0 46 0 0 0 +cpu2 46504 36 15916 1112321 441 0 326 0 0 0 +cpu3 47054 102 15683 1113230 533 0 60 0 0 0 +cpu4 28413 25 10776 1140321 217 0 8 0 0 0 +cpu5 29271 101 11586 1136270 672 0 30 0 0 0 +cpu6 29152 36 10276 1139721 319 0 29 0 0 0 +cpu7 29098 268 10164 1139282 555 0 31 0 0 0 +intr 8885917 17 0 0 0 0 0 0 0 1 79281 0 0 0 0 0 0 0 231237 0 0 0 0 250586 103 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 223424 190745 13 906 1283803 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +ctxt 38014093 +btime 1418183276 +processes 26442 +procs_running 2 +procs_blocked 1 +softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/symlinktargets +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/README +Lines: 2 +This directory contains some empty files that are the symlinks the files in the "fd" directory point to. +They are otherwise ignored by the tests +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/abc +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/def +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/ghi +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/uvw +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/xyz +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/cmdline b/vendor/github.com/prometheus/procfs/fixtures/26231/cmdline deleted file mode 100644 index d2d8ef887..000000000 Binary files a/vendor/github.com/prometheus/procfs/fixtures/26231/cmdline and /dev/null differ diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/comm b/vendor/github.com/prometheus/procfs/fixtures/26231/comm deleted file mode 100644 index f027e0d4b..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/comm +++ /dev/null @@ -1 +0,0 @@ -vim diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/exe b/vendor/github.com/prometheus/procfs/fixtures/26231/exe deleted file mode 120000 index a91bec4da..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/exe +++ /dev/null @@ -1 +0,0 @@ -/usr/bin/vim \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 b/vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 deleted file mode 120000 index da9c5dff3..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/abc \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 b/vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 deleted file mode 120000 index ca47b50ca..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/def \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/10 b/vendor/github.com/prometheus/procfs/fixtures/26231/fd/10 deleted file mode 120000 index c08683168..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/10 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/xyz \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 b/vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 deleted file mode 120000 index 66731c068..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/ghi \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 b/vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 deleted file mode 120000 index 0135dce35..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/uvw \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/io b/vendor/github.com/prometheus/procfs/fixtures/26231/io deleted file mode 100644 index b6210a7a7..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/io +++ /dev/null @@ -1,7 +0,0 @@ -rchar: 750339 -wchar: 818609 -syscr: 7405 -syscw: 5245 -read_bytes: 1024 -write_bytes: 2048 -cancelled_write_bytes: -1024 diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/limits b/vendor/github.com/prometheus/procfs/fixtures/26231/limits deleted file mode 100644 index 8b40108aa..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/limits +++ /dev/null @@ -1,17 +0,0 @@ -Limit Soft Limit Hard Limit Units -Max cpu time unlimited unlimited seconds -Max file size unlimited unlimited bytes -Max data size unlimited unlimited bytes -Max stack size 8388608 unlimited bytes -Max core file size 0 unlimited bytes -Max resident set unlimited unlimited bytes -Max processes 62898 62898 processes -Max open files 2048 4096 files -Max locked memory 65536 65536 bytes -Max address space 8589934592 unlimited bytes -Max file locks unlimited unlimited locks -Max pending signals 62898 62898 signals -Max msgqueue size 819200 819200 bytes -Max nice priority 0 0 -Max realtime priority 0 0 -Max realtime timeout unlimited unlimited us diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/mountstats b/vendor/github.com/prometheus/procfs/fixtures/26231/mountstats deleted file mode 100644 index a665c33da..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/mountstats +++ /dev/null @@ -1,19 +0,0 @@ -device rootfs mounted on / with fstype rootfs -device sysfs mounted on /sys with fstype sysfs -device proc mounted on /proc with fstype proc -device /dev/sda1 mounted on / with fstype ext4 -device 192.168.1.1:/srv/test mounted on /mnt/nfs/test with fstype nfs4 statvers=1.1 - opts: rw,vers=4.0,rsize=1048576,wsize=1048576,namlen=255,acregmin=3,acregmax=60,acdirmin=30,acdirmax=60,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none - age: 13968 - caps: caps=0xfff7,wtmult=512,dtsize=32768,bsize=0,namlen=255 - nfsv4: bm0=0xfdffafff,bm1=0xf9be3e,bm2=0x0,acl=0x0,pnfs=not configured - sec: flavor=1,pseudoflavor=1 - events: 52 226 0 0 1 13 398 0 0 331 0 47 0 0 77 0 0 77 0 0 0 0 0 0 0 0 0 - bytes: 1207640230 0 0 0 1210214218 0 295483 0 - RPC iostats version: 1.0 p/v: 100003/4 (nfs) - xprt: tcp 832 0 1 0 11 6428 6428 0 12154 0 24 26 5726 - per-op statistics - NULL: 0 0 0 0 0 0 0 0 - READ: 1298 1298 0 207680 1210292152 6 79386 79407 - WRITE: 0 0 0 0 0 0 0 0 - diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/net/dev b/vendor/github.com/prometheus/procfs/fixtures/26231/net/dev deleted file mode 100644 index f10895560..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/net/dev +++ /dev/null @@ -1,4 +0,0 @@ -Inter-| Receive | Transmit - face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed - lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 - eth0: 438 5 0 0 0 0 0 0 648 8 0 0 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/ns/mnt b/vendor/github.com/prometheus/procfs/fixtures/26231/ns/mnt deleted file mode 120000 index 9c52ca211..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/ns/mnt +++ /dev/null @@ -1 +0,0 @@ -mnt:[4026531840] \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/ns/net b/vendor/github.com/prometheus/procfs/fixtures/26231/ns/net deleted file mode 120000 index 1f0f79594..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/ns/net +++ /dev/null @@ -1 +0,0 @@ -net:[4026531993] \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26231/stat b/vendor/github.com/prometheus/procfs/fixtures/26231/stat deleted file mode 100644 index 438aaa9dc..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26231/stat +++ /dev/null @@ -1 +0,0 @@ -26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/cmdline b/vendor/github.com/prometheus/procfs/fixtures/26232/cmdline deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/comm b/vendor/github.com/prometheus/procfs/fixtures/26232/comm deleted file mode 100644 index 62361ca78..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/comm +++ /dev/null @@ -1 +0,0 @@ -ata_sff diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/0 b/vendor/github.com/prometheus/procfs/fixtures/26232/fd/0 deleted file mode 120000 index da9c5dff3..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/0 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/abc \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/1 b/vendor/github.com/prometheus/procfs/fixtures/26232/fd/1 deleted file mode 120000 index ca47b50ca..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/1 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/def \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/2 b/vendor/github.com/prometheus/procfs/fixtures/26232/fd/2 deleted file mode 120000 index 66731c068..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/2 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/ghi \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/3 b/vendor/github.com/prometheus/procfs/fixtures/26232/fd/3 deleted file mode 120000 index 0135dce35..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/3 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/uvw \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/4 b/vendor/github.com/prometheus/procfs/fixtures/26232/fd/4 deleted file mode 120000 index c08683168..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/fd/4 +++ /dev/null @@ -1 +0,0 @@ -../../symlinktargets/xyz \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/limits b/vendor/github.com/prometheus/procfs/fixtures/26232/limits deleted file mode 100644 index 3f9bf16a9..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/limits +++ /dev/null @@ -1,17 +0,0 @@ -Limit Soft Limit Hard Limit Units -Max cpu time unlimited unlimited seconds -Max file size unlimited unlimited bytes -Max data size unlimited unlimited bytes -Max stack size 8388608 unlimited bytes -Max core file size 0 unlimited bytes -Max resident set unlimited unlimited bytes -Max processes 29436 29436 processes -Max open files 1024 4096 files -Max locked memory 65536 65536 bytes -Max address space unlimited unlimited bytes -Max file locks unlimited unlimited locks -Max pending signals 29436 29436 signals -Max msgqueue size 819200 819200 bytes -Max nice priority 0 0 -Max realtime priority 0 0 -Max realtime timeout unlimited unlimited us diff --git a/vendor/github.com/prometheus/procfs/fixtures/26232/stat b/vendor/github.com/prometheus/procfs/fixtures/26232/stat deleted file mode 100644 index 321b16073..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/26232/stat +++ /dev/null @@ -1 +0,0 @@ -33 (ata_sff) S 2 0 0 0 -1 69238880 0 0 0 0 0 0 0 0 0 -20 1 0 5 0 0 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 18446744073709551615 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/584/stat b/vendor/github.com/prometheus/procfs/fixtures/584/stat deleted file mode 100644 index 65b9369d1..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/584/stat +++ /dev/null @@ -1,2 +0,0 @@ -1020 ((a b ) ( c d) ) R 28378 1020 28378 34842 1020 4218880 286 0 0 0 0 0 0 0 20 0 1 0 10839175 10395648 155 18446744073709551615 4194304 4238788 140736466511168 140736466511168 140609271124624 0 0 0 0 0 0 0 17 5 0 0 0 0 0 6336016 6337300 25579520 140736466515030 140736466515061 140736466515061 140736466518002 0 -#!/bin/cat /proc/self/stat diff --git a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/short/buddyinfo b/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/short/buddyinfo deleted file mode 100644 index 40e71ca35..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/short/buddyinfo +++ /dev/null @@ -1,3 +0,0 @@ -Node 0, zone -Node 0, zone -Node 0, zone diff --git a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/sizemismatch/buddyinfo b/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/sizemismatch/buddyinfo deleted file mode 100644 index 945636182..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/sizemismatch/buddyinfo +++ /dev/null @@ -1,3 +0,0 @@ -Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 -Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 0 -Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/valid/buddyinfo b/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/valid/buddyinfo deleted file mode 100644 index f90594a81..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/buddyinfo/valid/buddyinfo +++ /dev/null @@ -1,3 +0,0 @@ -Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 -Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 -Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/fs/xfs/stat b/vendor/github.com/prometheus/procfs/fixtures/fs/xfs/stat deleted file mode 100644 index f7ca7f940..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/fs/xfs/stat +++ /dev/null @@ -1,23 +0,0 @@ -extent_alloc 92447 97589 92448 93751 -abt 0 0 0 0 -blk_map 1767055 188820 184891 92447 92448 2140766 0 -bmbt 0 0 0 0 -dir 185039 92447 92444 136422 -trans 706 944304 0 -ig 185045 58807 0 126238 0 33637 22 -log 2883 113448 9 17360 739 -push_ail 945014 0 134260 15483 0 3940 464 159985 0 40 -xstrat 92447 0 -rw 107739 94045 -attr 4 0 0 0 -icluster 8677 7849 135802 -vnodes 92601 0 0 0 92444 92444 92444 0 -buf 2666287 7122 2659202 3599 2 7085 0 10297 7085 -abtb2 184941 1277345 13257 13278 0 0 0 0 0 0 0 0 0 0 2746147 -abtc2 345295 2416764 172637 172658 0 0 0 0 0 0 0 0 0 0 21406023 -bmbt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ibt2 343004 1358467 0 0 0 0 0 0 0 0 0 0 0 0 0 -fibt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -qm 0 0 0 0 0 0 0 0 -xpc 399724544 92823103 86219234 -debug 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/mdstat b/vendor/github.com/prometheus/procfs/fixtures/mdstat deleted file mode 100644 index 4430bdee2..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/mdstat +++ /dev/null @@ -1,26 +0,0 @@ -Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] -md3 : active raid6 sda1[8] sdh1[7] sdg1[6] sdf1[5] sde1[11] sdd1[3] sdc1[10] sdb1[9] - 5853468288 blocks super 1.2 level 6, 64k chunk, algorithm 2 [8/8] [UUUUUUUU] - -md127 : active raid1 sdi2[0] sdj2[1] - 312319552 blocks [2/2] [UU] - -md0 : active raid1 sdk[2](S) sdi1[0] sdj1[1] - 248896 blocks [2/2] [UU] - -md4 : inactive raid1 sda3[0] sdb3[1] - 4883648 blocks [2/2] [UU] - -md6 : active raid1 sdb2[2] sda2[0] - 195310144 blocks [2/1] [U_] - [=>...................] recovery = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec - -md8 : active raid1 sdb1[1] sda1[0] - 195310144 blocks [2/2] [UU] - [=>...................] resync = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec - -md7 : active raid6 sdb1[0] sde1[3] sdd1[2] sdc1[1] - 7813735424 blocks super 1.2 level 6, 512k chunk, algorithm 2 [4/3] [U_UU] - bitmap: 0/30 pages [0KB], 65536KB chunk - -unused devices: diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/dev b/vendor/github.com/prometheus/procfs/fixtures/net/dev deleted file mode 100644 index 2df786fa5..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/dev +++ /dev/null @@ -1,6 +0,0 @@ -Inter-| Receive | Transmit - face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed -vethf345468: 648 8 0 0 0 0 0 0 438 5 0 0 0 0 0 0 - lo: 1664039048 1566805 0 0 0 0 0 0 1664039048 1566805 0 0 0 0 0 0 -docker0: 2568 38 0 0 0 0 0 0 438 5 0 0 0 0 0 0 - eth0: 874354587 1036395 0 0 0 0 0 0 563352563 732147 0 0 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs b/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs deleted file mode 100644 index 5ee4bd2be..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs +++ /dev/null @@ -1,21 +0,0 @@ -IP Virtual Server version 1.2.1 (size=4096) -Prot LocalAddress:Port Scheduler Flags - -> RemoteAddress:Port Forward Weight ActiveConn InActConn -TCP C0A80016:0CEA wlc - -> C0A85216:0CEA Tunnel 100 248 2 - -> C0A85318:0CEA Tunnel 100 248 2 - -> C0A85315:0CEA Tunnel 100 248 1 -TCP C0A80039:0CEA wlc - -> C0A85416:0CEA Tunnel 0 0 0 - -> C0A85215:0CEA Tunnel 100 1499 0 - -> C0A83215:0CEA Tunnel 100 1498 0 -TCP C0A80037:0CEA wlc - -> C0A8321A:0CEA Tunnel 0 0 0 - -> C0A83120:0CEA Tunnel 100 0 0 -TCP [2620:0000:0000:0000:0000:0000:0000:0001]:0050 sh - -> [2620:0000:0000:0000:0000:0000:0000:0002]:0050 Route 1 0 0 - -> [2620:0000:0000:0000:0000:0000:0000:0003]:0050 Route 1 0 0 - -> [2620:0000:0000:0000:0000:0000:0000:0004]:0050 Route 1 1 1 -FWM 10001000 wlc - -> C0A8321A:0CEA Route 0 0 1 - -> C0A83215:0CEA Route 0 0 2 diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs_stats b/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs_stats deleted file mode 100644 index c00724e0f..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/ip_vs_stats +++ /dev/null @@ -1,6 +0,0 @@ - Total Incoming Outgoing Incoming Outgoing - Conns Packets Packets Bytes Bytes - 16AA370 E33656E5 0 51D8C8883AB3 0 - - Conns/s Pkts/s Pkts/s Bytes/s Bytes/s - 4 1FB3C 0 1282A8F 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfs b/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfs deleted file mode 100644 index 2e58e0544..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfs +++ /dev/null @@ -1,5 +0,0 @@ -net 18628 0 18628 6 -rpc 4329785 0 4338291 -proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 -proc3 22 1 4084749 29200 94754 32580 186 47747 7981 8639 0 6356 0 6962 0 7958 0 0 241 4 4 2 39 -proc4 61 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfsd b/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfsd deleted file mode 100644 index 4e8565f41..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/rpc/nfsd +++ /dev/null @@ -1,11 +0,0 @@ -rc 0 6 18622 -fh 0 0 0 0 0 -io 157286400 0 -th 8 0 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -ra 32 0 0 0 0 0 0 0 0 0 0 0 -net 18628 0 18628 6 -rpc 18628 0 0 0 0 -proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 -proc3 22 2 112 0 2719 111 0 0 0 0 0 0 0 0 0 0 0 27 216 0 2 1 0 -proc4 2 2 10853 -proc4ops 72 0 0 0 1098 2 0 0 0 0 8179 5896 0 0 0 0 5900 0 0 2 0 2 0 9609 0 2 150 1272 0 0 0 1236 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat b/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat deleted file mode 100644 index d278ace95..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/net/xfrm_stat +++ /dev/null @@ -1,28 +0,0 @@ -XfrmInError 1 -XfrmInBufferError 2 -XfrmInHdrError 4 -XfrmInNoStates 3 -XfrmInStateProtoError 40 -XfrmInStateModeError 100 -XfrmInStateSeqError 6000 -XfrmInStateExpired 4 -XfrmInStateMismatch 23451 -XfrmInStateInvalid 55555 -XfrmInTmplMismatch 51 -XfrmInNoPols 65432 -XfrmInPolBlock 100 -XfrmInPolError 10000 -XfrmOutError 1000000 -XfrmOutBundleGenError 43321 -XfrmOutBundleCheckError 555 -XfrmOutNoStates 869 -XfrmOutStateProtoError 4542 -XfrmOutStateModeError 4 -XfrmOutStateSeqError 543 -XfrmOutStateExpired 565 -XfrmOutPolBlock 43456 -XfrmOutPolDead 7656 -XfrmOutPolError 1454 -XfrmFwdHdrError 6654 -XfrmOutStateInvalid 28765 -XfrmAcquireError 24532 diff --git a/vendor/github.com/prometheus/procfs/fixtures/self b/vendor/github.com/prometheus/procfs/fixtures/self deleted file mode 120000 index 1eeedea3d..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/self +++ /dev/null @@ -1 +0,0 @@ -26231 \ No newline at end of file diff --git a/vendor/github.com/prometheus/procfs/fixtures/stat b/vendor/github.com/prometheus/procfs/fixtures/stat deleted file mode 100644 index 1582a8cb5..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/stat +++ /dev/null @@ -1,16 +0,0 @@ -cpu 301854 612 111922 8979004 3552 2 3944 0 0 0 -cpu0 44490 19 21045 1087069 220 1 3410 0 0 0 -cpu1 47869 23 16474 1110787 591 0 46 0 0 0 -cpu2 46504 36 15916 1112321 441 0 326 0 0 0 -cpu3 47054 102 15683 1113230 533 0 60 0 0 0 -cpu4 28413 25 10776 1140321 217 0 8 0 0 0 -cpu5 29271 101 11586 1136270 672 0 30 0 0 0 -cpu6 29152 36 10276 1139721 319 0 29 0 0 0 -cpu7 29098 268 10164 1139282 555 0 31 0 0 0 -intr 8885917 17 0 0 0 0 0 0 0 1 79281 0 0 0 0 0 0 0 231237 0 0 0 0 250586 103 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 223424 190745 13 906 1283803 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 38014093 -btime 1418183276 -processes 26442 -procs_running 2 -procs_blocked 1 -softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444 diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/README b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/README deleted file mode 100644 index 5cf184ea0..000000000 --- a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains some empty files that are the symlinks the files in the "fd" directory point to. -They are otherwise ignored by the tests diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/abc b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/abc deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/def b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/def deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/ghi b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/ghi deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/uvw b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/uvw deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/xyz b/vendor/github.com/prometheus/procfs/fixtures/symlinktargets/xyz deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go index 65f09223f..b6c6b2ce1 100644 --- a/vendor/github.com/prometheus/procfs/fs.go +++ b/vendor/github.com/prometheus/procfs/fs.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/fs_test.go b/vendor/github.com/prometheus/procfs/fs_test.go deleted file mode 100644 index e492cde55..000000000 --- a/vendor/github.com/prometheus/procfs/fs_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package procfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("procfs.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} - -func TestFSXFSStats(t *testing.T) { - stats, err := FS("fixtures").XFSStats() - if err != nil { - t.Fatalf("failed to parse XFS stats: %v", err) - } - - // Very lightweight test just to sanity check the path used - // to open XFS stats. Heavier tests in package xfs. - if want, got := uint32(92447), stats.ExtentAllocation.ExtentsAllocated; want != got { - t.Errorf("unexpected extents allocated:\nwant: %d\nhave: %d", want, got) - } -} diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index 5761b4570..e36d4a3bd 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/ipvs_test.go b/vendor/github.com/prometheus/procfs/ipvs_test.go deleted file mode 100644 index 13ceab80e..000000000 --- a/vendor/github.com/prometheus/procfs/ipvs_test.go +++ /dev/null @@ -1,237 +0,0 @@ -package procfs - -import ( - "net" - "testing" -) - -var ( - expectedIPVSStats = IPVSStats{ - Connections: 23765872, - IncomingPackets: 3811989221, - OutgoingPackets: 0, - IncomingBytes: 89991519156915, - OutgoingBytes: 0, - } - expectedIPVSBackendStatuses = []IPVSBackendStatus{ - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.24"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 1, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.84.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1499, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1498, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.26"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.49.32"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::2"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::3"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::4"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 1, - InactConn: 1, - }, - { - LocalMark: "10001000", - RemoteAddress: net.ParseIP("192.168.50.26"), - RemotePort: 3306, - Proto: "FWM", - Weight: 0, - ActiveConn: 0, - InactConn: 1, - }, - { - LocalMark: "10001000", - RemoteAddress: net.ParseIP("192.168.50.21"), - RemotePort: 3306, - Proto: "FWM", - Weight: 0, - ActiveConn: 0, - InactConn: 2, - }, - } -) - -func TestIPVSStats(t *testing.T) { - stats, err := FS("fixtures").NewIPVSStats() - if err != nil { - t.Fatal(err) - } - - if stats != expectedIPVSStats { - t.Errorf("want %+v, have %+v", expectedIPVSStats, stats) - } -} - -func TestParseIPPort(t *testing.T) { - ip := net.ParseIP("192.168.0.22") - port := uint16(3306) - - gotIP, gotPort, err := parseIPPort("C0A80016:0CEA") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, have %s:%d", ip, port, gotIP, gotPort) - } -} - -func TestParseIPPortInvalid(t *testing.T) { - testcases := []string{ - "", - "C0A80016", - "C0A800:1234", - "FOOBARBA:1234", - "C0A80016:0CEA:1234", - } - - for _, s := range testcases { - ip, port, err := parseIPPort(s) - if ip != nil || port != uint16(0) || err == nil { - t.Errorf("Expected error for input %s, have ip = %s, port = %v, err = %v", s, ip, port, err) - } - } -} - -func TestParseIPPortIPv6(t *testing.T) { - ip := net.ParseIP("dead:beef::1") - port := uint16(8080) - - gotIP, gotPort, err := parseIPPort("[DEAD:BEEF:0000:0000:0000:0000:0000:0001]:1F90") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, have %s:%d", ip, port, gotIP, gotPort) - } -} - -func TestIPVSBackendStatus(t *testing.T) { - backendStats, err := FS("fixtures").NewIPVSBackendStatus() - if err != nil { - t.Fatal(err) - } - if want, have := len(expectedIPVSBackendStatuses), len(backendStats); want != have { - t.Fatalf("want %d backend statuses, have %d", want, have) - } - - for idx, expect := range expectedIPVSBackendStatuses { - if !backendStats[idx].LocalAddress.Equal(expect.LocalAddress) { - t.Errorf("want LocalAddress %s, have %s", expect.LocalAddress, backendStats[idx].LocalAddress) - } - if backendStats[idx].LocalPort != expect.LocalPort { - t.Errorf("want LocalPort %d, have %d", expect.LocalPort, backendStats[idx].LocalPort) - } - if !backendStats[idx].RemoteAddress.Equal(expect.RemoteAddress) { - t.Errorf("want RemoteAddress %s, have %s", expect.RemoteAddress, backendStats[idx].RemoteAddress) - } - if backendStats[idx].RemotePort != expect.RemotePort { - t.Errorf("want RemotePort %d, have %d", expect.RemotePort, backendStats[idx].RemotePort) - } - if backendStats[idx].Proto != expect.Proto { - t.Errorf("want Proto %s, have %s", expect.Proto, backendStats[idx].Proto) - } - if backendStats[idx].Weight != expect.Weight { - t.Errorf("want Weight %d, have %d", expect.Weight, backendStats[idx].Weight) - } - if backendStats[idx].ActiveConn != expect.ActiveConn { - t.Errorf("want ActiveConn %d, have %d", expect.ActiveConn, backendStats[idx].ActiveConn) - } - if backendStats[idx].InactConn != expect.InactConn { - t.Errorf("want InactConn %d, have %d", expect.InactConn, backendStats[idx].InactConn) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go index d7a248c0d..9dc19583d 100644 --- a/vendor/github.com/prometheus/procfs/mdstat.go +++ b/vendor/github.com/prometheus/procfs/mdstat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/mdstat_test.go b/vendor/github.com/prometheus/procfs/mdstat_test.go deleted file mode 100644 index fa463c2fb..000000000 --- a/vendor/github.com/prometheus/procfs/mdstat_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package procfs - -import ( - "testing" -) - -func TestMDStat(t *testing.T) { - mdStates, err := FS("fixtures").ParseMDStat() - if err != nil { - t.Fatalf("parsing of reference-file failed entirely: %s", err) - } - - refs := map[string]MDStat{ - "md3": {"md3", "active", 8, 8, 5853468288, 5853468288}, - "md127": {"md127", "active", 2, 2, 312319552, 312319552}, - "md0": {"md0", "active", 2, 2, 248896, 248896}, - "md4": {"md4", "inactive", 2, 2, 4883648, 4883648}, - "md6": {"md6", "active", 1, 2, 195310144, 16775552}, - "md8": {"md8", "active", 2, 2, 195310144, 16775552}, - "md7": {"md7", "active", 3, 4, 7813735424, 7813735424}, - } - - if want, have := len(refs), len(mdStates); want != have { - t.Errorf("want %d parsed md-devices, have %d", want, have) - } - for _, md := range mdStates { - if want, have := refs[md.Name], md; want != have { - t.Errorf("%s: want %v, have %v", md.Name, want, have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index 6b2b0ba9d..e95ddbc67 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs // While implementing parsing of /proc/[pid]/mountstats, this blog was used diff --git a/vendor/github.com/prometheus/procfs/mountstats_test.go b/vendor/github.com/prometheus/procfs/mountstats_test.go deleted file mode 100644 index 8f04f5355..000000000 --- a/vendor/github.com/prometheus/procfs/mountstats_test.go +++ /dev/null @@ -1,273 +0,0 @@ -package procfs - -import ( - "fmt" - "reflect" - "strings" - "testing" - "time" -) - -func TestMountStats(t *testing.T) { - tests := []struct { - name string - s string - mounts []*Mount - invalid bool - }{ - { - name: "no devices", - s: `hello`, - }, - { - name: "device has too few fields", - s: `device foo`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs BAD on / with fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted BAD / with fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted on / BAD fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted on / with BAD rootfs`, - invalid: true, - }, - { - name: "device rootfs cannot have stats", - s: `device rootfs mounted on / with fstype rootfs stats`, - invalid: true, - }, - { - name: "NFSv4 device with too little info", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nhello", - invalid: true, - }, - { - name: "NFSv4 device with bad bytes", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nbytes: 0", - invalid: true, - }, - { - name: "NFSv4 device with bad events", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nevents: 0", - invalid: true, - }, - { - name: "NFSv4 device with bad per-op stats", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nper-op statistics\nFOO 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nxprt: tcp", - invalid: true, - }, - { - name: "NFSv4 device with bad transport version", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=foo\nxprt: tcp 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats version 1.0", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.0\nxprt: tcp 0 0 0 0 0 0 0 0 0 0 0 0 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats version 1.1", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nxprt: tcp 0 0 0 0 0 0 0 0 0 0", - invalid: true, - }, - { - name: "NFSv3 device with transport stats version 1.0 OK", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs statvers=1.0\nxprt: tcp 1 2 3 4 5 6 7 8 9 10", - mounts: []*Mount{{ - Device: "192.168.1.1:/srv", - Mount: "/mnt/nfs", - Type: "nfs", - Stats: &MountStatsNFS{ - StatVersion: "1.0", - Transport: NFSTransportStats{ - Port: 1, - Bind: 2, - Connect: 3, - ConnectIdleTime: 4, - IdleTime: 5 * time.Second, - Sends: 6, - Receives: 7, - BadTransactionIDs: 8, - CumulativeActiveRequests: 9, - CumulativeBacklog: 10, - }, - }, - }}, - }, - { - name: "device rootfs OK", - s: `device rootfs mounted on / with fstype rootfs`, - mounts: []*Mount{{ - Device: "rootfs", - Mount: "/", - Type: "rootfs", - }}, - }, - { - name: "NFSv3 device with minimal stats OK", - s: `device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs statvers=1.1`, - mounts: []*Mount{{ - Device: "192.168.1.1:/srv", - Mount: "/mnt/nfs", - Type: "nfs", - Stats: &MountStatsNFS{ - StatVersion: "1.1", - }, - }}, - }, - { - name: "fixtures OK", - mounts: []*Mount{ - { - Device: "rootfs", - Mount: "/", - Type: "rootfs", - }, - { - Device: "sysfs", - Mount: "/sys", - Type: "sysfs", - }, - { - Device: "proc", - Mount: "/proc", - Type: "proc", - }, - { - Device: "/dev/sda1", - Mount: "/", - Type: "ext4", - }, - { - Device: "192.168.1.1:/srv/test", - Mount: "/mnt/nfs/test", - Type: "nfs4", - Stats: &MountStatsNFS{ - StatVersion: "1.1", - Age: 13968 * time.Second, - Bytes: NFSBytesStats{ - Read: 1207640230, - ReadTotal: 1210214218, - ReadPages: 295483, - }, - Events: NFSEventsStats{ - InodeRevalidate: 52, - DnodeRevalidate: 226, - VFSOpen: 1, - VFSLookup: 13, - VFSAccess: 398, - VFSReadPages: 331, - VFSWritePages: 47, - VFSFlush: 77, - VFSFileRelease: 77, - }, - Operations: []NFSOperationStats{ - { - Operation: "NULL", - }, - { - Operation: "READ", - Requests: 1298, - Transmissions: 1298, - BytesSent: 207680, - BytesReceived: 1210292152, - CumulativeQueueTime: 6 * time.Millisecond, - CumulativeTotalResponseTime: 79386 * time.Millisecond, - CumulativeTotalRequestTime: 79407 * time.Millisecond, - }, - { - Operation: "WRITE", - }, - }, - Transport: NFSTransportStats{ - Port: 832, - Connect: 1, - IdleTime: 11 * time.Second, - Sends: 6428, - Receives: 6428, - CumulativeActiveRequests: 12154, - MaximumRPCSlotsUsed: 24, - CumulativeSendingQueue: 26, - CumulativePendingQueue: 5726, - }, - }, - }, - }, - }, - } - - for i, tt := range tests { - t.Logf("[%02d] test %q", i, tt.name) - - var mounts []*Mount - var err error - - if tt.s != "" { - mounts, err = parseMountStats(strings.NewReader(tt.s)) - } else { - proc, e := FS("fixtures").NewProc(26231) - if e != nil { - t.Fatalf("failed to create proc: %v", err) - } - - mounts, err = proc.MountStats() - } - - if tt.invalid && err == nil { - t.Error("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Errorf("unexpected error: %v", err) - } - - if want, have := tt.mounts, mounts; !reflect.DeepEqual(want, have) { - t.Errorf("mounts:\nwant:\n%v\nhave:\n%v", mountsStr(want), mountsStr(have)) - } - } -} - -func mountsStr(mounts []*Mount) string { - var out string - for i, m := range mounts { - out += fmt.Sprintf("[%d] %q on %q (%q)", i, m.Device, m.Mount, m.Type) - - stats, ok := m.Stats.(*MountStatsNFS) - if !ok { - out += "\n" - continue - } - - out += fmt.Sprintf("\n\t- v%s, age: %s", stats.StatVersion, stats.Age) - out += fmt.Sprintf("\n\t- bytes: %v", stats.Bytes) - out += fmt.Sprintf("\n\t- events: %v", stats.Events) - out += fmt.Sprintf("\n\t- transport: %v", stats.Transport) - out += fmt.Sprintf("\n\t- per-operation stats:") - - for _, o := range stats.Operations { - out += fmt.Sprintf("\n\t\t- %v", o) - } - - out += "\n" - } - - return out -} diff --git a/vendor/github.com/prometheus/procfs/net_dev.go b/vendor/github.com/prometheus/procfs/net_dev.go index f8c184efe..3f2523371 100644 --- a/vendor/github.com/prometheus/procfs/net_dev.go +++ b/vendor/github.com/prometheus/procfs/net_dev.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( @@ -171,7 +184,7 @@ func (nd NetDev) parseLine(rawLine string) (*NetDevLine, error) { } // Total aggregates the values across interfaces and returns a new NetDevLine. -// The Name field will be a sorted comma seperated list of interface names. +// The Name field will be a sorted comma separated list of interface names. func (nd NetDev) Total() NetDevLine { total := NetDevLine{} diff --git a/vendor/github.com/prometheus/procfs/net_dev_test.go b/vendor/github.com/prometheus/procfs/net_dev_test.go deleted file mode 100644 index a69d8b9b8..000000000 --- a/vendor/github.com/prometheus/procfs/net_dev_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package procfs - -import ( - "testing" -) - -func TestNetDevParseLine(t *testing.T) { - const rawLine = ` eth0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16` - - have, err := NetDev{}.parseLine(rawLine) - if err != nil { - t.Fatal(err) - } - - want := NetDevLine{"eth0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - if want != *have { - t.Errorf("want %v, have %v", want, have) - } -} - -func TestNewNetDev(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - nd, err := fs.NewNetDev() - if err != nil { - t.Fatal(err) - } - - lines := map[string]NetDevLine{ - "vethf345468": {Name: "vethf345468", RxBytes: 648, RxPackets: 8, TxBytes: 438, TxPackets: 5}, - "lo": {Name: "lo", RxBytes: 1664039048, RxPackets: 1566805, TxBytes: 1664039048, TxPackets: 1566805}, - "docker0": {Name: "docker0", RxBytes: 2568, RxPackets: 38, TxBytes: 438, TxPackets: 5}, - "eth0": {Name: "eth0", RxBytes: 874354587, RxPackets: 1036395, TxBytes: 563352563, TxPackets: 732147}, - } - - if want, have := len(lines), len(nd); want != have { - t.Errorf("want %d parsed net/dev lines, have %d", want, have) - } - for _, line := range nd { - if want, have := lines[line.Name], line; want != have { - t.Errorf("%s: want %v, have %v", line.Name, want, have) - } - } -} - -func TestProcNewNetDev(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - nd, err := p.NewNetDev() - if err != nil { - t.Fatal(err) - } - - lines := map[string]NetDevLine{ - "lo": {Name: "lo"}, - "eth0": {Name: "eth0", RxBytes: 438, RxPackets: 5, TxBytes: 648, TxPackets: 8}, - } - - if want, have := len(lines), len(nd); want != have { - t.Errorf("want %d parsed net/dev lines, have %d", want, have) - } - for _, line := range nd { - if want, have := lines[line.Name], line; want != have { - t.Errorf("%s: want %v, have %v", line.Name, want, have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/nfs/nfs.go b/vendor/github.com/prometheus/procfs/nfs/nfs.go index e2185b782..651bf6819 100644 --- a/vendor/github.com/prometheus/procfs/nfs/nfs.go +++ b/vendor/github.com/prometheus/procfs/nfs/nfs.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package nfsd implements parsing of /proc/net/rpc/nfsd. +// Package nfs implements parsing of /proc/net/rpc/nfsd. // Fields are documented in https://www.svennd.be/nfsd-stats-explained-procnetrpcnfsd/ package nfs @@ -136,8 +136,8 @@ type ClientV4Stats struct { Setattr uint64 FsInfo uint64 Renew uint64 - SetClientId uint64 - SetClientIdConfirm uint64 + SetClientID uint64 + SetClientIDConfirm uint64 Lock uint64 Lockt uint64 Locku uint64 @@ -156,13 +156,13 @@ type ClientV4Stats struct { ReadDir uint64 ServerCaps uint64 DelegReturn uint64 - GetAcl uint64 - SetAcl uint64 + GetACL uint64 + SetACL uint64 FsLocations uint64 ReleaseLockowner uint64 Secinfo uint64 FsidPresent uint64 - ExchangeId uint64 + ExchangeID uint64 CreateSession uint64 DestroySession uint64 Sequence uint64 @@ -173,11 +173,11 @@ type ClientV4Stats struct { LayoutCommit uint64 LayoutReturn uint64 SecinfoNoName uint64 - TestStateId uint64 - FreeStateId uint64 + TestStateID uint64 + FreeStateID uint64 GetDeviceList uint64 BindConnToSession uint64 - DestroyClientId uint64 + DestroyClientID uint64 Seek uint64 Allocate uint64 DeAllocate uint64 @@ -238,7 +238,7 @@ type V4Ops struct { RelLockOwner uint64 } -// RPCStats models all stats from /proc/net/rpc/nfs. +// ClientRPCStats models all stats from /proc/net/rpc/nfs. type ClientRPCStats struct { Network Network ClientRPC ClientRPC diff --git a/vendor/github.com/prometheus/procfs/nfs/parse.go b/vendor/github.com/prometheus/procfs/nfs/parse.go index 8f568f011..95a83cc5b 100644 --- a/vendor/github.com/prometheus/procfs/nfs/parse.go +++ b/vendor/github.com/prometheus/procfs/nfs/parse.go @@ -204,8 +204,8 @@ func parseClientV4Stats(v []uint64) (ClientV4Stats, error) { Setattr: v[10], FsInfo: v[11], Renew: v[12], - SetClientId: v[13], - SetClientIdConfirm: v[14], + SetClientID: v[13], + SetClientIDConfirm: v[14], Lock: v[15], Lockt: v[16], Locku: v[17], @@ -224,13 +224,13 @@ func parseClientV4Stats(v []uint64) (ClientV4Stats, error) { ReadDir: v[30], ServerCaps: v[31], DelegReturn: v[32], - GetAcl: v[33], - SetAcl: v[34], + GetACL: v[33], + SetACL: v[34], FsLocations: v[35], ReleaseLockowner: v[36], Secinfo: v[37], FsidPresent: v[38], - ExchangeId: v[39], + ExchangeID: v[39], CreateSession: v[40], DestroySession: v[41], Sequence: v[42], @@ -241,11 +241,11 @@ func parseClientV4Stats(v []uint64) (ClientV4Stats, error) { LayoutCommit: v[47], LayoutReturn: v[48], SecinfoNoName: v[49], - TestStateId: v[50], - FreeStateId: v[51], + TestStateID: v[50], + FreeStateID: v[51], GetDeviceList: v[52], BindConnToSession: v[53], - DestroyClientId: v[54], + DestroyClientID: v[54], Seek: v[55], Allocate: v[56], DeAllocate: v[57], diff --git a/vendor/github.com/prometheus/procfs/nfs/parse_nfs_test.go b/vendor/github.com/prometheus/procfs/nfs/parse_nfs_test.go deleted file mode 100644 index afe3db47e..000000000 --- a/vendor/github.com/prometheus/procfs/nfs/parse_nfs_test.go +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2018 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package nfs_test - -import ( - "reflect" - "strings" - "testing" - - "github.com/prometheus/procfs/nfs" -) - -func TestNewNFSClientRPCStats(t *testing.T) { - tests := []struct { - name string - content string - stats *nfs.ClientRPCStats - invalid bool - }{ - { - name: "invalid file", - content: "invalid", - invalid: true, - }, { - name: "good old kernel version file", - content: `net 70 70 69 45 -rpc 1218785755 374636 1218815394 -proc2 18 16 57 74 52 71 73 45 86 0 52 83 61 17 53 50 23 70 82 -proc3 22 0 1061909262 48906 4077635 117661341 5 29391916 2570425 2993289 590 0 0 7815 15 1130 0 3983 92385 13332 2 1 23729 -proc4 48 98 51 54 83 85 23 24 1 28 73 68 83 12 84 39 68 59 58 88 29 74 69 96 21 84 15 53 86 54 66 56 97 36 49 32 85 81 11 58 32 67 13 28 35 90 1 26 1337 -`, - stats: &nfs.ClientRPCStats{ - Network: nfs.Network{ - NetCount: 70, - UDPCount: 70, - TCPCount: 69, - TCPConnect: 45, - }, - ClientRPC: nfs.ClientRPC{ - RPCCount: 1218785755, - Retransmissions: 374636, - AuthRefreshes: 1218815394, - }, - V2Stats: nfs.V2Stats{ - Null: 16, - GetAttr: 57, - SetAttr: 74, - Root: 52, - Lookup: 71, - ReadLink: 73, - Read: 45, - WrCache: 86, - Write: 0, - Create: 52, - Remove: 83, - Rename: 61, - Link: 17, - SymLink: 53, - MkDir: 50, - RmDir: 23, - ReadDir: 70, - FsStat: 82, - }, - V3Stats: nfs.V3Stats{ - Null: 0, - GetAttr: 1061909262, - SetAttr: 48906, - Lookup: 4077635, - Access: 117661341, - ReadLink: 5, - Read: 29391916, - Write: 2570425, - Create: 2993289, - MkDir: 590, - SymLink: 0, - MkNod: 0, - Remove: 7815, - RmDir: 15, - Rename: 1130, - Link: 0, - ReadDir: 3983, - ReadDirPlus: 92385, - FsStat: 13332, - FsInfo: 2, - PathConf: 1, - Commit: 23729, }, - ClientV4Stats: nfs.ClientV4Stats{ - Null: 98, - Read: 51, - Write: 54, - Commit: 83, - Open: 85, - OpenConfirm: 23, - OpenNoattr: 24, - OpenDowngrade: 1, - Close: 28, - Setattr: 73, - FsInfo: 68, - Renew: 83, - SetClientId: 12, - SetClientIdConfirm: 84, - Lock: 39, - Lockt: 68, - Locku: 59, - Access: 58, - Getattr: 88, - Lookup: 29, - LookupRoot: 74, - Remove: 69, - Rename: 96, - Link: 21, - Symlink: 84, - Create: 15, - Pathconf: 53, - StatFs: 86, - ReadLink: 54, - ReadDir: 66, - ServerCaps: 56, - DelegReturn: 97, - GetAcl: 36, - SetAcl: 49, - FsLocations: 32, - ReleaseLockowner: 85, - Secinfo: 81, - FsidPresent: 11, - ExchangeId: 58, - CreateSession: 32, - DestroySession: 67, - Sequence: 13, - GetLeaseTime: 28, - ReclaimComplete: 35, - LayoutGet: 90, - GetDeviceInfo: 1, - LayoutCommit: 26, - LayoutReturn: 1337, - SecinfoNoName: 0, - TestStateId: 0, - FreeStateId: 0, - GetDeviceList: 0, - BindConnToSession: 0, - DestroyClientId: 0, - Seek: 0, - Allocate: 0, - DeAllocate: 0, - LayoutStats: 0, - Clone: 0, - }, - }, - }, { - name: "good file", - content: `net 18628 0 18628 6 -rpc 4329785 0 4338291 -proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 -proc3 22 1 4084749 29200 94754 32580 186 47747 7981 8639 0 6356 0 6962 0 7958 0 0 241 4 4 2 39 -proc4 61 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -`, - stats: &nfs.ClientRPCStats{ - Network: nfs.Network{ - NetCount: 18628, - UDPCount: 0, - TCPCount: 18628, - TCPConnect: 6, - }, - ClientRPC: nfs.ClientRPC{ - RPCCount: 4329785, - Retransmissions: 0, - AuthRefreshes: 4338291, - }, - V2Stats: nfs.V2Stats{ - Null: 2, - GetAttr: 69, - SetAttr: 0, - Root: 0, - Lookup: 4410, - ReadLink: 0, - Read: 0, - WrCache: 0, - Write: 0, - Create: 0, - Remove: 0, - Rename: 0, - Link: 0, - SymLink: 0, - MkDir: 0, - RmDir: 0, - ReadDir: 99, - FsStat: 2, - }, - V3Stats: nfs.V3Stats{ - Null: 1, - GetAttr: 4084749, - SetAttr: 29200, - Lookup: 94754, - Access: 32580, - ReadLink: 186, - Read: 47747, - Write: 7981, - Create: 8639, - MkDir: 0, - SymLink: 6356, - MkNod: 0, - Remove: 6962, - RmDir: 0, - Rename: 7958, - Link: 0, - ReadDir: 0, - ReadDirPlus: 241, - FsStat: 4, - FsInfo: 4, - PathConf: 2, - Commit: 39, - }, - ClientV4Stats: nfs.ClientV4Stats{ - Null: 1, - Read: 0, - Write: 0, - Commit: 0, - Open: 0, - OpenConfirm: 0, - OpenNoattr: 0, - OpenDowngrade: 0, - Close: 0, - Setattr: 0, - FsInfo: 0, - Renew: 0, - SetClientId: 1, - SetClientIdConfirm: 1, - Lock: 0, - Lockt: 0, - Locku: 0, - Access: 0, - Getattr: 0, - Lookup: 0, - LookupRoot: 0, - Remove: 2, - Rename: 0, - Link: 0, - Symlink: 0, - Create: 0, - Pathconf: 0, - StatFs: 0, - ReadLink: 0, - ReadDir: 0, - ServerCaps: 0, - DelegReturn: 0, - GetAcl: 0, - SetAcl: 0, - FsLocations: 0, - ReleaseLockowner: 0, - Secinfo: 0, - FsidPresent: 0, - ExchangeId: 0, - CreateSession: 0, - DestroySession: 0, - Sequence: 0, - GetLeaseTime: 0, - ReclaimComplete: 0, - LayoutGet: 0, - GetDeviceInfo: 0, - LayoutCommit: 0, - LayoutReturn: 0, - SecinfoNoName: 0, - TestStateId: 0, - FreeStateId: 0, - GetDeviceList: 0, - BindConnToSession: 0, - DestroyClientId: 0, - Seek: 0, - Allocate: 0, - DeAllocate: 0, - LayoutStats: 0, - Clone: 0, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - stats, err := nfs.ParseClientRPCStats(strings.NewReader(tt.content)) - - if tt.invalid && err == nil { - t.Fatal("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if want, have := tt.stats, stats; !reflect.DeepEqual(want, have) { - t.Fatalf("unexpected NFS stats:\nwant:\n%v\nhave:\n%v", want, have) - } - }) - } -} diff --git a/vendor/github.com/prometheus/procfs/nfs/parse_nfsd_test.go b/vendor/github.com/prometheus/procfs/nfs/parse_nfsd_test.go deleted file mode 100644 index b09b3b580..000000000 --- a/vendor/github.com/prometheus/procfs/nfs/parse_nfsd_test.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2018 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package nfs_test - -import ( - "reflect" - "strings" - "testing" - - "github.com/prometheus/procfs/nfs" -) - -func TestNewNFSdServerRPCStats(t *testing.T) { - tests := []struct { - name string - content string - stats *nfs.ServerRPCStats - invalid bool - }{ - { - name: "invalid file", - content: "invalid", - invalid: true, - }, { - name: "good file", - content: `rc 0 6 18622 -fh 0 0 0 0 0 -io 157286400 0 -th 8 0 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -ra 32 0 0 0 0 0 0 0 0 0 0 0 -net 18628 0 18628 6 -rpc 18628 0 0 0 0 -proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 -proc3 22 2 112 0 2719 111 0 0 0 0 0 0 0 0 0 0 0 27 216 0 2 1 0 -proc4 2 2 10853 -proc4ops 72 0 0 0 1098 2 0 0 0 0 8179 5896 0 0 0 0 5900 0 0 2 0 2 0 9609 0 2 150 1272 0 0 0 1236 0 0 0 0 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -`, - stats: &nfs.ServerRPCStats{ - ReplyCache: nfs.ReplyCache{ - Hits: 0, - Misses: 6, - NoCache: 18622, - }, - FileHandles: nfs.FileHandles{ - Stale: 0, - TotalLookups: 0, - AnonLookups: 0, - DirNoCache: 0, - NoDirNoCache: 0, - }, - InputOutput: nfs.InputOutput{ - Read: 157286400, - Write: 0, - }, - Threads: nfs.Threads{ - Threads: 8, - FullCnt: 0, - }, - ReadAheadCache: nfs.ReadAheadCache{ - CacheSize: 32, - CacheHistogram: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - NotFound: 0, - }, - Network: nfs.Network{ - NetCount: 18628, - UDPCount: 0, - TCPCount: 18628, - TCPConnect: 6, - }, - ServerRPC: nfs.ServerRPC{ - RPCCount: 18628, - BadCnt: 0, - BadFmt: 0, - BadAuth: 0, - BadcInt: 0, - }, - V2Stats: nfs.V2Stats{ - Null: 2, - GetAttr: 69, - SetAttr: 0, - Root: 0, - Lookup: 4410, - ReadLink: 0, - Read: 0, - WrCache: 0, - Write: 0, - Create: 0, - Remove: 0, - Rename: 0, - Link: 0, - SymLink: 0, - MkDir: 0, - RmDir: 0, - ReadDir: 99, - FsStat: 2, - }, - V3Stats: nfs.V3Stats{ - Null: 2, - GetAttr: 112, - SetAttr: 0, - Lookup: 2719, - Access: 111, - ReadLink: 0, - Read: 0, - Write: 0, - Create: 0, - MkDir: 0, - SymLink: 0, - MkNod: 0, - Remove: 0, - RmDir: 0, - Rename: 0, - Link: 0, - ReadDir: 27, - ReadDirPlus: 216, - FsStat: 0, - FsInfo: 2, - PathConf: 1, - Commit: 0, - }, - ServerV4Stats: nfs.ServerV4Stats{ - Null: 2, - Compound: 10853, - }, - V4Ops: nfs.V4Ops{ - Op0Unused: 0, - Op1Unused: 0, - Op2Future: 0, - Access: 1098, - Close: 2, - Commit: 0, - Create: 0, - DelegPurge: 0, - DelegReturn: 0, - GetAttr: 8179, - GetFH: 5896, - Link: 0, - Lock: 0, - Lockt: 0, - Locku: 0, - Lookup: 5900, - LookupRoot: 0, - Nverify: 0, - Open: 2, - OpenAttr: 0, - OpenConfirm: 2, - OpenDgrd: 0, - PutFH: 9609, - PutPubFH: 0, - PutRootFH: 2, - Read: 150, - ReadDir: 1272, - ReadLink: 0, - Remove: 0, - Rename: 0, - Renew: 1236, - RestoreFH: 0, - SaveFH: 0, - SecInfo: 0, - SetAttr: 0, - Verify: 3, - Write: 3, - RelLockOwner: 0, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - stats, err := nfs.ParseServerRPCStats(strings.NewReader(tt.content)) - - if tt.invalid && err == nil { - t.Fatal("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if want, have := tt.stats, stats; !reflect.DeepEqual(want, have) { - t.Fatalf("unexpected NFS stats:\nwant:\n%v\nhave:\n%v", want, have) - } - }) - } -} diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go index 8717e1fe0..7cf5b8acf 100644 --- a/vendor/github.com/prometheus/procfs/proc.go +++ b/vendor/github.com/prometheus/procfs/proc.go @@ -1,6 +1,20 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( + "bytes" "fmt" "io/ioutil" "os" @@ -113,7 +127,7 @@ func (p Proc) CmdLine() ([]string, error) { return []string{}, nil } - return strings.Split(string(data[:len(data)-1]), string(byte(0))), nil + return strings.Split(string(bytes.TrimRight(data, string("\x00"))), string(byte(0))), nil } // Comm returns the command name of a process. diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index e7f6674d0..0251c83bf 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_io_test.go b/vendor/github.com/prometheus/procfs/proc_io_test.go deleted file mode 100644 index 3aa1a1293..000000000 --- a/vendor/github.com/prometheus/procfs/proc_io_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package procfs - -import "testing" - -func TestProcIO(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewIO() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int64 - have int64 - }{ - {name: "RChar", want: 750339, have: int64(s.RChar)}, - {name: "WChar", want: 818609, have: int64(s.WChar)}, - {name: "SyscR", want: 7405, have: int64(s.SyscR)}, - {name: "SyscW", want: 5245, have: int64(s.SyscW)}, - {name: "ReadBytes", want: 1024, have: int64(s.ReadBytes)}, - {name: "WriteBytes", want: 2048, have: int64(s.WriteBytes)}, - {name: "CancelledWriteBytes", want: -1024, have: s.CancelledWriteBytes}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go index b684a5b55..f04ba6fda 100644 --- a/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/vendor/github.com/prometheus/procfs/proc_limits.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_limits_test.go b/vendor/github.com/prometheus/procfs/proc_limits_test.go deleted file mode 100644 index ac62a3bb6..000000000 --- a/vendor/github.com/prometheus/procfs/proc_limits_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package procfs - -import "testing" - -func TestNewLimits(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - l, err := p.NewLimits() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int64 - have int64 - }{ - {name: "cpu time", want: -1, have: l.CPUTime}, - {name: "open files", want: 2048, have: l.OpenFiles}, - {name: "msgqueue size", want: 819200, have: l.MsqqueueSize}, - {name: "nice priority", want: 0, have: l.NicePriority}, - {name: "address space", want: 8589934592, have: l.AddressSpace}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_ns.go b/vendor/github.com/prometheus/procfs/proc_ns.go index befdd2690..d06c26eba 100644 --- a/vendor/github.com/prometheus/procfs/proc_ns.go +++ b/vendor/github.com/prometheus/procfs/proc_ns.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_ns_test.go b/vendor/github.com/prometheus/procfs/proc_ns_test.go deleted file mode 100644 index aea3f6a6c..000000000 --- a/vendor/github.com/prometheus/procfs/proc_ns_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package procfs - -import ( - "testing" -) - -func TestNewNamespaces(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - namespaces, err := p.NewNamespaces() - if err != nil { - t.Fatal(err) - } - - expectedNamespaces := map[string]Namespace{ - "mnt": {"mnt", 4026531840}, - "net": {"net", 4026531993}, - } - - if want, have := len(expectedNamespaces), len(namespaces); want != have { - t.Errorf("want %d parsed namespaces, have %d", want, have) - } - for _, ns := range namespaces { - if want, have := expectedNamespaces[ns.Type], ns; want != have { - t.Errorf("%s: want %v, have %v", ns.Type, want, have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 724e271b9..3cf2a9f18 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_stat_test.go b/vendor/github.com/prometheus/procfs/proc_stat_test.go deleted file mode 100644 index a2ebcde78..000000000 --- a/vendor/github.com/prometheus/procfs/proc_stat_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package procfs - -import ( - "os" - "testing" -) - -func TestProcStat(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - have int - }{ - {name: "pid", want: 26231, have: s.PID}, - {name: "user time", want: 1677, have: int(s.UTime)}, - {name: "system time", want: 44, have: int(s.STime)}, - {name: "start time", want: 82375, have: int(s.Starttime)}, - {name: "virtual memory size", want: 56274944, have: s.VSize}, - {name: "resident set size", want: 1981, have: s.RSS}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} - -func TestProcStatComm(t *testing.T) { - s1, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - if want, have := "vim", s1.Comm; want != have { - t.Errorf("want comm %s, have %s", want, have) - } - - s2, err := testProcStat(584) - if err != nil { - t.Fatal(err) - } - if want, have := "(a b ) ( c d) ", s2.Comm; want != have { - t.Errorf("want comm %s, have %s", want, have) - } -} - -func TestProcStatVirtualMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 56274944, s.VirtualMemory(); want != have { - t.Errorf("want virtual memory %d, have %d", want, have) - } -} - -func TestProcStatResidentMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 1981*os.Getpagesize(), s.ResidentMemory(); want != have { - t.Errorf("want resident memory %d, have %d", want, have) - } -} - -func TestProcStatStartTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - time, err := s.StartTime() - if err != nil { - t.Fatal(err) - } - if want, have := 1418184099.75, time; want != have { - t.Errorf("want start time %f, have %f", want, have) - } -} - -func TestProcStatCPUTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 17.21, s.CPUTime(); want != have { - t.Errorf("want cpu time %f, have %f", want, have) - } -} - -func testProcStat(pid int) (ProcStat, error) { - p, err := FS("fixtures").NewProc(pid) - if err != nil { - return ProcStat{}, err - } - - return p.NewStat() -} diff --git a/vendor/github.com/prometheus/procfs/proc_test.go b/vendor/github.com/prometheus/procfs/proc_test.go deleted file mode 100644 index 104b3245d..000000000 --- a/vendor/github.com/prometheus/procfs/proc_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package procfs - -import ( - "reflect" - "sort" - "testing" -) - -func TestSelf(t *testing.T) { - fs := FS("fixtures") - - p1, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - p2, err := fs.Self() - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(p1, p2) { - t.Errorf("want process %v, have %v", p1, p2) - } -} - -func TestAllProcs(t *testing.T) { - procs, err := FS("fixtures").AllProcs() - if err != nil { - t.Fatal(err) - } - sort.Sort(procs) - for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { - if want, have := p.PID, procs[i].PID; want != have { - t.Errorf("want processes %d, have %d", want, have) - } - } -} - -func TestCmdLine(t *testing.T) { - for _, tt := range []struct { - process int - want []string - }{ - {process: 26231, want: []string{"vim", "test.go", "+10"}}, - {process: 26232, want: []string{}}, - } { - p1, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - c1, err := p1.CmdLine() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, c1) { - t.Errorf("want cmdline %v, have %v", tt.want, c1) - } - } -} - -func TestComm(t *testing.T) { - for _, tt := range []struct { - process int - want string - }{ - {process: 26231, want: "vim"}, - {process: 26232, want: "ata_sff"}, - } { - p1, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - c1, err := p1.Comm() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, c1) { - t.Errorf("want comm %v, have %v", tt.want, c1) - } - } -} - -func TestExecutable(t *testing.T) { - for _, tt := range []struct { - process int - want string - }{ - {process: 26231, want: "/usr/bin/vim"}, - {process: 26232, want: ""}, - } { - p, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - exe, err := p.Executable() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, exe) { - t.Errorf("want absolute path to cmdline %v, have %v", tt.want, exe) - } - } -} - -func TestFileDescriptors(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptors() - if err != nil { - t.Fatal(err) - } - sort.Sort(byUintptr(fds)) - if want := []uintptr{0, 1, 2, 3, 10}; !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, have %v", want, fds) - } -} - -func TestFileDescriptorTargets(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptorTargets() - if err != nil { - t.Fatal(err) - } - sort.Strings(fds) - var want = []string{ - "../../symlinktargets/abc", - "../../symlinktargets/def", - "../../symlinktargets/ghi", - "../../symlinktargets/uvw", - "../../symlinktargets/xyz", - } - if !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, have %v", want, fds) - } -} - -func TestFileDescriptorsLen(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - l, err := p1.FileDescriptorsLen() - if err != nil { - t.Fatal(err) - } - if want, have := 5, l; want != have { - t.Errorf("want fds %d, have %d", want, have) - } -} - -type byUintptr []uintptr - -func (a byUintptr) Len() int { return len(a) } -func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index 701f4df64..61eb6b0e3 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + package procfs import ( diff --git a/vendor/github.com/prometheus/procfs/stat_test.go b/vendor/github.com/prometheus/procfs/stat_test.go deleted file mode 100644 index c34ccce1a..000000000 --- a/vendor/github.com/prometheus/procfs/stat_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package procfs - -import "testing" - -func TestStat(t *testing.T) { - s, err := FS("fixtures").NewStat() - if err != nil { - t.Fatal(err) - } - - // cpu - if want, have := float64(301854)/userHZ, s.CPUTotal.User; want != have { - t.Errorf("want cpu/user %v, have %v", want, have) - } - if want, have := float64(31)/userHZ, s.CPU[7].SoftIRQ; want != have { - t.Errorf("want cpu7/softirq %v, have %v", want, have) - } - - // intr - if want, have := uint64(8885917), s.IRQTotal; want != have { - t.Errorf("want irq/total %d, have %d", want, have) - } - if want, have := uint64(1), s.IRQ[8]; want != have { - t.Errorf("want irq8 %d, have %d", want, have) - } - - // ctxt - if want, have := uint64(38014093), s.ContextSwitches; want != have { - t.Errorf("want context switches (ctxt) %d, have %d", want, have) - } - - // btime - if want, have := uint64(1418183276), s.BootTime; want != have { - t.Errorf("want boot time (btime) %d, have %d", want, have) - } - - // processes - if want, have := uint64(26442), s.ProcessCreated; want != have { - t.Errorf("want process created (processes) %d, have %d", want, have) - } - - // procs_running - if want, have := uint64(2), s.ProcessesRunning; want != have { - t.Errorf("want processes running (procs_running) %d, have %d", want, have) - } - - // procs_blocked - if want, have := uint64(1), s.ProcessesBlocked; want != have { - t.Errorf("want processes blocked (procs_blocked) %d, have %d", want, have) - } - - // softirq - if want, have := uint64(5057579), s.SoftIRQTotal; want != have { - t.Errorf("want softirq total %d, have %d", want, have) - } - - if want, have := uint64(508444), s.SoftIRQ.Rcu; want != have { - t.Errorf("want softirq RCU %d, have %d", want, have) - } - -} diff --git a/vendor/github.com/prometheus/procfs/sysfs/.gitignore b/vendor/github.com/prometheus/procfs/sysfs/.gitignore deleted file mode 100644 index 67fc140b9..000000000 --- a/vendor/github.com/prometheus/procfs/sysfs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -fixtures/ diff --git a/vendor/github.com/prometheus/procfs/sysfs/doc.go b/vendor/github.com/prometheus/procfs/sysfs/doc.go deleted file mode 100644 index 9a6c244e9..000000000 --- a/vendor/github.com/prometheus/procfs/sysfs/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package sysfs provides functions to retrieve system and kernel metrics -// from the pseudo-filesystem sys. -package sysfs diff --git a/vendor/github.com/prometheus/procfs/sysfs/fixtures.ttar b/vendor/github.com/prometheus/procfs/sysfs/fixtures.ttar deleted file mode 100644 index 0045e7d56..000000000 --- a/vendor/github.com/prometheus/procfs/sysfs/fixtures.ttar +++ /dev/null @@ -1,721 +0,0 @@ -Directory: fixtures -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/dirty_data -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_hits -Lines: 1 -289 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_day/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_five_minute/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_hour/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_hits -Lines: 1 -546 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata4/host3/target3:0:0/3:0:0:0/block/sdb/bcache/stats_total/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc/bcache -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc/bcache/io_errors -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc/bcache/metadata_written -Lines: 1 -512 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc/bcache/priority_stats -Lines: 5 -Unused: 99% -Metadata: 0% -Average: 10473 -Sectors per Q: 64 -Quantiles: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946] -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/devices/pci0000:00/0000:00:0d.0/ata5/host4/target4:0:0/4:0:0:0/block/sdc/bcache/written -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/average_key_size -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0 -Mode: 777 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/dirty_data -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_hits -Lines: 1 -289 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_day/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_five_minute/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_hour/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_hits -Lines: 1 -546 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/bdev0/stats_total/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/btree_cache_size -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache0 -Mode: 777 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache0/io_errors -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache0/metadata_written -Lines: 1 -512 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache0/priority_stats -Lines: 5 -Unused: 99% -Metadata: 0% -Average: 10473 -Sectors per Q: 64 -Quantiles: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946 20946] -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache0/written -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/cache_available_percent -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/congested -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/internal -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/internal/active_journal_entries -Lines: 1 -1 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/internal/btree_nodes -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/internal/btree_read_average_duration_us -Lines: 1 -1305 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/internal/cache_read_races -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/root_usage_percent -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_hits -Lines: 1 -289 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_day/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_five_minute/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_hit_ratio -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_hour/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/bypassed -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_bypass_hits -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_bypass_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_hit_ratio -Lines: 1 -100 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_hits -Lines: 1 -546 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_miss_collisions -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_misses -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/stats_total/cache_readaheads -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/bcache/deaddd54-c735-46d5-868e-f331c5fd7c74/tree_depth -Lines: 1 -0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/xfs -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/xfs/sda1 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/xfs/sda1/stats -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/xfs/sda1/stats/stats -Lines: 1 -extent_alloc 1 0 0 0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/xfs/sdb1 -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Directory: fixtures/fs/xfs/sdb1/stats -Mode: 755 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Path: fixtures/fs/xfs/sdb1/stats/stats -Lines: 1 -extent_alloc 2 0 0 0 -Mode: 644 -# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendor/github.com/prometheus/procfs/sysfs/fs.go b/vendor/github.com/prometheus/procfs/sysfs/fs.go deleted file mode 100644 index fb15d438a..000000000 --- a/vendor/github.com/prometheus/procfs/sysfs/fs.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sysfs - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/prometheus/procfs/bcache" - "github.com/prometheus/procfs/xfs" -) - -// FS represents the pseudo-filesystem sys, which provides an interface to -// kernel data structures. -type FS string - -// DefaultMountPoint is the common mount point of the sys filesystem. -const DefaultMountPoint = "/sys" - -// NewFS returns a new FS mounted under the given mountPoint. It will error -// if the mount point can't be read. -func NewFS(mountPoint string) (FS, error) { - info, err := os.Stat(mountPoint) - if err != nil { - return "", fmt.Errorf("could not read %s: %s", mountPoint, err) - } - if !info.IsDir() { - return "", fmt.Errorf("mount point %s is not a directory", mountPoint) - } - - return FS(mountPoint), nil -} - -// Path returns the path of the given subsystem relative to the sys root. -func (fs FS) Path(p ...string) string { - return filepath.Join(append([]string{string(fs)}, p...)...) -} - -// XFSStats retrieves XFS filesystem runtime statistics for each mounted XFS -// filesystem. Only available on kernel 4.4+. On older kernels, an empty -// slice of *xfs.Stats will be returned. -func (fs FS) XFSStats() ([]*xfs.Stats, error) { - matches, err := filepath.Glob(fs.Path("fs/xfs/*/stats/stats")) - if err != nil { - return nil, err - } - - stats := make([]*xfs.Stats, 0, len(matches)) - for _, m := range matches { - f, err := os.Open(m) - if err != nil { - return nil, err - } - - // "*" used in glob above indicates the name of the filesystem. - name := filepath.Base(filepath.Dir(filepath.Dir(m))) - - // File must be closed after parsing, regardless of success or - // failure. Defer is not used because of the loop. - s, err := xfs.ParseStats(f) - _ = f.Close() - if err != nil { - return nil, err - } - - s.Name = name - stats = append(stats, s) - } - - return stats, nil -} - -// BcacheStats retrieves bcache runtime statistics for each bcache. -func (fs FS) BcacheStats() ([]*bcache.Stats, error) { - matches, err := filepath.Glob(fs.Path("fs/bcache/*-*")) - if err != nil { - return nil, err - } - - stats := make([]*bcache.Stats, 0, len(matches)) - for _, uuidPath := range matches { - // "*-*" in glob above indicates the name of the bcache. - name := filepath.Base(uuidPath) - - // stats - s, err := bcache.GetStats(uuidPath) - if err != nil { - return nil, err - } - - s.Name = name - stats = append(stats, s) - } - - return stats, nil -} diff --git a/vendor/github.com/prometheus/procfs/sysfs/fs_test.go b/vendor/github.com/prometheus/procfs/sysfs/fs_test.go deleted file mode 100644 index 2b7402eca..000000000 --- a/vendor/github.com/prometheus/procfs/sysfs/fs_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sysfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("doc.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} - -func TestFSXFSStats(t *testing.T) { - stats, err := FS("fixtures").XFSStats() - if err != nil { - t.Fatalf("failed to parse XFS stats: %v", err) - } - - tests := []struct { - name string - allocated uint32 - }{ - { - name: "sda1", - allocated: 1, - }, - { - name: "sdb1", - allocated: 2, - }, - } - - const expect = 2 - - if l := len(stats); l != expect { - t.Fatalf("unexpected number of XFS stats: %d", l) - } - if l := len(tests); l != expect { - t.Fatalf("unexpected number of tests: %d", l) - } - - for i, tt := range tests { - if want, got := tt.name, stats[i].Name; want != got { - t.Errorf("unexpected stats name:\nwant: %q\nhave: %q", want, got) - } - - if want, got := tt.allocated, stats[i].ExtentAllocation.ExtentsAllocated; want != got { - t.Errorf("unexpected extents allocated:\nwant: %d\nhave: %d", want, got) - } - } -} - -func TestFSBcacheStats(t *testing.T) { - stats, err := FS("fixtures").BcacheStats() - if err != nil { - t.Fatalf("failed to parse bcache stats: %v", err) - } - - tests := []struct { - name string - bdevs int - caches int - }{ - { - name: "deaddd54-c735-46d5-868e-f331c5fd7c74", - bdevs: 1, - caches: 1, - }, - } - - const expect = 1 - - if l := len(stats); l != expect { - t.Fatalf("unexpected number of bcache stats: %d", l) - } - if l := len(tests); l != expect { - t.Fatalf("unexpected number of tests: %d", l) - } - - for i, tt := range tests { - if want, got := tt.name, stats[i].Name; want != got { - t.Errorf("unexpected stats name:\nwant: %q\nhave: %q", want, got) - } - - if want, got := tt.bdevs, len(stats[i].Bdevs); want != got { - t.Errorf("unexpected value allocated:\nwant: %d\nhave: %d", want, got) - } - - if want, got := tt.caches, len(stats[i].Caches); want != got { - t.Errorf("unexpected value allocated:\nwant: %d\nhave: %d", want, got) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/ttar b/vendor/github.com/prometheus/procfs/ttar index 8227a4a37..b0171a12b 100755 --- a/vendor/github.com/prometheus/procfs/ttar +++ b/vendor/github.com/prometheus/procfs/ttar @@ -1,11 +1,26 @@ #!/usr/bin/env bash + # Purpose: plain text tar format # Limitations: - only suitable for text files, directories, and symlinks # - stores only filename, content, and mode # - not designed for untrusted input - +# # Note: must work with bash version 3.2 (macOS) +# Copyright 2017 Roger Luethi +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + set -o errexit -o nounset # Sanitize environment (for instance, standard sorting of glob matches) @@ -13,6 +28,55 @@ export LC_ALL=C path="" CMD="" +ARG_STRING="$*" + +#------------------------------------------------------------------------------ +# Not all sed implementations can work on null bytes. In order to make ttar +# work out of the box on macOS, use Python as a stream editor. + +USE_PYTHON=0 + +PYTHON_CREATE_FILTER=$(cat << 'PCF' +#!/usr/bin/env python + +import re +import sys + +for line in sys.stdin: + line = re.sub(r'EOF', r'\EOF', line) + line = re.sub(r'NULLBYTE', r'\NULLBYTE', line) + line = re.sub('\x00', r'NULLBYTE', line) + sys.stdout.write(line) +PCF +) + +PYTHON_EXTRACT_FILTER=$(cat << 'PEF' +#!/usr/bin/env python + +import re +import sys + +for line in sys.stdin: + line = re.sub(r'(?/dev/null; then + echo "ERROR Python not found. Aborting." + exit 2 + fi + USE_PYTHON=1 + fi +} + +#------------------------------------------------------------------------------ function usage { bname=$(basename "$0") @@ -23,6 +87,7 @@ Usage: $bname [-C ] -c -f (create archive) Options: -C (change directory) + -v (verbose) Example: Change to sysfs directory, create ttar file from fixtures directory $bname -C sysfs -c -f sysfs/fixtures.ttar fixtures/ @@ -45,6 +110,8 @@ function set_cmd { CMD=$1 } +unset VERBOSE + while getopts :cf:htxvC: opt; do case $opt in c) @@ -142,8 +209,37 @@ function extract { fi while IFS= read -r line; do line_no=$(( line_no + 1 )) + local eof_without_newline if [ "$size" -gt 0 ]; then - echo "$line" >> "$path" + if [[ "$line" =~ [^\\]EOF ]]; then + # An EOF not preceeded by a backslash indicates that the line + # does not end with a newline + eof_without_newline=1 + else + eof_without_newline=0 + fi + # Replace NULLBYTE with null byte if at beginning of line + # Replace NULLBYTE with null byte unless preceeded by backslash + # Remove one backslash in front of NULLBYTE (if any) + # Remove EOF unless preceeded by backslash + # Remove one backslash in front of EOF + if [ $USE_PYTHON -eq 1 ]; then + echo -n "$line" | python -c "$PYTHON_EXTRACT_FILTER" >> "$path" + else + # The repeated pattern makes up for sed's lack of negative + # lookbehind assertions (for consecutive null bytes). + echo -n "$line" | \ + sed -e 's/^NULLBYTE/\x0/g; + s/\([^\\]\)NULLBYTE/\1\x0/g; + s/\([^\\]\)NULLBYTE/\1\x0/g; + s/\\NULLBYTE/NULLBYTE/g; + s/\([^\\]\)EOF/\1/g; + s/\\EOF/EOF/g; + ' >> "$path" + fi + if [[ "$eof_without_newline" -eq 0 ]]; then + echo >> "$path" + fi size=$(( size - 1 )) continue fi @@ -187,11 +283,14 @@ function get_mode { local mfile=$1 if [ -z "${STAT_OPTION:-}" ]; then if stat -c '%a' "$mfile" >/dev/null 2>&1; then + # GNU stat STAT_OPTION='-c' STAT_FORMAT='%a' else + # BSD stat STAT_OPTION='-f' - STAT_FORMAT='%A' + # Octal output, user/group/other (omit file type, sticky bit) + STAT_FORMAT='%OLp' fi fi stat "${STAT_OPTION}" "${STAT_FORMAT}" "$mfile" @@ -200,6 +299,7 @@ function get_mode { function _create { shopt -s nullglob local mode + local eof_without_newline while (( "$#" )); do file=$1 if [ -L "$file" ]; then @@ -223,8 +323,30 @@ function _create { elif [ -f "$file" ]; then echo "Path: $file" lines=$(wc -l "$file"|awk '{print $1}') + eof_without_newline=0 + if [[ "$(wc -c "$file"|awk '{print $1}')" -gt 0 ]] && \ + [[ "$(tail -c 1 "$file" | wc -l)" -eq 0 ]]; then + eof_without_newline=1 + lines=$((lines+1)) + fi echo "Lines: $lines" - cat "$file" + # Add backslash in front of EOF + # Add backslash in front of NULLBYTE + # Replace null byte with NULLBYTE + if [ $USE_PYTHON -eq 1 ]; then + < "$file" python -c "$PYTHON_CREATE_FILTER" + else + < "$file" \ + sed 's/EOF/\\EOF/g; + s/NULLBYTE/\\NULLBYTE/g; + s/\x0/NULLBYTE/g; + ' + fi + if [[ "$eof_without_newline" -eq 1 ]]; then + # Finish line with EOF to indicate that the original line did + # not end with a linefeed + echo "EOF" + fi mode=$(get_mode "$file") echo "Mode: $mode" vecho "$mode $file" @@ -249,9 +371,12 @@ function create { rm "$ttar_file" fi exec > "$ttar_file" + echo "# Archive created by ttar $ARG_STRING" _create "$@" } +test_environment + if [ -n "${CDIR:-}" ]; then if [[ "$ARCHIVE" != /* ]]; then # Relative path: preserve the archive's location before changing diff --git a/vendor/github.com/prometheus/procfs/xfrm_test.go b/vendor/github.com/prometheus/procfs/xfrm_test.go deleted file mode 100644 index 5918c390e..000000000 --- a/vendor/github.com/prometheus/procfs/xfrm_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2017 Prometheus Team -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package procfs - -import ( - "testing" -) - -func TestXfrmStats(t *testing.T) { - xfrmStats, err := FS("fixtures").NewXfrmStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "XfrmInError", want: 1, got: xfrmStats.XfrmInError}, - {name: "XfrmInBufferError", want: 2, got: xfrmStats.XfrmInBufferError}, - {name: "XfrmInHdrError", want: 4, got: xfrmStats.XfrmInHdrError}, - {name: "XfrmInNoStates", want: 3, got: xfrmStats.XfrmInNoStates}, - {name: "XfrmInStateProtoError", want: 40, got: xfrmStats.XfrmInStateProtoError}, - {name: "XfrmInStateModeError", want: 100, got: xfrmStats.XfrmInStateModeError}, - {name: "XfrmInStateSeqError", want: 6000, got: xfrmStats.XfrmInStateSeqError}, - {name: "XfrmInStateExpired", want: 4, got: xfrmStats.XfrmInStateExpired}, - {name: "XfrmInStateMismatch", want: 23451, got: xfrmStats.XfrmInStateMismatch}, - {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid}, - {name: "XfrmInTmplMismatch", want: 51, got: xfrmStats.XfrmInTmplMismatch}, - {name: "XfrmInNoPols", want: 65432, got: xfrmStats.XfrmInNoPols}, - {name: "XfrmInPolBlock", want: 100, got: xfrmStats.XfrmInPolBlock}, - {name: "XfrmInPolError", want: 10000, got: xfrmStats.XfrmInPolError}, - {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError}, - {name: "XfrmOutBundleGenError", want: 43321, got: xfrmStats.XfrmOutBundleGenError}, - {name: "XfrmOutBundleCheckError", want: 555, got: xfrmStats.XfrmOutBundleCheckError}, - {name: "XfrmOutNoStates", want: 869, got: xfrmStats.XfrmOutNoStates}, - {name: "XfrmOutStateProtoError", want: 4542, got: xfrmStats.XfrmOutStateProtoError}, - {name: "XfrmOutStateModeError", want: 4, got: xfrmStats.XfrmOutStateModeError}, - {name: "XfrmOutStateSeqError", want: 543, got: xfrmStats.XfrmOutStateSeqError}, - {name: "XfrmOutStateExpired", want: 565, got: xfrmStats.XfrmOutStateExpired}, - {name: "XfrmOutPolBlock", want: 43456, got: xfrmStats.XfrmOutPolBlock}, - {name: "XfrmOutPolDead", want: 7656, got: xfrmStats.XfrmOutPolDead}, - {name: "XfrmOutPolError", want: 1454, got: xfrmStats.XfrmOutPolError}, - {name: "XfrmFwdHdrError", want: 6654, got: xfrmStats.XfrmFwdHdrError}, - {name: "XfrmOutStateInvaliad", want: 28765, got: xfrmStats.XfrmOutStateInvalid}, - {name: "XfrmAcquireError", want: 24532, got: xfrmStats.XfrmAcquireError}, - {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid}, - {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError}, - } { - if test.want != test.got { - t.Errorf("Want %s %d, have %d", test.name, test.want, test.got) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/xfs/parse_test.go b/vendor/github.com/prometheus/procfs/xfs/parse_test.go deleted file mode 100644 index 2e946c2c5..000000000 --- a/vendor/github.com/prometheus/procfs/xfs/parse_test.go +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2017 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package xfs_test - -import ( - "reflect" - "strings" - "testing" - - "github.com/prometheus/procfs" - "github.com/prometheus/procfs/xfs" -) - -func TestParseStats(t *testing.T) { - tests := []struct { - name string - s string - fs bool - stats *xfs.Stats - invalid bool - }{ - { - name: "empty file OK", - }, - { - name: "short or empty lines and unknown labels ignored", - s: "one\n\ntwo 1 2 3\n", - stats: &xfs.Stats{}, - }, - { - name: "bad uint32", - s: "extent_alloc XXX", - invalid: true, - }, - { - name: "bad uint64", - s: "xpc XXX", - invalid: true, - }, - { - name: "extent_alloc bad", - s: "extent_alloc 1", - invalid: true, - }, - { - name: "extent_alloc OK", - s: "extent_alloc 1 2 3 4", - stats: &xfs.Stats{ - ExtentAllocation: xfs.ExtentAllocationStats{ - ExtentsAllocated: 1, - BlocksAllocated: 2, - ExtentsFreed: 3, - BlocksFreed: 4, - }, - }, - }, - { - name: "abt bad", - s: "abt 1", - invalid: true, - }, - { - name: "abt OK", - s: "abt 1 2 3 4", - stats: &xfs.Stats{ - AllocationBTree: xfs.BTreeStats{ - Lookups: 1, - Compares: 2, - RecordsInserted: 3, - RecordsDeleted: 4, - }, - }, - }, - { - name: "blk_map bad", - s: "blk_map 1", - invalid: true, - }, - { - name: "blk_map OK", - s: "blk_map 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - BlockMapping: xfs.BlockMappingStats{ - Reads: 1, - Writes: 2, - Unmaps: 3, - ExtentListInsertions: 4, - ExtentListDeletions: 5, - ExtentListLookups: 6, - ExtentListCompares: 7, - }, - }, - }, - { - name: "bmbt bad", - s: "bmbt 1", - invalid: true, - }, - { - name: "bmbt OK", - s: "bmbt 1 2 3 4", - stats: &xfs.Stats{ - BlockMapBTree: xfs.BTreeStats{ - Lookups: 1, - Compares: 2, - RecordsInserted: 3, - RecordsDeleted: 4, - }, - }, - }, - { - name: "dir bad", - s: "dir 1", - invalid: true, - }, - { - name: "dir OK", - s: "dir 1 2 3 4", - stats: &xfs.Stats{ - DirectoryOperation: xfs.DirectoryOperationStats{ - Lookups: 1, - Creates: 2, - Removes: 3, - Getdents: 4, - }, - }, - }, - { - name: "trans bad", - s: "trans 1", - invalid: true, - }, - { - name: "trans OK", - s: "trans 1 2 3", - stats: &xfs.Stats{ - Transaction: xfs.TransactionStats{ - Sync: 1, - Async: 2, - Empty: 3, - }, - }, - }, - { - name: "ig bad", - s: "ig 1", - invalid: true, - }, - { - name: "ig OK", - s: "ig 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - InodeOperation: xfs.InodeOperationStats{ - Attempts: 1, - Found: 2, - Recycle: 3, - Missed: 4, - Duplicate: 5, - Reclaims: 6, - AttributeChange: 7, - }, - }, - }, - { - name: "log bad", - s: "log 1", - invalid: true, - }, - { - name: "log OK", - s: "log 1 2 3 4 5", - stats: &xfs.Stats{ - LogOperation: xfs.LogOperationStats{ - Writes: 1, - Blocks: 2, - NoInternalBuffers: 3, - Force: 4, - ForceSleep: 5, - }, - }, - }, - { - name: "rw bad", - s: "rw 1", - invalid: true, - }, - { - name: "rw OK", - s: "rw 1 2", - stats: &xfs.Stats{ - ReadWrite: xfs.ReadWriteStats{ - Read: 1, - Write: 2, - }, - }, - }, - { - name: "attr bad", - s: "attr 1", - invalid: true, - }, - { - name: "attr OK", - s: "attr 1 2 3 4", - stats: &xfs.Stats{ - AttributeOperation: xfs.AttributeOperationStats{ - Get: 1, - Set: 2, - Remove: 3, - List: 4, - }, - }, - }, - { - name: "icluster bad", - s: "icluster 1", - invalid: true, - }, - { - name: "icluster OK", - s: "icluster 1 2 3", - stats: &xfs.Stats{ - InodeClustering: xfs.InodeClusteringStats{ - Iflush: 1, - Flush: 2, - FlushInode: 3, - }, - }, - }, - { - name: "vnodes bad", - s: "vnodes 1", - invalid: true, - }, - { - name: "vnodes (missing free) OK", - s: "vnodes 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - Vnode: xfs.VnodeStats{ - Active: 1, - Allocate: 2, - Get: 3, - Hold: 4, - Release: 5, - Reclaim: 6, - Remove: 7, - }, - }, - }, - { - name: "vnodes (with free) OK", - s: "vnodes 1 2 3 4 5 6 7 8", - stats: &xfs.Stats{ - Vnode: xfs.VnodeStats{ - Active: 1, - Allocate: 2, - Get: 3, - Hold: 4, - Release: 5, - Reclaim: 6, - Remove: 7, - Free: 8, - }, - }, - }, - { - name: "buf bad", - s: "buf 1", - invalid: true, - }, - { - name: "buf OK", - s: "buf 1 2 3 4 5 6 7 8 9", - stats: &xfs.Stats{ - Buffer: xfs.BufferStats{ - Get: 1, - Create: 2, - GetLocked: 3, - GetLockedWaited: 4, - BusyLocked: 5, - MissLocked: 6, - PageRetries: 7, - PageFound: 8, - GetRead: 9, - }, - }, - }, - { - name: "xpc bad", - s: "xpc 1", - invalid: true, - }, - { - name: "xpc OK", - s: "xpc 1 2 3", - stats: &xfs.Stats{ - ExtendedPrecision: xfs.ExtendedPrecisionStats{ - FlushBytes: 1, - WriteBytes: 2, - ReadBytes: 3, - }, - }, - }, - { - name: "fixtures OK", - fs: true, - stats: &xfs.Stats{ - ExtentAllocation: xfs.ExtentAllocationStats{ - ExtentsAllocated: 92447, - BlocksAllocated: 97589, - ExtentsFreed: 92448, - BlocksFreed: 93751, - }, - AllocationBTree: xfs.BTreeStats{ - Lookups: 0, - Compares: 0, - RecordsInserted: 0, - RecordsDeleted: 0, - }, - BlockMapping: xfs.BlockMappingStats{ - Reads: 1767055, - Writes: 188820, - Unmaps: 184891, - ExtentListInsertions: 92447, - ExtentListDeletions: 92448, - ExtentListLookups: 2140766, - ExtentListCompares: 0, - }, - BlockMapBTree: xfs.BTreeStats{ - Lookups: 0, - Compares: 0, - RecordsInserted: 0, - RecordsDeleted: 0, - }, - DirectoryOperation: xfs.DirectoryOperationStats{ - Lookups: 185039, - Creates: 92447, - Removes: 92444, - Getdents: 136422, - }, - Transaction: xfs.TransactionStats{ - Sync: 706, - Async: 944304, - Empty: 0, - }, - InodeOperation: xfs.InodeOperationStats{ - Attempts: 185045, - Found: 58807, - Recycle: 0, - Missed: 126238, - Duplicate: 0, - Reclaims: 33637, - AttributeChange: 22, - }, - LogOperation: xfs.LogOperationStats{ - Writes: 2883, - Blocks: 113448, - NoInternalBuffers: 9, - Force: 17360, - ForceSleep: 739, - }, - ReadWrite: xfs.ReadWriteStats{ - Read: 107739, - Write: 94045, - }, - AttributeOperation: xfs.AttributeOperationStats{ - Get: 4, - Set: 0, - Remove: 0, - List: 0, - }, - InodeClustering: xfs.InodeClusteringStats{ - Iflush: 8677, - Flush: 7849, - FlushInode: 135802, - }, - Vnode: xfs.VnodeStats{ - Active: 92601, - Allocate: 0, - Get: 0, - Hold: 0, - Release: 92444, - Reclaim: 92444, - Remove: 92444, - Free: 0, - }, - Buffer: xfs.BufferStats{ - Get: 2666287, - Create: 7122, - GetLocked: 2659202, - GetLockedWaited: 3599, - BusyLocked: 2, - MissLocked: 7085, - PageRetries: 0, - PageFound: 10297, - GetRead: 7085, - }, - ExtendedPrecision: xfs.ExtendedPrecisionStats{ - FlushBytes: 399724544, - WriteBytes: 92823103, - ReadBytes: 86219234, - }, - }, - }, - } - - for _, tt := range tests { - var ( - stats *xfs.Stats - err error - ) - - if tt.s != "" { - stats, err = xfs.ParseStats(strings.NewReader(tt.s)) - } - if tt.fs { - stats, err = procfs.FS("../fixtures").XFSStats() - } - - if tt.invalid && err == nil { - t.Error("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Errorf("unexpected error: %v", err) - } - - if want, have := tt.stats, stats; !reflect.DeepEqual(want, have) { - t.Errorf("unexpected XFS stats:\nwant:\n%v\nhave:\n%v", want, have) - } - } -} -- cgit v1.2.3-1-g7c22