From db3fe771a226f3eafffeecd040baa16eea4051ca Mon Sep 17 00:00:00 2001 From: Ta-Ching Date: Thu, 4 Feb 2016 20:00:53 +0800 Subject: [PATCH 1/5] support influxdb 0.9 --- Godeps/Godeps.json | 6 ++-- notifier/influxdb-notifier.go | 58 ++++++++++++++--------------------- 2 files changed, 26 insertions(+), 38 deletions(-) diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 842f36bf..38ea1a2d 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -38,9 +38,9 @@ "Rev": "5aa90455ce78d4d41578bafc86305e6e6b28d7d2" }, { - "ImportPath": "github.com/influxdb/influxdb/client", - "Comment": "v0.8.5", - "Rev": "9485e99796c53635fbf179b3e973c363937de00b" + "ImportPath": "github.com/influxdb/influxdb/client/v2", + "Comment": "v0.9.6", + "Rev": "7b3420b258bbc812c1ae61633ed47da873bb3800" }, { "ImportPath": "github.com/opsgenie/opsgenie-go-sdk/alerts", diff --git a/notifier/influxdb-notifier.go b/notifier/influxdb-notifier.go index edda00d6..da66ae2e 100644 --- a/notifier/influxdb-notifier.go +++ b/notifier/influxdb-notifier.go @@ -19,24 +19,21 @@ func (influxdb *InfluxdbNotifier) NotifierName() string { return influxdb.NotifName } -//Notify sends messages to the endpoint notifier func (influxdb *InfluxdbNotifier) Notify(messages Messages) bool { - config := &client.ClientConfig{ - Host: influxdb.Host, + influxdbClient, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: influxdb.Host, Username: influxdb.Username, Password: influxdb.Password, - Database: influxdb.Database, - } + }) - influxdbClient, err := client.New(config) if err != nil { log.Println("unable to access influxdb. can't send notification. ", err) return false } - seriesList := influxdb.toSeries(messages) - err = influxdbClient.WriteSeries(seriesList) + bp := influxdb.toSeries(messages) + err = influxdbClient.Write(bp) if err != nil { log.Println("unable to send notifications: ", err) @@ -47,36 +44,27 @@ func (influxdb *InfluxdbNotifier) Notify(messages Messages) bool { return true } -func (influxdb *InfluxdbNotifier) toSeries(messages Messages) []*client.Series { +func (influxdb *InfluxdbNotifier) toSeries(messages Messages) client.BatchPoints { seriesName := influxdb.SeriesName - columns := []string{ - "node", - "service", - "checks", - "notes", - "output", - "status", - } - - seriesList := make([]*client.Series, len(messages)) - for index, message := range messages { - - point := []interface{}{ - message.Node, - message.Service, - message.Check, - message.Notes, - message.Output, - message.Status, - } + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ + Database: influxdb.Database, + Precision: "s", + }) - series := &client.Series{ - Name: seriesName, - Columns: columns, - Points: [][]interface{}{point}, + for _, message := range messages { + // Create a point and add to batch + tags := map[string]string{"node": message.Node} + fields := map[string]interface{}{ + "node": message.Node, + "service": message.Service, + "check": message.Check, + "notes": message.Notes, + "output": message.Output, + "status": message.Status, } - seriesList[index] = series + pt, _ := client.NewPoint(seriesName, tags, fields, time.Now()) + bp.AddPoint(pt) } - return seriesList + return bp } From d88fbd23aeb66a301bc209d1c81140264d8775f2 Mon Sep 17 00:00:00 2001 From: Ta-Ching Date: Thu, 4 Feb 2016 20:32:35 +0800 Subject: [PATCH 2/5] update import influxdb dep --- notifier/influxdb-notifier.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notifier/influxdb-notifier.go b/notifier/influxdb-notifier.go index da66ae2e..e6ed15f3 100644 --- a/notifier/influxdb-notifier.go +++ b/notifier/influxdb-notifier.go @@ -2,7 +2,7 @@ package notifier import ( log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus" - "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/influxdb/influxdb/client" + "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2" ) type InfluxdbNotifier struct { From a937f74dfadbc6175ef6ac06bb74b254861e525f Mon Sep 17 00:00:00 2001 From: Ta-Ching Date: Thu, 4 Feb 2016 20:44:59 +0800 Subject: [PATCH 3/5] fix import --- notifier/influxdb-notifier.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/notifier/influxdb-notifier.go b/notifier/influxdb-notifier.go index e6ed15f3..12917492 100644 --- a/notifier/influxdb-notifier.go +++ b/notifier/influxdb-notifier.go @@ -1,6 +1,8 @@ package notifier import ( + "time" + log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2" ) From 74f9d2765b61c650c96ec3ffe6097e5c6d0e453a Mon Sep 17 00:00:00 2001 From: Ta-Ching Date: Thu, 4 Feb 2016 20:48:23 +0800 Subject: [PATCH 4/5] add influxdb 0.9.6 dep --- .../github.com/influxdb/influxdb/CHANGELOG.md | 1807 ++ .../influxdb/influxdb/CONTRIBUTING.md | 250 + .../github.com/influxdb/influxdb/DOCKER.md | 44 + .../github.com/influxdb/influxdb/Dockerfile | 24 + .../influxdb/Dockerfile_test_ubuntu32 | 12 + .../src/github.com/influxdb/influxdb/LICENSE | 20 + .../influxdb/LICENSE_OF_DEPENDENCIES.md | 19 + .../src/github.com/influxdb/influxdb/Makefile | 38 + .../github.com/influxdb/influxdb/QUERIES.md | 180 + .../github.com/influxdb/influxdb/README.md | 76 + .../influxdb/influxdb/build-docker.sh | 9 + .../src/github.com/influxdb/influxdb/build.py | 619 + .../influxdb/influxdb/circle-test.sh | 99 + .../github.com/influxdb/influxdb/circle.yml | 16 + .../influxdb/influxdb/client/example_test.go | 113 + .../influxdb/influxdb/client/influxdb_test.go | 560 + .../influxdb/influxdb/client/v2/client.go | 498 + .../influxdb/client/v2/client_test.go | 337 + .../influxdb/client/v2/example_test.go | 248 + .../influxdb/influxdb/cluster/balancer.go | 78 + .../influxdb/cluster/balancer_test.go | 115 + .../influxdb/influxdb/cluster/client_pool.go | 57 + .../influxdb/influxdb/cluster/config.go | 35 + .../influxdb/influxdb/cluster/config_test.go | 27 + .../influxdb/cluster/internal/data.pb.go | 154 + .../influxdb/cluster/internal/data.proto | 25 + .../influxdb/cluster/points_writer.go | 394 + .../influxdb/cluster/points_writer_test.go | 493 + .../influxdb/influxdb/cluster/rpc.go | 213 + .../influxdb/influxdb/cluster/rpc_test.go | 110 + .../influxdb/influxdb/cluster/service.go | 371 + .../influxdb/influxdb/cluster/service_test.go | 105 + .../influxdb/influxdb/cluster/shard_mapper.go | 259 + .../influxdb/cluster/shard_mapper_test.go | 110 + .../influxdb/influxdb/cluster/shard_writer.go | 165 + .../influxdb/cluster/shard_writer_test.go | 186 + .../influxdb/influxdb/cmd/influx/cli/cli.go | 786 + .../influxdb/cmd/influx/cli/cli_test.go | 442 + .../influxdb/influxdb/cmd/influx/main.go | 103 + .../influxdb/cmd/influx_inspect/info.go | 109 + .../influxdb/cmd/influx_inspect/main.go | 87 + .../influxdb/cmd/influx_inspect/tsm.go | 443 + .../cmd/influx_stress/examples/template.toml | 92 + .../cmd/influx_stress/influx_stress.go | 44 + .../influxdb/cmd/influxd/backup/backup.go | 170 + .../cmd/influxd/backup/backup_test.go | 125 + .../influxdb/cmd/influxd/help/help.go | 46 + .../influxdb/influxdb/cmd/influxd/main.go | 205 + .../influxdb/cmd/influxd/restore/restore.go | 260 + .../cmd/influxd/restore/restore_test.go | 155 + .../influxdb/cmd/influxd/run/command.go | 243 + .../influxdb/cmd/influxd/run/config.go | 233 + .../cmd/influxd/run/config_command.go | 83 + .../influxdb/cmd/influxd/run/config_test.go | 147 + .../influxdb/cmd/influxd/run/server.go | 646 + .../cmd/influxd/run/server_helpers_test.go | 377 + .../influxdb/cmd/influxd/run/server_test.go | 5460 ++++++ .../influxdb/cmd/influxd/run/server_test.md | 150 + .../github.com/influxdb/influxdb/errors.go | 45 + .../influxdb/influxdb/etc/burn-in/.rvmrc | 1 + .../influxdb/influxdb/etc/burn-in/Gemfile | 4 + .../influxdb/etc/burn-in/Gemfile.lock | 14 + .../influxdb/influxdb/etc/burn-in/burn-in.rb | 79 + .../influxdb/influxdb/etc/burn-in/log.rb | 23 + .../influxdb/etc/burn-in/random_gaussian.rb | 31 + .../influxdb/etc/burn-in/random_points.rb | 29 + .../influxdb/influxdb/etc/config.sample.toml | 323 + .../influxdb/influxdb/importer/README.md | 193 + .../influxdb/influxdb/importer/v8/importer.go | 248 + .../influxdb/influxdb/influxql/INFLUXQL.md | 707 + .../influxdb/influxdb/influxql/NOTES | 682 + .../influxdb/influxdb/influxql/ast.go | 3464 ++++ .../influxdb/influxdb/influxql/ast_test.go | 762 + .../influxdb/influxdb/influxql/doc.go | 64 + .../influxdb/influxdb/influxql/parser.go | 2524 +++ .../influxdb/influxdb/influxql/parser_test.go | 2169 +++ .../influxdb/influxdb/influxql/result.go | 183 + .../influxdb/influxdb/influxql/scanner.go | 565 + .../influxdb/influxql/scanner_test.go | 292 + .../influxdb/influxdb/influxql/token.go | 314 + .../github.com/influxdb/influxdb/influxvar.go | 45 + .../influxdb/influxdb/meta/config.go | 59 + .../influxdb/influxdb/meta/config_test.go | 39 + .../github.com/influxdb/influxdb/meta/data.go | 1294 ++ .../influxdb/influxdb/meta/data_test.go | 819 + .../influxdb/influxdb/meta/errors.go | 132 + .../influxdb/meta/internal/meta.pb.go | 1689 ++ .../influxdb/meta/internal/meta.proto | 377 + .../influxdb/influxdb/meta/proxy.go | 62 + .../github.com/influxdb/influxdb/meta/rpc.go | 536 + .../influxdb/influxdb/meta/rpc_test.go | 248 + .../influxdb/influxdb/meta/state.go | 514 + .../influxdb/meta/statement_executor.go | 410 + .../influxdb/meta/statement_executor_test.go | 1174 ++ .../influxdb/influxdb/meta/store.go | 2324 +++ .../influxdb/influxdb/meta/store_test.go | 1406 ++ .../influxdb/influxdb/models/points.go | 1389 ++ .../influxdb/influxdb/models/points_test.go | 1581 ++ .../influxdb/influxdb/models/rows.go | 59 + .../influxdb/influxdb/monitor/README.md | 73 + .../influxdb/influxdb/monitor/build_info.go | 20 + .../influxdb/influxdb/monitor/config.go | 35 + .../influxdb/influxdb/monitor/config_test.go | 30 + .../influxdb/influxdb/monitor/go_runtime.go | 19 + .../influxdb/influxdb/monitor/network.go | 21 + .../influxdb/influxdb/monitor/service.go | 439 + .../influxdb/influxdb/monitor/service_test.go | 72 + .../influxdb/monitor/statement_executor.go | 81 + .../influxdb/influxdb/monitor/system.go | 26 + .../github.com/influxdb/influxdb/nightly.sh | 57 + .../github.com/influxdb/influxdb/package.sh | 569 + .../influxdb/influxdb/pkg/READEME.md | 5 + .../influxdb/influxdb/pkg/escape/bytes.go | 45 + .../influxdb/pkg/escape/bytes_test.go | 45 + .../influxdb/influxdb/pkg/escape/strings.go | 34 + .../influxdb/influxdb/pkg/slices/strings.go | 40 + .../influxdb/scripts/influxdb.service | 21 + .../influxdb/influxdb/scripts/init.sh | 219 + .../influxdb/influxdb/scripts/logrotate | 8 + .../influxdb/influxdb/scripts/post-install.sh | 43 + .../influxdb/scripts/post-uninstall.sh | 17 + .../influxdb/influxdb/scripts/pre-install.sh | 10 + .../influxdb/services/admin/config.go | 23 + .../influxdb/services/admin/config_test.go | 32 + .../influxdb/services/admin/service.go | 111 + .../influxdb/services/admin/service_test.go | 33 + .../influxdb/services/collectd/README.md | 35 + .../services/collectd/collectd_test.conf | 209 + .../influxdb/services/collectd/config.go | 69 + .../influxdb/services/collectd/config_test.go | 32 + .../influxdb/services/collectd/service.go | 320 + .../services/collectd/service_test.go | 501 + .../services/collectd/test_client/README.md | 3 + .../services/collectd/test_client/client.go | 71 + .../services/continuous_querier/config.go | 65 + .../continuous_querier/config_test.go | 36 + .../continuous_querier/continuous_queries.md | 236 + .../services/continuous_querier/service.go | 404 + .../continuous_querier/service_test.go | 458 + .../services/copier/internal/internal.pb.go | 56 + .../services/copier/internal/internal.proto | 9 + .../influxdb/services/copier/service.go | 261 + .../influxdb/services/copier/service_test.go | 185 + .../influxdb/services/graphite/README.md | 194 + .../influxdb/services/graphite/config.go | 238 + .../influxdb/services/graphite/config_test.go | 167 + .../influxdb/services/graphite/parser.go | 388 + .../influxdb/services/graphite/parser_test.go | 663 + .../influxdb/services/graphite/service.go | 383 + .../services/graphite/service_test.go | 184 + .../influxdb/influxdb/services/hh/config.go | 58 + .../influxdb/services/hh/config_test.go | 73 + .../influxdb/influxdb/services/hh/doc.go | 5 + .../influxdb/influxdb/services/hh/limiter.go | 61 + .../influxdb/services/hh/limiter_test.go | 47 + .../influxdb/services/hh/node_processor.go | 293 + .../services/hh/node_processor_test.go | 155 + .../influxdb/influxdb/services/hh/queue.go | 717 + .../influxdb/services/hh/queue_test.go | 327 + .../influxdb/influxdb/services/hh/service.go | 270 + .../influxdb/services/httpd/config.go | 22 + .../influxdb/services/httpd/config_test.go | 52 + .../influxdb/services/httpd/handler.go | 940 + .../influxdb/services/httpd/handler_test.go | 549 + .../services/httpd/response_logger.go | 153 + .../influxdb/services/httpd/service.go | 137 + .../influxdb/services/opentsdb/README.md | 10 + .../influxdb/services/opentsdb/config.go | 59 + .../influxdb/services/opentsdb/config_test.go | 41 + .../influxdb/services/opentsdb/handler.go | 186 + .../influxdb/services/opentsdb/service.go | 397 + .../services/opentsdb/service_test.go | 167 + .../influxdb/services/precreator/README.md | 13 + .../influxdb/services/precreator/config.go | 32 + .../services/precreator/config_test.go | 31 + .../influxdb/services/precreator/service.go | 100 + .../services/precreator/service_test.go | 59 + .../influxdb/services/registration/config.go | 27 + .../services/registration/config_test.go | 33 + .../influxdb/services/registration/service.go | 204 + .../influxdb/services/retention/config.go | 16 + .../services/retention/config_test.go | 27 + .../influxdb/services/retention/service.go | 135 + .../influxdb/services/snapshotter/service.go | 145 + .../services/snapshotter/service_test.go | 1 + .../influxdb/services/subscriber/config.go | 10 + .../services/subscriber/config_test.go | 23 + .../influxdb/services/subscriber/service.go | 269 + .../services/subscriber/service_test.go | 448 + .../influxdb/services/subscriber/udp.go | 40 + .../influxdb/influxdb/services/udp/README.md | 125 + .../influxdb/influxdb/services/udp/config.go | 69 + .../influxdb/services/udp/config_test.go | 42 + .../influxdb/influxdb/services/udp/service.go | 230 + .../influxdb/influxdb/shared/admin/README.md | 15 + .../influxdb/shared/admin/css/admin.css | 87 + .../influxdb/shared/admin/css/bootstrap.css | 6584 +++++++ .../admin/css/dropdowns-enhancement.css | 294 + .../fonts/glyphicons-halflings-regular.eot | Bin 0 -> 20127 bytes .../fonts/glyphicons-halflings-regular.svg | 288 + .../fonts/glyphicons-halflings-regular.ttf | Bin 0 -> 45404 bytes .../fonts/glyphicons-halflings-regular.woff | Bin 0 -> 23424 bytes .../fonts/glyphicons-halflings-regular.woff2 | Bin 0 -> 18028 bytes .../shared/admin/img/influxdb-light400.png | Bin 0 -> 19775 bytes .../influxdb/influxdb/shared/admin/index.html | 200 + .../influxdb/shared/admin/js/admin.js | 466 + .../admin/js/vendor/bootstrap-3.3.5.min.js | 7 + .../admin/js/vendor/jquery-2.1.4.min.js | 4 + .../admin/js/vendor/react-0.13.3.min.js | 16 + .../influxdb/influxdb/snapshot/snapshot.go | 529 + .../influxdb/snapshot/snapshot_test.go | 293 + .../influxdb/influxdb/statik/statik.go | 10 + .../influxdb/influxdb/stress/README.md | 47 + .../influxdb/influxdb/stress/basic.go | 542 + .../influxdb/influxdb/stress/config.go | 96 + .../influxdb/influxdb/stress/run.go | 344 + .../influxdb/influxdb/stress/stress.toml | 53 + .../influxdb/influxdb/stress/stress_test.go | 597 + .../stress/stress_test_server/server.go | 73 + .../influxdb/influxdb/stress/template.go | 63 + .../influxdb/influxdb/stress/util.go | 132 + .../github.com/influxdb/influxdb/tcp/mux.go | 154 + .../influxdb/influxdb/tcp/mux_test.go | 137 + .../influxdb/influxdb/test-32bit-docker.sh | 4 + .../influxdb/influxdb/tests/README.md | 4 + .../influxdb/tests/create_future_writes.sh | 22 + .../tests/create_write_multiple_query.sh | 14 + .../tests/create_write_single_query.sh | 19 + ..._with_multiple_measurements_values_tags.sh | 23 + ...e_write_single_with_multiple_tags_query.sh | 11 + .../influxdb/tests/distinct-data-scenarios.sh | 35 + .../influxdb/tests/read_write_gzip.sh | 15 + .../influxdb/influxdb/tests/siege/.gitignore | 1 + .../influxdb/influxdb/tests/siege/README.md | 66 + .../influxdb/influxdb/tests/siege/urlgen | 107 + .../influxdb/influxdb/tests/tmux/3_shards | 28 + .../influxdb/influxdb/tests/tmux/README.md | 31 + .../influxdb/influxdb/tests/tmux/sample.json | 16000 ++++++++++++++++ .../influxdb/influxdb/tests/tmux/seed.sh | 13 + .../influxdb/tests/tmux/server_8086.toml | 7 + .../influxdb/tests/tmux/server_8087.toml | 7 + .../influxdb/tests/tmux/server_8088.toml | 7 + .../influxdb/influxdb/tests/urlgen/urlgen.go | 58 + .../github.com/influxdb/influxdb/toml/toml.go | 72 + .../influxdb/influxdb/toml/toml_test.go | 45 + .../influxdb/influxdb/tsdb/README.md | 91 + .../influxdb/influxdb/tsdb/aggregate.go | 892 + .../influxdb/influxdb/tsdb/batcher.go | 147 + .../influxdb/influxdb/tsdb/batcher_test.go | 146 + .../influxdb/influxdb/tsdb/config.go | 153 + .../influxdb/influxdb/tsdb/cursor.go | 408 + .../influxdb/influxdb/tsdb/cursor_test.go | 333 + .../github.com/influxdb/influxdb/tsdb/doc.go | 5 + .../influxdb/influxdb/tsdb/engine.go | 194 + .../influxdb/influxdb/tsdb/engine/b1/b1.go | 812 + .../influxdb/tsdb/engine/b1/b1_test.go | 198 + .../influxdb/influxdb/tsdb/engine/bz1/bz1.go | 878 + .../influxdb/tsdb/engine/bz1/bz1_test.go | 486 + .../influxdb/influxdb/tsdb/engine/engine.go | 7 + .../influxdb/tsdb/engine/tsm1/DESIGN.md | 421 + .../influxdb/tsdb/engine/tsm1/bool.go | 141 + .../influxdb/tsdb/engine/tsm1/bool_test.go | 107 + .../influxdb/tsdb/engine/tsm1/cache.go | 333 + .../influxdb/tsdb/engine/tsm1/cache_test.go | 321 + .../influxdb/tsdb/engine/tsm1/cursor.go | 486 + .../influxdb/tsdb/engine/tsm1/cursor_test.go | 204 + .../influxdb/tsdb/engine/tsm1/data_file.go | 949 + .../tsdb/engine/tsm1/data_file_test.go | 514 + .../influxdb/tsdb/engine/tsm1/encoding.go | 623 + .../tsdb/engine/tsm1/encoding_test.go | 529 + .../influxdb/tsdb/engine/tsm1/file_store.go | 213 + .../tsdb/engine/tsm1/file_store_test.go | 283 + .../influxdb/tsdb/engine/tsm1/float.go | 241 + .../influxdb/tsdb/engine/tsm1/float_test.go | 269 + .../influxdb/influxdb/tsdb/engine/tsm1/int.go | 293 + .../influxdb/tsdb/engine/tsm1/int_test.go | 522 + .../influxdb/tsdb/engine/tsm1/string.go | 96 + .../influxdb/tsdb/engine/tsm1/string_test.go | 123 + .../influxdb/tsdb/engine/tsm1/timestamp.go | 309 + .../tsdb/engine/tsm1/timestamp_test.go | 465 + .../influxdb/tsdb/engine/tsm1/tombstone.go | 116 + .../tsdb/engine/tsm1/tombstone_test.go | 95 + .../influxdb/tsdb/engine/tsm1/tsm1.go | 2371 +++ .../influxdb/tsdb/engine/tsm1/tsm1_test.go | 1874 ++ .../influxdb/influxdb/tsdb/engine/tsm1/tx.go | 69 + .../influxdb/influxdb/tsdb/engine/tsm1/wal.go | 816 + .../influxdb/tsdb/engine/tsm1/wal_test.go | 553 + .../influxdb/tsdb/engine/tsm1/write_lock.go | 96 + .../tsdb/engine/tsm1/write_lock_test.go | 166 + .../influxdb/influxdb/tsdb/engine/wal/wal.go | 1612 ++ .../influxdb/tsdb/engine/wal/wal_test.go | 740 + .../influxdb/influxdb/tsdb/engine_test.go | 3 + .../influxdb/influxdb/tsdb/executor.go | 8 + .../influxdb/influxdb/tsdb/functions.go | 1711 ++ .../influxdb/influxdb/tsdb/functions_test.go | 865 + .../influxdb/tsdb/internal/meta.pb.go | 122 + .../influxdb/tsdb/internal/meta.proto | 27 + .../github.com/influxdb/influxdb/tsdb/into.go | 61 + .../influxdb/influxdb/tsdb/mapper.go | 149 + .../influxdb/influxdb/tsdb/mapper_test.go | 614 + .../github.com/influxdb/influxdb/tsdb/meta.go | 1595 ++ .../influxdb/influxdb/tsdb/meta_test.go | 302 + .../influxdb/influxdb/tsdb/query_executor.go | 1056 + .../influxdb/tsdb/query_executor_test.go | 493 + .../github.com/influxdb/influxdb/tsdb/raw.go | 950 + .../influxdb/influxdb/tsdb/raw_test.go | 1044 + .../influxdb/influxdb/tsdb/shard.go | 797 + .../influxdb/influxdb/tsdb/shard_test.go | 348 + .../influxdb/tsdb/show_measurements.go | 247 + .../influxdb/influxdb/tsdb/show_tag_keys.go | 315 + .../influxdb/influxdb/tsdb/snapshot_writer.go | 123 + .../influxdb/influxdb/tsdb/store.go | 455 + .../influxdb/influxdb/tsdb/store_test.go | 346 + .../github.com/influxdb/influxdb/uuid/uuid.go | 95 + 314 files changed, 119284 insertions(+) create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/CHANGELOG.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/CONTRIBUTING.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/DOCKER.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile_test_ubuntu32 create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE_OF_DEPENDENCIES.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/Makefile create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/QUERIES.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/README.md create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/build-docker.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/build.py create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/circle-test.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/circle.yml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/client/example_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/client/influxdb_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/example_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/client_pool.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.pb.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.proto create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/main.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/info.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/main.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/tsm.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/examples/template.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/influx_stress.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/help/help.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/main.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/command.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_command.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_helpers_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/errors.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/.rvmrc create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile.lock create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/burn-in.rb create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/log.rb create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_gaussian.rb create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_points.rb create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/etc/config.sample.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/importer/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/importer/v8/importer.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/INFLUXQL.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/NOTES create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/ast.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/ast_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/doc.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/parser.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/parser_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/result.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/scanner.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/scanner_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/token.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/influxvar.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/data.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/data_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/errors.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/internal/meta.pb.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/internal/meta.proto create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/proxy.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/rpc.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/rpc_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/state.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/statement_executor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/statement_executor_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/store.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/meta/store_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/models/points.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/models/points_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/models/rows.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/build_info.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/go_runtime.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/network.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/statement_executor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/monitor/system.go create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/nightly.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/package.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/pkg/READEME.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/pkg/escape/bytes.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/pkg/escape/bytes_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/pkg/escape/strings.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/pkg/slices/strings.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/influxdb.service create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/init.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/logrotate create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/post-install.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/post-uninstall.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/scripts/pre-install.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/admin/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/admin/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/admin/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/admin/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/collectd_test.conf create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/test_client/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/collectd/test_client/client.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/continuous_querier/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/continuous_querier/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/continuous_querier/continuous_queries.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/continuous_querier/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/continuous_querier/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/copier/internal/internal.pb.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/copier/internal/internal.proto create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/copier/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/copier/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/parser.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/parser_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/graphite/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/doc.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/limiter.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/limiter_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/node_processor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/node_processor_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/queue.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/queue_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/hh/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/handler.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/handler_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/response_logger.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/httpd/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/handler.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/opentsdb/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/precreator/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/precreator/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/precreator/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/precreator/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/precreator/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/registration/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/registration/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/registration/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/retention/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/retention/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/retention/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/snapshotter/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/snapshotter/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/subscriber/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/subscriber/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/subscriber/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/subscriber/service_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/subscriber/udp.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/udp/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/udp/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/udp/config_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/services/udp/service.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/css/admin.css create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/css/bootstrap.css create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/css/dropdowns-enhancement.css create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/fonts/glyphicons-halflings-regular.eot create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/fonts/glyphicons-halflings-regular.svg create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/fonts/glyphicons-halflings-regular.ttf create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/fonts/glyphicons-halflings-regular.woff create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/fonts/glyphicons-halflings-regular.woff2 create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/img/influxdb-light400.png create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/index.html create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/js/admin.js create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/js/vendor/bootstrap-3.3.5.min.js create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/js/vendor/jquery-2.1.4.min.js create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/shared/admin/js/vendor/react-0.13.3.min.js create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/snapshot/snapshot.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/snapshot/snapshot_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/statik/statik.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/basic.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/run.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/stress.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/stress_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/stress_test_server/server.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/template.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/stress/util.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tcp/mux.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tcp/mux_test.go create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/test-32bit-docker.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/README.md create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/create_future_writes.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/create_write_multiple_query.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/create_write_single_query.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/create_write_single_with_multiple_measurements_values_tags.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/create_write_single_with_multiple_tags_query.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/distinct-data-scenarios.sh create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/read_write_gzip.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/siege/.gitignore create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/siege/README.md create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/siege/urlgen create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/3_shards create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/sample.json create mode 100755 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/seed.sh create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/server_8086.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/server_8087.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/tmux/server_8088.toml create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tests/urlgen/urlgen.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/toml/toml.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/toml/toml_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/README.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/aggregate.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/batcher.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/batcher_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/config.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/cursor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/cursor_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/doc.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/b1/b1.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/b1/b1_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/bz1/bz1.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/bz1/bz1_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/engine.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/DESIGN.md create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/bool.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/bool_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/cache.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/cache_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/cursor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/cursor_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/data_file.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/data_file_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/encoding.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/encoding_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/file_store.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/file_store_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/float.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/float_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/int.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/int_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/string.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/string_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/timestamp.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/timestamp_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/tombstone.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/tombstone_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/tsm1.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/tsm1_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/tx.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/wal.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/wal_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/write_lock.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/tsm1/write_lock_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/wal/wal.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine/wal/wal_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/engine_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/executor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/functions.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/functions_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/internal/meta.pb.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/internal/meta.proto create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/into.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/mapper.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/mapper_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/meta.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/meta_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/query_executor.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/query_executor_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/raw.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/raw_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/shard.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/shard_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/show_measurements.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/show_tag_keys.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/snapshot_writer.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/store.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/tsdb/store_test.go create mode 100644 Godeps/_workspace/src/github.com/influxdb/influxdb/uuid/uuid.go diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/CHANGELOG.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/CHANGELOG.md new file mode 100644 index 00000000..e9d09829 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/CHANGELOG.md @@ -0,0 +1,1807 @@ +## v0.9.6 [unreleased] + +### Features +- [#4790](https://github.com/influxdb/influxdb/pull/4790): Allow openTSDB point-level error logging to be disabled + +### Bugfixes +- [#4768](https://github.com/influxdb/influxdb/pull/4768): CLI history skips blank lines. Thanks @pires +- [#4766](https://github.com/influxdb/influxdb/pull/4766): Update CLI usage output. Thanks @aneshas +- [#4804](https://github.com/influxdb/influxdb/pull/4804): Complete lint for services/admin. Thanks @nii236 +- [#4796](https://github.com/influxdb/influxdb/pull/4796): Check point without fields. Thanks @CrazyJvm + +## v0.9.5 [unreleased] + +### Release Notes + +- Field names for the internal stats have been changed to be more inline with Go style. +- 0.9.5 is reverting to Go 1.4.2 due to unresolved issues with Go 1.5.1. + +There are breaking changes in this release: +- The filesystem hierarchy for packages has been changed, namely: + - Binaries are now located in `/usr/bin` (previously `/opt/influxdb`) + - Configuration files are now located in `/etc/influxdb` (previously `/etc/opt/influxdb`) + - Data directories are now located in `/var/lib/influxdb` (previously `/var/opt/influxdb`) + - Scripts are now located in `/usr/lib/influxdb/scripts` (previously `/opt/influxdb`) + +### Features +- [#4098](https://github.com/influxdb/influxdb/pull/4702): Support 'history' command at CLI +- [#4098](https://github.com/influxdb/influxdb/issues/4098): Enable `golint` on the code base - uuid subpackage +- [#4141](https://github.com/influxdb/influxdb/pull/4141): Control whether each query should be logged +- [#4065](https://github.com/influxdb/influxdb/pull/4065): Added precision support in cmd client. Thanks @sbouchex +- [#4140](https://github.com/influxdb/influxdb/pull/4140): Make storage engine configurable +- [#4161](https://github.com/influxdb/influxdb/pull/4161): Implement bottom selector function +- [#4204](https://github.com/influxdb/influxdb/pull/4204): Allow module-level selection for SHOW STATS +- [#4208](https://github.com/influxdb/influxdb/pull/4208): Allow module-level selection for SHOW DIAGNOSTICS +- [#4196](https://github.com/influxdb/influxdb/pull/4196): Export tsdb.Iterator +- [#4198](https://github.com/influxdb/influxdb/pull/4198): Add basic cluster-service stats +- [#4262](https://github.com/influxdb/influxdb/pull/4262): Allow configuration of UDP retention policy +- [#4265](https://github.com/influxdb/influxdb/pull/4265): Add statistics for Hinted-Handoff +- [#4284](https://github.com/influxdb/influxdb/pull/4284): Add exponential backoff for hinted-handoff failures +- [#4310](https://github.com/influxdb/influxdb/pull/4310): Support dropping non-Raft nodes. Work mostly by @corylanou +- [#4348](https://github.com/influxdb/influxdb/pull/4348): Public ApplyTemplate function for graphite parser. +- [#4178](https://github.com/influxdb/influxdb/pull/4178): Support fields in graphite parser. Thanks @roobert! +- [#4409](https://github.com/influxdb/influxdb/pull/4409): wire up INTO queries. +- [#4379](https://github.com/influxdb/influxdb/pull/4379): Auto-create database for UDP input. +- [#4375](https://github.com/influxdb/influxdb/pull/4375): Add Subscriptions so data can be 'forked' out of InfluxDB to another third party. +- [#4506](https://github.com/influxdb/influxdb/pull/4506): Register with Enterprise service and upload stats, if token is available. +- [#4516](https://github.com/influxdb/influxdb/pull/4516): Hinted-handoff refactor, with new statistics and diagnostics +- [#4501](https://github.com/influxdb/influxdb/pull/4501): Allow filtering SHOW MEASUREMENTS by regex. +- [#4547](https://github.com/influxdb/influxdb/pull/4547): Allow any node to be dropped, even a raft node (even the leader). +- [#4600](https://github.com/influxdb/influxdb/pull/4600): ping endpoint can wait for leader +- [#4648](https://github.com/influxdb/influxdb/pull/4648): UDP Client (v2 client) +- [#4690](https://github.com/influxdb/influxdb/pull/4690): SHOW SHARDS now includes database and policy. Thanks @pires +- [#4676](https://github.com/influxdb/influxdb/pull/4676): UDP service listener performance enhancements +- [#4659](https://github.com/influxdb/influxdb/pull/4659): Support IF EXISTS for DROP DATABASE. Thanks @ch33hau +- [#4721](https://github.com/influxdb/influxdb/pull/4721): Export tsdb.InterfaceValues +- [#4681](https://github.com/influxdb/influxdb/pull/4681): Increase default buffer size for collectd and graphite listeners +- [#4659](https://github.com/influxdb/influxdb/pull/4659): Support IF EXISTS for DROP DATABASE +- [#4685](https://github.com/influxdb/influxdb/pull/4685): Automatically promote node to raft peer if drop server results in removing a raft peer. + +### Bugfixes +- [#4193](https://github.com/influxdb/influxdb/issues/4193): Less than or equal to inequality is not inclusive for time in where clause +- [#4235](https://github.com/influxdb/influxdb/issues/4235): "ORDER BY DESC" doesn't properly order +- [#4789](https://github.com/influxdb/influxdb/pull/4789): Decode WHERE fields during aggregates. Fix [issue #4701](https://github.com/influxdb/influxdb/issues/4701). +- [#4778](https://github.com/influxdb/influxdb/pull/4778): If there are no points to count, count is 0. +- [#4715](https://github.com/influxdb/influxdb/pull/4715): Fix panic during Raft-close. Fix [issue #4707](https://github.com/influxdb/influxdb/issues/4707). Thanks @oiooj +- [#4643](https://github.com/influxdb/influxdb/pull/4643): Fix panic during backup restoration. Thanks @oiooj +- [#4632](https://github.com/influxdb/influxdb/pull/4632): Fix parsing of IPv6 hosts in client package. Thanks @miguelxpn +- [#4389](https://github.com/influxdb/influxdb/pull/4389): Don't add a new segment file on each hinted-handoff purge cycle. +- [#4166](https://github.com/influxdb/influxdb/pull/4166): Fix parser error on invalid SHOW +- [#3457](https://github.com/influxdb/influxdb/issues/3457): [0.9.3] cannot select field names with prefix + "." that match the measurement name +- [#4704](https://github.com/influxdb/influxdb/pull/4704). Tighten up command parsing within CLI. Thanks @pires +- [#4225](https://github.com/influxdb/influxdb/pull/4225): Always display diags in name-sorted order +- [#4111](https://github.com/influxdb/influxdb/pull/4111): Update pre-commit hook for go vet composites +- [#4136](https://github.com/influxdb/influxdb/pull/4136): Return an error-on-write if target retention policy does not exist. Thanks for the report @ymettier +- [#4228](https://github.com/influxdb/influxdb/pull/4228): Add build timestamp to version information. +- [#4124](https://github.com/influxdb/influxdb/issues/4124): Missing defer/recover/panic idiom in HTTPD service +- [#4238](https://github.com/influxdb/influxdb/pull/4238): Fully disable hinted-handoff service if so requested. +- [#4165](https://github.com/influxdb/influxdb/pull/4165): Tag all Go runtime stats when writing to internal database. +- [#4586](https://github.com/influxdb/influxdb/pull/4586): Exit when invalid engine is selected +- [#4118](https://github.com/influxdb/influxdb/issues/4118): Return consistent, correct result for SHOW MEASUREMENTS with multiple AND conditions +- [#4191](https://github.com/influxdb/influxdb/pull/4191): Correctly marshal remote mapper responses. Fixes [#4170](https://github.com/influxdb/influxdb/issues/4170) +- [#4222](https://github.com/influxdb/influxdb/pull/4222): Graphite TCP connections should not block shutdown +- [#4180](https://github.com/influxdb/influxdb/pull/4180): Cursor & SelectMapper Refactor +- [#1577](https://github.com/influxdb/influxdb/issues/1577): selectors (e.g. min, max, first, last) should have equivalents to return the actual point +- [#4264](https://github.com/influxdb/influxdb/issues/4264): Refactor map functions to use list of values +- [#4278](https://github.com/influxdb/influxdb/pull/4278): Fix error marshalling across the cluster +- [#4149](https://github.com/influxdb/influxdb/pull/4149): Fix derivative unnecessarily requires aggregate function. Thanks @peekeri! +- [#4674](https://github.com/influxdb/influxdb/pull/4674): Fix panic during restore. Thanks @simcap. +- [#4725](https://github.com/influxdb/influxdb/pull/4725): Don't list deleted shards during SHOW SHARDS. +- [#4237](https://github.com/influxdb/influxdb/issues/4237): DERIVATIVE() edge conditions +- [#4263](https://github.com/influxdb/influxdb/issues/4263): derivative does not work when data is missing +- [#4293](https://github.com/influxdb/influxdb/pull/4293): Ensure shell is invoked when touching PID file. Thanks @christopherjdickson +- [#4296](https://github.com/influxdb/influxdb/pull/4296): Reject line protocol ending with '-'. Fixes [#4272](https://github.com/influxdb/influxdb/issues/4272) +- [#4333](https://github.com/influxdb/influxdb/pull/4333): Retry monitor storage creation and storage only on Leader. +- [#4276](https://github.com/influxdb/influxdb/issues/4276): Walk DropSeriesStatement & check for empty sources +- [#4465](https://github.com/influxdb/influxdb/pull/4465): Actually display a message if the CLI can't connect to the database. +- [#4342](https://github.com/influxdb/influxdb/pull/4342): Fix mixing aggregates and math with non-aggregates. Thanks @kostya-sh. +- [#4349](https://github.com/influxdb/influxdb/issues/4349): If HH can't unmarshal a block, skip that block. +- [#4502](https://github.com/influxdb/influxdb/pull/4502): Don't crash on Graphite close, if Graphite not fully open. Thanks for the report @ranjib +- [#4354](https://github.com/influxdb/influxdb/pull/4353): Fully lock node queues during hinted handoff. Fixes one cause of missing data on clusters. +- [#4357](https://github.com/influxdb/influxdb/issues/4357): Fix similar float values encoding overflow Thanks @dgryski! +- [#4344](https://github.com/influxdb/influxdb/issues/4344): Make client.Write default to client.precision if none is given. +- [#3429](https://github.com/influxdb/influxdb/issues/3429): Incorrect parsing of regex containing '/' +- [#4374](https://github.com/influxdb/influxdb/issues/4374): Add tsm1 quickcheck tests +- [#4644](https://github.com/influxdb/influxdb/pull/4644): Check for response errors during token check, fixes issue [#4641](https://github.com/influxdb/influxdb/issues/4641) +- [#4377](https://github.com/influxdb/influxdb/pull/4377): Hinted handoff should not process dropped nodes +- [#4365](https://github.com/influxdb/influxdb/issues/4365): Prevent panic in DecodeSameTypeBlock +- [#4280](https://github.com/influxdb/influxdb/issues/4280): Only drop points matching WHERE clause +- [#4443](https://github.com/influxdb/influxdb/pull/4443): Fix race condition while listing store's shards. Fixes [#4442](https://github.com/influxdb/influxdb/issues/4442) +- [#4410](https://github.com/influxdb/influxdb/pull/4410): Fix infinite recursion in statement string(). Thanks @kostya-sh +- [#4360](https://github.com/influxdb/influxdb/issues/4360): Aggregate Selectors overwrite values during post-processing +- [#4421](https://github.com/influxdb/influxdb/issues/4421): Fix line protocol accepting tags with no values +- [#4434](https://github.com/influxdb/influxdb/pull/4434): Allow 'E' for scientific values. Fixes [#4433](https://github.com/influxdb/influxdb/issues/4433) +- [#4431](https://github.com/influxdb/influxdb/issues/4431): Add tsm1 WAL QuickCheck +- [#4438](https://github.com/influxdb/influxdb/pull/4438): openTSDB service shutdown fixes +- [#4447](https://github.com/influxdb/influxdb/pull/4447): Fixes to logrotate file. Thanks @linsomniac. +- [#3820](https://github.com/influxdb/influxdb/issues/3820): Fix js error in admin UI. +- [#4460](https://github.com/influxdb/influxdb/issues/4460): tsm1 meta lint +- [#4415](https://github.com/influxdb/influxdb/issues/4415): Selector (like max, min, first, etc) return a string instead of timestamp +- [#4472](https://github.com/influxdb/influxdb/issues/4472): Fix 'too many points in GROUP BY interval' error +- [#4475](https://github.com/influxdb/influxdb/issues/4475): Fix SHOW TAG VALUES error message. +- [#4486](https://github.com/influxdb/influxdb/pull/4486): Fix missing comments for runner package +- [#4497](https://github.com/influxdb/influxdb/pull/4497): Fix sequence in meta proto +- [#3367](https://github.com/influxdb/influxdb/issues/3367): Negative timestamps are parsed correctly by the line protocol. +- [#4563](https://github.com/influxdb/influxdb/pull/4536): Fix broken subscriptions updates. +- [#4538](https://github.com/influxdb/influxdb/issues/4538): Dropping database under a write load causes panics +- [#4582](https://github.com/influxdb/influxdb/pull/4582): Correct logging tags in cluster and TCP package. Thanks @oiooj +- [#4513](https://github.com/influxdb/influxdb/issues/4513): TSM1: panic: runtime error: index out of range +- [#4521](https://github.com/influxdb/influxdb/issues/4521): TSM1: panic: decode of short block: got 1, exp 9 +- [#4587](https://github.com/influxdb/influxdb/pull/4587): Prevent NaN float values from being stored +- [#4596](https://github.com/influxdb/influxdb/pull/4596): Skip empty string for start position when parsing line protocol @Thanks @ch33hau +- [#4610](https://github.com/influxdb/influxdb/pull/4610): Make internal stats names consistent with Go style. +- [#4625](https://github.com/influxdb/influxdb/pull/4625): Correctly handle bad write requests. Thanks @oiooj. +- [#4650](https://github.com/influxdb/influxdb/issues/4650): Importer should skip empty lines +- [#4651](https://github.com/influxdb/influxdb/issues/4651): Importer doesn't flush out last batch +- [#4602](https://github.com/influxdb/influxdb/issues/4602): Fixes data race between PointsWriter and Subscriber services. +- [#4691](https://github.com/influxdb/influxdb/issues/4691): Enable toml test `TestConfig_Encode`. +- [#4283](https://github.com/influxdb/influxdb/pull/4283): Disable HintedHandoff if configuration is not set. +- [#4703](https://github.com/influxdb/influxdb/pull/4703): Complete lint for cmd/influx. Thanks @pablolmiranda + +## v0.9.4 [2015-09-14] + +### Release Notes +With this release InfluxDB is moving to Go 1.5. + +### Features +- [#4050](https://github.com/influxdb/influxdb/pull/4050): Add stats to collectd +- [#3771](https://github.com/influxdb/influxdb/pull/3771): Close idle Graphite TCP connections +- [#3755](https://github.com/influxdb/influxdb/issues/3755): Add option to build script. Thanks @fg2it +- [#3863](https://github.com/influxdb/influxdb/pull/3863): Move to Go 1.5 +- [#3892](https://github.com/influxdb/influxdb/pull/3892): Support IF NOT EXISTS for CREATE DATABASE +- [#3916](https://github.com/influxdb/influxdb/pull/3916): New statistics and diagnostics support. Graphite first to be instrumented. +- [#3901](https://github.com/influxdb/influxdb/pull/3901): Add consistency level option to influx cli Thanks @takayuki +- [#4048](https://github.com/influxdb/influxdb/pull/4048): Add statistics to Continuous Query service +- [#4049](https://github.com/influxdb/influxdb/pull/4049): Add stats to the UDP input +- [#3876](https://github.com/influxdb/influxdb/pull/3876): Allow the following syntax in CQs: INTO "1hPolicy".:MEASUREMENT +- [#3975](https://github.com/influxdb/influxdb/pull/3975): Add shard copy service +- [#3986](https://github.com/influxdb/influxdb/pull/3986): Support sorting by time desc +- [#3930](https://github.com/influxdb/influxdb/pull/3930): Wire up TOP aggregate function - fixes [#1821](https://github.com/influxdb/influxdb/issues/1821) +- [#4045](https://github.com/influxdb/influxdb/pull/4045): Instrument cluster-level points writer +- [#3996](https://github.com/influxdb/influxdb/pull/3996): Add statistics to httpd package +- [#4003](https://github.com/influxdb/influxdb/pull/4033): Add logrotate configuration. +- [#4043](https://github.com/influxdb/influxdb/pull/4043): Add stats and batching to openTSDB input +- [#4042](https://github.com/influxdb/influxdb/pull/4042): Add pending batches control to batcher +- [#4006](https://github.com/influxdb/influxdb/pull/4006): Add basic statistics for shards +- [#4072](https://github.com/influxdb/influxdb/pull/4072): Add statistics for the WAL. + +### Bugfixes +- [#4042](https://github.com/influxdb/influxdb/pull/4042): Set UDP input batching defaults as needed. +- [#3785](https://github.com/influxdb/influxdb/issues/3785): Invalid time stamp in graphite metric causes panic +- [#3804](https://github.com/influxdb/influxdb/pull/3804): init.d script fixes, fixes issue 3803. +- [#3823](https://github.com/influxdb/influxdb/pull/3823): Deterministic ordering for first() and last() +- [#3869](https://github.com/influxdb/influxdb/issues/3869): Seemingly deadlocked when ingesting metrics via graphite plugin +- [#3856](https://github.com/influxdb/influxdb/pull/3856): Minor changes to retention enforcement. +- [#3884](https://github.com/influxdb/influxdb/pull/3884): Fix two panics in WAL that can happen at server startup +- [#3868](https://github.com/influxdb/influxdb/pull/3868): Add shell option to start the daemon on CentOS. Thanks @SwannCroiset. +- [#3886](https://github.com/influxdb/influxdb/pull/3886): Prevent write timeouts due to lock contention in WAL +- [#3574](https://github.com/influxdb/influxdb/issues/3574): Querying data node causes panic +- [#3913](https://github.com/influxdb/influxdb/issues/3913): Convert meta shard owners to objects +- [#4026](https://github.com/influxdb/influxdb/pull/4026): Support multiple Graphite inputs. Fixes issue [#3636](https://github.com/influxdb/influxdb/issues/3636) +- [#3927](https://github.com/influxdb/influxdb/issues/3927): Add WAL lock to prevent timing lock contention +- [#3928](https://github.com/influxdb/influxdb/issues/3928): Write fails for multiple points when tag starts with quote +- [#3901](https://github.com/influxdb/influxdb/pull/3901): Unblock relaxed write consistency level Thanks @takayuki! +- [#3950](https://github.com/influxdb/influxdb/pull/3950): Limit bz1 quickcheck tests to 10 iterations on CI +- [#3977](https://github.com/influxdb/influxdb/pull/3977): Silence wal logging during testing +- [#3931](https://github.com/influxdb/influxdb/pull/3931): Don't precreate shard groups entirely in the past +- [#3960](https://github.com/influxdb/influxdb/issues/3960): possible "catch up" bug with nodes down in a cluster +- [#3980](https://github.com/influxdb/influxdb/pull/3980): 'service stop' waits until service actually stops. Fixes issue #3548. +- [#4016](https://github.com/influxdb/influxdb/pull/4016): Shutdown Graphite UDP on SIGTERM. +- [#4034](https://github.com/influxdb/influxdb/pull/4034): Rollback bolt tx on mapper open error +- [#3848](https://github.com/influxdb/influxdb/issues/3848): restart influxdb causing panic +- [#3881](https://github.com/influxdb/influxdb/issues/3881): panic: runtime error: invalid memory address or nil pointer dereference +- [#3926](https://github.com/influxdb/influxdb/issues/3926): First or last value of `GROUP BY time(x)` is often null. Fixed by [#4038](https://github.com/influxdb/influxdb/pull/4038) +- [#4053](https://github.com/influxdb/influxdb/pull/4053): Prohibit dropping default retention policy. +- [#4060](https://github.com/influxdb/influxdb/pull/4060): Don't log EOF error in openTSDB input. +- [#3978](https://github.com/influxdb/influxdb/issues/3978): [0.9.3] (regression) cannot use GROUP BY * with more than a single field in SELECT clause +- [#4058](https://github.com/influxdb/influxdb/pull/4058): Disable bz1 recompression +- [#3902](https://github.com/influxdb/influxdb/issues/3902): [0.9.3] DB should not crash when using invalid expression "GROUP BY time" +- [#3718](https://github.com/influxdb/influxdb/issues/3718): Derivative query with group by time but no aggregate function should fail parse + +## v0.9.3 [2015-08-26] + +### Release Notes + +There are breaking changes in this release. + - To store data points as integers you must now append `i` to the number if using the line protocol. + - If you have a UDP input configured, you should check the UDP section of [the new sample configuration file](https://github.com/influxdb/influxdb/blob/master/etc/config.sample.toml) to learn how to modify existing configuration files, as 0.9.3 now expects multiple UDP inputs. + - Configuration files must now have an entry for `wal-dir` in the `[data]` section. Check [new sample configuration file](https://github.com/influxdb/influxdb/blob/master/etc/config.sample.toml) for more details. + - The implicit `GROUP BY *` that was added to every `SELECT *` has been removed. Instead any tags in the data are now part of the columns in the returned query. + +Please see the *Features* section below for full details. + +### Features +- [#3376](https://github.com/influxdb/influxdb/pull/3376): Support for remote shard query mapping +- [#3372](https://github.com/influxdb/influxdb/pull/3372): Support joining nodes to existing cluster +- [#3426](https://github.com/influxdb/influxdb/pull/3426): Additional logging for continuous queries. Thanks @jhorwit2 +- [#3478](https://github.com/influxdb/influxdb/pull/3478): Support incremental cluster joins +- [#3519](https://github.com/influxdb/influxdb/pull/3519): **--BREAKING CHANGE--** Update line protocol to require trailing i for field values that are integers +- [#3529](https://github.com/influxdb/influxdb/pull/3529): Add TLS support for OpenTSDB plugin. Thanks @nathanielc +- [#3421](https://github.com/influxdb/influxdb/issues/3421): Should update metastore and cluster if IP or hostname changes +- [#3502](https://github.com/influxdb/influxdb/pull/3502): Importer for 0.8.9 data via the CLI +- [#3564](https://github.com/influxdb/influxdb/pull/3564): Fix alias, maintain column sort order +- [#3585](https://github.com/influxdb/influxdb/pull/3585): Additional test coverage for non-existent fields +- [#3246](https://github.com/influxdb/influxdb/issues/3246): Allow overriding of configuration parameters using environment variables +- [#3599](https://github.com/influxdb/influxdb/pull/3599): **--BREAKING CHANGE--** Support multiple UDP inputs. Thanks @tpitale +- [#3636](https://github.com/influxdb/influxdb/pull/3639): Cap auto-created retention policy replica count at 3 +- [#3641](https://github.com/influxdb/influxdb/pull/3641): Logging enhancements and single-node rename +- [#3635](https://github.com/influxdb/influxdb/pull/3635): Add build branch to version output. +- [#3115](https://github.com/influxdb/influxdb/pull/3115): Various init.d script improvements. Thanks @KoeSystems. +- [#3628](https://github.com/influxdb/influxdb/pull/3628): Wildcard expansion of tags and fields for raw queries +- [#3721](https://github.com/influxdb/influxdb/pull/3721): interpret number literals compared against time as nanoseconds from epoch +- [#3514](https://github.com/influxdb/influxdb/issues/3514): Implement WAL outside BoltDB with compaction +- [#3544](https://github.com/influxdb/influxdb/pull/3544): Implement compression on top of BoltDB +- [#3795](https://github.com/influxdb/influxdb/pull/3795): Throttle import +- [#3584](https://github.com/influxdb/influxdb/pull/3584): Import/export documenation + +### Bugfixes +- [#3405](https://github.com/influxdb/influxdb/pull/3405): Prevent database panic when fields are missing. Thanks @jhorwit2 +- [#3411](https://github.com/influxdb/influxdb/issues/3411): 500 timeout on write +- [#3420](https://github.com/influxdb/influxdb/pull/3420): Catch opentsdb malformed tags. Thanks @nathanielc. +- [#3404](https://github.com/influxdb/influxdb/pull/3404): Added support for escaped single quotes in query string. Thanks @jhorwit2 +- [#3414](https://github.com/influxdb/influxdb/issues/3414): Shard mappers perform query re-writing +- [#3525](https://github.com/influxdb/influxdb/pull/3525): check if fields are valid during parse time. +- [#3511](https://github.com/influxdb/influxdb/issues/3511): Sending a large number of tag causes panic +- [#3288](https://github.com/influxdb/influxdb/issues/3288): Run go fuzz on the line-protocol input +- [#3545](https://github.com/influxdb/influxdb/issues/3545): Fix parsing string fields with newlines +- [#3579](https://github.com/influxdb/influxdb/issues/3579): Revert breaking change to `client.NewClient` function +- [#3580](https://github.com/influxdb/influxdb/issues/3580): Do not allow wildcards with fields in select statements +- [#3530](https://github.com/influxdb/influxdb/pull/3530): Aliasing a column no longer works +- [#3436](https://github.com/influxdb/influxdb/issues/3436): Fix panic in hinted handoff queue processor +- [#3401](https://github.com/influxdb/influxdb/issues/3401): Derivative on non-numeric fields panics db +- [#3583](https://github.com/influxdb/influxdb/issues/3583): Inserting value in scientific notation with a trailing i causes panic +- [#3611](https://github.com/influxdb/influxdb/pull/3611): Fix query arithmetic with integers +- [#3326](https://github.com/influxdb/influxdb/issues/3326): simple regex query fails with cryptic error +- [#3618](https://github.com/influxdb/influxdb/pull/3618): Fix collectd stats panic on i386. Thanks @richterger +- [#3625](https://github.com/influxdb/influxdb/pull/3625): Don't panic when aggregate and raw queries are in a single statement +- [#3629](https://github.com/influxdb/influxdb/pull/3629): Use sensible batching defaults for Graphite. +- [#3638](https://github.com/influxdb/influxdb/pull/3638): Cluster config fixes and removal of meta.peers config field +- [#3640](https://github.com/influxdb/influxdb/pull/3640): Shutdown Graphite service when signal received. +- [#3632](https://github.com/influxdb/influxdb/issues/3632): Make single-node host renames more seamless +- [#3656](https://github.com/influxdb/influxdb/issues/3656): Silence snapshotter logger for testing +- [#3651](https://github.com/influxdb/influxdb/pull/3651): Fully remove series when dropped. +- [#3517](https://github.com/influxdb/influxdb/pull/3517): Batch CQ writes to avoid timeouts. Thanks @dim. +- [#3522](https://github.com/influxdb/influxdb/pull/3522): Consume CQ results on request timeouts. Thanks @dim. +- [#3646](https://github.com/influxdb/influxdb/pull/3646): Fix nil FieldCodec panic. +- [#3672](https://github.com/influxdb/influxdb/pull/3672): Reduce in-memory index by 20%-30% +- [#3673](https://github.com/influxdb/influxdb/pull/3673): Improve query performance by removing unnecessary tagset sorting. +- [#3676](https://github.com/influxdb/influxdb/pull/3676): Improve query performance by memomizing mapper output keys. +- [#3686](https://github.com/influxdb/influxdb/pull/3686): Ensure 'p' parameter is not logged, even on OPTIONS requests. +- [#3687](https://github.com/influxdb/influxdb/issues/3687): Fix panic: runtime error: makeslice: len out of range in hinted handoff +- [#3697](https://github.com/influxdb/influxdb/issues/3697): Correctly merge non-chunked results for same series. Fix issue #3242. +- [#3708](https://github.com/influxdb/influxdb/issues/3708): Fix double escaping measurement name during cluster replication +- [#3704](https://github.com/influxdb/influxdb/issues/3704): cluster replication issue for measurement name containing backslash +- [#3681](https://github.com/influxdb/influxdb/issues/3681): Quoted measurement names fail +- [#3681](https://github.com/influxdb/influxdb/issues/3682): Fix inserting string value with backslashes +- [#3735](https://github.com/influxdb/influxdb/issues/3735): Append to small bz1 blocks +- [#3736](https://github.com/influxdb/influxdb/pull/3736): Update shard group duration with retention policy changes. Thanks for the report @papylhomme +- [#3539](https://github.com/influxdb/influxdb/issues/3539): parser incorrectly accepts NaN as numerical value, but not always +- [#3790](https://github.com/influxdb/influxdb/pull/3790): Fix line protocol parsing equals in measurements and NaN values +- [#3778](https://github.com/influxdb/influxdb/pull/3778): Don't panic if SELECT on time. +- [#3824](https://github.com/influxdb/influxdb/issues/3824): tsdb.Point.MarshalBinary needs to support all number types +- [#3828](https://github.com/influxdb/influxdb/pull/3828): Support all number types when decoding a point +- [#3853](https://github.com/influxdb/influxdb/pull/3853): Use 4KB default block size for bz1 +- [#3607](https://github.com/influxdb/influxdb/issues/3607): Fix unable to query influxdb due to deadlock in metastore. Thanks @ccutrer! + +## v0.9.2 [2015-07-24] + +### Features +- [#3177](https://github.com/influxdb/influxdb/pull/3177): Client supports making HTTPS requests. Thanks @jipperinbham +- [#3299](https://github.com/influxdb/influxdb/pull/3299): Refactor query engine for distributed query support. +- [#3334](https://github.com/influxdb/influxdb/pull/3334): Clean shutdown of influxd. Thanks @mcastilho + +### Bugfixes + +- [#3180](https://github.com/influxdb/influxdb/pull/3180): Log GOMAXPROCS, version, and commit on startup. +- [#3218](https://github.com/influxdb/influxdb/pull/3218): Allow write timeouts to be configurable. +- [#3184](https://github.com/influxdb/influxdb/pull/3184): Support basic auth in admin interface. Thanks @jipperinbham! +- [#3236](https://github.com/influxdb/influxdb/pull/3236): Fix display issues in admin interface. +- [#3232](https://github.com/influxdb/influxdb/pull/3232): Set logging prefix for metastore. +- [#3230](https://github.com/influxdb/influxdb/issues/3230): panic: unable to parse bool value +- [#3245](https://github.com/influxdb/influxdb/issues/3245): Error using graphite plugin with multiple filters +- [#3223](https://github.com/influxdb/influxdb/issues/323): default graphite template cannot have extra tags +- [#3255](https://github.com/influxdb/influxdb/pull/3255): Flush WAL on start-up as soon as possible. +- [#3289](https://github.com/influxdb/influxdb/issues/3289): InfluxDB crashes on floats without decimal +- [#3298](https://github.com/influxdb/influxdb/pull/3298): Corrected WAL & flush parameters in default config. Thanks @jhorwit2 +- [#3152](https://github.com/influxdb/influxdb/issues/3159): High CPU Usage with unsorted writes +- [#3307](https://github.com/influxdb/influxdb/pull/3307): Fix regression parsing boolean values True/False +- [#3304](https://github.com/influxdb/influxdb/pull/3304): Fixed httpd logger to log user from query params. Thanks @jhorwit2 +- [#3332](https://github.com/influxdb/influxdb/pull/3332): Add SLIMIT and SOFFSET to string version of AST. +- [#3335](https://github.com/influxdb/influxdb/pull/3335): Don't drop all data on DROP DATABASE. Thanks to @PierreF for the report +- [#2761](https://github.com/influxdb/influxdb/issues/2761): Make SHOW RETENTION POLICIES consistent with other queries. +- [#3356](https://github.com/influxdb/influxdb/pull/3356): Disregard semicolons after database name in use command. Thanks @timraymond. +- [#3351](https://github.com/influxdb/influxdb/pull/3351): Handle malformed regex comparisons during parsing. Thanks @rnubel +- [#3244](https://github.com/influxdb/influxdb/pull/3244): Wire up admin privilege grant and revoke. +- [#3259](https://github.com/influxdb/influxdb/issues/3259): Respect privileges for queries. +- [#3256](https://github.com/influxdb/influxdb/pull/3256): Remove unnecessary timeout in WaitForLeader(). Thanks @cannium. +- [#3380](https://github.com/influxdb/influxdb/issue/3380): Parser fix, only allow ORDER BY ASC and ORDER BY time ASC. +- [#3319](https://github.com/influxdb/influxdb/issues/3319): restarting process irrevocably BREAKS measurements with spaces +- [#3453](https://github.com/influxdb/influxdb/issues/3453): Remove outdated `dump` command from CLI. +- [#3463](https://github.com/influxdb/influxdb/issues/3463): Fix aggregate queries and time precision on where clauses. + +## v0.9.1 [2015-07-02] + +### Features + +- [2650](https://github.com/influxdb/influxdb/pull/2650): Add SHOW GRANTS FOR USER statement. Thanks @n1tr0g. +- [3125](https://github.com/influxdb/influxdb/pull/3125): Graphite Input Protocol Parsing +- [2746](https://github.com/influxdb/influxdb/pull/2746): New Admin UI/interface +- [3036](https://github.com/influxdb/influxdb/pull/3036): Write Ahead Log (WAL) +- [3014](https://github.com/influxdb/influxdb/issues/3014): Implement Raft snapshots + +### Bugfixes + +- [3013](https://github.com/influxdb/influxdb/issues/3013): Panic error with inserting values with commas +- [#2956](https://github.com/influxdb/influxdb/issues/2956): Type mismatch in derivative +- [#2908](https://github.com/influxdb/influxdb/issues/2908): Field mismatch error messages need to be updated +- [#2931](https://github.com/influxdb/influxdb/pull/2931): Services and reporting should wait until cluster has leader. +- [#2943](https://github.com/influxdb/influxdb/issues/2943): Ensure default retention policies are fully replicated +- [#2948](https://github.com/influxdb/influxdb/issues/2948): Field mismatch error message to include measurement name +- [#2919](https://github.com/influxdb/influxdb/issues/2919): Unable to insert negative floats +- [#2935](https://github.com/influxdb/influxdb/issues/2935): Hook CPU and memory profiling back up. +- [#2960](https://github.com/influxdb/influxdb/issues/2960): Cluster Write Errors. +- [#2928](https://github.com/influxdb/influxdb/pull/2928): Start work to set InfluxDB version in HTTP response headers. Thanks @neonstalwart. +- [#2969](https://github.com/influxdb/influxdb/pull/2969): Actually set HTTP version in responses. +- [#2993](https://github.com/influxdb/influxdb/pull/2993): Don't log each UDP batch. +- [#2994](https://github.com/influxdb/influxdb/pull/2994): Don't panic during wilcard expansion if no default database specified. +- [#3002](https://github.com/influxdb/influxdb/pull/3002): Remove measurement from shard's index on DROP MEASUREMENT. +- [#3021](https://github.com/influxdb/influxdb/pull/3021): Correct set HTTP write trace logging. Thanks @vladlopes. +- [#3027](https://github.com/influxdb/influxdb/pull/3027): Enforce minimum retention policy duration of 1 hour. +- [#3030](https://github.com/influxdb/influxdb/pull/3030): Fix excessive logging of shard creation. +- [#3038](https://github.com/influxdb/influxdb/pull/3038): Don't check deleted shards for precreation. Thanks @vladlopes. +- [#3033](https://github.com/influxdb/influxdb/pull/3033): Add support for marshaling `uint64` in client. +- [#3090](https://github.com/influxdb/influxdb/pull/3090): Remove database from TSDB index on DROP DATABASE. +- [#2944](https://github.com/influxdb/influxdb/issues/2944): Don't require "WHERE time" when creating continuous queries. +- [#3075](https://github.com/influxdb/influxdb/pull/3075): GROUP BY correctly when different tags have same value. +- [#3078](https://github.com/influxdb/influxdb/pull/3078): Fix CLI panic on malformed INSERT. +- [#2102](https://github.com/influxdb/influxdb/issues/2102): Re-work Graphite input and metric processing +- [#2996](https://github.com/influxdb/influxdb/issues/2996): Graphite Input Parsing +- [#3136](https://github.com/influxdb/influxdb/pull/3136): Fix various issues with init.d script. Thanks @ miguelcnf. +- [#2996](https://github.com/influxdb/influxdb/issues/2996): Graphite Input Parsing +- [#3127](https://github.com/influxdb/influxdb/issues/3127): Trying to insert a number larger than the largest signed 64-bit number kills influxd +- [#3131](https://github.com/influxdb/influxdb/pull/3131): Copy batch tags to each point before marshalling +- [#3155](https://github.com/influxdb/influxdb/pull/3155): Instantiate UDP batcher before listening for UDP traffic, otherwise a panic may result. +- [#2678](https://github.com/influxdb/influxdb/issues/2678): Server allows tags with an empty string for the key and/or value +- [#3061](https://github.com/influxdb/influxdb/issues/3061): syntactically incorrect line protocol insert panics the database +- [#2608](https://github.com/influxdb/influxdb/issues/2608): drop measurement while writing points to that measurement has race condition that can panic +- [#3183](https://github.com/influxdb/influxdb/issues/3183): using line protocol measurement names cannot contain commas +- [#3193](https://github.com/influxdb/influxdb/pull/3193): Fix panic for SHOW STATS and in collectd +- [#3102](https://github.com/influxdb/influxdb/issues/3102): Add authentication cache +- [#3209](https://github.com/influxdb/influxdb/pull/3209): Dump Run() errors to stderr +- [#3217](https://github.com/influxdb/influxdb/pull/3217): Allow WAL partition flush delay to be configurable. + +## v0.9.0 [2015-06-11] + +### Bugfixes + +- [#2869](https://github.com/influxdb/influxdb/issues/2869): Adding field to existing measurement causes panic +- [#2849](https://github.com/influxdb/influxdb/issues/2849): RC32: Frequent write errors +- [#2700](https://github.com/influxdb/influxdb/issues/2700): Incorrect error message in database EncodeFields +- [#2897](https://github.com/influxdb/influxdb/pull/2897): Ensure target Graphite database exists +- [#2898](https://github.com/influxdb/influxdb/pull/2898): Ensure target openTSDB database exists +- [#2895](https://github.com/influxdb/influxdb/pull/2895): Use Graphite input defaults where necessary +- [#2900](https://github.com/influxdb/influxdb/pull/2900): Use openTSDB input defaults where necessary +- [#2886](https://github.com/influxdb/influxdb/issues/2886): Refactor backup & restore +- [#2804](https://github.com/influxdb/influxdb/pull/2804): BREAKING: change time literals to be single quoted in InfluxQL. Thanks @nvcook42! +- [#2906](https://github.com/influxdb/influxdb/pull/2906): Restrict replication factor to the cluster size +- [#2905](https://github.com/influxdb/influxdb/pull/2905): Restrict clusters to 3 peers +- [#2904](https://github.com/influxdb/influxdb/pull/2904): Re-enable server reporting. +- [#2917](https://github.com/influxdb/influxdb/pull/2917): Fix int64 field values. +- [#2920](https://github.com/influxdb/influxdb/issues/2920): Ensure collectd database exists + +## v0.9.0-rc33 [2015-06-09] + +### Bugfixes + +- [#2816](https://github.com/influxdb/influxdb/pull/2816): Enable UDP service. Thanks @renan- +- [#2824](https://github.com/influxdb/influxdb/pull/2824): Add missing call to WaitGroup.Done in execConn. Thanks @liyichao +- [#2823](https://github.com/influxdb/influxdb/pull/2823): Convert OpenTSDB to a service. +- [#2838](https://github.com/influxdb/influxdb/pull/2838): Set auto-created retention policy period to infinite. +- [#2829](https://github.com/influxdb/influxdb/pull/2829): Re-enable Graphite support as a new Service-style component. +- [#2814](https://github.com/influxdb/influxdb/issues/2814): Convert collectd to a service. +- [#2852](https://github.com/influxdb/influxdb/pull/2852): Don't panic when altering retention policies. Thanks for the report @huhongbo +- [#2857](https://github.com/influxdb/influxdb/issues/2857): Fix parsing commas in string field values. +- [#2833](https://github.com/influxdb/influxdb/pull/2833): Make the default config valid. +- [#2859](https://github.com/influxdb/influxdb/pull/2859): Fix panic on aggregate functions. +- [#2878](https://github.com/influxdb/influxdb/pull/2878): Re-enable shard precreation. +- [2865](https://github.com/influxdb/influxdb/pull/2865) -- Return an empty set of results if database does not exist in shard metadata. + +### Features +- [2858](https://github.com/influxdb/influxdb/pull/2858): Support setting openTSDB write consistency. + +## v0.9.0-rc32 [2015-06-07] + +### Release Notes + +This released introduced an updated write path and clustering design. The data format has also changed, so you'll need to wipe out your data to upgrade from RC31. There should be no other data changes before v0.9.0 is released. + +### Features +- [#1997](https://github.com/influxdb/influxdb/pull/1997): Update SELECT * to return tag values. +- [#2599](https://github.com/influxdb/influxdb/issues/2599): Add "epoch" URL param and return JSON time values as epoch instead of date strings. +- [#2682](https://github.com/influxdb/influxdb/issues/2682): Adding pr checklist to CONTRIBUTING.md +- [#2683](https://github.com/influxdb/influxdb/issues/2683): Add batching support to Graphite inputs. +- [#2687](https://github.com/influxdb/influxdb/issues/2687): Add batching support to Collectd inputs. +- [#2696](https://github.com/influxdb/influxdb/pull/2696): Add line protocol. This is now the preferred way to write data. +- [#2751](https://github.com/influxdb/influxdb/pull/2751): Add UDP input. UDP only supports the line protocol now. +- [#2684](https://github.com/influxdb/influxdb/pull/2684): Include client timeout configuration. Thanks @vladlopes! + +### Bugfixes +- [#2776](https://github.com/influxdb/influxdb/issues/2776): Re-implement retention policy enforcement. +- [#2635](https://github.com/influxdb/influxdb/issues/2635): Fix querying against boolean field in WHERE clause. +- [#2644](https://github.com/influxdb/influxdb/issues/2644): Make SHOW queries work with FROM //. +- [#2501](https://github.com/influxdb/influxdb/issues/2501): Name the FlagSet for the shell and add a version flag. Thanks @neonstalwart +- [#2647](https://github.com/influxdb/influxdb/issues/2647): Fixes typos in sample config file - thanks @claws! + +## v0.9.0-rc31 [2015-05-21] + +### Features +- [#1822](https://github.com/influxdb/influxdb/issues/1822): Wire up DERIVATIVE aggregate +- [#1477](https://github.com/influxdb/influxdb/issues/1477): Wire up non_negative_derivative function +- [#2557](https://github.com/influxdb/influxdb/issues/2557): Fix false positive error with `GROUP BY time` +- [#1891](https://github.com/influxdb/influxdb/issues/1891): Wire up COUNT DISTINCT aggregate +- [#1989](https://github.com/influxdb/influxdb/issues/1989): Implement `SELECT tagName FROM m` + +### Bugfixes +- [#2545](https://github.com/influxdb/influxdb/pull/2545): Use "value" as the field name for graphite input. Thanks @cannium. +- [#2558](https://github.com/influxdb/influxdb/pull/2558): Fix client response check - thanks @vladlopes! +- [#2566](https://github.com/influxdb/influxdb/pull/2566): Wait until each data write has been commited by the Raft cluster. +- [#2602](https://github.com/influxdb/influxdb/pull/2602): CLI execute command exits without cleaning up liner package. +- [#2610](https://github.com/influxdb/influxdb/pull/2610): Fix shard group creation +- [#2596](https://github.com/influxdb/influxdb/pull/2596): RC30: `panic: runtime error: index out of range` when insert data points. +- [#2592](https://github.com/influxdb/influxdb/pull/2592): Should return an error if user attempts to group by a field. +- [#2499](https://github.com/influxdb/influxdb/pull/2499): Issuing a select query with tag as a values causes panic. +- [#2612](https://github.com/influxdb/influxdb/pull/2612): Query planner should validate distinct is passed a field. +- [#2531](https://github.com/influxdb/influxdb/issues/2531): Fix select with 3 or more terms in where clause. +- [#2564](https://github.com/influxdb/influxdb/issues/2564): Change "name" to "measurement" in JSON for writes. + +## PRs +- [#2569](https://github.com/influxdb/influxdb/pull/2569): Add derivative functions +- [#2598](https://github.com/influxdb/influxdb/pull/2598): Implement tag support in SELECT statements +- [#2624](https://github.com/influxdb/influxdb/pull/2624): Remove references to SeriesID in `DROP SERIES` handlers. + +## v0.9.0-rc30 [2015-05-12] + +### Release Notes + +This release has a breaking API change for writes -- the field previously called `timestamp` has been renamed to `time`. + +### Features +- [#2254](https://github.com/influxdb/influxdb/pull/2254): Add Support for OpenTSDB HTTP interface. Thanks @tcolgate +- [#2525](https://github.com/influxdb/influxdb/pull/2525): Serve broker diagnostics over HTTP +- [#2186](https://github.com/influxdb/influxdb/pull/2186): The default status code for queries is now `200 OK` +- [#2298](https://github.com/influxdb/influxdb/pull/2298): Successful writes now return a status code of `204 No Content` - thanks @neonstalwart! +- [#2549](https://github.com/influxdb/influxdb/pull/2549): Raft election timeout to 5 seconds, so system is more forgiving of CPU loads. +- [#2568](https://github.com/influxdb/influxdb/pull/2568): Wire up SELECT DISTINCT. + +### Bugfixes +- [#2535](https://github.com/influxdb/influxdb/pull/2535): Return exit status 0 if influxd already running. Thanks @haim0n. +- [#2521](https://github.com/influxdb/influxdb/pull/2521): Don't truncate topic data until fully replicated. +- [#2509](https://github.com/influxdb/influxdb/pull/2509): Parse config file correctly during restore. Thanks @neonstalwart +- [#2536](https://github.com/influxdb/influxdb/issues/2532): Set leader ID on restart of single-node cluster. +- [#2448](https://github.com/influxdb/influxdb/pull/2448): Fix inconsistent data type - thanks @cannium! +- [#2108](https://github.com/influxdb/influxdb/issues/2108): Change `timestamp` to `time` - thanks @neonstalwart! +- [#2539](https://github.com/influxdb/influxdb/issues/2539): Add additional vote request logging. +- [#2541](https://github.com/influxdb/influxdb/issues/2541): Update messaging client connection index with every message. +- [#2542](https://github.com/influxdb/influxdb/issues/2542): Throw parser error for invalid aggregate without where time. +- [#2548](https://github.com/influxdb/influxdb/issues/2548): Return an error when numeric aggregate applied to non-numeric data. +- [#2487](https://github.com/influxdb/influxdb/issues/2487): Aggregate query with exact timestamp causes panic. Thanks @neonstalwart! +- [#2552](https://github.com/influxdb/influxdb/issues/2552): Run CQ that is actually passed into go-routine. +- [#2553](https://github.com/influxdb/influxdb/issues/2553): Fix race condition during CQ execution. +- [#2557](https://github.com/influxdb/influxdb/issues/2557): RC30 WHERE time filter Regression. + +## v0.9.0-rc29 [2015-05-05] + +### Features +- [#2410](https://github.com/influxdb/influxdb/pull/2410): If needed, brokers respond with data nodes for peer shard replication. +- [#2469](https://github.com/influxdb/influxdb/pull/2469): Reduce default max topic size from 1GB to 50MB. +- [#1824](https://github.com/influxdb/influxdb/pull/1824): Wire up MEDIAN aggregate. Thanks @neonstalwart! + +### Bugfixes +- [#2446](https://github.com/influxdb/influxdb/pull/2446): Correctly count number of queries executed. Thanks @neonstalwart +- [#2452](https://github.com/influxdb/influxdb/issues/2452): Fix panic with shard stats on multiple clusters +- [#2453](https://github.com/influxdb/influxdb/pull/2453): Do not require snapshot on Log.WriteEntriesTo(). +- [#2460](https://github.com/influxdb/influxdb/issues/2460): Collectd input should use "value" for fields values. Fixes 2412. Thanks @josh-padnick +- [#2465](https://github.com/influxdb/influxdb/pull/2465): HTTP response logging paniced with chunked requests. Thanks @Jackkoz +- [#2475](https://github.com/influxdb/influxdb/pull/2475): RLock server when checking if shards groups are required during write. +- [#2471](https://github.com/influxdb/influxdb/issues/2471): Function calls normalized to be lower case. Fixes percentile not working when called uppercase. Thanks @neonstalwart +- [#2281](https://github.com/influxdb/influxdb/issues/2281): Fix Bad Escape error when parsing regex + +## v0.9.0-rc28 [2015-04-27] + +### Features +- [#2410](https://github.com/influxdb/influxdb/pull/2410) Allow configuration of Raft timers +- [#2354](https://github.com/influxdb/influxdb/pull/2354) Wire up STDDEV. Thanks @neonstalwart! + +### Bugfixes +- [#2374](https://github.com/influxdb/influxdb/issues/2374): Two different panics during SELECT percentile +- [#2404](https://github.com/influxdb/influxdb/pull/2404): Mean and percentile function fixes +- [#2408](https://github.com/influxdb/influxdb/pull/2408): Fix snapshot 500 error +- [#1896](https://github.com/influxdb/influxdb/issues/1896): Excessive heartbeater logging of "connection refused" on cluster node stop +- [#2418](https://github.com/influxdb/influxdb/pull/2418): Fix raft node getting stuck in candidate state +- [#2415](https://github.com/influxdb/influxdb/pull/2415): Raft leader ID now set on election after failover. Thanks @xiaost +- [#2426](https://github.com/influxdb/influxdb/pull/2426): Fix race condition around listener address in openTSDB server. +- [#2426](https://github.com/influxdb/influxdb/pull/2426): Fix race condition around listener address in Graphite server. +- [#2429](https://github.com/influxdb/influxdb/pull/2429): Ensure no field value is null. +- [#2431](https://github.com/influxdb/influxdb/pull/2431): Always append shard path in diags. Thanks @marcosnils +- [#2441](https://github.com/influxdb/influxdb/pull/2441): Correctly release server RLock during "drop series". +- [#2445](https://github.com/influxdb/influxdb/pull/2445): Read locks and data race fixes + +## v0.9.0-rc27 [04-23-2015] + +### Features +- [#2398](https://github.com/influxdb/influxdb/pull/2398) Track more stats and report errors for shards. + +### Bugfixes +- [#2370](https://github.com/influxdb/influxdb/pull/2370): Fix data race in openTSDB endpoint. +- [#2371](https://github.com/influxdb/influxdb/pull/2371): Don't set client to nil when closing broker Fixes #2352 +- [#2372](https://github.com/influxdb/influxdb/pull/2372): Fix data race in graphite endpoint. +- [#2373](https://github.com/influxdb/influxdb/pull/2373): Actually allow HTTP logging to be controlled. +- [#2376](https://github.com/influxdb/influxdb/pull/2376): Encode all types of integers. Thanks @jtakkala. +- [#2376](https://github.com/influxdb/influxdb/pull/2376): Add shard path to existing diags value. Fix issue #2369. +- [#2386](https://github.com/influxdb/influxdb/pull/2386): Fix shard datanodes stats getting appended too many times +- [#2393](https://github.com/influxdb/influxdb/pull/2393): Fix default hostname for connecting to cluster. +- [#2390](https://github.com/influxdb/influxdb/pull/2390): Handle large sums when calculating means - thanks @neonstalwart! +- [#2391](https://github.com/influxdb/influxdb/pull/2391): Unable to write points through Go client when authentication enabled +- [#2400](https://github.com/influxdb/influxdb/pull/2400): Always send auth headers for client requests if present + +## v0.9.0-rc26 [04-21-2015] + +### Features +- [#2301](https://github.com/influxdb/influxdb/pull/2301): Distributed query load balancing and failover +- [#2336](https://github.com/influxdb/influxdb/pull/2336): Handle distributed queries when shards != data nodes +- [#2353](https://github.com/influxdb/influxdb/pull/2353): Distributed Query/Clustering Fixes + +### Bugfixes +- [#2297](https://github.com/influxdb/influxdb/pull/2297): create /var/run during startup. Thanks @neonstalwart. +- [#2312](https://github.com/influxdb/influxdb/pull/2312): Re-use httpclient for continuous queries +- [#2318](https://github.com/influxdb/influxdb/pull/2318): Remove pointless use of 'done' channel for collectd. +- [#2242](https://github.com/influxdb/influxdb/pull/2242): Distributed Query should balance requests +- [#2243](https://github.com/influxdb/influxdb/pull/2243): Use Limit Reader instead of fixed 1MB/1GB slice for DQ +- [#2190](https://github.com/influxdb/influxdb/pull/2190): Implement failover to other data nodes for distributed queries +- [#2324](https://github.com/influxdb/influxdb/issues/2324): Race in Broker.Close()/Broker.RunContinousQueryProcessing() +- [#2325](https://github.com/influxdb/influxdb/pull/2325): Cluster open fixes +- [#2326](https://github.com/influxdb/influxdb/pull/2326): Fix parse error in CREATE CONTINUOUS QUERY +- [#2300](https://github.com/influxdb/influxdb/pull/2300): Refactor integration tests. Properly close Graphite/OpenTSDB listeners. +- [#2338](https://github.com/influxdb/influxdb/pull/2338): Fix panic if tag key isn't double quoted when it should have been +- [#2340](https://github.com/influxdb/influxdb/pull/2340): Fix SHOW DIAGNOSTICS panic if any shard was non-local. +- [#2351](https://github.com/influxdb/influxdb/pull/2351): Fix data race by rlocking shard during diagnostics. +- [#2348](https://github.com/influxdb/influxdb/pull/2348): Data node fail to join cluster in 0.9.0rc25 +- [#2343](https://github.com/influxdb/influxdb/pull/2343): Node falls behind Metastore updates +- [#2334](https://github.com/influxdb/influxdb/pull/2334): Test Partial replication is very problematic +- [#2272](https://github.com/influxdb/influxdb/pull/2272): clustering: influxdb 0.9.0-rc23 panics when doing a GET with merge_metrics in a +- [#2350](https://github.com/influxdb/influxdb/pull/2350): Issue fix for :influxd -hostname localhost. +- [#2367](https://github.com/influxdb/influxdb/pull/2367): PR for issue #2350 - Always use localhost, not host name. + +## v0.9.0-rc25 [2015-04-15] + +### Bugfixes +- [#2282](https://github.com/influxdb/influxdb/pull/2282): Use "value" as field name for OpenTSDB input. +- [#2283](https://github.com/influxdb/influxdb/pull/2283): Fix bug when restarting an entire existing cluster. +- [#2293](https://github.com/influxdb/influxdb/pull/2293): Open cluster listener before starting broker. +- [#2287](https://github.com/influxdb/influxdb/pull/2287): Fix data race during SHOW RETENTION POLICIES. +- [#2288](https://github.com/influxdb/influxdb/pull/2288): Fix expression parsing bug. +- [#2294](https://github.com/influxdb/influxdb/pull/2294): Fix async response flushing (invalid chunked response error). + +## Features +- [#2276](https://github.com/influxdb/influxdb/pull/2276): Broker topic truncation. +- [#2292](https://github.com/influxdb/influxdb/pull/2292): Wire up drop CQ statement - thanks @neonstalwart! +- [#2290](https://github.com/influxdb/influxdb/pull/2290): Allow hostname argument to override default config - thanks @neonstalwart! +- [#2295](https://github.com/influxdb/influxdb/pull/2295): Use nil as default return value for MapCount - thanks @neonstalwart! +- [#2246](https://github.com/influxdb/influxdb/pull/2246): Allow HTTP logging to be controlled. + +## v0.9.0-rc24 [2015-04-13] + +### Bugfixes +- [#2255](https://github.com/influxdb/influxdb/pull/2255): Fix panic when changing default retention policy. +- [#2257](https://github.com/influxdb/influxdb/pull/2257): Add "snapshotting" pseudo state & log entry cache. +- [#2261](https://github.com/influxdb/influxdb/pull/2261): Support int64 value types. +- [#2191](https://github.com/influxdb/influxdb/pull/2191): Case-insensitive check for "fill" +- [#2274](https://github.com/influxdb/influxdb/pull/2274): Snapshot and HTTP API endpoints +- [#2265](https://github.com/influxdb/influxdb/pull/2265): Fix auth for CLI. + +## v0.9.0-rc23 [2015-04-11] + +### Features +- [#2202](https://github.com/influxdb/influxdb/pull/2202): Initial implementation of Distributed Queries +- [#2202](https://github.com/influxdb/influxdb/pull/2202): 64-bit Series IDs. INCOMPATIBLE WITH PREVIOUS DATASTORES. + +### Bugfixes +- [#2225](https://github.com/influxdb/influxdb/pull/2225): Make keywords completely case insensitive +- [#2228](https://github.com/influxdb/influxdb/pull/2228): Accept keyword default unquoted in ALTER RETENTION POLICY statement +- [#2236](https://github.com/influxdb/influxdb/pull/2236): Immediate term changes, fix stale write issue, net/http/pprof +- [#2213](https://github.com/influxdb/influxdb/pull/2213): Seed random number generator for election timeout. Thanks @cannium. + +## v0.9.0-rc22 [2015-04-09] + +### Features +- [#2214](https://github.com/influxdb/influxdb/pull/2214): Added the option to influx CLI to execute single command and exit. Thanks @n1tr0g + +### Bugfixes +- [#2223](https://github.com/influxdb/influxdb/pull/2223): Always notify term change on RequestVote + +## v0.9.0-rc21 [2015-04-09] + +### Features +- [#870](https://github.com/influxdb/influxdb/pull/870): Add support for OpenTSDB telnet input protocol. Thanks @tcolgate +- [#2180](https://github.com/influxdb/influxdb/pull/2180): Allow http write handler to decode gzipped body +- [#2175](https://github.com/influxdb/influxdb/pull/2175): Separate broker and data nodes +- [#2158](https://github.com/influxdb/influxdb/pull/2158): Allow user password to be changed. Thanks @n1tr0g +- [#2201](https://github.com/influxdb/influxdb/pull/2201): Bring back config join URLs +- [#2121](https://github.com/influxdb/influxdb/pull/2121): Parser refactor + +### Bugfixes +- [#2181](https://github.com/influxdb/influxdb/pull/2181): Fix panic on "SHOW DIAGNOSTICS". +- [#2170](https://github.com/influxdb/influxdb/pull/2170): Make sure queries on missing tags return 200 status. +- [#2197](https://github.com/influxdb/influxdb/pull/2197): Lock server during Open(). +- [#2200](https://github.com/influxdb/influxdb/pull/2200): Re-enable Continuous Queries. +- [#2203](https://github.com/influxdb/influxdb/pull/2203): Fix race condition on continuous queries. +- [#2217](https://github.com/influxdb/influxdb/pull/2217): Only revert to follower if new term is greater. +- [#2219](https://github.com/influxdb/influxdb/pull/2219): Persist term change to disk when candidate. Thanks @cannium + +## v0.9.0-rc20 [2015-04-04] + +### Features +- [#2128](https://github.com/influxdb/influxdb/pull/2128): Data node discovery from brokers +- [#2142](https://github.com/influxdb/influxdb/pull/2142): Support chunked queries +- [#2154](https://github.com/influxdb/influxdb/pull/2154): Node redirection +- [#2168](https://github.com/influxdb/influxdb/pull/2168): Return raft term from vote, add term logging + +### Bugfixes +- [#2147](https://github.com/influxdb/influxdb/pull/2147): Set Go Max procs in a better location +- [#2137](https://github.com/influxdb/influxdb/pull/2137): Refactor `results` to `response`. Breaking Go Client change. +- [#2151](https://github.com/influxdb/influxdb/pull/2151): Ignore replay commands on the metastore. +- [#2152](https://github.com/influxdb/influxdb/issues/2152): Influxd process with stats enabled crashing with 'Unsuported protocol scheme for ""' +- [#2156](https://github.com/influxdb/influxdb/pull/2156): Propagate error when resolving UDP address in Graphite UDP server. +- [#2163](https://github.com/influxdb/influxdb/pull/2163): Fix up paths for default data and run storage. +- [#2164](https://github.com/influxdb/influxdb/pull/2164): Append STDOUT/STDERR in initscript. +- [#2165](https://github.com/influxdb/influxdb/pull/2165): Better name for config section for stats and diags. +- [#2165](https://github.com/influxdb/influxdb/pull/2165): Monitoring database and retention policy are not configurable. +- [#2167](https://github.com/influxdb/influxdb/pull/2167): Add broker log recovery. +- [#2166](https://github.com/influxdb/influxdb/pull/2166): Don't panic if presented with a field of unknown type. +- [#2149](https://github.com/influxdb/influxdb/pull/2149): Fix unit tests for win32 when directory doesn't exist. +- [#2150](https://github.com/influxdb/influxdb/pull/2150): Fix unit tests for win32 when a connection is refused. + +## v0.9.0-rc19 [2015-04-01] + +### Features +- [#2143](https://github.com/influxdb/influxdb/pull/2143): Add raft term logging. + +### Bugfixes +- [#2145](https://github.com/influxdb/influxdb/pull/2145): Encode toml durations correctly which fixes default configuration generation `influxd config`. + +## v0.9.0-rc18 [2015-03-31] + +### Bugfixes +- [#2100](https://github.com/influxdb/influxdb/pull/2100): Use channel to synchronize collectd shutdown. +- [#2100](https://github.com/influxdb/influxdb/pull/2100): Synchronize access to shard index. +- [#2131](https://github.com/influxdb/influxdb/pull/2131): Optimize marshalTags(). +- [#2130](https://github.com/influxdb/influxdb/pull/2130): Make fewer calls to marshalTags(). +- [#2105](https://github.com/influxdb/influxdb/pull/2105): Support != for tag values. Fix issue #2097, thanks to @smonkewitz for bug report. +- [#2105](https://github.com/influxdb/influxdb/pull/2105): Support !~ tags values. +- [#2138](https://github.com/influxdb/influxdb/pull/2136): Use map for marshaledTags cache. + +## v0.9.0-rc17 [2015-03-29] + +### Features +- [#2076](https://github.com/influxdb/influxdb/pull/2076): Separate stdout and stderr output in init.d script +- [#2091](https://github.com/influxdb/influxdb/pull/2091): Support disabling snapshot endpoint. +- [#2081](https://github.com/influxdb/influxdb/pull/2081): Support writing diagnostic data into the internal database. +- [#2095](https://github.com/influxdb/influxdb/pull/2095): Improved InfluxDB client docs. Thanks @derailed + +### Bugfixes +- [#2093](https://github.com/influxdb/influxdb/pull/2093): Point precision not marshalled correctly. Thanks @derailed +- [#2084](https://github.com/influxdb/influxdb/pull/2084): Allowing leading underscores in identifiers. +- [#2080](https://github.com/influxdb/influxdb/pull/2080): Graphite logs in seconds, not milliseconds. +- [#2101](https://github.com/influxdb/influxdb/pull/2101): SHOW DATABASES should name returned series "databases". +- [#2104](https://github.com/influxdb/influxdb/pull/2104): Include NEQ when calculating field filters. +- [#2112](https://github.com/influxdb/influxdb/pull/2112): Set GOMAXPROCS on startup. This may have been causing extra leader elections, which would cause a number of other bugs or instability. +- [#2111](https://github.com/influxdb/influxdb/pull/2111) and [#2025](https://github.com/influxdb/influxdb/issues/2025): Raft stability fixes. Non-contiguous log error and others. +- [#2114](https://github.com/influxdb/influxdb/pull/2114): Correctly start influxd on platforms without start-stop-daemon. + +## v0.9.0-rc16 [2015-03-24] + +### Features +- [#2058](https://github.com/influxdb/influxdb/pull/2058): Track number of queries executed in stats. +- [#2059](https://github.com/influxdb/influxdb/pull/2059): Retention policies sorted by name on return to client. +- [#2061](https://github.com/influxdb/influxdb/pull/2061): Implement SHOW DIAGNOSTICS. +- [#2064](https://github.com/influxdb/influxdb/pull/2064): Allow init.d script to return influxd version. +- [#2053](https://github.com/influxdb/influxdb/pull/2053): Implment backup and restore. +- [#1631](https://github.com/influxdb/influxdb/pull/1631): Wire up DROP CONTINUOUS QUERY. + +### Bugfixes +- [#2037](https://github.com/influxdb/influxdb/pull/2037): Don't check 'configExists' at Run() level. +- [#2039](https://github.com/influxdb/influxdb/pull/2039): Don't panic if getting current user fails. +- [#2034](https://github.com/influxdb/influxdb/pull/2034): GROUP BY should require an aggregate. +- [#2040](https://github.com/influxdb/influxdb/pull/2040): Add missing top-level help for config command. +- [#2057](https://github.com/influxdb/influxdb/pull/2057): Move racy "in order" test to integration test suite. +- [#2060](https://github.com/influxdb/influxdb/pull/2060): Reload server shard map on restart. +- [#2068](https://github.com/influxdb/influxdb/pull/2068): Fix misspelled JSON field. +- [#2067](https://github.com/influxdb/influxdb/pull/2067): Fixed issue where some queries didn't properly pull back data (introduced in RC15). Fixing intervals for GROUP BY. + +## v0.9.0-rc15 [2015-03-19] + +### Features +- [#2000](https://github.com/influxdb/influxdb/pull/2000): Log broker path when broker fails to start. Thanks @gst. +- [#2007](https://github.com/influxdb/influxdb/pull/2007): Track shard-level stats. + +### Bugfixes +- [#2001](https://github.com/influxdb/influxdb/pull/2001): Ensure measurement not found returns status code 200. +- [#1985](https://github.com/influxdb/influxdb/pull/1985): Set content-type JSON header before actually writing header. Thanks @dstrek. +- [#2003](https://github.com/influxdb/influxdb/pull/2003): Set timestamp when writing monitoring stats. +- [#2004](https://github.com/influxdb/influxdb/pull/2004): Limit group by to MaxGroupByPoints (currently 100,000). +- [#2016](https://github.com/influxdb/influxdb/pull/2016): Fixing bucket alignment for group by. Thanks @jnutzmann +- [#2021](https://github.com/influxdb/influxdb/pull/2021): Remove unnecessary formatting from log message. Thanks @simonkern + + +## v0.9.0-rc14 [2015-03-18] + +### Bugfixes +- [#1999](https://github.com/influxdb/influxdb/pull/1999): Return status code 200 for measurement not found errors on show series. + +## v0.9.0-rc13 [2015-03-17] + +### Features +- [#1974](https://github.com/influxdb/influxdb/pull/1974): Add time taken for request to the http server logs. + +### Bugfixes +- [#1971](https://github.com/influxdb/influxdb/pull/1971): Fix leader id initialization. +- [#1975](https://github.com/influxdb/influxdb/pull/1975): Require `q` parameter for query endpoint. +- [#1969](https://github.com/influxdb/influxdb/pull/1969): Print loaded config. +- [#1987](https://github.com/influxdb/influxdb/pull/1987): Fix config print startup statement for when no config is provided. +- [#1990](https://github.com/influxdb/influxdb/pull/1990): Drop measurement was taking too long due to transactions. + +## v0.9.0-rc12 [2015-03-15] + +### Bugfixes +- [#1942](https://github.com/influxdb/influxdb/pull/1942): Sort wildcard names. +- [#1957](https://github.com/influxdb/influxdb/pull/1957): Graphite numbers are always float64. +- [#1955](https://github.com/influxdb/influxdb/pull/1955): Prohibit creation of databases with no name. Thanks @dullgiulio +- [#1952](https://github.com/influxdb/influxdb/pull/1952): Handle delete statement with an error. Thanks again to @dullgiulio + +### Features +- [#1935](https://github.com/influxdb/influxdb/pull/1935): Implement stateless broker for Raft. +- [#1936](https://github.com/influxdb/influxdb/pull/1936): Implement "SHOW STATS" and self-monitoring + +### Features +- [#1909](https://github.com/influxdb/influxdb/pull/1909): Implement a dump command. + +## v0.9.0-rc11 [2015-03-13] + +### Bugfixes +- [#1917](https://github.com/influxdb/influxdb/pull/1902): Creating Infinite Retention Policy Failed. +- [#1758](https://github.com/influxdb/influxdb/pull/1758): Add Graphite Integration Test. +- [#1929](https://github.com/influxdb/influxdb/pull/1929): Default Retention Policy incorrectly auto created. +- [#1930](https://github.com/influxdb/influxdb/pull/1930): Auto create database for graphite if not specified. +- [#1908](https://github.com/influxdb/influxdb/pull/1908): Cosmetic CLI output fixes. +- [#1931](https://github.com/influxdb/influxdb/pull/1931): Add default column to SHOW RETENTION POLICIES. +- [#1937](https://github.com/influxdb/influxdb/pull/1937): OFFSET should be allowed to be 0. + +### Features +- [#1902](https://github.com/influxdb/influxdb/pull/1902): Enforce retention policies to have a minimum duration. +- [#1906](https://github.com/influxdb/influxdb/pull/1906): Add show servers to query language. +- [#1925](https://github.com/influxdb/influxdb/pull/1925): Add `fill(none)`, `fill(previous)`, and `fill()` to queries. + +## v0.9.0-rc10 [2015-03-09] + +### Bugfixes +- [#1867](https://github.com/influxdb/influxdb/pull/1867): Fix race accessing topic replicas map +- [#1864](https://github.com/influxdb/influxdb/pull/1864): fix race in startStateLoop +- [#1753](https://github.com/influxdb/influxdb/pull/1874): Do Not Panic on Missing Dirs +- [#1877](https://github.com/influxdb/influxdb/pull/1877): Broker clients track broker leader +- [#1862](https://github.com/influxdb/influxdb/pull/1862): Fix memory leak in `httpd.serveWait`. Thanks @mountkin +- [#1883](https://github.com/influxdb/influxdb/pull/1883): RLock server during retention policy enforcement. Thanks @grisha +- [#1868](https://github.com/influxdb/influxdb/pull/1868): Use `BatchPoints` for `client.Write` method. Thanks @vladlopes, @georgmu, @d2g, @evanphx, @akolosov. +- [#1881](https://github.com/influxdb/influxdb/pull/1881): Update documentation for `client` package. Misc library tweaks. +- Fix queries with multiple where clauses on tags, times and fields. Fix queries that have where clauses on fields not in the select + +### Features +- [#1875](https://github.com/influxdb/influxdb/pull/1875): Support trace logging of Raft. +- [#1895](https://github.com/influxdb/influxdb/pull/1895): Auto-create a retention policy when a database is created. +- [#1897](https://github.com/influxdb/influxdb/pull/1897): Pre-create shard groups. +- [#1900](https://github.com/influxdb/influxdb/pull/1900): Change `LIMIT` to `SLIMIT` and implement `LIMIT` and `OFFSET` + +## v0.9.0-rc9 [2015-03-06] + +### Bugfixes +- [#1872](https://github.com/influxdb/influxdb/pull/1872): Fix "stale term" errors with raft + +## v0.9.0-rc8 [2015-03-05] + +### Bugfixes +- [#1836](https://github.com/influxdb/influxdb/pull/1836): Store each parsed shell command in history file. +- [#1789](https://github.com/influxdb/influxdb/pull/1789): add --config-files option to fpm command. Thanks @kylezh +- [#1859](https://github.com/influxdb/influxdb/pull/1859): Queries with a `GROUP BY *` clause were returning a 500 if done against a measurement that didn't exist + +### Features +- [#1755](https://github.com/influxdb/influxdb/pull/1848): Support JSON data ingest over UDP +- [#1857](https://github.com/influxdb/influxdb/pull/1857): Support retention policies with infinite duration +- [#1858](https://github.com/influxdb/influxdb/pull/1858): Enable detailed tracing of write path + +## v0.9.0-rc7 [2015-03-02] + +### Features +- [#1813](https://github.com/influxdb/influxdb/pull/1813): Queries for missing measurements or fields now return a 200 with an error message in the series JSON. +- [#1826](https://github.com/influxdb/influxdb/pull/1826), [#1827](https://github.com/influxdb/influxdb/pull/1827): Fixed queries with `WHERE` clauses against fields. + +### Bugfixes + +- [#1744](https://github.com/influxdb/influxdb/pull/1744): Allow retention policies to be modified without specifying replication factor. Thanks @kylezh +- [#1809](https://github.com/influxdb/influxdb/pull/1809): Packaging post-install script unconditionally removes init.d symlink. Thanks @sineos + +## v0.9.0-rc6 [2015-02-27] + +### Bugfixes + +- [#1780](https://github.com/influxdb/influxdb/pull/1780): Malformed identifiers get through the parser +- [#1775](https://github.com/influxdb/influxdb/pull/1775): Panic "index out of range" on some queries +- [#1744](https://github.com/influxdb/influxdb/pull/1744): Select shard groups which completely encompass time range. Thanks @kylezh. + +## v0.9.0-rc5 [2015-02-27] + +### Bugfixes + +- [#1752](https://github.com/influxdb/influxdb/pull/1752): remove debug log output from collectd. +- [#1720](https://github.com/influxdb/influxdb/pull/1720): Parse Series IDs as unsigned 32-bits. +- [#1767](https://github.com/influxdb/influxdb/pull/1767): Drop Series was failing across shards. Issue #1761. +- [#1773](https://github.com/influxdb/influxdb/pull/1773): Fix bug when merging series together that have unequal number of points in a group by interval +- [#1771](https://github.com/influxdb/influxdb/pull/1771): Make `SHOW SERIES` return IDs and support `LIMIT` and `OFFSET` + +### Features + +- [#1698](https://github.com/influxdb/influxdb/pull/1698): Wire up DROP MEASUREMENT + +## v0.9.0-rc4 [2015-02-24] + +### Bugfixes + +- Fix authentication issue with continuous queries +- Print version in the log on startup + +## v0.9.0-rc3 [2015-02-23] + +### Features + +- [#1659](https://github.com/influxdb/influxdb/pull/1659): WHERE against regexes: `WHERE =~ '.*asdf' +- [#1580](https://github.com/influxdb/influxdb/pull/1580): Add support for fields with bool, int, or string data types +- [#1687](https://github.com/influxdb/influxdb/pull/1687): Change `Rows` to `Series` in results output. BREAKING API CHANGE +- [#1629](https://github.com/influxdb/influxdb/pull/1629): Add support for `DROP SERIES` queries +- [#1632](https://github.com/influxdb/influxdb/pull/1632): Add support for `GROUP BY *` to return all series within a measurement +- [#1689](https://github.com/influxdb/influxdb/pull/1689): Change `SHOW TAG VALUES WITH KEY="foo"` to use the key name in the result. BREAKING API CHANGE +- [#1699](https://github.com/influxdb/influxdb/pull/1699): Add CPU and memory profiling options to daemon +- [#1672](https://github.com/influxdb/influxdb/pull/1672): Add index tracking to metastore. Makes downed node recovery actually work +- [#1591](https://github.com/influxdb/influxdb/pull/1591): Add `spread` aggregate function +- [#1576](https://github.com/influxdb/influxdb/pull/1576): Add `first` and `last` aggregate functions +- [#1573](https://github.com/influxdb/influxdb/pull/1573): Add `stddev` aggregate function +- [#1565](https://github.com/influxdb/influxdb/pull/1565): Add the admin interface back into the server and update for new API +- [#1562](https://github.com/influxdb/influxdb/pull/1562): Enforce retention policies +- [#1700](https://github.com/influxdb/influxdb/pull/1700): Change `Values` to `Fields` on writes. BREAKING API CHANGE +- [#1706](https://github.com/influxdb/influxdb/pull/1706): Add support for `LIMIT` and `OFFSET`, which work on the number of series returned in a query. To limit the number of data points use a `WHERE time` clause + +### Bugfixes + +- [#1636](https://github.com/influxdb/influxdb/issues/1636): Don't store number of fields in raw data. THIS IS A BREAKING DATA CHANGE. YOU MUST START WITH A FRESH DATABASE +- [#1701](https://github.com/influxdb/influxdb/pull/1701), [#1667](https://github.com/influxdb/influxdb/pull/1667), [#1663](https://github.com/influxdb/influxdb/pull/1663), [#1615](https://github.com/influxdb/influxdb/pull/1615): Raft fixes +- [#1644](https://github.com/influxdb/influxdb/pull/1644): Add batching support for significantly improved write performance +- [#1704](https://github.com/influxdb/influxdb/pull/1704): Fix queries that pull back raw data (i.e. ones without aggregate functions) +- [#1718](https://github.com/influxdb/influxdb/pull/1718): Return an error on write if any of the points are don't have at least one field +- [#1806](https://github.com/influxdb/influxdb/pull/1806): Fix regex parsing. Change regex syntax to use / delimiters. + + +## v0.9.0-rc1,2 [no public release] + +### Features + +- Support for tags added +- New queries for showing measurement names, tag keys, and tag values +- Renamed shard spaces to retention policies +- Deprecated matching against regex in favor of explicit writing and querying on retention policies +- Pure Go InfluxQL parser +- Switch to BoltDB as underlying datastore +- BoltDB backed metastore to store schema information +- Updated HTTP API to only have two endpoints `/query` and `/write` +- Added all administrative functions to the query language +- Change cluster architecture to have brokers and data nodes +- Switch to streaming Raft implementation +- In memory inverted index of the tag data +- Pure Go implementation! + +## v0.8.6 [2014-11-15] + +### Features + +- [Issue #973](https://github.com/influxdb/influxdb/issues/973). Support + joining using a regex or list of time series +- [Issue #1068](https://github.com/influxdb/influxdb/issues/1068). Print + the processor chain when the query is started + +### Bugfixes + +- [Issue #584](https://github.com/influxdb/influxdb/issues/584). Don't + panic if the process died while initializing +- [Issue #663](https://github.com/influxdb/influxdb/issues/663). Make + sure all sub servies are closed when are stopping InfluxDB +- [Issue #671](https://github.com/influxdb/influxdb/issues/671). Fix + the Makefile package target for Mac OSX +- [Issue #800](https://github.com/influxdb/influxdb/issues/800). Use + su instead of sudo in the init script. This fixes the startup problem + on RHEL 6. +- [Issue #925](https://github.com/influxdb/influxdb/issues/925). Don't + generate invalid query strings for single point queries +- [Issue #943](https://github.com/influxdb/influxdb/issues/943). Don't + take two snapshots at the same time +- [Issue #947](https://github.com/influxdb/influxdb/issues/947). Exit + nicely if the daemon doesn't have permission to write to the log. +- [Issue #959](https://github.com/influxdb/influxdb/issues/959). Stop using + closed connections in the protobuf client. +- [Issue #978](https://github.com/influxdb/influxdb/issues/978). Check + for valgrind and mercurial in the configure script +- [Issue #996](https://github.com/influxdb/influxdb/issues/996). Fill should + fill the time range even if no points exists in the given time range +- [Issue #1008](https://github.com/influxdb/influxdb/issues/1008). Return + an appropriate exit status code depending on whether the process exits + due to an error or exits gracefully. +- [Issue #1024](https://github.com/influxdb/influxdb/issues/1024). Hitting + open files limit causes influxdb to create shards in loop. +- [Issue #1069](https://github.com/influxdb/influxdb/issues/1069). Fix + deprecated interface endpoint in Admin UI. +- [Issue #1076](https://github.com/influxdb/influxdb/issues/1076). Fix + the timestamps of data points written by the collectd plugin. (Thanks, + @renchap for reporting this bug) +- [Issue #1078](https://github.com/influxdb/influxdb/issues/1078). Make sure + we don't resurrect shard directories for shards that have already expired +- [Issue #1085](https://github.com/influxdb/influxdb/issues/1085). Set + the connection string of the local raft node +- [Issue #1092](https://github.com/influxdb/influxdb/issues/1093). Set + the connection string of the local node in the raft snapshot. +- [Issue #1100](https://github.com/influxdb/influxdb/issues/1100). Removing + a non-existent shard space causes the cluster to panic. +- [Issue #1113](https://github.com/influxdb/influxdb/issues/1113). A nil + engine.ProcessorChain causes a panic. + +## v0.8.5 [2014-10-27] + +### Features + +- [Issue #1055](https://github.com/influxdb/influxdb/issues/1055). Allow + graphite and collectd input plugins to have separate binding address + +### Bugfixes + +- [Issue #1058](https://github.com/influxdb/influxdb/issues/1058). Use + the query language instead of the continuous query endpoints that + were removed in 0.8.4 +- [Issue #1022](https://github.com/influxdb/influxdb/issues/1022). Return + an +Inf or NaN instead of panicing when we encounter a divide by zero +- [Issue #821](https://github.com/influxdb/influxdb/issues/821). Don't + scan through points when we hit the limit +- [Issue #1051](https://github.com/influxdb/influxdb/issues/1051). Fix + timestamps when the collectd is used and low resolution timestamps + is set. + +## v0.8.4 [2014-10-24] + +### Bugfixes + +- Remove the continuous query api endpoints since the query language + has all the features needed to list and delete continuous queries. +- [Issue #778](https://github.com/influxdb/influxdb/issues/778). Selecting + from a non-existent series should give a better error message indicating + that the series doesn't exist +- [Issue #988](https://github.com/influxdb/influxdb/issues/988). Check + the arguments of `top()` and `bottom()` +- [Issue #1021](https://github.com/influxdb/influxdb/issues/1021). Make + redirecting to standard output and standard error optional instead of + going to `/dev/null`. This can now be configured by setting `$STDOUT` + in `/etc/default/influxdb` +- [Issue #985](https://github.com/influxdb/influxdb/issues/985). Make + sure we drop a shard only when there's no one using it. Otherwise, the + shard can be closed when another goroutine is writing to it which will + cause random errors and possibly corruption of the database. + +### Features + +- [Issue #1047](https://github.com/influxdb/influxdb/issues/1047). Allow + merge() to take a list of series (as opposed to a regex in #72) + +## v0.8.4-rc.1 [2014-10-21] + +### Bugfixes + +- [Issue #1040](https://github.com/influxdb/influxdb/issues/1040). Revert + to older raft snapshot if the latest one is corrupted +- [Issue #1004](https://github.com/influxdb/influxdb/issues/1004). Querying + for data outside of existing shards returns an empty response instead of + throwing a `Couldn't lookup columns` error +- [Issue #1020](https://github.com/influxdb/influxdb/issues/1020). Change + init script exit codes to conform to the lsb standards. (Thanks, @spuder) +- [Issue #1011](https://github.com/influxdb/influxdb/issues/1011). Fix + the tarball for homebrew so that rocksdb is included and the directory + structure is clean +- [Issue #1007](https://github.com/influxdb/influxdb/issues/1007). Fix + the content type when an error occurs and the client requests + compression. +- [Issue #916](https://github.com/influxdb/influxdb/issues/916). Set + the ulimit in the init script with a way to override the limit +- [Issue #742](https://github.com/influxdb/influxdb/issues/742). Fix + rocksdb for Mac OSX +- [Issue #387](https://github.com/influxdb/influxdb/issues/387). Aggregations + with group by time(1w), time(1m) and time(1y) (for week, month and + year respectively) will cause the start time and end time of the bucket + to fall on the logical boundaries of the week, month or year. +- [Issue #334](https://github.com/influxdb/influxdb/issues/334). Derivative + for queries with group by time() and fill(), will take the difference + between the first value in the bucket and the first value of the next + bucket. +- [Issue #972](https://github.com/influxdb/influxdb/issues/972). Don't + assign duplicate server ids + +### Features + +- [Issue #722](https://github.com/influxdb/influxdb/issues/722). Add + an install target to the Makefile +- [Issue #1032](https://github.com/influxdb/influxdb/issues/1032). Include + the admin ui static assets in the binary +- [Issue #1019](https://github.com/influxdb/influxdb/issues/1019). Upgrade + to rocksdb 3.5.1 +- [Issue #992](https://github.com/influxdb/influxdb/issues/992). Add + an input plugin for collectd. (Thanks, @kimor79) +- [Issue #72](https://github.com/influxdb/influxdb/issues/72). Support merge + for multiple series using regex syntax + +## v0.8.3 [2014-09-24] + +### Bugfixes + +- [Issue #885](https://github.com/influxdb/influxdb/issues/885). Multiple + queries separated by semicolons work as expected. Queries are process + sequentially +- [Issue #652](https://github.com/influxdb/influxdb/issues/652). Return an + error if an invalid column is used in the where clause +- [Issue #794](https://github.com/influxdb/influxdb/issues/794). Fix case + insensitive regex matching +- [Issue #853](https://github.com/influxdb/influxdb/issues/853). Move + cluster config from raft to API. +- [Issue #714](https://github.com/influxdb/influxdb/issues/714). Don't + panic on invalid boolean operators. +- [Issue #843](https://github.com/influxdb/influxdb/issues/843). Prevent blank database names +- [Issue #780](https://github.com/influxdb/influxdb/issues/780). Fix + fill() for all aggregators +- [Issue #923](https://github.com/influxdb/influxdb/issues/923). Enclose + table names in double quotes in the result of GetQueryString() +- [Issue #923](https://github.com/influxdb/influxdb/issues/923). Enclose + table names in double quotes in the result of GetQueryString() +- [Issue #967](https://github.com/influxdb/influxdb/issues/967). Return an + error if the storage engine can't be created +- [Issue #954](https://github.com/influxdb/influxdb/issues/954). Don't automatically + create shards which was causing too many shards to be created when used with + grafana +- [Issue #939](https://github.com/influxdb/influxdb/issues/939). Aggregation should + ignore null values and invalid values, e.g. strings with mean(). +- [Issue #964](https://github.com/influxdb/influxdb/issues/964). Parse + big int in queries properly. + +## v0.8.2 [2014-09-05] + +### Bugfixes + +- [Issue #886](https://github.com/influxdb/influxdb/issues/886). Update shard space to not set defaults + +- [Issue #867](https://github.com/influxdb/influxdb/issues/867). Add option to return shard space mappings in list series + +### Bugfixes + +- [Issue #652](https://github.com/influxdb/influxdb/issues/652). Return + a meaningful error if an invalid column is used in where clause + after joining multiple series + +## v0.8.2 [2014-09-08] + +### Features + +- Added API endpoint to update shard space definitions + +### Bugfixes + +- [Issue #886](https://github.com/influxdb/influxdb/issues/886). Shard space regexes reset after restart of InfluxDB + +## v0.8.1 [2014-09-03] + +- [Issue #896](https://github.com/influxdb/influxdb/issues/896). Allow logging to syslog. Thanks @malthe + +### Bugfixes + +- [Issue #868](https://github.com/influxdb/influxdb/issues/868). Don't panic when upgrading a snapshot from 0.7.x +- [Issue #887](https://github.com/influxdb/influxdb/issues/887). The first continuous query shouldn't trigger backfill if it had backfill disabled +- [Issue #674](https://github.com/influxdb/influxdb/issues/674). Graceful exit when config file is invalid. (Thanks, @DavidBord) +- [Issue #857](https://github.com/influxdb/influxdb/issues/857). More informative list servers api. (Thanks, @oliveagle) + +## v0.8.0 [2014-08-22] + +### Features + +- [Issue #850](https://github.com/influxdb/influxdb/issues/850). Makes the server listing more informative + +### Bugfixes + +- [Issue #779](https://github.com/influxdb/influxdb/issues/779). Deleting expired shards isn't thread safe. +- [Issue #860](https://github.com/influxdb/influxdb/issues/860). Load database config should validate shard spaces. +- [Issue #862](https://github.com/influxdb/influxdb/issues/862). Data migrator should have option to set delay time. + +## v0.8.0-rc.5 [2014-08-15] + +### Features + +- [Issue #376](https://github.com/influxdb/influxdb/issues/376). List series should support regex filtering +- [Issue #745](https://github.com/influxdb/influxdb/issues/745). Add continuous queries to the database config +- [Issue #746](https://github.com/influxdb/influxdb/issues/746). Add data migration tool for 0.8.0 + +### Bugfixes + +- [Issue #426](https://github.com/influxdb/influxdb/issues/426). Fill should fill the entire time range that is requested +- [Issue #740](https://github.com/influxdb/influxdb/issues/740). Don't emit non existent fields when joining series with different fields +- [Issue #744](https://github.com/influxdb/influxdb/issues/744). Admin site should have all assets locally +- [Issue #767](https://github.com/influxdb/influxdb/issues/768). Remove shards whenever they expire +- [Issue #781](https://github.com/influxdb/influxdb/issues/781). Don't emit non existent fields when joining series with different fields +- [Issue #791](https://github.com/influxdb/influxdb/issues/791). Move database config loader to be an API endpoint +- [Issue #809](https://github.com/influxdb/influxdb/issues/809). Migration path from 0.7 -> 0.8 +- [Issue #811](https://github.com/influxdb/influxdb/issues/811). Gogoprotobuf removed `ErrWrongType`, which is depended on by Raft +- [Issue #820](https://github.com/influxdb/influxdb/issues/820). Query non-local shard with time range to avoid getting back points not in time range +- [Issue #827](https://github.com/influxdb/influxdb/issues/827). Don't leak file descriptors in the WAL +- [Issue #830](https://github.com/influxdb/influxdb/issues/830). List series should return series in lexicographic sorted order +- [Issue #831](https://github.com/influxdb/influxdb/issues/831). Move create shard space to be db specific + +## v0.8.0-rc.4 [2014-07-29] + +### Bugfixes + +- [Issue #774](https://github.com/influxdb/influxdb/issues/774). Don't try to parse "inf" shard retention policy +- [Issue #769](https://github.com/influxdb/influxdb/issues/769). Use retention duration when determining expired shards. (Thanks, @shugo) +- [Issue #736](https://github.com/influxdb/influxdb/issues/736). Only db admins should be able to drop a series +- [Issue #713](https://github.com/influxdb/influxdb/issues/713). Null should be a valid fill value +- [Issue #644](https://github.com/influxdb/influxdb/issues/644). Graphite api should write data in batches to the coordinator +- [Issue #740](https://github.com/influxdb/influxdb/issues/740). Panic when distinct fields are selected from an inner join +- [Issue #781](https://github.com/influxdb/influxdb/issues/781). Panic when distinct fields are added after an inner join + +## v0.8.0-rc.3 [2014-07-21] + +### Bugfixes + +- [Issue #752](https://github.com/influxdb/influxdb/issues/752). `./configure` should use goroot to find gofmt +- [Issue #758](https://github.com/influxdb/influxdb/issues/758). Clarify the reason behind graphite input plugin not starting. (Thanks, @otoolep) +- [Issue #759](https://github.com/influxdb/influxdb/issues/759). Don't revert the regex in the shard space. (Thanks, @shugo) +- [Issue #760](https://github.com/influxdb/influxdb/issues/760). Removing a server should remove it from the shard server ids. (Thanks, @shugo) +- [Issue #772](https://github.com/influxdb/influxdb/issues/772). Add sentinel values to all db. This caused the last key in the db to not be fetched properly. + + +## v0.8.0-rc.2 [2014-07-15] + +- This release is to fix a build error in rc1 which caused rocksdb to not be available +- Bump up the `max-open-files` option to 1000 on all storage engines +- Lower the `write-buffer-size` to 1000 + +## v0.8.0-rc.1 [2014-07-15] + +### Features + +- [Issue #643](https://github.com/influxdb/influxdb/issues/643). Support pretty print json. (Thanks, @otoolep) +- [Issue #641](https://github.com/influxdb/influxdb/issues/641). Support multiple storage engines +- [Issue #665](https://github.com/influxdb/influxdb/issues/665). Make build tmp directory configurable in the make file. (Thanks, @dgnorton) +- [Issue #667](https://github.com/influxdb/influxdb/issues/667). Enable compression on all GET requests and when writing data +- [Issue #648](https://github.com/influxdb/influxdb/issues/648). Return permissions when listing db users. (Thanks, @nicolai86) +- [Issue #682](https://github.com/influxdb/influxdb/issues/682). Allow continuous queries to run without backfill (Thanks, @dhammika) +- [Issue #689](https://github.com/influxdb/influxdb/issues/689). **REQUIRES DATA MIGRATION** Move metadata into raft +- [Issue #255](https://github.com/influxdb/influxdb/issues/255). Support millisecond precision using `ms` suffix +- [Issue #95](https://github.com/influxdb/influxdb/issues/95). Drop database should not be synchronous +- [Issue #571](https://github.com/influxdb/influxdb/issues/571). Add support for arbitrary number of shard spaces and retention policies +- Default storage engine changed to RocksDB + +### Bugfixes + +- [Issue #651](https://github.com/influxdb/influxdb/issues/651). Change permissions of symlink which fix some installation issues. (Thanks, @Dieterbe) +- [Issue #670](https://github.com/influxdb/influxdb/issues/670). Don't warn on missing influxdb user on fresh installs +- [Issue #676](https://github.com/influxdb/influxdb/issues/676). Allow storing high precision integer values without losing any information +- [Issue #695](https://github.com/influxdb/influxdb/issues/695). Prevent having duplicate field names in the write payload. (Thanks, @seunglee150) +- [Issue #731](https://github.com/influxdb/influxdb/issues/731). Don't enable the udp plugin if the `enabled` option is set to false +- [Issue #733](https://github.com/influxdb/influxdb/issues/733). Print an `INFO` message when the input plugin is disabled +- [Issue #707](https://github.com/influxdb/influxdb/issues/707). Graphite input plugin should work payload delimited by any whitespace character +- [Issue #734](https://github.com/influxdb/influxdb/issues/734). Don't buffer non replicated writes +- [Issue #465](https://github.com/influxdb/influxdb/issues/465). Recreating a currently deleting db or series doesn't bring back the old data anymore +- [Issue #358](https://github.com/influxdb/influxdb/issues/358). **BREAKING** List series should return as a single series +- [Issue #499](https://github.com/influxdb/influxdb/issues/499). **BREAKING** Querying non-existent database or series will return an error +- [Issue #570](https://github.com/influxdb/influxdb/issues/570). InfluxDB crashes during delete/drop of database +- [Issue #592](https://github.com/influxdb/influxdb/issues/592). Drop series is inefficient + +## v0.7.3 [2014-06-13] + +### Bugfixes + +- [Issue #637](https://github.com/influxdb/influxdb/issues/637). Truncate log files if the last request wasn't written properly +- [Issue #646](https://github.com/influxdb/influxdb/issues/646). CRITICAL: Duplicate shard ids for new shards if old shards are deleted. + +## v0.7.2 [2014-05-30] + +### Features + +- [Issue #521](https://github.com/influxdb/influxdb/issues/521). MODE works on all datatypes (Thanks, @richthegeek) + +### Bugfixes + +- [Issue #418](https://github.com/influxdb/influxdb/pull/418). Requests or responses larger than MAX_REQUEST_SIZE break things. +- [Issue #606](https://github.com/influxdb/influxdb/issues/606). InfluxDB will fail to start with invalid permission if log.txt didn't exist +- [Issue #602](https://github.com/influxdb/influxdb/issues/602). Merge will fail to work across shards + +### Features + +## v0.7.1 [2014-05-29] + +### Bugfixes + +- [Issue #579](https://github.com/influxdb/influxdb/issues/579). Reject writes to nonexistent databases +- [Issue #597](https://github.com/influxdb/influxdb/issues/597). Force compaction after deleting data + +### Features + +- [Issue #476](https://github.com/influxdb/influxdb/issues/476). Support ARM architecture +- [Issue #578](https://github.com/influxdb/influxdb/issues/578). Support aliasing for expressions in parenthesis +- [Issue #544](https://github.com/influxdb/influxdb/pull/544). Support forcing node removal from a cluster +- [Issue #591](https://github.com/influxdb/influxdb/pull/591). Support multiple udp input plugins (Thanks, @tpitale) +- [Issue #600](https://github.com/influxdb/influxdb/pull/600). Report version, os, arch, and raftName once per day. + +## v0.7.0 [2014-05-23] + +### Bugfixes + +- [Issue #557](https://github.com/influxdb/influxdb/issues/557). Group by time(1y) doesn't work while time(365d) works +- [Issue #547](https://github.com/influxdb/influxdb/issues/547). Add difference function (Thanks, @mboelstra) +- [Issue #550](https://github.com/influxdb/influxdb/issues/550). Fix tests on 32-bit ARM +- [Issue #524](https://github.com/influxdb/influxdb/issues/524). Arithmetic operators and where conditions don't play nice together +- [Issue #561](https://github.com/influxdb/influxdb/issues/561). Fix missing query in parsing errors +- [Issue #563](https://github.com/influxdb/influxdb/issues/563). Add sample config for graphite over udp +- [Issue #537](https://github.com/influxdb/influxdb/issues/537). Incorrect query syntax causes internal error +- [Issue #565](https://github.com/influxdb/influxdb/issues/565). Empty series names shouldn't cause a panic +- [Issue #575](https://github.com/influxdb/influxdb/issues/575). Single point select doesn't interpret timestamps correctly +- [Issue #576](https://github.com/influxdb/influxdb/issues/576). We shouldn't set timestamps and sequence numbers when listing cq +- [Issue #560](https://github.com/influxdb/influxdb/issues/560). Use /dev/urandom instead of /dev/random +- [Issue #502](https://github.com/influxdb/influxdb/issues/502). Fix a + race condition in assigning id to db+series+field (Thanks @ohurvitz + for reporting this bug and providing a script to repro) + +### Features + +- [Issue #567](https://github.com/influxdb/influxdb/issues/567). Allow selecting from multiple series names by separating them with commas (Thanks, @peekeri) + +### Deprecated + +- [Issue #460](https://github.com/influxdb/influxdb/issues/460). Don't start automatically after installing +- [Issue #529](https://github.com/influxdb/influxdb/issues/529). Don't run influxdb as root +- [Issue #443](https://github.com/influxdb/influxdb/issues/443). Use `name` instead of `username` when returning cluster admins + +## v0.6.5 [2014-05-19] + +### Features + +- [Issue #551](https://github.com/influxdb/influxdb/issues/551). Add TOP and BOTTOM aggregate functions (Thanks, @chobie) + +### Bugfixes + +- [Issue #555](https://github.com/influxdb/influxdb/issues/555). Fix a regression introduced in the raft snapshot format + +## v0.6.4 [2014-05-16] + +### Features + +- Make the write batch size configurable (also applies to deletes) +- Optimize writing to multiple series +- [Issue #546](https://github.com/influxdb/influxdb/issues/546). Add UDP support for Graphite API (Thanks, @peekeri) + +### Bugfixes + +- Fix a bug in shard logic that caused short term shards to be clobbered with long term shards +- [Issue #489](https://github.com/influxdb/influxdb/issues/489). Remove replication factor from CreateDatabase command + +## v0.6.3 [2014-05-13] + +### Features + +- [Issue #505](https://github.com/influxdb/influxdb/issues/505). Return a version header with http the response (Thanks, @majst01) +- [Issue #520](https://github.com/influxdb/influxdb/issues/520). Print the version to the log file + +### Bugfixes + +- [Issue #516](https://github.com/influxdb/influxdb/issues/516). Close WAL log/index files when they aren't being used +- [Issue #532](https://github.com/influxdb/influxdb/issues/532). Don't log graphite connection EOF as an error +- [Issue #535](https://github.com/influxdb/influxdb/issues/535). WAL Replay hangs if response isn't received +- [Issue #538](https://github.com/influxdb/influxdb/issues/538). Don't panic if the same series existed twice in the request with different columns +- [Issue #536](https://github.com/influxdb/influxdb/issues/536). Joining the cluster after shards are creating shouldn't cause new nodes to panic +- [Issue #539](https://github.com/influxdb/influxdb/issues/539). count(distinct()) with fill shouldn't panic on empty groups +- [Issue #534](https://github.com/influxdb/influxdb/issues/534). Create a new series when interpolating + +## v0.6.2 [2014-05-09] + +### Bugfixes + +- [Issue #511](https://github.com/influxdb/influxdb/issues/511). Don't automatically create the database when a db user is created +- [Issue #512](https://github.com/influxdb/influxdb/issues/512). Group by should respect null values +- [Issue #518](https://github.com/influxdb/influxdb/issues/518). Filter Infinities and NaNs from the returned json +- [Issue #522](https://github.com/influxdb/influxdb/issues/522). Committing requests while replaying caused the WAL to skip some log files +- [Issue #369](https://github.com/influxdb/influxdb/issues/369). Fix some edge cases with WAL recovery + +## v0.6.1 [2014-05-06] + +### Bugfixes + +- [Issue #500](https://github.com/influxdb/influxdb/issues/500). Support `y` suffix in time durations +- [Issue #501](https://github.com/influxdb/influxdb/issues/501). Writes with invalid payload should be rejected +- [Issue #507](https://github.com/influxdb/influxdb/issues/507). New cluster admin passwords don't propagate properly to other nodes in a cluster +- [Issue #508](https://github.com/influxdb/influxdb/issues/508). Don't replay WAL entries for servers with no shards +- [Issue #464](https://github.com/influxdb/influxdb/issues/464). Admin UI shouldn't draw graphs for string columns +- [Issue #480](https://github.com/influxdb/influxdb/issues/480). Large values on the y-axis get cut off + +## v0.6.0 [2014-05-02] + +### Feature + +- [Issue #477](https://github.com/influxdb/influxdb/issues/477). Add a udp json interface (Thanks, Julien Ammous) +- [Issue #491](https://github.com/influxdb/influxdb/issues/491). Make initial root password settable through env variable (Thanks, Edward Muller) + +### Bugfixes + +- [Issue #469](https://github.com/influxdb/influxdb/issues/469). Drop continuous queries when a database is dropped +- [Issue #431](https://github.com/influxdb/influxdb/issues/431). Don't log to standard output if a log file is specified in the config file +- [Issue #483](https://github.com/influxdb/influxdb/issues/483). Return 409 if a database already exist (Thanks, Edward Muller) +- [Issue #486](https://github.com/influxdb/influxdb/issues/486). Columns used in the target of continuous query shouldn't be inserted in the time series +- [Issue #490](https://github.com/influxdb/influxdb/issues/490). Database user password's cannot be changed (Thanks, Edward Muller) +- [Issue #495](https://github.com/influxdb/influxdb/issues/495). Enforce write permissions properly + +## v0.5.12 [2014-04-29] + +### Bugfixes + +- [Issue #419](https://github.com/influxdb/influxdb/issues/419),[Issue #478](https://github.com/influxdb/influxdb/issues/478). Allow hostname, raft and protobuf ports to be changed, without requiring manual intervention from the user + +## v0.5.11 [2014-04-25] + +### Features + +- [Issue #471](https://github.com/influxdb/influxdb/issues/471). Read and write permissions should be settable through the http api + +### Bugfixes + +- [Issue #323](https://github.com/influxdb/influxdb/issues/323). Continuous queries should guard against data loops +- [Issue #473](https://github.com/influxdb/influxdb/issues/473). Engine memory optimization + +## v0.5.10 [2014-04-22] + +### Features + +- [Issue #463](https://github.com/influxdb/influxdb/issues/463). Allow series names to use any character (escape by wrapping in double quotes) +- [Issue #447](https://github.com/influxdb/influxdb/issues/447). Allow @ in usernames +- [Issue #466](https://github.com/influxdb/influxdb/issues/466). Allow column names to use any character (escape by wrapping in double quotes) + +### Bugfixes + +- [Issue #458](https://github.com/influxdb/influxdb/issues/458). Continuous queries with group by time() and a column should insert sequence numbers of 1 +- [Issue #457](https://github.com/influxdb/influxdb/issues/457). Deleting series that start with capital letters should work + +## v0.5.9 [2014-04-18] + +### Bugfixes + +- [Issue #446](https://github.com/influxdb/influxdb/issues/446). Check for (de)serialization errors +- [Issue #456](https://github.com/influxdb/influxdb/issues/456). Continuous queries failed if one of the group by columns had null value +- [Issue #455](https://github.com/influxdb/influxdb/issues/455). Comparison operators should ignore null values + +## v0.5.8 [2014-04-17] + +- Renamed config.toml.sample to config.sample.toml + +### Bugfixes + +- [Issue #244](https://github.com/influxdb/influxdb/issues/244). Reconstruct the query from the ast +- [Issue #449](https://github.com/influxdb/influxdb/issues/449). Heartbeat timeouts can cause reading from connection to lock up +- [Issue #451](https://github.com/influxdb/influxdb/issues/451). Reduce the aggregation state that is kept in memory so that + aggregation queries over large periods of time don't take insance amount of memory + +## v0.5.7 [2014-04-15] + +### Features + +- Queries are now logged as INFO in the log file before they run + +### Bugfixes + +- [Issue #328](https://github.com/influxdb/influxdb/issues/328). Join queries with math expressions don't work +- [Issue #440](https://github.com/influxdb/influxdb/issues/440). Heartbeat timeouts in logs +- [Issue #442](https://github.com/influxdb/influxdb/issues/442). shouldQuerySequentially didn't work as expected + causing count(*) queries on large time series to use + lots of memory +- [Issue #437](https://github.com/influxdb/influxdb/issues/437). Queries with negative constants don't parse properly +- [Issue #432](https://github.com/influxdb/influxdb/issues/432). Deleted data using a delete query is resurrected after a server restart +- [Issue #439](https://github.com/influxdb/influxdb/issues/439). Report the right location of the error in the query +- Fix some bugs with the WAL recovery on startup + +## v0.5.6 [2014-04-08] + +### Features + +- [Issue #310](https://github.com/influxdb/influxdb/issues/310). Request should support multiple timeseries +- [Issue #416](https://github.com/influxdb/influxdb/issues/416). Improve the time it takes to drop database + +### Bugfixes + +- [Issue #413](https://github.com/influxdb/influxdb/issues/413). Don't assume that group by interval is greater than a second +- [Issue #415](https://github.com/influxdb/influxdb/issues/415). Include the database when sending an auth error back to the user +- [Issue #421](https://github.com/influxdb/influxdb/issues/421). Make read timeout a config option +- [Issue #392](https://github.com/influxdb/influxdb/issues/392). Different columns in different shards returns invalid results when a query spans those shards + +### Bugfixes + +## v0.5.5 [2014-04-04] + +- Upgrade leveldb 1.10 -> 1.15 + + This should be a backward compatible change, but is here for documentation only + +### Feature + +- Add a command line option to repair corrupted leveldb databases on startup +- [Issue #401](https://github.com/influxdb/influxdb/issues/401). No limit on the number of columns in the group by clause + +### Bugfixes + +- [Issue #398](https://github.com/influxdb/influxdb/issues/398). Support now() and NOW() in the query lang +- [Issue #403](https://github.com/influxdb/influxdb/issues/403). Filtering should work with join queries +- [Issue #404](https://github.com/influxdb/influxdb/issues/404). Filtering with invalid condition shouldn't crash the server +- [Issue #405](https://github.com/influxdb/influxdb/issues/405). Percentile shouldn't crash for small number of values +- [Issue #408](https://github.com/influxdb/influxdb/issues/408). Make InfluxDB recover from internal bugs and panics +- [Issue #390](https://github.com/influxdb/influxdb/issues/390). Multiple response.WriteHeader when querying as admin +- [Issue #407](https://github.com/influxdb/influxdb/issues/407). Start processing continuous queries only after the WAL is initialized +- Close leveldb databases properly if we couldn't create a new Shard. See leveldb\_shard\_datastore\_test:131 + +## v0.5.4 [2014-04-02] + +### Bugfixes + +- [Issue #386](https://github.com/influxdb/influxdb/issues/386). Drop series should work with series containing dots +- [Issue #389](https://github.com/influxdb/influxdb/issues/389). Filtering shouldn't stop prematurely +- [Issue #341](https://github.com/influxdb/influxdb/issues/341). Make the number of shards that are queried in parallel configurable +- [Issue #394](https://github.com/influxdb/influxdb/issues/394). Support count(distinct) and count(DISTINCT) +- [Issue #362](https://github.com/influxdb/influxdb/issues/362). Limit should be enforced after aggregation + +## v0.5.3 [2014-03-31] + +### Bugfixes + +- [Issue #378](https://github.com/influxdb/influxdb/issues/378). Indexing should return if there are no requests added since the last index +- [Issue #370](https://github.com/influxdb/influxdb/issues/370). Filtering and limit should be enforced on the shards +- [Issue #379](https://github.com/influxdb/influxdb/issues/379). Boolean columns should be usable in where clauses +- [Issue #381](https://github.com/influxdb/influxdb/issues/381). Should be able to do deletes as a cluster admin + +## v0.5.2 [2014-03-28] + +### Bugfixes + +- [Issue #342](https://github.com/influxdb/influxdb/issues/342). Data resurrected after a server restart +- [Issue #367](https://github.com/influxdb/influxdb/issues/367). Influxdb won't start if the api port is commented out +- [Issue #355](https://github.com/influxdb/influxdb/issues/355). Return an error on wrong time strings +- [Issue #331](https://github.com/influxdb/influxdb/issues/331). Allow negative time values in the where clause +- [Issue #371](https://github.com/influxdb/influxdb/issues/371). Seris index isn't deleted when the series is dropped +- [Issue #360](https://github.com/influxdb/influxdb/issues/360). Store and recover continuous queries + +## v0.5.1 [2014-03-24] + +### Bugfixes + +- Revert the version of goraft due to a bug found in the latest version + +## v0.5.0 [2014-03-24] + +### Features + +- [Issue #293](https://github.com/influxdb/influxdb/pull/293). Implement a Graphite listener + +### Bugfixes + +- [Issue #340](https://github.com/influxdb/influxdb/issues/340). Writing many requests while replaying seems to cause commits out of order + +## v0.5.0-rc.6 [2014-03-20] + +### Bugfixes + +- Increase raft election timeout to avoid unecessary relections +- Sort points before writing them to avoid an explosion in the request + number when the points are written randomly +- [Issue #335](https://github.com/influxdb/influxdb/issues/335). Fixes regexp for interpolating more than one column value in continuous queries +- [Issue #318](https://github.com/influxdb/influxdb/pull/318). Support EXPLAIN queries +- [Issue #333](https://github.com/influxdb/influxdb/pull/333). Fail + when the password is too short or too long instead of passing it to + the crypto library + +## v0.5.0-rc.5 [2014-03-11] + +### Bugfixes + +- [Issue #312](https://github.com/influxdb/influxdb/issues/312). WAL should wait for server id to be set before recovering +- [Issue #301](https://github.com/influxdb/influxdb/issues/301). Use ref counting to guard against race conditions in the shard cache +- [Issue #319](https://github.com/influxdb/influxdb/issues/319). Propagate engine creation error correctly to the user +- [Issue #316](https://github.com/influxdb/influxdb/issues/316). Make + sure we don't starve goroutines if we get an access denied error + from one of the shards +- [Issue #306](https://github.com/influxdb/influxdb/issues/306). Deleting/Dropping database takes a lot of memory +- [Issue #302](https://github.com/influxdb/influxdb/issues/302). Should be able to set negative timestamps on points +- [Issue #327](https://github.com/influxdb/influxdb/issues/327). Make delete queries not use WAL. This addresses #315, #317 and #314 +- [Issue #321](https://github.com/influxdb/influxdb/issues/321). Make sure we split points on shards properly + +## v0.5.0-rc.4 [2014-03-07] + +### Bugfixes + +- [Issue #298](https://github.com/influxdb/influxdb/issues/298). Fix limit when querying multiple shards +- [Issue #305](https://github.com/influxdb/influxdb/issues/305). Shard ids not unique after restart +- [Issue #309](https://github.com/influxdb/influxdb/issues/309). Don't relog the requests on the remote server +- Fix few bugs in the WAL and refactor the way it works (this requires purging the WAL from previous rc) + +## v0.5.0-rc.3 [2014-03-03] + +### Bugfixes +- [Issue #69](https://github.com/influxdb/influxdb/issues/69). Support column aliases +- [Issue #287](https://github.com/influxdb/influxdb/issues/287). Make the lru cache size configurable +- [Issue #38](https://github.com/influxdb/influxdb/issues/38). Fix a memory leak discussed in this story +- [Issue #286](https://github.com/influxdb/influxdb/issues/286). Make the number of open shards configurable +- Make LevelDB use the max open files configuration option. + +## v0.5.0-rc.2 [2014-02-27] + +### Bugfixes + +- [Issue #274](https://github.com/influxdb/influxdb/issues/274). Crash after restart +- [Issue #277](https://github.com/influxdb/influxdb/issues/277). Ensure duplicate shards won't be created +- [Issue #279](https://github.com/influxdb/influxdb/issues/279). Limits not working on regex queries +- [Issue #281](https://github.com/influxdb/influxdb/issues/281). `./influxdb -v` should print the sha when building from source +- [Issue #283](https://github.com/influxdb/influxdb/issues/283). Dropping shard and restart in cluster causes panic. +- [Issue #288](https://github.com/influxdb/influxdb/issues/288). Sequence numbers should be unique per server id + +## v0.5.0-rc.1 [2014-02-25] + +### Bugfixes + +- Ensure large deletes don't take too much memory +- [Issue #240](https://github.com/influxdb/influxdb/pull/240). Unable to query against columns with `.` in the name. +- [Issue #250](https://github.com/influxdb/influxdb/pull/250). different result between normal and continuous query with "group by" clause +- [Issue #216](https://github.com/influxdb/influxdb/pull/216). Results with no points should exclude columns and points + +### Features + +- [Issue #243](https://github.com/influxdb/influxdb/issues/243). Should have endpoint to GET a user's attributes. +- [Issue #269](https://github.com/influxdb/influxdb/pull/269), [Issue #65](https://github.com/influxdb/influxdb/issues/65) New clustering architecture (see docs), with the side effect that queries can be distributed between multiple shards +- [Issue #164](https://github.com/influxdb/influxdb/pull/269),[Issue #103](https://github.com/influxdb/influxdb/pull/269),[Issue #166](https://github.com/influxdb/influxdb/pull/269),[Issue #165](https://github.com/influxdb/influxdb/pull/269),[Issue #132](https://github.com/influxdb/influxdb/pull/269) Make request log a log file instead of leveldb with recovery on startup + +### Deprecated + +- [Issue #189](https://github.com/influxdb/influxdb/issues/189). `/cluster_admins` and `/db/:db/users` return usernames in a `name` key instead of `username` key. +- [Issue #216](https://github.com/influxdb/influxdb/pull/216). Results with no points should exclude columns and points + +## v0.4.4 [2014-02-05] + +### Features + +- Make the leveldb max open files configurable in the toml file + +## v0.4.3 [2014-01-31] + +### Bugfixes + +- [Issue #225](https://github.com/influxdb/influxdb/issues/225). Remove a hard limit on the points returned by the datastore +- [Issue #223](https://github.com/influxdb/influxdb/issues/223). Null values caused count(distinct()) to panic +- [Issue #224](https://github.com/influxdb/influxdb/issues/224). Null values broke replication due to protobuf limitation + +## v0.4.1 [2014-01-30] + +### Features + +- [Issue #193](https://github.com/influxdb/influxdb/issues/193). Allow logging to stdout. Thanks @schmurfy +- [Issue #190](https://github.com/influxdb/influxdb/pull/190). Add support for SSL. +- [Issue #194](https://github.com/influxdb/influxdb/pull/194). Should be able to disable Admin interface. + +### Bugfixes + +- [Issue #33](https://github.com/influxdb/influxdb/issues/33). Don't call WriteHeader more than once per request +- [Issue #195](https://github.com/influxdb/influxdb/issues/195). Allow the bind address to be configurable, Thanks @schmurfy. +- [Issue #199](https://github.com/influxdb/influxdb/issues/199). Make the test timeout configurable +- [Issue #200](https://github.com/influxdb/influxdb/issues/200). Selecting `time` or `sequence_number` silently fail +- [Issue #215](https://github.com/influxdb/influxdb/pull/215). Server fails to start up after Raft log compaction and restart. + +## v0.4.0 [2014-01-17] + +## Features + +- [Issue #86](https://github.com/influxdb/influxdb/issues/86). Support arithmetic expressions in select clause +- [Issue #92](https://github.com/influxdb/influxdb/issues/92). Change '==' to '=' and '!=' to '<>' +- [Issue #88](https://github.com/influxdb/influxdb/issues/88). Support datetime strings +- [Issue #64](https://github.com/influxdb/influxdb/issues/64). Shard writes and queries across cluster with replay for briefly downed nodes (< 24 hrs) +- [Issue #78](https://github.com/influxdb/influxdb/issues/78). Sequence numbers persist across restarts so they're not reused +- [Issue #102](https://github.com/influxdb/influxdb/issues/102). Support expressions in where condition +- [Issue #101](https://github.com/influxdb/influxdb/issues/101). Support expressions in aggregates +- [Issue #62](https://github.com/influxdb/influxdb/issues/62). Support updating and deleting column values +- [Issue #96](https://github.com/influxdb/influxdb/issues/96). Replicate deletes in a cluster +- [Issue #94](https://github.com/influxdb/influxdb/issues/94). delete queries +- [Issue #116](https://github.com/influxdb/influxdb/issues/116). Use proper logging +- [Issue #40](https://github.com/influxdb/influxdb/issues/40). Use TOML instead of JSON in the config file +- [Issue #99](https://github.com/influxdb/influxdb/issues/99). Support list series in the query language +- [Issue #149](https://github.com/influxdb/influxdb/issues/149). Cluster admins should be able to perform reads and writes. +- [Issue #108](https://github.com/influxdb/influxdb/issues/108). Querying one point using `time =` +- [Issue #114](https://github.com/influxdb/influxdb/issues/114). Servers should periodically check that they're consistent. +- [Issue #93](https://github.com/influxdb/influxdb/issues/93). Should be able to drop a time series +- [Issue #177](https://github.com/influxdb/influxdb/issues/177). Support drop series in the query language. +- [Issue #184](https://github.com/influxdb/influxdb/issues/184). Implement Raft log compaction. +- [Issue #153](https://github.com/influxdb/influxdb/issues/153). Implement continuous queries + +### Bugfixes + +- [Issue #90](https://github.com/influxdb/influxdb/issues/90). Group by multiple columns panic +- [Issue #89](https://github.com/influxdb/influxdb/issues/89). 'Group by' combined with 'where' not working +- [Issue #106](https://github.com/influxdb/influxdb/issues/106). Don't panic if we only see one point and can't calculate derivative +- [Issue #105](https://github.com/influxdb/influxdb/issues/105). Panic when using a where clause that reference columns with null values +- [Issue #61](https://github.com/influxdb/influxdb/issues/61). Remove default limits from queries +- [Issue #118](https://github.com/influxdb/influxdb/issues/118). Make column names starting with '_' legal +- [Issue #121](https://github.com/influxdb/influxdb/issues/121). Don't fall back to the cluster admin auth if the db user auth fails +- [Issue #127](https://github.com/influxdb/influxdb/issues/127). Return error on delete queries with where condition that don't have time +- [Issue #117](https://github.com/influxdb/influxdb/issues/117). Fill empty groups with default values +- [Issue #150](https://github.com/influxdb/influxdb/pull/150). Fix parser for when multiple divisions look like a regex. +- [Issue #158](https://github.com/influxdb/influxdb/issues/158). Logged deletes should be stored with the time range if missing. +- [Issue #136](https://github.com/influxdb/influxdb/issues/136). Make sure writes are replicated in order to avoid triggering replays +- [Issue #145](https://github.com/influxdb/influxdb/issues/145). Server fails to join cluster if all starting at same time. +- [Issue #176](https://github.com/influxdb/influxdb/issues/176). Drop database should take effect on all nodes +- [Issue #180](https://github.com/influxdb/influxdb/issues/180). Column names not returned when running multi-node cluster and writing more than one point. +- [Issue #182](https://github.com/influxdb/influxdb/issues/182). Queries with invalid limit clause crash the server + +### Deprecated + +- deprecate '==' and '!=' in favor of '=' and '<>', respectively +- deprecate `/dbs` (for listing databases) in favor of a more consistent `/db` endpoint +- deprecate `username` field for a more consistent `name` field in `/db/:db/users` and `/cluster_admins` +- deprecate endpoints `/db/:db/admins/:user` in favor of using `/db/:db/users/:user` which should + be used to update user flags, password, etc. +- Querying for column names that don't exist no longer throws an error. + +## v0.3.2 + +## Features + +- [Issue #82](https://github.com/influxdb/influxdb/issues/82). Add endpoint for listing available admin interfaces. +- [Issue #80](https://github.com/influxdb/influxdb/issues/80). Support durations when specifying start and end time +- [Issue #81](https://github.com/influxdb/influxdb/issues/81). Add support for IN + +## Bugfixes + +- [Issue #75](https://github.com/influxdb/influxdb/issues/75). Don't allow time series names that start with underscore +- [Issue #85](https://github.com/influxdb/influxdb/issues/85). Non-existing columns exist after they have been queried before + +## v0.3.0 + +## Features + +- [Issue #51](https://github.com/influxdb/influxdb/issues/51). Implement first and last aggregates +- [Issue #35](https://github.com/influxdb/influxdb/issues/35). Support table aliases in Join Queries +- [Issue #71](https://github.com/influxdb/influxdb/issues/71). Add WillReturnSingleSeries to the Query +- [Issue #61](https://github.com/influxdb/influxdb/issues/61). Limit should default to 10k +- [Issue #59](https://github.com/influxdb/influxdb/issues/59). Add histogram aggregate function + +## Bugfixes + +- Fix join and merges when the query is a descending order query +- [Issue #57](https://github.com/influxdb/influxdb/issues/57). Don't panic when type of time != float +- [Issue #63](https://github.com/influxdb/influxdb/issues/63). Aggregate queries should not have a sequence_number column + +## v0.2.0 + +### Features + +- [Issue #37](https://github.com/influxdb/influxdb/issues/37). Support the negation of the regex matcher !~ +- [Issue #47](https://github.com/influxdb/influxdb/issues/47). Spill out query and database detail at the time of bug report + +### Bugfixes + +- [Issue #36](https://github.com/influxdb/influxdb/issues/36). The regex operator should be =~ not ~= +- [Issue #39](https://github.com/influxdb/influxdb/issues/39). Return proper content types from the http api +- [Issue #42](https://github.com/influxdb/influxdb/issues/42). Make the api consistent with the docs +- [Issue #41](https://github.com/influxdb/influxdb/issues/41). Table/Points not deleted when database is dropped +- [Issue #45](https://github.com/influxdb/influxdb/issues/45). Aggregation shouldn't mess up the order of the points +- [Issue #44](https://github.com/influxdb/influxdb/issues/44). Fix crashes on RHEL 5.9 +- [Issue #34](https://github.com/influxdb/influxdb/issues/34). Ascending order always return null for columns that have a null value +- [Issue #55](https://github.com/influxdb/influxdb/issues/55). Limit should limit the points that match the Where clause +- [Issue #53](https://github.com/influxdb/influxdb/issues/53). Writing null values via HTTP API fails + +### Deprecated + +- Preparing to deprecate `/dbs` (for listing databases) in favor of a more consistent `/db` endpoint +- Preparing to deprecate `username` field for a more consistent `name` field in the `/db/:db/users` +- Preparing to deprecate endpoints `/db/:db/admins/:user` in favor of using `/db/:db/users/:user` which should + be used to update user flags, password, etc. + +## v0.1.0 + +### Features + +- [Issue #29](https://github.com/influxdb/influxdb/issues/29). Semicolon is now optional in queries +- [Issue #31](https://github.com/influxdb/influxdb/issues/31). Support Basic Auth as well as query params for authentication. + +### Bugfixes + +- Don't allow creating users with empty username +- [Issue #22](https://github.com/influxdb/influxdb/issues/22). Don't set goroot if it was set +- [Issue #25](https://github.com/influxdb/influxdb/issues/25). Fix queries that use the median aggregator +- [Issue #26](https://github.com/influxdb/influxdb/issues/26). Default log and db directories should be in /opt/influxdb/shared/data +- [Issue #27](https://github.com/influxdb/influxdb/issues/27). Group by should not blow up if the one of the columns in group by has null values +- [Issue #30](https://github.com/influxdb/influxdb/issues/30). Column indexes/names getting off somehow +- [Issue #32](https://github.com/influxdb/influxdb/issues/32). Fix many typos in the codebase. Thanks @pborreli + +## v0.0.9 + +#### Features + +- Add stddev(...) support +- Better docs, thanks @auxesis and @d-snp. + +#### Bugfixes + +- Set PYTHONPATH and CC appropriately on mac os x. +- [Issue #18](https://github.com/influxdb/influxdb/issues/18). Fix 386 debian and redhat packages +- [Issue #23](https://github.com/influxdb/influxdb/issues/23). Fix the init scripts on redhat + +## v0.0.8 + +#### Features + +- Add a way to reset the root password from the command line. +- Add distinct(..) and derivative(...) support +- Print test coverage if running go1.2 + +#### Bugfixes + +- Fix the default admin site path in the .deb and .rpm packages. +- Fix the configuration filename in the .tar.gz package. + +## v0.0.7 + +#### Features + +- include the admin site in the repo to make it easier for newcomers. + +## v0.0.6 + +#### Features + +- Add count(distinct(..)) support + +#### Bugfixes + +- Reuse levigo read/write options. + +## v0.0.5 + +#### Features + +- Cache passwords in memory to speed up password verification +- Add MERGE and INNER JOIN support + +#### Bugfixes + +- All columns should be returned if `select *` was used +- Read/Write benchmarks + +## v0.0.2 + +#### Features + +- Add an admin UI +- Deb and RPM packages + +#### Bugfixes + +- Fix some nil pointer dereferences +- Cleanup the aggregators implementation + +## v0.0.1 [2013-10-22] + + * Initial Release diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/CONTRIBUTING.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/CONTRIBUTING.md new file mode 100644 index 00000000..d578f1fe --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/CONTRIBUTING.md @@ -0,0 +1,250 @@ +Contributing to InfluxDB +======================== + +Bug reports +--------------- +Before you file an issue, please search existing issues in case it has already been filed, or perhaps even fixed. If you file an issue, please include the following. +* Full details of your operating system (or distribution) e.g. 64-bit Ubuntu 14.04. +* The version of InfluxDB you are running +* Whether you installed it using a pre-built package, or built it from source. +* A small test case, if applicable, that demonstrates the issues. + +Remember the golden rule of bug reports: **The easier you make it for us to reproduce the problem, the faster it will get fixed.** +If you have never written a bug report before, or if you want to brush up on your bug reporting skills, we recommend reading [Simon Tatham's essay "How to Report Bugs Effectively."](http://www.chiark.greenend.org.uk/~sgtatham/bugs.html) + +Test cases should be in the form of `curl` commands. For example: +```bash +# create database +curl -G http://localhost:8086/query --data-urlencode "q=CREATE DATABASE mydb" + +# create retention policy +curl -G http://localhost:8086/query --data-urlencode "q=CREATE RETENTION POLICY myrp ON mydb DURATION 365d REPLICATION 1 DEFAULT" + +# write data +curl -X POST http://localhost:8086/write --data-urlencode "db=mydb" --data-binary "cpu,region=useast,host=server_1,service=redis value=61" + +# Delete a Measurement +curl -G http://localhost:8086/query --data-urlencode 'db=mydb' --data-urlencode 'q=DROP MEASUREMENT cpu' + +# Query the Measurement +# Bug: expected it to return no data, but data comes back. +curl -G http://localhost:8086/query --data-urlencode 'db=mydb' --data-urlencode 'q=SELECT * from cpu' +``` +**If you don't include a clear test case like this, your issue may not be investigated, and may even be closed**. If writing the data is too difficult, please zip up your data directory and include a link to it in your bug report. + +Please note that issues are *not the place to file general questions* such as "how do I use collectd with InfluxDB?" Questions of this nature should be sent to the [Google Group](https://groups.google.com/forum/#!forum/influxdb), not filed as issues. Issues like this will be closed. + +Feature requests +--------------- +We really like to receive feature requests, as it helps us prioritize our work. Please be clear about your requirements, as incomplete feature requests may simply be closed if we don't understand what you would like to see added to InfluxDB. + +Contributing to the source code +--------------- + +InfluxDB follows standard Go project structure. This means that all +your go development are done in `$GOPATH/src`. GOPATH can be any +directory under which InfluxDB and all its dependencies will be +cloned. For more details on recommended go project's structure, see +[How to Write Go Code](http://golang.org/doc/code.html) and +[Go: Best Practices for Production Environments](http://peter.bourgon.org/go-in-production/), or you can just follow +the steps below. + +Submitting a pull request +------------ +To submit a pull request you should fork the InfluxDB repository, and make your change on a feature branch of your fork. Then generate a pull request from your branch against *master* of the InfluxDB repository. Include in your pull request details of your change -- the why *and* the how -- as well as the testing your performed. Also, be sure to run the test suite with your change in place. Changes that cause tests to fail cannot be merged. + +There will usually be some back and forth as we finalize the change, but once that completes it may be merged. + +To assist in review for the PR, please add the following to your pull request comment: + +```md +- [ ] CHANGELOG.md updated +- [ ] Rebased/mergable +- [ ] Tests pass +- [ ] Sign [CLA](http://influxdb.com/community/cla.html) (if not already signed) +``` + +Signing the CLA +--------------- + +If you are going to be contributing back to InfluxDB please take a +second to sign our CLA, which can be found +[on our website](http://influxdb.com/community/cla.html). + +Installing Go +------------- +InfluxDB requires Go 1.4 or greater. + +At InfluxDB we find gvm, a Go version manager, useful for installing Go. For instructions +on how to install it see [the gvm page on github](https://github.com/moovweb/gvm). + +After installing gvm you can install and set the default go version by +running the following: + + gvm install go1.4.2 + gvm use go1.4.2 --default + +Revision Control Systems +------------- +Go has the ability to import remote packages via revision control systems with the `go get` command. To ensure that you can retrieve any remote package, be sure to install the following rcs software to your system. +Currently the project only depends on `git` and `mercurial`. + +* [Install Git](http://git-scm.com/book/en/Getting-Started-Installing-Git) +* [Install Mercurial](http://mercurial.selenic.com/wiki/Download) + +Getting the source +------ +Setup the project structure and fetch the repo like so: + +```bash + mkdir $HOME/gocodez + export GOPATH=$HOME/gocodez + go get github.com/influxdb/influxdb +``` + +You can add the line `export GOPATH=$HOME/gocodez` to your bash/zsh file to be set for every shell instead of having to manually run it everytime. + +Cloning a fork +------------- +If you wish to work with fork of InfluxDB, your own fork for example, you must still follow the directory structure above. But instead of cloning the main repo, instead clone your fork. Follow the steps below to work with a fork: + +```bash + export GOPATH=$HOME/gocodez + mkdir -p $GOPATH/src/github.com/influxdb + cd $GOPATH/src/github.com/influxdb + git clone git@github.com:/influxdb +``` + +Retaining the directory structure `$GOPATH/src/github.com/influxdb` is necessary so that Go imports work correctly. + +Pre-commit checks +------------- + +We have a pre-commit hook to make sure code is formatted properly and vetted before you commit any changes. We strongly recommend using the pre-commit hook to guard against accidentally committing unformatted code. To use the pre-commit hook, run the following: +```bash + cd $GOPATH/src/github.com/influxdb/influxdb + cp .hooks/pre-commit .git/hooks/ +``` +In case the commit is rejected because it's not formatted you can run +the following to format the code: + +``` +go fmt ./... +go vet ./... +``` + +To install go vet, run the following command: +``` +go get golang.org/x/tools/cmd/vet +``` + +NOTE: If you have not installed mercurial, the above command will fail. See [Revision Control Systems](#revision-control-systems) above. + +For more information on `go vet`, [read the GoDoc](https://godoc.org/golang.org/x/tools/cmd/vet). + +Build and Test +----- + +Make sure you have Go installed and the project structure as shown above. To then build the project, execute the following commands: + +```bash +cd $GOPATH/src/github.com/influxdb +go get -u -f -t ./... +go build ./... +``` + +To then install the binaries, run the following command. They can be found in `$GOPATH/bin`. Please note that the InfluxDB binary is named `influxd`, not `influxdb`. + +```bash +go install ./... +``` + +To set the version and commit flags during the build pass the following to the build command: + +```bash +-ldflags="-X main.version $VERSION -X main.branch $BRANCH -X main.commit $COMMIT -X main.buildTime $TIME" +``` + +where `$VERSION` is the version, `$BRANCH` is the branch, `$COMMIT` is the git commit hash, and `$TIME` is the build timestamp. + +If you want to build packages, see `package.sh` help: +```bash +package.sh -h +``` + +To run the tests, execute the following command: + +```bash +cd $GOPATH/src/github.com/influxdb/influxdb +go test -v ./... + +# run tests that match some pattern +go test -run=TestDatabase . -v + +# run tests and show coverage +go test -coverprofile /tmp/cover . && go tool cover -html /tmp/cover +``` + +To install go cover, run the following command: +``` +go get golang.org/x/tools/cmd/cover +``` + +Generated Google Protobuf code +----------------- +Most changes to the source do not require that the generated protocol buffer code be changed. But if you need to modify the protocol buffer code, you'll first need to install the protocol buffers toolchain. + +First install the [protocol buffer compiler](https://developers.google.com/protocol-buffers/ +) 2.6.1 or later for your OS: + +Then install the go plugins: + +```bash +go get github.com/gogo/protobuf/proto +go get github.com/gogo/protobuf/protoc-gen-gogo +go get github.com/gogo/protobuf/gogoproto +``` + +Finally run, `go generate` after updating any `*.proto` file: + +```bash +go generate ./... +``` +**Trouleshooting** + +If generating the protobuf code is failing for you, check each of the following: + * Ensure the protobuf library can be found. Make sure that `LD_LIBRRARY_PATH` includes the directory in which the library `libprotoc.so` has been installed. + * Ensure the command `protoc-gen-gogo`, found in `GOPATH/bin`, is on your path. This can be done by adding `GOPATH/bin` to `PATH`. + +Profiling +----- +When troubleshooting problems with CPU or memory the Go toolchain can be helpful. You can start InfluxDB with CPU or memory profiling turned on. For example: + +```sh +# start influx with profiling +./influxd -cpuprofile influxd.prof +# run queries, writes, whatever you're testing +# Quit out of influxd and influxd.prof will then be written. +# open up pprof to examine the profiling data. +go tool pprof ./influxd influxd.prof +# once inside run "web", opens up browser with the CPU graph +# can also run "web " to zoom in. Or "list " to see specific lines +``` +Note that when you pass the binary to `go tool pprof` *you must specify the path to the binary*. + +Use of third-party packages +------------ +A third-party package is defined as one that is not part of the standard Go distribution. Generally speaking we prefer to minimize our use of third-party packages, and avoid them unless absolutely necessarily. We'll often write a little bit of code rather than pull in a third-party package. Of course, we do use some third-party packages -- most importantly we use [BoltDB](https://github.com/boltdb/bolt) as the storage engine. So to maximise the chance your change will be accepted by us, use only the standard libraries, or the third-party packages we have decided to use. + +For rationale, check out the post [The Case Against Third Party Libraries](http://blog.gopheracademy.com/advent-2014/case-against-3pl/). + +Continuous Integration testing +----- +InfluxDB uses CircleCI for continuous integration testing. To see how the code is built and tested, check out [this file](https://github.com/influxdb/influxdb/blob/master/circle-test.sh). It closely follows the build and test process outlined above. You can see the exact version of Go InfluxDB uses for testing by consulting that file. + +Useful links +------------ +- [Useful techniques in Go](http://arslan.io/ten-useful-techniques-in-go) +- [Go in production](http://peter.bourgon.org/go-in-production/) +- [Principles of designing Go APIs with channels](https://inconshreveable.com/07-08-2014/principles-of-designing-go-apis-with-channels/) +- [Common mistakes in Golang](http://soryy.com/blog/2014/common-mistakes-with-go-lang/). Especially this section `Loops, Closures, and Local Variables` diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/DOCKER.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/DOCKER.md new file mode 100644 index 00000000..e78187d9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/DOCKER.md @@ -0,0 +1,44 @@ +# Docker Setup +======================== + +This document describes how to build and run a minimal InfluxDB container under Docker. Currently, it has only been tested for local development and assumes that you have a working docker environment. + +## Building Image + +To build a docker image for InfluxDB from your current checkout, run the following: + +``` +$ ./build-docker.sh +``` + +This script uses the `golang:1.5` image to build a fully static binary of `influxd` and then adds it to a minimal `scratch` image. + +To build the image using a different version of go: + +``` +$ GO_VER=1.4.2 ./build-docker.sh +``` + +Available version can be found [here](https://hub.docker.com/_/golang/). + +## Single Node Container + +This will start an interactive, single-node, that publishes the containers port `8086` and `8088` to the hosts ports `8086` and `8088` respectively. This is identical to starting `influxd` manually. + +``` +$ docker run -it -p 8086:8086 -p 8088:8088 influxdb +``` + +## Multi-Node Cluster + +This will create a simple 3-node cluster. The data is stored within the container and will be lost when the container is removed. This is only useful for test clusters. + +The `HOST_IP` env variable should be your host IP if running under linux or the virtualbox VM IP if running under OSX. On OSX, this would be something like: `$(docker-machine ip dev)` or `$(boot2docker ip)` depending on which docker tool you are using. + +``` +$ export HOST_IP= +$ docker run -it -p 8086:8086 -p 8088:8088 influxdb -hostname $HOST_IP:8088 +$ docker run -it -p 8186:8086 -p 8188:8088 influxdb -hostname $HOST_IP:8188 -join $HOST_IP:8088 +$ docker run -it -p 8286:8086 -p 8288:8088 influxdb -hostname $HOST_IP:8288 -join $HOST_IP:8088 +``` + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile b/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile new file mode 100644 index 00000000..d30cd300 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile @@ -0,0 +1,24 @@ +FROM busybox:ubuntu-14.04 + +MAINTAINER Jason Wilder "" + +# admin, http, udp, cluster, graphite, opentsdb, collectd +EXPOSE 8083 8086 8086/udp 8088 2003 4242 25826 + +WORKDIR /app + +# copy binary into image +COPY influxd /app/ + +# Add influxd to the PATH +ENV PATH=/app:$PATH + +# Generate a default config +RUN influxd config > /etc/influxdb.toml + +# Use /data for all disk storage +RUN sed -i 's/dir = "\/.*influxdb/dir = "\/data/' /etc/influxdb.toml + +VOLUME ["/data"] + +ENTRYPOINT ["influxd", "--config", "/etc/influxdb.toml"] diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile_test_ubuntu32 b/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile_test_ubuntu32 new file mode 100644 index 00000000..d67a91a8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/Dockerfile_test_ubuntu32 @@ -0,0 +1,12 @@ +FROM 32bit/ubuntu:14.04 + +RUN apt-get update && apt-get install -y python-software-properties software-properties-common git +RUN add-apt-repository ppa:evarlast/golang1.4 +RUN apt-get update && apt-get install -y -o Dpkg::Options::="--force-overwrite" golang-go + +ENV GOPATH=/root/go +RUN mkdir -p /root/go/src/github.com/influxdb/influxdb +RUN mkdir -p /tmp/artifacts + +VOLUME /root/go/src/github.com/influxdb/influxdb +VOLUME /tmp/artifacts diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE b/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE new file mode 100644 index 00000000..d5022270 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2015 Errplane Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE_OF_DEPENDENCIES.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE_OF_DEPENDENCIES.md new file mode 100644 index 00000000..7aae45f9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/LICENSE_OF_DEPENDENCIES.md @@ -0,0 +1,19 @@ +# List +- github.com/gogo/protobuf/proto [BSD LICENSE](https://github.com/gogo/protobuf/blob/master/LICENSE) +- gopkg.in/fatih/pool.v2 [MIT LICENSE](https://github.com/fatih/pool/blob/v2.0.0/LICENSE) +- github.com/BurntSushi/toml [WTFPL LICENSE](https://github.com/BurntSushi/toml/blob/master/COPYING) +- github.com/peterh/liner [MIT LICENSE](https://github.com/peterh/liner/blob/master/COPYING) +- github.com/davecgh/go-spew/spew [ISC LICENSE](https://github.com/davecgh/go-spew/blob/master/LICENSE) +- github.com/hashicorp/raft [MPL LICENSE](https://github.com/hashicorp/raft/blob/master/LICENSE) +- github.com/rakyll/statik/fs [APACHE LICENSE](https://github.com/rakyll/statik/blob/master/LICENSE) +- github.com/kimor79/gollectd [BSD LICENSE](https://github.com/kimor79/gollectd/blob/master/LICENSE) +- github.com/bmizerany/pat [MIT LICENSE](https://github.com/bmizerany/pat#license) +- react 0.13.3 [BSD LICENSE](https://github.com/facebook/react/blob/master/LICENSE) +- bootstrap 3.3.5 [MIT LICENSE](https://github.com/twbs/bootstrap/blob/master/LICENSE) +- jquery 2.1.4 [MIT LICENSE](https://github.com/jquery/jquery/blob/master/LICENSE.txt) +- glyphicons [LICENSE](http://glyphicons.com/license/) +- github.com/golang/snappy [BSD LICENSE](https://github.com/golang/snappy/blob/master/LICENSE) +- github.com/boltdb/bolt [MIT LICENSE](https://github.com/boltdb/bolt/blob/master/LICENSE) +- collectd.org [ISC LICENSE](https://github.com/collectd/go-collectd/blob/master/LICENSE) +- golang.org/x/crypto/* [BSD LICENSE](https://github.com/golang/crypto/blob/master/LICENSE) + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/Makefile b/Godeps/_workspace/src/github.com/influxdb/influxdb/Makefile new file mode 100644 index 00000000..66863bf9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/Makefile @@ -0,0 +1,38 @@ +PACKAGES=$(shell find . -name '*.go' -print0 | xargs -0 -n1 dirname | sort --unique) + +default: + +metalint: deadcode cyclo aligncheck defercheck structcheck lint errcheck + +deadcode: + @deadcode $(PACKAGES) 2>&1 + +cyclo: + @gocyclo -over 10 $(PACKAGES) + +aligncheck: + @aligncheck $(PACKAGES) + +defercheck: + @defercheck $(PACKAGES) + + +structcheck: + @structcheck $(PACKAGES) + +lint: + @for pkg in $(PACKAGES); do golint $$pkg; done + +errcheck: + @for pkg in $(PACKAGES); do \ + errcheck -ignorepkg=bytes,fmt -ignore=":(Rollback|Close)" $$pkg \ + done + +tools: + go get github.com/remyoudompheng/go-misc/deadcode + go get github.com/alecthomas/gocyclo + go get github.com/opennota/check/... + go get github.com/golang/lint/golint + go get github.com/kisielk/errcheck + +.PHONY: default,metalint,deadcode,cyclo,aligncheck,defercheck,structcheck,lint,errcheck,tools \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/QUERIES.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/QUERIES.md new file mode 100644 index 00000000..46a9eb1d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/QUERIES.md @@ -0,0 +1,180 @@ +The top level name is called a measurement. These names can contain any characters. Then there are field names, field values, tag keys and tag values, which can also contain any characters. However, if the measurement, field, or tag contains any character other than [A-Z,a-z,0-9,_], or if it starts with a digit, it must be double-quoted. Therefore anywhere a measurement name, field key, or tag key appears it should be wrapped in double quotes. + +# Databases & retention policies + +```sql +-- create a database +CREATE DATABASE + +-- create a retention policy +CREATE RETENTION POLICY ON DURATION REPLICATION [DEFAULT] + +-- alter retention policy +ALTER RETENTION POLICY ON (DURATION | REPLICATION | DEFAULT)+ + +-- drop a database +DROP DATABASE + +-- drop a retention policy +DROP RETENTION POLICY ON +``` +where `` is either `INF` for infinite retention, or an integer followed by the desired unit of time: u,ms,s,m,h,d,w for microseconds, milliseconds, seconds, minutes, hours, days, or weeks, respectively. `` must be an integer. + +If present, `DEFAULT` sets the retention policy as the default retention policy for writes and reads. + +# Users and permissions + +```sql +-- create user +CREATE USER WITH PASSWORD '' + +-- grant privilege on a database +GRANT ON TO + +-- grant cluster admin privileges +GRANT ALL [PRIVILEGES] TO + +-- revoke privilege +REVOKE ON FROM + +-- revoke all privileges for a DB +REVOKE ALL [PRIVILEGES] ON FROM + +-- revoke all privileges including cluster admin +REVOKE ALL [PRIVILEGES] FROM + +-- combine db creation with privilege assignment (user must already exist) +CREATE DATABASE GRANT TO +CREATE DATABASE REVOKE FROM + +-- delete a user +DROP USER + + +``` +where ` := READ | WRITE | All `. + +Authentication must be enabled in the influxdb.conf file for user permissions to be in effect. + +By default, newly created users have no privileges to any databases. + +Cluster administration privileges automatically grant full read and write permissions to all databases, regardless of subsequent database-specific privilege revocation statements. + +# Select + +```sql +SELECT mean(value) from cpu WHERE host = 'serverA' AND time > now() - 4h GROUP BY time(5m) + +SELECT mean(value) from cpu WHERE time > now() - 4h GROUP BY time(5m), region +``` + +## Group By + +# Delete + +# Series + +## Destroy + +```sql +DROP MEASUREMENT +DROP MEASUREMENT cpu WHERE region = 'uswest' +``` + +## Show + +Show series queries are for pulling out individual series from measurement names and tag data. They're useful for discovery. + +```sql +-- show all databases +SHOW DATABASES + +-- show measurement names +SHOW MEASUREMENTS +SHOW MEASUREMENTS LIMIT 15 +SHOW MEASUREMENTS LIMIT 10 OFFSET 40 +SHOW MEASUREMENTS WHERE service = 'redis' +-- LIMIT and OFFSET can be applied to any of the SHOW type queries + +-- show all series across all measurements/tagsets +SHOW SERIES + +-- get a show of all series for any measurements where tag key region = tak value 'uswest' +SHOW SERIES WHERE region = 'uswest' + +SHOW SERIES FROM cpu_load WHERE region = 'uswest' LIMIT 10 + +-- returns the 100 - 109 rows in the result. In the case of SHOW SERIES, which returns +-- series split into measurements. Each series counts as a row. So you could see only a +-- single measurement returned, but 10 series within it. +SHOW SERIES FROM cpu_load WHERE region = 'uswest' LIMIT 10 OFFSET 100 + +-- show all retention policies on a database +SHOW RETENTION POLICIES ON mydb + +-- get a show of all tag keys across all measurements +SHOW TAG KEYS + +-- show all the tag keys for a given measurement +SHOW TAG KEYS FROM cpu +SHOW TAG KEYS FROM temperature, wind_speed + +-- show all the tag values. note that a single WHERE TAG KEY = '...' clause is required +SHOW TAG VALUES WITH TAG KEY = 'region' +SHOW TAG VALUES FROM cpu WHERE region = 'uswest' WITH TAG KEY = 'host' + +-- and you can do stuff against fields +SHOW FIELD KEYS FROM cpu + +-- but you can't do this +SHOW FIELD VALUES +-- we don't index field values, so this query should be invalid. + +-- show all users +SHOW USERS +``` + +Note that `FROM` and `WHERE` are optional clauses in most of the show series queries. + +And the show series output looks like this: + +```json +[ + { + "name": "cpu", + "columns": ["id", "region", "host"], + "values": [ + 1, "uswest", "servera", + 2, "uswest", "serverb" + ] + }, + { + "name": "reponse_time", + "columns": ["id", "application", "host"], + "values": [ + 3, "myRailsApp", "servera" + ] + } +] +``` + +# Continuous Queries + +Continuous queries are going to be inspired by MySQL `TRIGGER` syntax: + +http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html + +Instead of having automatically-assigned ids, named continuous queries allows for some level of duplication prevention, +particularly in the case where creation is scripted. + +## Create + + CREATE CONTINUOUS QUERY AS SELECT ... FROM ... + +## Destroy + + DROP CONTINUOUS QUERY + +## List + + SHOW CONTINUOUS QUERIES diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/README.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/README.md new file mode 100644 index 00000000..ce11e05d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/README.md @@ -0,0 +1,76 @@ +# InfluxDB [![Circle CI](https://circleci.com/gh/influxdb/influxdb/tree/master.svg?style=svg)](https://circleci.com/gh/influxdb/influxdb/tree/master) + +## An Open-Source, Distributed, Time Series Database + +> InfluxDB v0.9.0 is now out. Going forward, the 0.9.x series of releases will not make breaking API changes or breaking changes to the underlying data storage. However, 0.9.0 clustering should be considered an alpha release. + +InfluxDB is an open source **distributed time series database** with +**no external dependencies**. It's useful for recording metrics, +events, and performing analytics. + +## Features + +* Built-in [HTTP API](http://influxdb.com/docs/v0.9/concepts/reading_and_writing_data.html) so you don't have to write any server side code to get up and running. +* Data can be tagged, allowing very flexible querying. +* SQL-like query language. +* Clustering is supported out of the box, so that you can scale horizontally to handle your data. +* Simple to install and manage, and fast to get data in and out. +* It aims to answer queries in real-time. That means every data point is + indexed as it comes in and is immediately available in queries that + should return in < 100ms. + +## Getting Started +*The following directions apply only to the 0.9.0 release or building from the source on master.* + +### Building + +You don't need to build the project to use it - you can use any of our +[pre-built packages](http://influxdb.com/download/index.html) to install InfluxDB. That's +the recommended way to get it running. However, if you want to contribute to the core of InfluxDB, you'll need to build. +For those adventurous enough, you can +[follow along on our docs](http://github.com/influxdb/influxdb/blob/master/CONTRIBUTING.md). + +### Starting InfluxDB +* `service influxdb start` if you have installed InfluxDB using an official Debian or RPM package. +* `systemctl start influxdb` if you have installed InfluxDB using an official Debian or RPM package, and are running a distro with `systemd`. For example, Ubuntu 15 or later. +* `$GOPATH/bin/influxd` if you have built InfluxDB from source. + +### Creating your first database + +``` +curl -G 'http://localhost:8086/query' --data-urlencode "q=CREATE DATABASE mydb" +``` + +### Insert some data +``` +curl -XPOST 'http://localhost:8086/write?db=mydb' \ +-d 'cpu,host=server01,region=uswest load=42 1434055562000000000' + +curl -XPOST 'http://localhost:8086/write?db=mydb' \ +-d 'cpu,host=server02,region=uswest load=78 1434055562000000000' + +curl -XPOST 'http://localhost:8086/write?db=mydb' \ +-d 'cpu,host=server03,region=useast load=15.4 1434055562000000000' +``` + +### Query for the data +```JSON +curl -G http://localhost:8086/query?pretty=true --data-urlencode "db=mydb" \ +--data-urlencode "q=SELECT * FROM cpu WHERE host='server01' AND time < now() - 1d" +``` + +### Analyze the data +```JSON +curl -G http://localhost:8086/query?pretty=true --data-urlencode "db=mydb" \ +--data-urlencode "q=SELECT mean(load) FROM cpu WHERE region='uswest'" +``` + +## Helpful Links + +* Understand the [design goals and motivations of the project](http://influxdb.com/docs/v0.9/introduction/overview.html). +* Follow the [getting started guide](http://influxdb.com/docs/v0.9/introduction/getting_started.html) to find out how to install InfluxDB, start writing more data, and issue more queries - in just a few minutes. +* See the [HTTP API documentation to start writing a library for your favorite language](http://influxdb.com/docs/v0.9/concepts/reading_and_writing_data.html). + +## Looking for Support? + +InfluxDB has technical support subscriptions to help your project succeed. We offer Developer Support for organizations in active development and Production Support for companies requiring the best response times and SLAs on technical fixes. Visit our [support page](https://influxdb.com/support/index.html) to learn which subscription is right for you, or contact sales@influxdb.com for a quote. diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/build-docker.sh b/Godeps/_workspace/src/github.com/influxdb/influxdb/build-docker.sh new file mode 100755 index 00000000..0dea62d2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/build-docker.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +set -e -x + +GO_VER=${GO_VER:-1.5} + +docker run -it -v "${GOPATH}":/gopath -v "$(pwd)":/app -e "GOPATH=/gopath" -w /app golang:$GO_VER sh -c 'CGO_ENABLED=0 go build -a --installsuffix cgo --ldflags="-s" -o influxd ./cmd/influxd' + +docker build -t influxdb . diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/build.py b/Godeps/_workspace/src/github.com/influxdb/influxdb/build.py new file mode 100755 index 00000000..20d1bcfb --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/build.py @@ -0,0 +1,619 @@ +#!/usr/bin/env python2.7 +# +# This is the InfluxDB build script. +# +# Current caveats: +# - Does not currently build ARM builds/packages +# - Does not checkout the correct commit/branch (for now, you will need to do so manually) +# - Has external dependencies for packaging (fpm) and uploading (boto) +# + +import sys +import os +import subprocess +import time +import datetime +import shutil +import tempfile +import hashlib +import re + +try: + import boto + from boto.s3.key import Key +except ImportError: + pass + +# PACKAGING VARIABLES +INSTALL_ROOT_DIR = "/usr/bin" +LOG_DIR = "/var/log/influxdb" +DATA_DIR = "/var/lib/influxdb" +SCRIPT_DIR = "/usr/lib/influxdb/scripts" +CONFIG_DIR = "/etc/influxdb" +LOGROTATE_DIR = "/etc/logrotate.d" + +INIT_SCRIPT = "scripts/init.sh" +SYSTEMD_SCRIPT = "scripts/influxdb.service" +PREINST_SCRIPT = "scripts/pre-install.sh" +POSTINST_SCRIPT = "scripts/post-install.sh" +POSTUNINST_SCRIPT = "scripts/post-uninstall.sh" +LOGROTATE_SCRIPT = "scripts/logrotate" +DEFAULT_CONFIG = "etc/config.sample.toml" + +# META-PACKAGE VARIABLES +PACKAGE_LICENSE = "MIT" +PACKAGE_URL = "https://github.com/influxdb/influxdb" +MAINTAINER = "InfluxData" +VENDOR = "InfluxData" +DESCRIPTION = "A distributed time-series database." + +# SCRIPT START +prereqs = [ 'git', 'go' ] +optional_prereqs = [ 'gvm', 'fpm', 'rpmbuild' ] + +fpm_common_args = "-f -s dir --log error \ + --vendor {} \ + --url {} \ + --after-install {} \ + --before-install {} \ + --after-remove {} \ + --license {} \ + --maintainer {} \ + --config-files {} \ + --config-files {} \ + --description \"{}\"".format( + VENDOR, + PACKAGE_URL, + POSTINST_SCRIPT, + PREINST_SCRIPT, + POSTUNINST_SCRIPT, + PACKAGE_LICENSE, + MAINTAINER, + CONFIG_DIR, + LOGROTATE_DIR, + DESCRIPTION) + +targets = { + 'influx' : './cmd/influx/main.go', + 'influxd' : './cmd/influxd/main.go', + 'influx_stress' : './cmd/influx_stress/influx_stress.go', + 'influx_inspect' : './cmd/influx_inspect/*.go', +} + +supported_builds = { + # TODO(rossmcdonald): Add support for multiple GOARM values + 'darwin': [ "amd64", "386" ], + # Windows is not currently supported in InfluxDB 0.9.5 due to use of mmap + # 'windows': [ "amd64", "386", "arm" ], + 'linux': [ "amd64", "386", "arm" ] +} +supported_go = [ '1.5.1', '1.4.2' ] +supported_packages = { + "darwin": [ "tar", "zip" ], + "linux": [ "deb", "rpm", "tar", "zip" ], + "windows": [ "tar", "zip" ], +} + +def run(command, allow_failure=False, shell=False): + out = None + try: + if shell: + out = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=shell) + else: + out = subprocess.check_output(command.split(), stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + print "" + print "Executed command failed!" + print "-- Command run was: {}".format(command) + print "-- Failure was: {}".format(e.output) + if allow_failure: + print "Continuing..." + return out + else: + print "" + print "Stopping." + sys.exit(1) + except OSError as e: + print "" + print "Invalid command!" + print "-- Command run was: {}".format(command) + print "-- Failure was: {}".format(e) + if allow_failure: + print "Continuing..." + return out + else: + print "" + print "Stopping." + sys.exit(1) + else: + return out + +def create_temp_dir(): + return tempfile.mkdtemp(prefix="influxdb-build.") + +def get_current_version(): + command = "git describe --always --tags --abbrev=0" + out = run(command) + return out.strip() + +def get_current_commit(short=False): + command = None + if short: + command = "git log --pretty=format:'%h' -n 1" + else: + command = "git rev-parse HEAD" + out = run(command) + return out.strip('\'\n\r ') + +def get_current_branch(): + command = "git rev-parse --abbrev-ref HEAD" + out = run(command) + return out.strip() + +def get_system_arch(): + return os.uname()[4] + +def get_system_platform(): + if sys.platform.startswith("linux"): + return "linux" + else: + return sys.platform + +def get_go_version(): + out = run("go version") + matches = re.search('go version go(\S+)', out) + if matches is not None: + return matches.groups()[0].strip() + return None + +def check_path_for(b): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + full_path = os.path.join(path, b) + if os.path.isfile(full_path) and os.access(full_path, os.X_OK): + return full_path + +def check_environ(build_dir = None): + print "\nChecking environment:" + for v in [ "GOPATH", "GOBIN" ]: + print "\t- {} -> {}".format(v, os.environ.get(v)) + + cwd = os.getcwd() + if build_dir == None and os.environ.get("GOPATH") and os.environ.get("GOPATH") not in cwd: + print "\n!! WARNING: Your current directory is not under your GOPATH! This probably won't work." + +def check_prereqs(): + print "\nChecking for dependencies:" + for req in prereqs: + print "\t- {} ->".format(req), + path = check_path_for(req) + if path: + print "{}".format(path) + else: + print "?" + for req in optional_prereqs: + print "\t- {} (optional) ->".format(req), + path = check_path_for(req) + if path: + print "{}".format(path) + else: + print "?" + print "" + +def upload_packages(packages, nightly=False): + print "Uploading packages to S3..." + print "" + c = boto.connect_s3() + # TODO(rossmcdonald) - Set to different S3 bucket for release vs nightly + bucket = c.get_bucket('influxdb-nightly') + for p in packages: + name = os.path.basename(p) + if bucket.get_key(name) is None or nightly: + print "\t - Uploading {}...".format(name), + k = Key(bucket) + k.key = name + if nightly: + n = k.set_contents_from_filename(p, replace=True) + else: + n = k.set_contents_from_filename(p, replace=False) + k.make_public() + print "[ DONE ]" + else: + print "\t - Not uploading {}, already exists.".format(p) + print "" + +def run_tests(): + get_command = "go get -d -t ./..." + print "Retrieving Go dependencies...", + run(get_command) + print "done." + print "Running tests..." + code = os.system("go test ./...") + if code != 0: + print "Tests Failed" + return False + else: + print "Tests Passed" + return True + +def build(version=None, + branch=None, + commit=None, + platform=None, + arch=None, + nightly=False, + rc=None, + race=False, + clean=False, + outdir="."): + print "-------------------------" + print "" + print "Build plan:" + print "\t- version: {}".format(version) + if rc: + print "\t- release candidate: {}".format(rc) + print "\t- commit: {}".format(commit) + print "\t- branch: {}".format(branch) + print "\t- platform: {}".format(platform) + print "\t- arch: {}".format(arch) + print "\t- nightly? {}".format(str(nightly).lower()) + print "\t- race enabled? {}".format(str(race).lower()) + print "" + + if not os.path.exists(outdir): + os.makedirs(outdir) + elif clean and outdir != '/': + print "Cleaning build directory..." + shutil.rmtree(outdir) + os.makedirs(outdir) + + if rc: + # If a release candidate, update the version information accordingly + version = "{}rc{}".format(version, rc) + + print "Starting build..." + for b, c in targets.iteritems(): + print "\t- Building '{}'...".format(os.path.join(outdir, b)), + build_command = "" + build_command += "GOOS={} GOOARCH={} ".format(platform, arch) + if arch == "arm": + # TODO(rossmcdonald): Add GOARM variables for ARM builds + build_command += "GOOARM={} ".format(6) + build_command += "go build -o {} ".format(os.path.join(outdir, b)) + if race: + build_command += "-race " + go_version = get_go_version() + if "1.4" in go_version: + build_command += "-ldflags=\"-X main.buildTime '{}' ".format(datetime.datetime.utcnow().isoformat()) + build_command += "-X main.version {} ".format(version) + build_command += "-X main.branch {} ".format(branch) + build_command += "-X main.commit {}\" ".format(get_current_commit()) + else: + build_command += "-ldflags=\"-X main.buildTime='{}' ".format(datetime.datetime.utcnow().isoformat()) + build_command += "-X main.version={} ".format(version) + build_command += "-X main.branch={} ".format(branch) + build_command += "-X main.commit={}\" ".format(get_current_commit()) + build_command += c + out = run(build_command, shell=True) + print "[ DONE ]" + print "" + +def create_dir(path): + try: + os.makedirs(path) + except OSError as e: + print e + +def rename_file(fr, to): + try: + os.rename(fr, to) + except OSError as e: + print e + # Return the original filename + return fr + else: + # Return the new filename + return to + +def copy_file(fr, to): + try: + shutil.copy(fr, to) + except OSError as e: + print e + +def create_package_fs(build_root): + print "\t- Creating a filesystem hierarchy from directory: {}".format(build_root) + # Using [1:] for the path names due to them being absolute + # (will overwrite previous paths, per 'os.path.join' documentation) + dirs = [ INSTALL_ROOT_DIR[1:], LOG_DIR[1:], DATA_DIR[1:], SCRIPT_DIR[1:], CONFIG_DIR[1:], LOGROTATE_DIR[1:] ] + for d in dirs: + create_dir(os.path.join(build_root, d)) + os.chmod(os.path.join(build_root, d), 0755) + +def package_scripts(build_root): + print "\t- Copying scripts and sample configuration to build directory" + shutil.copyfile(INIT_SCRIPT, os.path.join(build_root, SCRIPT_DIR[1:], INIT_SCRIPT.split('/')[1])) + os.chmod(os.path.join(build_root, SCRIPT_DIR[1:], INIT_SCRIPT.split('/')[1]), 0644) + shutil.copyfile(SYSTEMD_SCRIPT, os.path.join(build_root, SCRIPT_DIR[1:], SYSTEMD_SCRIPT.split('/')[1])) + os.chmod(os.path.join(build_root, SCRIPT_DIR[1:], SYSTEMD_SCRIPT.split('/')[1]), 0644) + shutil.copyfile(LOGROTATE_SCRIPT, os.path.join(build_root, SCRIPT_DIR[1:], LOGROTATE_SCRIPT.split('/')[1])) + os.chmod(os.path.join(build_root, SCRIPT_DIR[1:], LOGROTATE_SCRIPT.split('/')[1]), 0644) + shutil.copyfile(DEFAULT_CONFIG, os.path.join(build_root, CONFIG_DIR[1:], "influxdb.conf")) + os.chmod(os.path.join(build_root, CONFIG_DIR[1:], "influxdb.conf"), 0644) + +def go_get(update=False): + get_command = None + if update: + get_command = "go get -u -f -d ./..." + else: + get_command = "go get -d ./..." + print "Retrieving Go dependencies...", + run(get_command) + print "done.\n" + +def generate_md5_from_file(path): + m = hashlib.md5() + with open(path, 'rb') as f: + for chunk in iter(lambda: f.read(4096), b""): + m.update(chunk) + return m.hexdigest() + +def build_packages(build_output, version, nightly=False, rc=None, iteration=1): + outfiles = [] + tmp_build_dir = create_temp_dir() + try: + print "-------------------------" + print "" + print "Packaging..." + for p in build_output: + # Create top-level folder displaying which platform (linux, etc) + create_dir(os.path.join(tmp_build_dir, p)) + for a in build_output[p]: + current_location = build_output[p][a] + # Create second-level directory displaying the architecture (amd64, etc)p + build_root = os.path.join(tmp_build_dir, p, a) + # Create directory tree to mimic file system of package + create_dir(build_root) + create_package_fs(build_root) + # Copy in packaging and miscellaneous scripts + package_scripts(build_root) + # Copy newly-built binaries to packaging directory + for b in targets: + if p == 'windows': + b = b + '.exe' + fr = os.path.join(current_location, b) + to = os.path.join(build_root, INSTALL_ROOT_DIR[1:], b) + print "\t- [{}][{}] - Moving from '{}' to '{}'".format(p, a, fr, to) + copy_file(fr, to) + # Package the directory structure + for package_type in supported_packages[p]: + print "\t- Packaging directory '{}' as '{}'...".format(build_root, package_type), + name = "influxdb" + if package_type in ['zip', 'tar']: + if nightly: + name = '{}-nightly_{}_{}'.format(name, p, a) + else: + name = '{}-{}_{}_{}'.format(name, version, p, a) + if package_type == 'tar': + # Add `tar.gz` to path to ensure a small package size + current_location = os.path.join(current_location, name + '.tar.gz') + if package_type == 'deb' and rc: + # For debs with an RC, just append to version number + version += "-rc{}".format(rc) + fpm_command = "fpm {} --name {} -a {} -t {} --version {} -C {} -p {} ".format( + fpm_common_args, + name, + a, + package_type, + version, + build_root, + current_location) + if package_type == "rpm": + fpm_command += "--depends coreutils " + # For rpms with RC, add to iteration for adherence to Fedora packaging standard: + # http://fedoraproject.org/wiki/Packaging%3aNamingGuidelines#NonNumericRelease + if rc: + fpm_command += "--iteration 0.{}.rc{} ".format(iteration, rc) + else: + fpm_command += "--iteration 1 ".format(iteration) + out = run(fpm_command, shell=True) + matches = re.search(':path=>"(.*)"', out) + outfile = None + if matches is not None: + outfile = matches.groups()[0] + if outfile is None: + print "[ COULD NOT DETERMINE OUTPUT ]" + else: + # Strip nightly version (the unix epoch) from filename + if nightly and package_type == 'deb': + outfile = rename_file(outfile, outfile.replace("{}".format(version), "nightly")) + elif nightly and package_type == 'rpm': + outfile = rename_file(outfile, outfile.replace("{}-1".format(version), "nightly")) + outfiles.append(os.path.join(os.getcwd(), outfile)) + print "[ DONE ]" + # Display MD5 hash for generated package + print "\t\tMD5 = {}".format(generate_md5_from_file(outfile)) + print "" + return outfiles + finally: + # Cleanup + shutil.rmtree(tmp_build_dir) + +def print_usage(): + print "Usage: ./build.py [options]" + print "" + print "Options:" + print "\t --outdir= \n\t\t- Send build output to a specified path. Defaults to ./build." + print "\t --arch= \n\t\t- Build for specified architecture. Acceptable values: x86_64|amd64, 386, arm, or all" + print "\t --platform= \n\t\t- Build for specified platform. Acceptable values: linux, windows, darwin, or all" + print "\t --version= \n\t\t- Version information to apply to build metadata. If not specified, will be pulled from repo tag." + print "\t --commit= \n\t\t- Use specific commit for build (currently a NOOP)." + print "\t --branch= \n\t\t- Build from a specific branch (currently a NOOP)." + print "\t --rc= \n\t\t- Whether or not the build is a release candidate (affects version information)." + print "\t --race \n\t\t- Whether the produced build should have race detection enabled." + print "\t --package \n\t\t- Whether the produced builds should be packaged for the target platform(s)." + print "\t --nightly \n\t\t- Whether the produced build is a nightly (affects version information)." + print "\t --update \n\t\t- Whether dependencies should be updated prior to building." + print "\t --test \n\t\t- Run Go tests. Will not produce a build." + print "\t --clean \n\t\t- Clean the build output directory prior to creating build." + print "" + +def print_package_summary(packages): + print packages + +def main(): + # Command-line arguments + outdir = "build" + commit = None + target_platform = None + target_arch = None + nightly = False + race = False + branch = None + version = get_current_version() + rc = None + package = False + update = False + clean = False + upload = False + test = False + iteration = 1 + + for arg in sys.argv[1:]: + if '--outdir' in arg: + # Output directory. If none is specified, then builds will be placed in the same directory. + output_dir = arg.split("=")[1] + if '--commit' in arg: + # Commit to build from. If none is specified, then it will build from the most recent commit. + commit = arg.split("=")[1] + if '--branch' in arg: + # Branch to build from. If none is specified, then it will build from the current branch. + branch = arg.split("=")[1] + elif '--arch' in arg: + # Target architecture. If none is specified, then it will build for the current arch. + target_arch = arg.split("=")[1] + elif '--platform' in arg: + # Target platform. If none is specified, then it will build for the current platform. + target_platform = arg.split("=")[1] + elif '--version' in arg: + # Version to assign to this build (0.9.5, etc) + version = arg.split("=")[1] + elif '--rc' in arg: + # Signifies that this is a release candidate build. + rc = arg.split("=")[1] + elif '--race' in arg: + # Signifies that race detection should be enabled. + race = True + elif '--package' in arg: + # Signifies that race detection should be enabled. + package = True + elif '--nightly' in arg: + # Signifies that this is a nightly build. + nightly = True + elif '--update' in arg: + # Signifies that race detection should be enabled. + update = True + elif '--upload' in arg: + # Signifies that the resulting packages should be uploaded to S3 + upload = True + elif '--test' in arg: + # Run tests and exit + test = True + elif '--clean' in arg: + # Signifies that the outdir should be deleted before building + clean = True + elif '--iteration' in arg: + iteration = arg.split("=")[1] + elif '--help' in arg: + print_usage() + return 0 + else: + print "!! Unknown argument: {}".format(arg) + print_usage() + return 1 + + if nightly: + if rc: + print "!! Cannot be both nightly and a release candidate! Stopping." + return 1 + # In order to support nightly builds on the repository, we are adding the epoch timestamp + # to the version so that version numbers are always greater than the previous nightly. + version = "{}.n{}".format(version, int(time.time())) + + # Pre-build checks + check_environ() + check_prereqs() + + if not commit: + commit = get_current_commit(short=True) + if not branch: + branch = get_current_branch() + if not target_arch: + target_arch = get_system_arch() + if not target_platform: + target_platform = get_system_platform() + + if target_arch == "x86_64": + target_arch = "amd64" + + build_output = {} + # TODO(rossmcdonald): Prepare git repo for build (checking out correct branch/commit, etc.) + # prepare(branch=branch, commit=commit) + if test: + if not run_tests(): + return 1 + return 0 + + go_get(update=update) + + platforms = [] + single_build = True + if target_platform == 'all': + platforms = supported_builds.keys() + single_build = False + else: + platforms = [target_platform] + + for platform in platforms: + build_output.update( { platform : {} } ) + archs = [] + if target_arch == "all": + single_build = False + archs = supported_builds.get(platform) + else: + archs = [target_arch] + for arch in archs: + od = outdir + if not single_build: + od = os.path.join(outdir, platform, arch) + build(version=version, + branch=branch, + commit=commit, + platform=platform, + arch=arch, + nightly=nightly, + rc=rc, + race=race, + clean=clean, + outdir=od) + build_output.get(platform).update( { arch : od } ) + + # Build packages + if package: + if not check_path_for("fpm"): + print "!! Cannot package without command 'fpm'. Stopping." + return 1 + packages = build_packages(build_output, version, nightly=nightly, rc=rc, iteration=iteration) + # TODO(rossmcdonald): Add nice output for print_package_summary() + # print_package_summary(packages) + # Optionally upload to S3 + if upload: + upload_packages(packages, nightly=nightly) + return 0 + +if __name__ == '__main__': + sys.exit(main()) + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/circle-test.sh b/Godeps/_workspace/src/github.com/influxdb/influxdb/circle-test.sh new file mode 100755 index 00000000..f4ac8d7d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/circle-test.sh @@ -0,0 +1,99 @@ +#!/bin/bash +# +# This is the InfluxDB CircleCI test script. Using this script allows total control +# the environment in which the build and test is run, and matches the official +# build process for InfluxDB. + +BUILD_DIR=$HOME/influxdb-build +GO_VERSION=go1.4.2 +PARALLELISM="-parallel 256" +TIMEOUT="-timeout 480s" + +# Executes the given statement, and exits if the command returns a non-zero code. +function exit_if_fail { + command=$@ + echo "Executing '$command'" + $command + rc=$? + if [ $rc -ne 0 ]; then + echo "'$command' returned $rc." + exit $rc + fi +} + +# Check that go fmt has been run. +function check_go_fmt { + fmtcount=`git ls-files | grep '.go$' | xargs gofmt -l 2>&1 | wc -l` + if [ $fmtcount -gt 0 ]; then + echo "run 'go fmt ./...' to format your source code." + exit 1 + fi +} + +# Check that go vet passes. +function check_go_vet { + # Due to the way composites work, vet will fail for some of our tests so we ignore it + vetcount=`go tool vet --composites=false ./ 2>&1 | wc -l` + if [ $vetcount -gt 0 ]; then + echo "run 'go tool vet --composites=false ./' to see the errors it flags and correct your source code." + exit 1 + fi +} + +source $HOME/.gvm/scripts/gvm +exit_if_fail gvm use $GO_VERSION + +# Set up the build directory, and then GOPATH. +exit_if_fail mkdir $BUILD_DIR +export GOPATH=$BUILD_DIR +exit_if_fail mkdir -p $GOPATH/src/github.com/influxdb + +# Dump some test config to the log. +echo "Test configuration" +echo "========================================" +echo "\$HOME: $HOME" +echo "\$GOPATH: $GOPATH" +echo "\$CIRCLE_BRANCH: $CIRCLE_BRANCH" + +# Move the checked-out source to a better location. +exit_if_fail mv $HOME/influxdb $GOPATH/src/github.com/influxdb +exit_if_fail cd $GOPATH/src/github.com/influxdb/influxdb +exit_if_fail git branch --set-upstream-to=origin/$CIRCLE_BRANCH $CIRCLE_BRANCH + +# Install the code. +exit_if_fail cd $GOPATH/src/github.com/influxdb/influxdb +exit_if_fail go get -t -d -v ./... +exit_if_fail git checkout $CIRCLE_BRANCH # 'go get' switches to master. Who knew? Switch back. +check_go_fmt +check_go_vet +exit_if_fail go build -v ./... + +# Run the tests. +case $CIRCLE_NODE_INDEX in + 0) + go test $PARALLELISM $TIMEOUT -v ./... 2>&1 | tee $CIRCLE_ARTIFACTS/test_logs.txt + rc=${PIPESTATUS[0]} + ;; + 1) + INFLUXDB_DATA_ENGINE="tsm1" go test $PARALLELISM $TIMEOUT -v ./... 2>&1 | tee $CIRCLE_ARTIFACTS/test_logs.txt + rc=${PIPESTATUS[0]} + ;; + 2) + # 32bit tests. + if [[ -e ~/docker/image.tar ]]; then docker load -i ~/docker/image.tar; fi + docker build -f Dockerfile_test_ubuntu32 -t ubuntu-32-influxdb-test . + mkdir -p ~/docker; docker save ubuntu-32-influxdb-test > ~/docker/image.tar + exit_if_fail docker build -f Dockerfile_test_ubuntu32 -t ubuntu-32-influxdb-test . + docker run -v $(pwd):/root/go/src/github.com/influxdb/influxdb -e "CI=${CI}" \ + -v ${CIRCLE_ARTIFACTS}:/tmp/artifacts \ + -t ubuntu-32-influxdb-test bash \ + -c "cd /root/go/src/github.com/influxdb/influxdb && go get -t -d -v ./... && go build -v ./... && go test ${PARALLELISM} ${TIMEOUT} -v ./... 2>&1 | tee /tmp/artifacts/test_logs_i386.txt && exit \${PIPESTATUS[0]}" + rc=$? + ;; + 3) + GORACE="halt_on_error=1" go test $PARALLELISM $TIMEOUT -v -race ./... 2>&1 | tee $CIRCLE_ARTIFACTS/test_logs_race.txt + rc=${PIPESTATUS[0]} + ;; +esac + +exit $rc diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/circle.yml b/Godeps/_workspace/src/github.com/influxdb/influxdb/circle.yml new file mode 100644 index 00000000..8f616c96 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/circle.yml @@ -0,0 +1,16 @@ +machine: + services: + - docker + pre: + - bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer) + - source $HOME/.gvm/scripts/gvm; gvm install go1.4.2 --binary + +dependencies: + override: + - mkdir -p ~/docker + cache_directories: + - "~/docker" +test: + override: + - bash circle-test.sh: + parallel: true diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/client/example_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/example_test.go new file mode 100644 index 00000000..e2dc10b7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/example_test.go @@ -0,0 +1,113 @@ +package client_test + +import ( + "fmt" + "log" + "math/rand" + "net/url" + "os" + "strconv" + "time" + + "github.com/influxdb/influxdb/client" +) + +func ExampleNewClient() { + host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) + if err != nil { + log.Fatal(err) + } + + // NOTE: this assumes you've setup a user and have setup shell env variables, + // namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below. + conf := client.Config{ + URL: *host, + Username: os.Getenv("INFLUX_USER"), + Password: os.Getenv("INFLUX_PWD"), + } + con, err := client.NewClient(conf) + if err != nil { + log.Fatal(err) + } + log.Println("Connection", con) +} + +func ExampleClient_Ping() { + host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) + if err != nil { + log.Fatal(err) + } + con, err := client.NewClient(client.Config{URL: *host}) + if err != nil { + log.Fatal(err) + } + + dur, ver, err := con.Ping() + if err != nil { + log.Fatal(err) + } + log.Printf("Happy as a hippo! %v, %s", dur, ver) +} + +func ExampleClient_Query() { + host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) + if err != nil { + log.Fatal(err) + } + con, err := client.NewClient(client.Config{URL: *host}) + if err != nil { + log.Fatal(err) + } + + q := client.Query{ + Command: "select count(value) from shapes", + Database: "square_holes", + } + if response, err := con.Query(q); err == nil && response.Error() == nil { + log.Println(response.Results) + } +} + +func ExampleClient_Write() { + host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) + if err != nil { + log.Fatal(err) + } + con, err := client.NewClient(client.Config{URL: *host}) + if err != nil { + log.Fatal(err) + } + + var ( + shapes = []string{"circle", "rectangle", "square", "triangle"} + colors = []string{"red", "blue", "green"} + sampleSize = 1000 + pts = make([]client.Point, sampleSize) + ) + + rand.Seed(42) + for i := 0; i < sampleSize; i++ { + pts[i] = client.Point{ + Measurement: "shapes", + Tags: map[string]string{ + "color": strconv.Itoa(rand.Intn(len(colors))), + "shape": strconv.Itoa(rand.Intn(len(shapes))), + }, + Fields: map[string]interface{}{ + "value": rand.Intn(sampleSize), + }, + Time: time.Now(), + Precision: "s", + } + } + + bps := client.BatchPoints{ + Points: pts, + Database: "BumbeBeeTuna", + RetentionPolicy: "default", + } + _, err = con.Write(bps) + if err != nil { + log.Fatal(err) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/client/influxdb_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/influxdb_test.go new file mode 100644 index 00000000..0a1981c8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/influxdb_test.go @@ -0,0 +1,560 @@ +package client_test + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/influxdb/influxdb/client" +) + +func BenchmarkUnmarshalJSON2Tags(b *testing.B) { + var bp client.BatchPoints + data := []byte(` +{ + "database": "foo", + "retentionPolicy": "bar", + "points": [ + { + "name": "cpu", + "tags": { + "host": "server01", + "region": "us-east1" + }, + "time": 14244733039069373, + "precision": "n", + "fields": { + "value": 4541770385657154000 + } + } + ] +} +`) + + for i := 0; i < b.N; i++ { + if err := json.Unmarshal(data, &bp); err != nil { + b.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) + } + b.SetBytes(int64(len(data))) + } +} + +func BenchmarkUnmarshalJSON10Tags(b *testing.B) { + var bp client.BatchPoints + data := []byte(` +{ + "database": "foo", + "retentionPolicy": "bar", + "points": [ + { + "name": "cpu", + "tags": { + "host": "server01", + "region": "us-east1", + "tag1": "value1", + "tag2": "value2", + "tag2": "value3", + "tag4": "value4", + "tag5": "value5", + "tag6": "value6", + "tag7": "value7", + "tag8": "value8" + }, + "time": 14244733039069373, + "precision": "n", + "fields": { + "value": 4541770385657154000 + } + } + ] +} +`) + + for i := 0; i < b.N; i++ { + if err := json.Unmarshal(data, &bp); err != nil { + b.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) + } + b.SetBytes(int64(len(data))) + } +} + +func TestNewClient(t *testing.T) { + config := client.Config{} + _, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_Ping(t *testing.T) { + ts := emptyTestServer() + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + d, version, err := c.Ping() + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + if d == 0 { + t.Fatalf("expected a duration greater than zero. actual %v", d) + } + if version != "x.x" { + t.Fatalf("unexpected version. expected %s, actual %v", "x.x", version) + } +} + +func TestClient_Query(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var data client.Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + query := client.Query{} + _, err = c.Query(query) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_BasicAuth(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u, p, ok := r.BasicAuth() + + if !ok { + t.Errorf("basic auth error") + } + if u != "username" { + t.Errorf("unexpected username, expected %q, actual %q", "username", u) + } + if p != "password" { + t.Errorf("unexpected password, expected %q, actual %q", "password", p) + } + w.WriteHeader(http.StatusNoContent) + })) + defer ts.Close() + + u, _ := url.Parse(ts.URL) + u.User = url.UserPassword("username", "password") + config := client.Config{URL: *u, Username: "username", Password: "password"} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + _, _, err = c.Ping() + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_Write(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var data client.Response + w.WriteHeader(http.StatusNoContent) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + bp := client.BatchPoints{} + r, err := c.Write(bp) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + if r != nil { + t.Fatalf("unexpected response. expected %v, actual %v", nil, r) + } +} + +func TestClient_UserAgent(t *testing.T) { + receivedUserAgent := "" + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + receivedUserAgent = r.UserAgent() + + var data client.Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + _, err := http.Get(ts.URL) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + tests := []struct { + name string + userAgent string + expected string + }{ + { + name: "Empty user agent", + userAgent: "", + expected: "InfluxDBClient", + }, + { + name: "Custom user agent", + userAgent: "Test Influx Client", + expected: "Test Influx Client", + }, + } + + for _, test := range tests { + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u, UserAgent: test.userAgent} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + receivedUserAgent = "" + query := client.Query{} + _, err = c.Query(query) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + if !strings.HasPrefix(receivedUserAgent, test.expected) { + t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + + receivedUserAgent = "" + bp := client.BatchPoints{} + _, err = c.Write(bp) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + if !strings.HasPrefix(receivedUserAgent, test.expected) { + t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + + receivedUserAgent = "" + _, _, err = c.Ping() + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + if receivedUserAgent != test.expected { + t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + } +} + +func TestPoint_UnmarshalEpoch(t *testing.T) { + now := time.Now() + tests := []struct { + name string + epoch int64 + precision string + expected time.Time + }{ + { + name: "nanoseconds", + epoch: now.UnixNano(), + precision: "n", + expected: now, + }, + { + name: "microseconds", + epoch: now.Round(time.Microsecond).UnixNano() / int64(time.Microsecond), + precision: "u", + expected: now.Round(time.Microsecond), + }, + { + name: "milliseconds", + epoch: now.Round(time.Millisecond).UnixNano() / int64(time.Millisecond), + precision: "ms", + expected: now.Round(time.Millisecond), + }, + { + name: "seconds", + epoch: now.Round(time.Second).UnixNano() / int64(time.Second), + precision: "s", + expected: now.Round(time.Second), + }, + { + name: "minutes", + epoch: now.Round(time.Minute).UnixNano() / int64(time.Minute), + precision: "m", + expected: now.Round(time.Minute), + }, + { + name: "hours", + epoch: now.Round(time.Hour).UnixNano() / int64(time.Hour), + precision: "h", + expected: now.Round(time.Hour), + }, + { + name: "max int64", + epoch: 9223372036854775807, + precision: "n", + expected: time.Unix(0, 9223372036854775807), + }, + { + name: "100 years from now", + epoch: now.Add(time.Hour * 24 * 365 * 100).UnixNano(), + precision: "n", + expected: now.Add(time.Hour * 24 * 365 * 100), + }, + } + + for _, test := range tests { + t.Logf("testing %q\n", test.name) + data := []byte(fmt.Sprintf(`{"time": %d, "precision":"%s"}`, test.epoch, test.precision)) + t.Logf("json: %s", string(data)) + var p client.Point + err := json.Unmarshal(data, &p) + if err != nil { + t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) + } + if !p.Time.Equal(test.expected) { + t.Fatalf("Unexpected time. expected: %v, actual: %v", test.expected, p.Time) + } + } +} + +func TestPoint_UnmarshalRFC(t *testing.T) { + now := time.Now().UTC() + tests := []struct { + name string + rfc string + now time.Time + expected time.Time + }{ + { + name: "RFC3339Nano", + rfc: time.RFC3339Nano, + now: now, + expected: now, + }, + { + name: "RFC3339", + rfc: time.RFC3339, + now: now.Round(time.Second), + expected: now.Round(time.Second), + }, + } + + for _, test := range tests { + t.Logf("testing %q\n", test.name) + ts := test.now.Format(test.rfc) + data := []byte(fmt.Sprintf(`{"time": %q}`, ts)) + t.Logf("json: %s", string(data)) + var p client.Point + err := json.Unmarshal(data, &p) + if err != nil { + t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) + } + if !p.Time.Equal(test.expected) { + t.Fatalf("Unexpected time. expected: %v, actual: %v", test.expected, p.Time) + } + } +} + +func TestPoint_MarshalOmitempty(t *testing.T) { + now := time.Now().UTC() + tests := []struct { + name string + point client.Point + now time.Time + expected string + }{ + { + name: "all empty", + point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}}, + now: now, + expected: `{"measurement":"cpu","fields":{"value":1.1}}`, + }, + { + name: "with time", + point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Time: now}, + now: now, + expected: fmt.Sprintf(`{"measurement":"cpu","time":"%s","fields":{"value":1.1}}`, now.Format(time.RFC3339Nano)), + }, + { + name: "with tags", + point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Tags: map[string]string{"foo": "bar"}}, + now: now, + expected: `{"measurement":"cpu","tags":{"foo":"bar"},"fields":{"value":1.1}}`, + }, + { + name: "with precision", + point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Precision: "ms"}, + now: now, + expected: `{"measurement":"cpu","fields":{"value":1.1},"precision":"ms"}`, + }, + } + + for _, test := range tests { + t.Logf("testing %q\n", test.name) + b, err := json.Marshal(&test.point) + if err != nil { + t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) + } + if test.expected != string(b) { + t.Fatalf("Unexpected result. expected: %v, actual: %v", test.expected, string(b)) + } + } +} + +func TestEpochToTime(t *testing.T) { + now := time.Now() + + tests := []struct { + name string + epoch int64 + precision string + expected time.Time + }{ + {name: "nanoseconds", epoch: now.UnixNano(), precision: "n", expected: now}, + {name: "microseconds", epoch: now.Round(time.Microsecond).UnixNano() / int64(time.Microsecond), precision: "u", expected: now.Round(time.Microsecond)}, + {name: "milliseconds", epoch: now.Round(time.Millisecond).UnixNano() / int64(time.Millisecond), precision: "ms", expected: now.Round(time.Millisecond)}, + {name: "seconds", epoch: now.Round(time.Second).UnixNano() / int64(time.Second), precision: "s", expected: now.Round(time.Second)}, + {name: "minutes", epoch: now.Round(time.Minute).UnixNano() / int64(time.Minute), precision: "m", expected: now.Round(time.Minute)}, + {name: "hours", epoch: now.Round(time.Hour).UnixNano() / int64(time.Hour), precision: "h", expected: now.Round(time.Hour)}, + } + + for _, test := range tests { + t.Logf("testing %q\n", test.name) + tm, e := client.EpochToTime(test.epoch, test.precision) + if e != nil { + t.Fatalf("unexpected error: expected %v, actual: %v", nil, e) + } + if tm != test.expected { + t.Fatalf("unexpected time: expected %v, actual %v", test.expected, tm) + } + } +} + +// helper functions + +func emptyTestServer() *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Influxdb-Version", "x.x") + return + })) +} + +// Ensure that data with epoch times can be decoded. +func TestBatchPoints_Normal(t *testing.T) { + var bp client.BatchPoints + data := []byte(` +{ + "database": "foo", + "retentionPolicy": "bar", + "points": [ + { + "name": "cpu", + "tags": { + "host": "server01" + }, + "time": 14244733039069373, + "precision": "n", + "values": { + "value": 4541770385657154000 + } + }, + { + "name": "cpu", + "tags": { + "host": "server01" + }, + "time": 14244733039069380, + "precision": "n", + "values": { + "value": 7199311900554737000 + } + } + ] +} +`) + + if err := json.Unmarshal(data, &bp); err != nil { + t.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) + } +} + +func TestClient_Timeout(t *testing.T) { + done := make(chan bool) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + <-done + })) + defer ts.Close() + defer func() { done <- true }() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u, Timeout: 500 * time.Millisecond} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + query := client.Query{} + _, err = c.Query(query) + if err == nil { + t.Fatalf("unexpected success. expected timeout error") + } else if !strings.Contains(err.Error(), "request canceled") && + !strings.Contains(err.Error(), "use of closed network connection") { + t.Fatalf("unexpected error. expected 'request canceled' error, got %v", err) + } +} + +func TestClient_NoTimeout(t *testing.T) { + if testing.Short() { + t.Skip("skipping in short mode") + } + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(1 * time.Second) + var data client.Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + + query := client.Query{} + _, err = c.Query(query) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_ParseConnectionString_IPv6(t *testing.T) { + path := "[fdf5:9ede:1875:0:a9ee:a600:8fe3:d495]:8086" + u, err := client.ParseConnectionString(path, false) + if err != nil { + t.Fatalf("unexpected error, expected %v, actual %v", nil, err) + } + if u.Host != path { + t.Fatalf("ipv6 parse failed, expected %s, actual %s", path, u.Host) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client.go new file mode 100644 index 00000000..4dce0c28 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client.go @@ -0,0 +1,498 @@ +package client + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net" + "net/http" + "net/url" + "time" + + "github.com/influxdb/influxdb/models" +) + +// UDPPayloadSize is a reasonable default payload size for UDP packets that +// could be travelling over the internet. +const ( + UDPPayloadSize = 512 +) + +type HTTPConfig struct { + // Addr should be of the form "http://host:port" + // or "http://[ipv6-host%zone]:port". + Addr string + + // Username is the influxdb username, optional + Username string + + // Password is the influxdb password, optional + Password string + + // UserAgent is the http User Agent, defaults to "InfluxDBClient" + UserAgent string + + // Timeout for influxdb writes, defaults to no timeout + Timeout time.Duration + + // InsecureSkipVerify gets passed to the http client, if true, it will + // skip https certificate verification. Defaults to false + InsecureSkipVerify bool +} + +type UDPConfig struct { + // Addr should be of the form "host:port" + // or "[ipv6-host%zone]:port". + Addr string + + // PayloadSize is the maximum size of a UDP client message, optional + // Tune this based on your network. Defaults to UDPBufferSize. + PayloadSize int +} + +type BatchPointsConfig struct { + // Precision is the write precision of the points, defaults to "ns" + Precision string + + // Database is the database to write points to + Database string + + // RetentionPolicy is the retention policy of the points + RetentionPolicy string + + // Write consistency is the number of servers required to confirm write + WriteConsistency string +} + +// Client is a client interface for writing & querying the database +type Client interface { + // Write takes a BatchPoints object and writes all Points to InfluxDB. + Write(bp BatchPoints) error + + // Query makes an InfluxDB Query on the database. This will fail if using + // the UDP client. + Query(q Query) (*Response, error) + + // Close releases any resources a Client may be using. + Close() error +} + +// NewClient creates a client interface from the given config. +func NewHTTPClient(conf HTTPConfig) (Client, error) { + if conf.UserAgent == "" { + conf.UserAgent = "InfluxDBClient" + } + + u, err := url.Parse(conf.Addr) + if err != nil { + return nil, err + } else if u.Scheme != "http" && u.Scheme != "https" { + m := fmt.Sprintf("Unsupported protocol scheme: %s, your address"+ + " must start with http:// or https://", u.Scheme) + return nil, errors.New(m) + } + + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: conf.InsecureSkipVerify, + }, + } + return &client{ + url: u, + username: conf.Username, + password: conf.Password, + useragent: conf.UserAgent, + httpClient: &http.Client{ + Timeout: conf.Timeout, + Transport: tr, + }, + }, nil +} + +// Close releases the client's resources. +func (c *client) Close() error { + return nil +} + +// NewUDPClient returns a client interface for writing to an InfluxDB UDP +// service from the given config. +func NewUDPClient(conf UDPConfig) (Client, error) { + var udpAddr *net.UDPAddr + udpAddr, err := net.ResolveUDPAddr("udp", conf.Addr) + if err != nil { + return nil, err + } + + conn, err := net.DialUDP("udp", nil, udpAddr) + if err != nil { + return nil, err + } + + payloadSize := conf.PayloadSize + if payloadSize == 0 { + payloadSize = UDPPayloadSize + } + + return &udpclient{ + conn: conn, + payloadSize: payloadSize, + }, nil +} + +// Close releases the udpclient's resources. +func (uc *udpclient) Close() error { + return uc.conn.Close() +} + +type client struct { + url *url.URL + username string + password string + useragent string + httpClient *http.Client +} + +type udpclient struct { + conn *net.UDPConn + payloadSize int +} + +// BatchPoints is an interface into a batched grouping of points to write into +// InfluxDB together. BatchPoints is NOT thread-safe, you must create a separate +// batch for each goroutine. +type BatchPoints interface { + // AddPoint adds the given point to the Batch of points + AddPoint(p *Point) + // Points lists the points in the Batch + Points() []*Point + + // Precision returns the currently set precision of this Batch + Precision() string + // SetPrecision sets the precision of this batch. + SetPrecision(s string) error + + // Database returns the currently set database of this Batch + Database() string + // SetDatabase sets the database of this Batch + SetDatabase(s string) + + // WriteConsistency returns the currently set write consistency of this Batch + WriteConsistency() string + // SetWriteConsistency sets the write consistency of this Batch + SetWriteConsistency(s string) + + // RetentionPolicy returns the currently set retention policy of this Batch + RetentionPolicy() string + // SetRetentionPolicy sets the retention policy of this Batch + SetRetentionPolicy(s string) +} + +// NewBatchPoints returns a BatchPoints interface based on the given config. +func NewBatchPoints(conf BatchPointsConfig) (BatchPoints, error) { + if conf.Precision == "" { + conf.Precision = "ns" + } + if _, err := time.ParseDuration("1" + conf.Precision); err != nil { + return nil, err + } + bp := &batchpoints{ + database: conf.Database, + precision: conf.Precision, + retentionPolicy: conf.RetentionPolicy, + writeConsistency: conf.WriteConsistency, + } + return bp, nil +} + +type batchpoints struct { + points []*Point + database string + precision string + retentionPolicy string + writeConsistency string +} + +func (bp *batchpoints) AddPoint(p *Point) { + bp.points = append(bp.points, p) +} + +func (bp *batchpoints) Points() []*Point { + return bp.points +} + +func (bp *batchpoints) Precision() string { + return bp.precision +} + +func (bp *batchpoints) Database() string { + return bp.database +} + +func (bp *batchpoints) WriteConsistency() string { + return bp.writeConsistency +} + +func (bp *batchpoints) RetentionPolicy() string { + return bp.retentionPolicy +} + +func (bp *batchpoints) SetPrecision(p string) error { + if _, err := time.ParseDuration("1" + p); err != nil { + return err + } + bp.precision = p + return nil +} + +func (bp *batchpoints) SetDatabase(db string) { + bp.database = db +} + +func (bp *batchpoints) SetWriteConsistency(wc string) { + bp.writeConsistency = wc +} + +func (bp *batchpoints) SetRetentionPolicy(rp string) { + bp.retentionPolicy = rp +} + +type Point struct { + pt models.Point +} + +// NewPoint returns a point with the given timestamp. If a timestamp is not +// given, then data is sent to the database without a timestamp, in which case +// the server will assign local time upon reception. NOTE: it is recommended +// to send data without a timestamp. +func NewPoint( + name string, + tags map[string]string, + fields map[string]interface{}, + t ...time.Time, +) (*Point, error) { + var T time.Time + if len(t) > 0 { + T = t[0] + } + + pt, err := models.NewPoint(name, tags, fields, T) + if err != nil { + return nil, err + } + return &Point{ + pt: pt, + }, nil +} + +// String returns a line-protocol string of the Point +func (p *Point) String() string { + return p.pt.String() +} + +// PrecisionString returns a line-protocol string of the Point, at precision +func (p *Point) PrecisionString(precison string) string { + return p.pt.PrecisionString(precison) +} + +// Name returns the measurement name of the point +func (p *Point) Name() string { + return p.pt.Name() +} + +// Name returns the tags associated with the point +func (p *Point) Tags() map[string]string { + return p.pt.Tags() +} + +// Time return the timestamp for the point +func (p *Point) Time() time.Time { + return p.pt.Time() +} + +// UnixNano returns the unix nano time of the point +func (p *Point) UnixNano() int64 { + return p.pt.UnixNano() +} + +// Fields returns the fields for the point +func (p *Point) Fields() map[string]interface{} { + return p.pt.Fields() +} + +func (uc *udpclient) Write(bp BatchPoints) error { + var b bytes.Buffer + var d time.Duration + d, _ = time.ParseDuration("1" + bp.Precision()) + + for _, p := range bp.Points() { + pointstring := p.pt.RoundedString(d) + "\n" + + // Write and reset the buffer if we reach the max size + if b.Len()+len(pointstring) >= uc.payloadSize { + if _, err := uc.conn.Write(b.Bytes()); err != nil { + return err + } + b.Reset() + } + + if _, err := b.WriteString(pointstring); err != nil { + return err + } + } + + _, err := uc.conn.Write(b.Bytes()) + return err +} + +func (c *client) Write(bp BatchPoints) error { + var b bytes.Buffer + + for _, p := range bp.Points() { + if _, err := b.WriteString(p.pt.PrecisionString(bp.Precision())); err != nil { + return err + } + + if err := b.WriteByte('\n'); err != nil { + return err + } + } + + u := c.url + u.Path = "write" + req, err := http.NewRequest("POST", u.String(), &b) + if err != nil { + return err + } + req.Header.Set("Content-Type", "") + req.Header.Set("User-Agent", c.useragent) + if c.username != "" { + req.SetBasicAuth(c.username, c.password) + } + + params := req.URL.Query() + params.Set("db", bp.Database()) + params.Set("rp", bp.RetentionPolicy()) + params.Set("precision", bp.Precision()) + params.Set("consistency", bp.WriteConsistency()) + req.URL.RawQuery = params.Encode() + + resp, err := c.httpClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + + if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK { + var err = fmt.Errorf(string(body)) + return err + } + + return nil +} + +// Query defines a query to send to the server +type Query struct { + Command string + Database string + Precision string +} + +// NewQuery returns a query object +// database and precision strings can be empty strings if they are not needed +// for the query. +func NewQuery(command, database, precision string) Query { + return Query{ + Command: command, + Database: database, + Precision: precision, + } +} + +// Response represents a list of statement results. +type Response struct { + Results []Result + Err error +} + +// Error returns the first error from any statement. +// Returns nil if no errors occurred on any statements. +func (r *Response) Error() error { + if r.Err != nil { + return r.Err + } + for _, result := range r.Results { + if result.Err != nil { + return result.Err + } + } + return nil +} + +// Result represents a resultset returned from a single statement. +type Result struct { + Series []models.Row + Err error +} + +func (uc *udpclient) Query(q Query) (*Response, error) { + return nil, fmt.Errorf("Querying via UDP is not supported") +} + +// Query sends a command to the server and returns the Response +func (c *client) Query(q Query) (*Response, error) { + u := c.url + u.Path = "query" + + req, err := http.NewRequest("GET", u.String(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "") + req.Header.Set("User-Agent", c.useragent) + if c.username != "" { + req.SetBasicAuth(c.username, c.password) + } + + params := req.URL.Query() + params.Set("q", q.Command) + params.Set("db", q.Database) + if q.Precision != "" { + params.Set("epoch", q.Precision) + } + req.URL.RawQuery = params.Encode() + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + var response Response + dec := json.NewDecoder(resp.Body) + dec.UseNumber() + decErr := dec.Decode(&response) + + // ignore this error if we got an invalid status code + if decErr != nil && decErr.Error() == "EOF" && resp.StatusCode != http.StatusOK { + decErr = nil + } + // If we got a valid decode error, send that back + if decErr != nil { + return nil, decErr + } + // If we don't have an error in our json response, and didn't get statusOK + // then send back an error + if resp.StatusCode != http.StatusOK && response.Error() == nil { + return &response, fmt.Errorf("received status code %d from server", + resp.StatusCode) + } + return &response, nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client_test.go new file mode 100644 index 00000000..5f1e908a --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/client_test.go @@ -0,0 +1,337 @@ +package client + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" +) + +func TestUDPClient_Query(t *testing.T) { + config := UDPConfig{Addr: "localhost:8089"} + c, err := NewUDPClient(config) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + defer c.Close() + query := Query{} + _, err = c.Query(query) + if err == nil { + t.Error("Querying UDP client should fail") + } +} + +func TestUDPClient_Write(t *testing.T) { + config := UDPConfig{Addr: "localhost:8089"} + c, err := NewUDPClient(config) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + defer c.Close() + + bp, err := NewBatchPoints(BatchPointsConfig{}) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + + fields := make(map[string]interface{}) + fields["value"] = 1.0 + pt, _ := NewPoint("cpu", make(map[string]string), fields) + bp.AddPoint(pt) + + err = c.Write(bp) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestUDPClient_BadAddr(t *testing.T) { + config := UDPConfig{Addr: "foobar@wahoo"} + c, err := NewUDPClient(config) + if err == nil { + defer c.Close() + t.Error("Expected resolve error") + } +} + +func TestClient_Query(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var data Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + config := HTTPConfig{Addr: ts.URL} + c, _ := NewHTTPClient(config) + defer c.Close() + + query := Query{} + _, err := c.Query(query) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_BasicAuth(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u, p, ok := r.BasicAuth() + + if !ok { + t.Errorf("basic auth error") + } + if u != "username" { + t.Errorf("unexpected username, expected %q, actual %q", "username", u) + } + if p != "password" { + t.Errorf("unexpected password, expected %q, actual %q", "password", p) + } + var data Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + config := HTTPConfig{Addr: ts.URL, Username: "username", Password: "password"} + c, _ := NewHTTPClient(config) + defer c.Close() + + query := Query{} + _, err := c.Query(query) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_Write(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var data Response + w.WriteHeader(http.StatusNoContent) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + config := HTTPConfig{Addr: ts.URL} + c, _ := NewHTTPClient(config) + defer c.Close() + + bp, err := NewBatchPoints(BatchPointsConfig{}) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + err = c.Write(bp) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } +} + +func TestClient_UserAgent(t *testing.T) { + receivedUserAgent := "" + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + receivedUserAgent = r.UserAgent() + + var data Response + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(data) + })) + defer ts.Close() + + _, err := http.Get(ts.URL) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + + tests := []struct { + name string + userAgent string + expected string + }{ + { + name: "Empty user agent", + userAgent: "", + expected: "InfluxDBClient", + }, + { + name: "Custom user agent", + userAgent: "Test Influx Client", + expected: "Test Influx Client", + }, + } + + for _, test := range tests { + + config := HTTPConfig{Addr: ts.URL, UserAgent: test.userAgent} + c, _ := NewHTTPClient(config) + defer c.Close() + + receivedUserAgent = "" + query := Query{} + _, err = c.Query(query) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + if !strings.HasPrefix(receivedUserAgent, test.expected) { + t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + + receivedUserAgent = "" + bp, _ := NewBatchPoints(BatchPointsConfig{}) + err = c.Write(bp) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + if !strings.HasPrefix(receivedUserAgent, test.expected) { + t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + + receivedUserAgent = "" + _, err := c.Query(query) + if err != nil { + t.Errorf("unexpected error. expected %v, actual %v", nil, err) + } + if receivedUserAgent != test.expected { + t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) + } + } +} + +func TestClient_PointString(t *testing.T) { + const shortForm = "2006-Jan-02" + time1, _ := time.Parse(shortForm, "2013-Feb-03") + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields, time1) + + s := "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39 1359849600000000000" + if p.String() != s { + t.Errorf("Point String Error, got %s, expected %s", p.String(), s) + } + + s = "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39 1359849600000" + if p.PrecisionString("ms") != s { + t.Errorf("Point String Error, got %s, expected %s", + p.PrecisionString("ms"), s) + } +} + +func TestClient_PointWithoutTimeString(t *testing.T) { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields) + + s := "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39" + if p.String() != s { + t.Errorf("Point String Error, got %s, expected %s", p.String(), s) + } + + if p.PrecisionString("ms") != s { + t.Errorf("Point String Error, got %s, expected %s", + p.PrecisionString("ms"), s) + } +} + +func TestClient_PointName(t *testing.T) { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields) + + exp := "cpu_usage" + if p.Name() != exp { + t.Errorf("Error, got %s, expected %s", + p.Name(), exp) + } +} + +func TestClient_PointTags(t *testing.T) { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields) + + if !reflect.DeepEqual(tags, p.Tags()) { + t.Errorf("Error, got %v, expected %v", + p.Tags(), tags) + } +} + +func TestClient_PointUnixNano(t *testing.T) { + const shortForm = "2006-Jan-02" + time1, _ := time.Parse(shortForm, "2013-Feb-03") + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields, time1) + + exp := int64(1359849600000000000) + if p.UnixNano() != exp { + t.Errorf("Error, got %d, expected %d", + p.UnixNano(), exp) + } +} + +func TestClient_PointFields(t *testing.T) { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} + p, _ := NewPoint("cpu_usage", tags, fields) + + if !reflect.DeepEqual(fields, p.Fields()) { + t.Errorf("Error, got %v, expected %v", + p.Fields(), fields) + } +} + +func TestBatchPoints_PrecisionError(t *testing.T) { + _, err := NewBatchPoints(BatchPointsConfig{Precision: "foobar"}) + if err == nil { + t.Errorf("Precision: foobar should have errored") + } + + bp, _ := NewBatchPoints(BatchPointsConfig{Precision: "ns"}) + err = bp.SetPrecision("foobar") + if err == nil { + t.Errorf("Precision: foobar should have errored") + } +} + +func TestBatchPoints_SettersGetters(t *testing.T) { + bp, _ := NewBatchPoints(BatchPointsConfig{ + Precision: "ns", + Database: "db", + RetentionPolicy: "rp", + WriteConsistency: "wc", + }) + if bp.Precision() != "ns" { + t.Errorf("Expected: %s, got %s", bp.Precision(), "ns") + } + if bp.Database() != "db" { + t.Errorf("Expected: %s, got %s", bp.Database(), "db") + } + if bp.RetentionPolicy() != "rp" { + t.Errorf("Expected: %s, got %s", bp.RetentionPolicy(), "rp") + } + if bp.WriteConsistency() != "wc" { + t.Errorf("Expected: %s, got %s", bp.WriteConsistency(), "wc") + } + + bp.SetDatabase("db2") + bp.SetRetentionPolicy("rp2") + bp.SetWriteConsistency("wc2") + err := bp.SetPrecision("s") + if err != nil { + t.Errorf("Did not expect error: %s", err.Error()) + } + + if bp.Precision() != "s" { + t.Errorf("Expected: %s, got %s", bp.Precision(), "s") + } + if bp.Database() != "db2" { + t.Errorf("Expected: %s, got %s", bp.Database(), "db2") + } + if bp.RetentionPolicy() != "rp2" { + t.Errorf("Expected: %s, got %s", bp.RetentionPolicy(), "rp2") + } + if bp.WriteConsistency() != "wc2" { + t.Errorf("Expected: %s, got %s", bp.WriteConsistency(), "wc2") + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/example_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/example_test.go new file mode 100644 index 00000000..ae899d8e --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/client/v2/example_test.go @@ -0,0 +1,248 @@ +package client_test + +import ( + "fmt" + "math/rand" + "os" + "time" + + "github.com/influxdb/influxdb/client/v2" +) + +// Create a new client +func ExampleClient() { + // NOTE: this assumes you've setup a user and have setup shell env variables, + // namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below. + _, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: "http://localhost:8086", + Username: os.Getenv("INFLUX_USER"), + Password: os.Getenv("INFLUX_PWD"), + }) + if err != nil { + fmt.Println("Error creating InfluxDB Client: ", err.Error()) + } +} + +// Write a point using the UDP client +func ExampleClient_uDP() { + // Make client + config := client.UDPConfig{Addr: "localhost:8089"} + c, err := client.NewUDPClient(config) + if err != nil { + fmt.Println("Error: ", err.Error()) + } + defer c.Close() + + // Create a new point batch + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ + Precision: "s", + }) + + // Create a point and add to batch + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) + if err != nil { + fmt.Println("Error: ", err.Error()) + } + bp.AddPoint(pt) + + // Write the batch + c.Write(bp) +} + +// Write a point using the HTTP client +func ExampleClient_write() { + // Make client + c, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: "http://localhost:8086", + }) + if err != nil { + fmt.Println("Error creating InfluxDB Client: ", err.Error()) + } + defer c.Close() + + // Create a new point batch + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ + Database: "BumbleBeeTuna", + Precision: "s", + }) + + // Create a point and add to batch + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) + if err != nil { + fmt.Println("Error: ", err.Error()) + } + bp.AddPoint(pt) + + // Write the batch + c.Write(bp) +} + +// Create a batch and add a point +func ExampleBatchPoints() { + // Create a new point batch + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ + Database: "BumbleBeeTuna", + Precision: "s", + }) + + // Create a point and add to batch + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) + if err != nil { + fmt.Println("Error: ", err.Error()) + } + bp.AddPoint(pt) +} + +// Using the BatchPoints setter functions +func ExampleBatchPoints_setters() { + // Create a new point batch + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{}) + bp.SetDatabase("BumbleBeeTuna") + bp.SetPrecision("ms") + + // Create a point and add to batch + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) + if err != nil { + fmt.Println("Error: ", err.Error()) + } + bp.AddPoint(pt) +} + +// Create a new point with a timestamp +func ExamplePoint() { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) + if err == nil { + fmt.Println("We created a point: ", pt.String()) + } +} + +// Create a new point without a timestamp +func ExamplePoint_withoutTime() { + tags := map[string]string{"cpu": "cpu-total"} + fields := map[string]interface{}{ + "idle": 10.1, + "system": 53.3, + "user": 46.6, + } + pt, err := client.NewPoint("cpu_usage", tags, fields) + if err == nil { + fmt.Println("We created a point w/o time: ", pt.String()) + } +} + +// Write 1000 points +func ExampleClient_write1000() { + sampleSize := 1000 + + // Make client + c, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: "http://localhost:8086", + }) + if err != nil { + fmt.Println("Error creating InfluxDB Client: ", err.Error()) + } + defer c.Close() + + rand.Seed(42) + + bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ + Database: "systemstats", + Precision: "us", + }) + + for i := 0; i < sampleSize; i++ { + regions := []string{"us-west1", "us-west2", "us-west3", "us-east1"} + tags := map[string]string{ + "cpu": "cpu-total", + "host": fmt.Sprintf("host%d", rand.Intn(1000)), + "region": regions[rand.Intn(len(regions))], + } + + idle := rand.Float64() * 100.0 + fields := map[string]interface{}{ + "idle": idle, + "busy": 100.0 - idle, + } + + pt, err := client.NewPoint( + "cpu_usage", + tags, + fields, + time.Now(), + ) + if err != nil { + println("Error:", err.Error()) + continue + } + bp.AddPoint(pt) + } + + err = c.Write(bp) + if err != nil { + fmt.Println("Error: ", err.Error()) + } +} + +// Make a Query +func ExampleClient_query() { + // Make client + c, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: "http://localhost:8086", + }) + if err != nil { + fmt.Println("Error creating InfluxDB Client: ", err.Error()) + } + defer c.Close() + + q := client.NewQuery("SELECT count(value) FROM shapes", "square_holes", "ns") + if response, err := c.Query(q); err == nil && response.Error() == nil { + fmt.Println(response.Results) + } +} + +// Create a Database with a query +func ExampleClient_createDatabase() { + // Make client + c, err := client.NewHTTPClient(client.HTTPConfig{ + Addr: "http://localhost:8086", + }) + if err != nil { + fmt.Println("Error creating InfluxDB Client: ", err.Error()) + } + defer c.Close() + + q := client.NewQuery("CREATE DATABASE telegraf", "", "") + if response, err := c.Query(q); err == nil && response.Error() == nil { + fmt.Println(response.Results) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer.go new file mode 100644 index 00000000..cf7efddd --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer.go @@ -0,0 +1,78 @@ +package cluster + +import ( + "math/rand" + + "github.com/influxdb/influxdb/meta" +) + +// Balancer represents a load-balancing algorithm for a set of nodes +type Balancer interface { + // Next returns the next Node according to the balancing method + // or nil if there are no nodes available + Next() *meta.NodeInfo +} + +type nodeBalancer struct { + nodes []meta.NodeInfo // data nodes to balance between + p int // current node index +} + +// NewNodeBalancer create a shuffled, round-robin balancer so that +// multiple instances will return nodes in randomized order and each +// each returned node will be repeated in a cycle +func NewNodeBalancer(nodes []meta.NodeInfo) Balancer { + // make a copy of the node slice so we can randomize it + // without affecting the original instance as well as ensure + // that each Balancer returns nodes in a different order + b := &nodeBalancer{} + + b.nodes = make([]meta.NodeInfo, len(nodes)) + copy(b.nodes, nodes) + + b.shuffle() + return b +} + +// shuffle randomizes the ordering the balancers available nodes +func (b *nodeBalancer) shuffle() { + for i := range b.nodes { + j := rand.Intn(i + 1) + b.nodes[i], b.nodes[j] = b.nodes[j], b.nodes[i] + } +} + +// online returns a slice of the nodes that are online +func (b *nodeBalancer) online() []meta.NodeInfo { + return b.nodes + // now := time.Now().UTC() + // up := []meta.NodeInfo{} + // for _, n := range b.nodes { + // if n.OfflineUntil.After(now) { + // continue + // } + // up = append(up, n) + // } + // return up +} + +// Next returns the next available nodes +func (b *nodeBalancer) Next() *meta.NodeInfo { + // only use online nodes + up := b.online() + + // no nodes online + if len(up) == 0 { + return nil + } + + // rollover back to the beginning + if b.p >= len(up) { + b.p = 0 + } + + d := &up[b.p] + b.p++ + + return d +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer_test.go new file mode 100644 index 00000000..dd4a834c --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/balancer_test.go @@ -0,0 +1,115 @@ +package cluster_test + +import ( + "fmt" + "testing" + + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/meta" +) + +func NewNodes() []meta.NodeInfo { + var nodes []meta.NodeInfo + for i := 1; i <= 2; i++ { + nodes = append(nodes, meta.NodeInfo{ + ID: uint64(i), + Host: fmt.Sprintf("localhost:999%d", i), + }) + } + return nodes +} + +func TestBalancerEmptyNodes(t *testing.T) { + b := cluster.NewNodeBalancer([]meta.NodeInfo{}) + got := b.Next() + if got != nil { + t.Errorf("expected nil, got %v", got) + } +} + +func TestBalancerUp(t *testing.T) { + nodes := NewNodes() + b := cluster.NewNodeBalancer(nodes) + + // First node in randomized round-robin order + first := b.Next() + if first == nil { + t.Errorf("expected datanode, got %v", first) + } + + // Second node in randomized round-robin order + second := b.Next() + if second == nil { + t.Errorf("expected datanode, got %v", second) + } + + // Should never get the same node in order twice + if first.ID == second.ID { + t.Errorf("expected first != second. got %v = %v", first.ID, second.ID) + } +} + +/* +func TestBalancerDown(t *testing.T) { + nodes := NewNodes() + b := cluster.NewNodeBalancer(nodes) + + nodes[0].Down() + + // First node in randomized round-robin order + first := b.Next() + if first == nil { + t.Errorf("expected datanode, got %v", first) + } + + // Second node should rollover to the first up node + second := b.Next() + if second == nil { + t.Errorf("expected datanode, got %v", second) + } + + // Health node should be returned each time + if first.ID != 2 && first.ID != second.ID { + t.Errorf("expected first != second. got %v = %v", first.ID, second.ID) + } +} +*/ + +/* +func TestBalancerBackUp(t *testing.T) { + nodes := newDataNodes() + b := cluster.NewNodeBalancer(nodes) + + nodes[0].Down() + + for i := 0; i < 3; i++ { + got := b.Next() + if got == nil { + t.Errorf("expected datanode, got %v", got) + } + + if exp := uint64(2); got.ID != exp { + t.Errorf("wrong node id: exp %v, got %v", exp, got.ID) + } + } + + nodes[0].Up() + + // First node in randomized round-robin order + first := b.Next() + if first == nil { + t.Errorf("expected datanode, got %v", first) + } + + // Second node should rollover to the first up node + second := b.Next() + if second == nil { + t.Errorf("expected datanode, got %v", second) + } + + // Should get both nodes returned + if first.ID == second.ID { + t.Errorf("expected first != second. got %v = %v", first.ID, second.ID) + } +} +*/ diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/client_pool.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/client_pool.go new file mode 100644 index 00000000..fed7e18e --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/client_pool.go @@ -0,0 +1,57 @@ +package cluster + +import ( + "net" + "sync" + + "gopkg.in/fatih/pool.v2" +) + +type clientPool struct { + mu sync.RWMutex + pool map[uint64]pool.Pool +} + +func newClientPool() *clientPool { + return &clientPool{ + pool: make(map[uint64]pool.Pool), + } +} + +func (c *clientPool) setPool(nodeID uint64, p pool.Pool) { + c.mu.Lock() + c.pool[nodeID] = p + c.mu.Unlock() +} + +func (c *clientPool) getPool(nodeID uint64) (pool.Pool, bool) { + c.mu.RLock() + p, ok := c.pool[nodeID] + c.mu.RUnlock() + return p, ok +} + +func (c *clientPool) size() int { + c.mu.RLock() + var size int + for _, p := range c.pool { + size += p.Len() + } + c.mu.RUnlock() + return size +} + +func (c *clientPool) conn(nodeID uint64) (net.Conn, error) { + c.mu.RLock() + conn, err := c.pool[nodeID].Get() + c.mu.RUnlock() + return conn, err +} + +func (c *clientPool) close() { + c.mu.Lock() + for _, p := range c.pool { + p.Close() + } + c.mu.Unlock() +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config.go new file mode 100644 index 00000000..3a67b32d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config.go @@ -0,0 +1,35 @@ +package cluster + +import ( + "time" + + "github.com/influxdb/influxdb/toml" +) + +const ( + // DefaultWriteTimeout is the default timeout for a complete write to succeed. + DefaultWriteTimeout = 5 * time.Second + + // DefaultShardWriterTimeout is the default timeout set on shard writers. + DefaultShardWriterTimeout = 5 * time.Second + + // DefaultShardMapperTimeout is the default timeout set on shard mappers. + DefaultShardMapperTimeout = 5 * time.Second +) + +// Config represents the configuration for the clustering service. +type Config struct { + ForceRemoteShardMapping bool `toml:"force-remote-mapping"` + WriteTimeout toml.Duration `toml:"write-timeout"` + ShardWriterTimeout toml.Duration `toml:"shard-writer-timeout"` + ShardMapperTimeout toml.Duration `toml:"shard-mapper-timeout"` +} + +// NewConfig returns an instance of Config with defaults. +func NewConfig() Config { + return Config{ + WriteTimeout: toml.Duration(DefaultWriteTimeout), + ShardWriterTimeout: toml.Duration(DefaultShardWriterTimeout), + ShardMapperTimeout: toml.Duration(DefaultShardMapperTimeout), + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config_test.go new file mode 100644 index 00000000..db5e5ddc --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/config_test.go @@ -0,0 +1,27 @@ +package cluster_test + +import ( + "testing" + "time" + + "github.com/BurntSushi/toml" + "github.com/influxdb/influxdb/cluster" +) + +func TestConfig_Parse(t *testing.T) { + // Parse configuration. + var c cluster.Config + if _, err := toml.Decode(` +shard-writer-timeout = "10s" +write-timeout = "20s" +`, &c); err != nil { + t.Fatal(err) + } + + // Validate configuration. + if time.Duration(c.ShardWriterTimeout) != 10*time.Second { + t.Fatalf("unexpected shard-writer timeout: %s", c.ShardWriterTimeout) + } else if time.Duration(c.WriteTimeout) != 20*time.Second { + t.Fatalf("unexpected write timeout s: %s", c.WriteTimeout) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.pb.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.pb.go new file mode 100644 index 00000000..f9546390 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.pb.go @@ -0,0 +1,154 @@ +// Code generated by protoc-gen-gogo. +// source: internal/data.proto +// DO NOT EDIT! + +/* +Package internal is a generated protocol buffer package. + +It is generated from these files: + internal/data.proto + +It has these top-level messages: + WriteShardRequest + WriteShardResponse + MapShardRequest + MapShardResponse +*/ +package internal + +import proto "github.com/gogo/protobuf/proto" +import fmt "fmt" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +type WriteShardRequest struct { + ShardID *uint64 `protobuf:"varint,1,req,name=ShardID" json:"ShardID,omitempty"` + Points [][]byte `protobuf:"bytes,2,rep,name=Points" json:"Points,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *WriteShardRequest) Reset() { *m = WriteShardRequest{} } +func (m *WriteShardRequest) String() string { return proto.CompactTextString(m) } +func (*WriteShardRequest) ProtoMessage() {} + +func (m *WriteShardRequest) GetShardID() uint64 { + if m != nil && m.ShardID != nil { + return *m.ShardID + } + return 0 +} + +func (m *WriteShardRequest) GetPoints() [][]byte { + if m != nil { + return m.Points + } + return nil +} + +type WriteShardResponse struct { + Code *int32 `protobuf:"varint,1,req,name=Code" json:"Code,omitempty"` + Message *string `protobuf:"bytes,2,opt,name=Message" json:"Message,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *WriteShardResponse) Reset() { *m = WriteShardResponse{} } +func (m *WriteShardResponse) String() string { return proto.CompactTextString(m) } +func (*WriteShardResponse) ProtoMessage() {} + +func (m *WriteShardResponse) GetCode() int32 { + if m != nil && m.Code != nil { + return *m.Code + } + return 0 +} + +func (m *WriteShardResponse) GetMessage() string { + if m != nil && m.Message != nil { + return *m.Message + } + return "" +} + +type MapShardRequest struct { + ShardID *uint64 `protobuf:"varint,1,req,name=ShardID" json:"ShardID,omitempty"` + Query *string `protobuf:"bytes,2,req,name=Query" json:"Query,omitempty"` + ChunkSize *int32 `protobuf:"varint,3,req,name=ChunkSize" json:"ChunkSize,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MapShardRequest) Reset() { *m = MapShardRequest{} } +func (m *MapShardRequest) String() string { return proto.CompactTextString(m) } +func (*MapShardRequest) ProtoMessage() {} + +func (m *MapShardRequest) GetShardID() uint64 { + if m != nil && m.ShardID != nil { + return *m.ShardID + } + return 0 +} + +func (m *MapShardRequest) GetQuery() string { + if m != nil && m.Query != nil { + return *m.Query + } + return "" +} + +func (m *MapShardRequest) GetChunkSize() int32 { + if m != nil && m.ChunkSize != nil { + return *m.ChunkSize + } + return 0 +} + +type MapShardResponse struct { + Code *int32 `protobuf:"varint,1,req,name=Code" json:"Code,omitempty"` + Message *string `protobuf:"bytes,2,opt,name=Message" json:"Message,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=Data" json:"Data,omitempty"` + TagSets []string `protobuf:"bytes,4,rep,name=TagSets" json:"TagSets,omitempty"` + Fields []string `protobuf:"bytes,5,rep,name=Fields" json:"Fields,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MapShardResponse) Reset() { *m = MapShardResponse{} } +func (m *MapShardResponse) String() string { return proto.CompactTextString(m) } +func (*MapShardResponse) ProtoMessage() {} + +func (m *MapShardResponse) GetCode() int32 { + if m != nil && m.Code != nil { + return *m.Code + } + return 0 +} + +func (m *MapShardResponse) GetMessage() string { + if m != nil && m.Message != nil { + return *m.Message + } + return "" +} + +func (m *MapShardResponse) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func (m *MapShardResponse) GetTagSets() []string { + if m != nil { + return m.TagSets + } + return nil +} + +func (m *MapShardResponse) GetFields() []string { + if m != nil { + return m.Fields + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.proto b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.proto new file mode 100644 index 00000000..fed14bad --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/internal/data.proto @@ -0,0 +1,25 @@ +package internal; + +message WriteShardRequest { + required uint64 ShardID = 1; + repeated bytes Points = 2; +} + +message WriteShardResponse { + required int32 Code = 1; + optional string Message = 2; +} + +message MapShardRequest { + required uint64 ShardID = 1; + required string Query = 2; + required int32 ChunkSize = 3; +} + +message MapShardResponse { + required int32 Code = 1; + optional string Message = 2; + optional bytes Data = 3; + repeated string TagSets = 4; + repeated string Fields = 5; +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer.go new file mode 100644 index 00000000..91505890 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer.go @@ -0,0 +1,394 @@ +package cluster + +import ( + "errors" + "expvar" + "fmt" + "log" + "os" + "strings" + "sync" + "time" + + "github.com/influxdb/influxdb" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/models" + "github.com/influxdb/influxdb/tsdb" +) + +// ConsistencyLevel represent a required replication criteria before a write can +// be returned as successful +type ConsistencyLevel int + +// The statistics generated by the "write" mdoule +const ( + statWriteReq = "req" + statPointWriteReq = "pointReq" + statPointWriteReqLocal = "pointReqLocal" + statPointWriteReqRemote = "pointReqRemote" + statWriteOK = "writeOk" + statWritePartial = "writePartial" + statWriteTimeout = "writeTimeout" + statWriteErr = "writeError" + statWritePointReqHH = "pointReqHH" + statSubWriteOK = "subWriteOk" + statSubWriteDrop = "subWriteDrop" +) + +const ( + // ConsistencyLevelAny allows for hinted hand off, potentially no write happened yet + ConsistencyLevelAny ConsistencyLevel = iota + + // ConsistencyLevelOne requires at least one data node acknowledged a write + ConsistencyLevelOne + + // ConsistencyLevelQuorum requires a quorum of data nodes to acknowledge a write + ConsistencyLevelQuorum + + // ConsistencyLevelAll requires all data nodes to acknowledge a write + ConsistencyLevelAll +) + +var ( + // ErrTimeout is returned when a write times out. + ErrTimeout = errors.New("timeout") + + // ErrPartialWrite is returned when a write partially succeeds but does + // not meet the requested consistency level. + ErrPartialWrite = errors.New("partial write") + + // ErrWriteFailed is returned when no writes succeeded. + ErrWriteFailed = errors.New("write failed") + + // ErrInvalidConsistencyLevel is returned when parsing the string version + // of a consistency level. + ErrInvalidConsistencyLevel = errors.New("invalid consistency level") +) + +// ParseConsistencyLevel converts a consistency level string to the corresponding ConsistencyLevel const +func ParseConsistencyLevel(level string) (ConsistencyLevel, error) { + switch strings.ToLower(level) { + case "any": + return ConsistencyLevelAny, nil + case "one": + return ConsistencyLevelOne, nil + case "quorum": + return ConsistencyLevelQuorum, nil + case "all": + return ConsistencyLevelAll, nil + default: + return 0, ErrInvalidConsistencyLevel + } +} + +// PointsWriter handles writes across multiple local and remote data nodes. +type PointsWriter struct { + mu sync.RWMutex + closing chan struct{} + WriteTimeout time.Duration + Logger *log.Logger + + MetaStore interface { + NodeID() uint64 + Database(name string) (di *meta.DatabaseInfo, err error) + RetentionPolicy(database, policy string) (*meta.RetentionPolicyInfo, error) + CreateShardGroupIfNotExists(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) + ShardOwner(shardID uint64) (string, string, *meta.ShardGroupInfo) + } + + TSDBStore interface { + CreateShard(database, retentionPolicy string, shardID uint64) error + WriteToShard(shardID uint64, points []models.Point) error + } + + ShardWriter interface { + WriteShard(shardID, ownerID uint64, points []models.Point) error + } + + HintedHandoff interface { + WriteShard(shardID, ownerID uint64, points []models.Point) error + } + + Subscriber interface { + Points() chan<- *WritePointsRequest + } + subPoints chan<- *WritePointsRequest + + statMap *expvar.Map +} + +// NewPointsWriter returns a new instance of PointsWriter for a node. +func NewPointsWriter() *PointsWriter { + return &PointsWriter{ + closing: make(chan struct{}), + WriteTimeout: DefaultWriteTimeout, + Logger: log.New(os.Stderr, "[write] ", log.LstdFlags), + statMap: influxdb.NewStatistics("write", "write", nil), + } +} + +// ShardMapping contains a mapping of a shards to a points. +type ShardMapping struct { + Points map[uint64][]models.Point // The points associated with a shard ID + Shards map[uint64]*meta.ShardInfo // The shards that have been mapped, keyed by shard ID +} + +// NewShardMapping creates an empty ShardMapping +func NewShardMapping() *ShardMapping { + return &ShardMapping{ + Points: map[uint64][]models.Point{}, + Shards: map[uint64]*meta.ShardInfo{}, + } +} + +// MapPoint maps a point to shard +func (s *ShardMapping) MapPoint(shardInfo *meta.ShardInfo, p models.Point) { + points, ok := s.Points[shardInfo.ID] + if !ok { + s.Points[shardInfo.ID] = []models.Point{p} + } else { + s.Points[shardInfo.ID] = append(points, p) + } + s.Shards[shardInfo.ID] = shardInfo +} + +// Open opens the communication channel with the point writer +func (w *PointsWriter) Open() error { + w.mu.Lock() + defer w.mu.Unlock() + w.closing = make(chan struct{}) + if w.Subscriber != nil { + w.subPoints = w.Subscriber.Points() + } + return nil +} + +// Close closes the communication channel with the point writer +func (w *PointsWriter) Close() error { + w.mu.Lock() + defer w.mu.Unlock() + if w.closing != nil { + close(w.closing) + } + if w.subPoints != nil { + // 'nil' channels always block so this makes the + // select statement in WritePoints hit its default case + // dropping any in-flight writes. + w.subPoints = nil + } + return nil +} + +// MapShards maps the points contained in wp to a ShardMapping. If a point +// maps to a shard group or shard that does not currently exist, it will be +// created before returning the mapping. +func (w *PointsWriter) MapShards(wp *WritePointsRequest) (*ShardMapping, error) { + + // holds the start time ranges for required shard groups + timeRanges := map[time.Time]*meta.ShardGroupInfo{} + + rp, err := w.MetaStore.RetentionPolicy(wp.Database, wp.RetentionPolicy) + if err != nil { + return nil, err + } + if rp == nil { + return nil, influxdb.ErrRetentionPolicyNotFound(wp.RetentionPolicy) + } + + for _, p := range wp.Points { + timeRanges[p.Time().Truncate(rp.ShardGroupDuration)] = nil + } + + // holds all the shard groups and shards that are required for writes + for t := range timeRanges { + sg, err := w.MetaStore.CreateShardGroupIfNotExists(wp.Database, wp.RetentionPolicy, t) + if err != nil { + return nil, err + } + timeRanges[t] = sg + } + + mapping := NewShardMapping() + for _, p := range wp.Points { + sg := timeRanges[p.Time().Truncate(rp.ShardGroupDuration)] + sh := sg.ShardFor(p.HashID()) + mapping.MapPoint(&sh, p) + } + return mapping, nil +} + +// WritePointsInto is a copy of WritePoints that uses a tsdb structure instead of +// a cluster structure for information. This is to avoid a circular dependency +func (w *PointsWriter) WritePointsInto(p *tsdb.IntoWriteRequest) error { + req := WritePointsRequest{ + Database: p.Database, + RetentionPolicy: p.RetentionPolicy, + ConsistencyLevel: ConsistencyLevelAny, + Points: p.Points, + } + return w.WritePoints(&req) +} + +// WritePoints writes across multiple local and remote data nodes according the consistency level. +func (w *PointsWriter) WritePoints(p *WritePointsRequest) error { + w.statMap.Add(statWriteReq, 1) + w.statMap.Add(statPointWriteReq, int64(len(p.Points))) + + if p.RetentionPolicy == "" { + db, err := w.MetaStore.Database(p.Database) + if err != nil { + return err + } else if db == nil { + return influxdb.ErrDatabaseNotFound(p.Database) + } + p.RetentionPolicy = db.DefaultRetentionPolicy + } + + shardMappings, err := w.MapShards(p) + if err != nil { + return err + } + + // Write each shard in it's own goroutine and return as soon + // as one fails. + ch := make(chan error, len(shardMappings.Points)) + for shardID, points := range shardMappings.Points { + go func(shard *meta.ShardInfo, database, retentionPolicy string, points []models.Point) { + ch <- w.writeToShard(shard, p.Database, p.RetentionPolicy, p.ConsistencyLevel, points) + }(shardMappings.Shards[shardID], p.Database, p.RetentionPolicy, points) + } + + // Send points to subscriptions if possible. + ok := false + // We need to lock just in case the channel is about to be nil'ed + w.mu.RLock() + select { + case w.subPoints <- p: + ok = true + default: + } + w.mu.RUnlock() + if ok { + w.statMap.Add(statSubWriteOK, 1) + } else { + w.statMap.Add(statSubWriteDrop, 1) + } + + for range shardMappings.Points { + select { + case <-w.closing: + return ErrWriteFailed + case err := <-ch: + if err != nil { + return err + } + } + } + return nil +} + +// writeToShards writes points to a shard and ensures a write consistency level has been met. If the write +// partially succeeds, ErrPartialWrite is returned. +func (w *PointsWriter) writeToShard(shard *meta.ShardInfo, database, retentionPolicy string, + consistency ConsistencyLevel, points []models.Point) error { + // The required number of writes to achieve the requested consistency level + required := len(shard.Owners) + switch consistency { + case ConsistencyLevelAny, ConsistencyLevelOne: + required = 1 + case ConsistencyLevelQuorum: + required = required/2 + 1 + } + + // response channel for each shard writer go routine + type AsyncWriteResult struct { + Owner meta.ShardOwner + Err error + } + ch := make(chan *AsyncWriteResult, len(shard.Owners)) + + for _, owner := range shard.Owners { + go func(shardID uint64, owner meta.ShardOwner, points []models.Point) { + if w.MetaStore.NodeID() == owner.NodeID { + w.statMap.Add(statPointWriteReqLocal, int64(len(points))) + + err := w.TSDBStore.WriteToShard(shardID, points) + // If we've written to shard that should exist on the current node, but the store has + // not actually created this shard, tell it to create it and retry the write + if err == tsdb.ErrShardNotFound { + err = w.TSDBStore.CreateShard(database, retentionPolicy, shardID) + if err != nil { + ch <- &AsyncWriteResult{owner, err} + return + } + err = w.TSDBStore.WriteToShard(shardID, points) + } + ch <- &AsyncWriteResult{owner, err} + return + } + + w.statMap.Add(statPointWriteReqRemote, int64(len(points))) + err := w.ShardWriter.WriteShard(shardID, owner.NodeID, points) + if err != nil && tsdb.IsRetryable(err) { + // The remote write failed so queue it via hinted handoff + w.statMap.Add(statWritePointReqHH, int64(len(points))) + hherr := w.HintedHandoff.WriteShard(shardID, owner.NodeID, points) + + // If the write consistency level is ANY, then a successful hinted handoff can + // be considered a successful write so send nil to the response channel + // otherwise, let the original error propagate to the response channel + if hherr == nil && consistency == ConsistencyLevelAny { + ch <- &AsyncWriteResult{owner, nil} + return + } + } + ch <- &AsyncWriteResult{owner, err} + + }(shard.ID, owner, points) + } + + var wrote int + timeout := time.After(w.WriteTimeout) + var writeError error + for range shard.Owners { + select { + case <-w.closing: + return ErrWriteFailed + case <-timeout: + w.statMap.Add(statWriteTimeout, 1) + // return timeout error to caller + return ErrTimeout + case result := <-ch: + // If the write returned an error, continue to the next response + if result.Err != nil { + w.statMap.Add(statWriteErr, 1) + w.Logger.Printf("write failed for shard %d on node %d: %v", shard.ID, result.Owner.NodeID, result.Err) + + // Keep track of the first error we see to return back to the client + if writeError == nil { + writeError = result.Err + } + continue + } + + wrote++ + + // We wrote the required consistency level + if wrote >= required { + w.statMap.Add(statWriteOK, 1) + return nil + } + } + } + + if wrote > 0 { + w.statMap.Add(statWritePartial, 1) + return ErrPartialWrite + } + + if writeError != nil { + return fmt.Errorf("write failed: %v", writeError) + } + + return ErrWriteFailed +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer_test.go new file mode 100644 index 00000000..d0f57fbc --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/points_writer_test.go @@ -0,0 +1,493 @@ +package cluster_test + +import ( + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/models" +) + +// Ensures the points writer maps a single point to a single shard. +func TestPointsWriter_MapShards_One(t *testing.T) { + ms := MetaStore{} + rp := NewRetentionPolicy("myp", time.Hour, 3) + + ms.NodeIDFn = func() uint64 { return 1 } + ms.RetentionPolicyFn = func(db, retentionPolicy string) (*meta.RetentionPolicyInfo, error) { + return rp, nil + } + + ms.CreateShardGroupIfNotExistsFn = func(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) { + return &rp.ShardGroups[0], nil + } + + c := cluster.PointsWriter{MetaStore: ms} + pr := &cluster.WritePointsRequest{ + Database: "mydb", + RetentionPolicy: "myrp", + ConsistencyLevel: cluster.ConsistencyLevelOne, + } + pr.AddPoint("cpu", 1.0, time.Now(), nil) + + var ( + shardMappings *cluster.ShardMapping + err error + ) + if shardMappings, err = c.MapShards(pr); err != nil { + t.Fatalf("unexpected an error: %v", err) + } + + if exp := 1; len(shardMappings.Points) != exp { + t.Errorf("MapShards() len mismatch. got %v, exp %v", len(shardMappings.Points), exp) + } +} + +// Ensures the points writer maps a multiple points across shard group boundaries. +func TestPointsWriter_MapShards_Multiple(t *testing.T) { + ms := MetaStore{} + rp := NewRetentionPolicy("myp", time.Hour, 3) + AttachShardGroupInfo(rp, []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }) + AttachShardGroupInfo(rp, []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }) + + ms.NodeIDFn = func() uint64 { return 1 } + ms.RetentionPolicyFn = func(db, retentionPolicy string) (*meta.RetentionPolicyInfo, error) { + return rp, nil + } + + ms.CreateShardGroupIfNotExistsFn = func(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) { + for i, sg := range rp.ShardGroups { + if timestamp.Equal(sg.StartTime) || timestamp.After(sg.StartTime) && timestamp.Before(sg.EndTime) { + return &rp.ShardGroups[i], nil + } + } + panic("should not get here") + } + + c := cluster.PointsWriter{MetaStore: ms} + pr := &cluster.WritePointsRequest{ + Database: "mydb", + RetentionPolicy: "myrp", + ConsistencyLevel: cluster.ConsistencyLevelOne, + } + + // Three points that range over the shardGroup duration (1h) and should map to two + // distinct shards + pr.AddPoint("cpu", 1.0, time.Unix(0, 0), nil) + pr.AddPoint("cpu", 2.0, time.Unix(0, 0).Add(time.Hour), nil) + pr.AddPoint("cpu", 3.0, time.Unix(0, 0).Add(time.Hour+time.Second), nil) + + var ( + shardMappings *cluster.ShardMapping + err error + ) + if shardMappings, err = c.MapShards(pr); err != nil { + t.Fatalf("unexpected an error: %v", err) + } + + if exp := 2; len(shardMappings.Points) != exp { + t.Errorf("MapShards() len mismatch. got %v, exp %v", len(shardMappings.Points), exp) + } + + for _, points := range shardMappings.Points { + // First shard shoud have 1 point w/ first point added + if len(points) == 1 && points[0].Time() != pr.Points[0].Time() { + t.Fatalf("MapShards() value mismatch. got %v, exp %v", points[0].Time(), pr.Points[0].Time()) + } + + // Second shard shoud have the last two points added + if len(points) == 2 && points[0].Time() != pr.Points[1].Time() { + t.Fatalf("MapShards() value mismatch. got %v, exp %v", points[0].Time(), pr.Points[1].Time()) + } + + if len(points) == 2 && points[1].Time() != pr.Points[2].Time() { + t.Fatalf("MapShards() value mismatch. got %v, exp %v", points[1].Time(), pr.Points[2].Time()) + } + } +} + +func TestPointsWriter_WritePoints(t *testing.T) { + tests := []struct { + name string + database string + retentionPolicy string + consistency cluster.ConsistencyLevel + + // the responses returned by each shard write call. node ID 1 = pos 0 + err []error + expErr error + }{ + // Consistency one + { + name: "write one success", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelOne, + err: []error{nil, nil, nil}, + expErr: nil, + }, + { + name: "write one error", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelOne, + err: []error{fmt.Errorf("a failure"), fmt.Errorf("a failure"), fmt.Errorf("a failure")}, + expErr: fmt.Errorf("write failed: a failure"), + }, + + // Consistency any + { + name: "write any success", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelAny, + err: []error{fmt.Errorf("a failure"), nil, fmt.Errorf("a failure")}, + expErr: nil, + }, + // Consistency all + { + name: "write all success", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelAll, + err: []error{nil, nil, nil}, + expErr: nil, + }, + { + name: "write all, 2/3, partial write", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelAll, + err: []error{nil, fmt.Errorf("a failure"), nil}, + expErr: cluster.ErrPartialWrite, + }, + { + name: "write all, 1/3 (failure)", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelAll, + err: []error{nil, fmt.Errorf("a failure"), fmt.Errorf("a failure")}, + expErr: cluster.ErrPartialWrite, + }, + + // Consistency quorum + { + name: "write quorum, 1/3 failure", + consistency: cluster.ConsistencyLevelQuorum, + database: "mydb", + retentionPolicy: "myrp", + err: []error{fmt.Errorf("a failure"), fmt.Errorf("a failure"), nil}, + expErr: cluster.ErrPartialWrite, + }, + { + name: "write quorum, 2/3 success", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelQuorum, + err: []error{nil, nil, fmt.Errorf("a failure")}, + expErr: nil, + }, + { + name: "write quorum, 3/3 success", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelQuorum, + err: []error{nil, nil, nil}, + expErr: nil, + }, + + // Error write error + { + name: "no writes succeed", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelOne, + err: []error{fmt.Errorf("a failure"), fmt.Errorf("a failure"), fmt.Errorf("a failure")}, + expErr: fmt.Errorf("write failed: a failure"), + }, + + // Hinted handoff w/ ANY + { + name: "hinted handoff write succeed", + database: "mydb", + retentionPolicy: "myrp", + consistency: cluster.ConsistencyLevelAny, + err: []error{fmt.Errorf("a failure"), fmt.Errorf("a failure"), fmt.Errorf("a failure")}, + expErr: nil, + }, + + // Write to non-existent database + { + name: "write to non-existent database", + database: "doesnt_exist", + retentionPolicy: "", + consistency: cluster.ConsistencyLevelAny, + err: []error{nil, nil, nil}, + expErr: fmt.Errorf("database not found: doesnt_exist"), + }, + } + + for _, test := range tests { + + pr := &cluster.WritePointsRequest{ + Database: test.database, + RetentionPolicy: test.retentionPolicy, + ConsistencyLevel: test.consistency, + } + + // Three points that range over the shardGroup duration (1h) and should map to two + // distinct shards + pr.AddPoint("cpu", 1.0, time.Unix(0, 0), nil) + pr.AddPoint("cpu", 2.0, time.Unix(0, 0).Add(time.Hour), nil) + pr.AddPoint("cpu", 3.0, time.Unix(0, 0).Add(time.Hour+time.Second), nil) + + // copy to prevent data race + theTest := test + sm := cluster.NewShardMapping() + sm.MapPoint( + &meta.ShardInfo{ID: uint64(1), Owners: []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }}, + pr.Points[0]) + sm.MapPoint( + &meta.ShardInfo{ID: uint64(2), Owners: []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }}, + pr.Points[1]) + sm.MapPoint( + &meta.ShardInfo{ID: uint64(2), Owners: []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }}, + pr.Points[2]) + + // Local cluster.Node ShardWriter + // lock on the write increment since these functions get called in parallel + var mu sync.Mutex + sw := &fakeShardWriter{ + ShardWriteFn: func(shardID, nodeID uint64, points []models.Point) error { + mu.Lock() + defer mu.Unlock() + return theTest.err[int(nodeID)-1] + }, + } + + store := &fakeStore{ + WriteFn: func(shardID uint64, points []models.Point) error { + mu.Lock() + defer mu.Unlock() + return theTest.err[0] + }, + } + + hh := &fakeShardWriter{ + ShardWriteFn: func(shardID, nodeID uint64, points []models.Point) error { + return nil + }, + } + + ms := NewMetaStore() + ms.DatabaseFn = func(database string) (*meta.DatabaseInfo, error) { + return nil, nil + } + ms.NodeIDFn = func() uint64 { return 1 } + + subPoints := make(chan *cluster.WritePointsRequest, 1) + sub := Subscriber{} + sub.PointsFn = func() chan<- *cluster.WritePointsRequest { + return subPoints + } + + c := cluster.NewPointsWriter() + c.MetaStore = ms + c.ShardWriter = sw + c.TSDBStore = store + c.HintedHandoff = hh + c.Subscriber = sub + + c.Open() + defer c.Close() + + err := c.WritePoints(pr) + if err == nil && test.expErr != nil { + t.Errorf("PointsWriter.WritePoints(): '%s' error: got %v, exp %v", test.name, err, test.expErr) + } + + if err != nil && test.expErr == nil { + t.Errorf("PointsWriter.WritePoints(): '%s' error: got %v, exp %v", test.name, err, test.expErr) + } + if err != nil && test.expErr != nil && err.Error() != test.expErr.Error() { + t.Errorf("PointsWriter.WritePoints(): '%s' error: got %v, exp %v", test.name, err, test.expErr) + } + if test.expErr == nil { + select { + case p := <-subPoints: + if p != pr { + t.Errorf("PointsWriter.WritePoints(): '%s' error: unexpected WritePointsRequest got %v, exp %v", test.name, p, pr) + } + default: + t.Errorf("PointsWriter.WritePoints(): '%s' error: Subscriber.Points not called", test.name) + } + } + } +} + +var shardID uint64 + +type fakeShardWriter struct { + ShardWriteFn func(shardID, nodeID uint64, points []models.Point) error +} + +func (f *fakeShardWriter) WriteShard(shardID, nodeID uint64, points []models.Point) error { + return f.ShardWriteFn(shardID, nodeID, points) +} + +type fakeStore struct { + WriteFn func(shardID uint64, points []models.Point) error + CreateShardfn func(database, retentionPolicy string, shardID uint64) error +} + +func (f *fakeStore) WriteToShard(shardID uint64, points []models.Point) error { + return f.WriteFn(shardID, points) +} + +func (f *fakeStore) CreateShard(database, retentionPolicy string, shardID uint64) error { + return f.CreateShardfn(database, retentionPolicy, shardID) +} + +func NewMetaStore() *MetaStore { + ms := &MetaStore{} + rp := NewRetentionPolicy("myp", time.Hour, 3) + AttachShardGroupInfo(rp, []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }) + AttachShardGroupInfo(rp, []meta.ShardOwner{ + {NodeID: 1}, + {NodeID: 2}, + {NodeID: 3}, + }) + + ms.RetentionPolicyFn = func(db, retentionPolicy string) (*meta.RetentionPolicyInfo, error) { + return rp, nil + } + + ms.CreateShardGroupIfNotExistsFn = func(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) { + for i, sg := range rp.ShardGroups { + if timestamp.Equal(sg.StartTime) || timestamp.After(sg.StartTime) && timestamp.Before(sg.EndTime) { + return &rp.ShardGroups[i], nil + } + } + panic("should not get here") + } + return ms +} + +type MetaStore struct { + NodeIDFn func() uint64 + RetentionPolicyFn func(database, name string) (*meta.RetentionPolicyInfo, error) + CreateShardGroupIfNotExistsFn func(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) + DatabaseFn func(database string) (*meta.DatabaseInfo, error) + ShardOwnerFn func(shardID uint64) (string, string, *meta.ShardGroupInfo) +} + +func (m MetaStore) NodeID() uint64 { return m.NodeIDFn() } + +func (m MetaStore) RetentionPolicy(database, name string) (*meta.RetentionPolicyInfo, error) { + return m.RetentionPolicyFn(database, name) +} + +func (m MetaStore) CreateShardGroupIfNotExists(database, policy string, timestamp time.Time) (*meta.ShardGroupInfo, error) { + return m.CreateShardGroupIfNotExistsFn(database, policy, timestamp) +} + +func (m MetaStore) Database(database string) (*meta.DatabaseInfo, error) { + return m.DatabaseFn(database) +} + +func (m MetaStore) ShardOwner(shardID uint64) (string, string, *meta.ShardGroupInfo) { + return m.ShardOwnerFn(shardID) +} + +type Subscriber struct { + PointsFn func() chan<- *cluster.WritePointsRequest +} + +func (s Subscriber) Points() chan<- *cluster.WritePointsRequest { + return s.PointsFn() +} + +func NewRetentionPolicy(name string, duration time.Duration, nodeCount int) *meta.RetentionPolicyInfo { + shards := []meta.ShardInfo{} + owners := []meta.ShardOwner{} + for i := 1; i <= nodeCount; i++ { + owners = append(owners, meta.ShardOwner{NodeID: uint64(i)}) + } + + // each node is fully replicated with each other + shards = append(shards, meta.ShardInfo{ + ID: nextShardID(), + Owners: owners, + }) + + rp := &meta.RetentionPolicyInfo{ + Name: "myrp", + ReplicaN: nodeCount, + Duration: duration, + ShardGroupDuration: duration, + ShardGroups: []meta.ShardGroupInfo{ + meta.ShardGroupInfo{ + ID: nextShardID(), + StartTime: time.Unix(0, 0), + EndTime: time.Unix(0, 0).Add(duration).Add(-1), + Shards: shards, + }, + }, + } + return rp +} + +func AttachShardGroupInfo(rp *meta.RetentionPolicyInfo, owners []meta.ShardOwner) { + var startTime, endTime time.Time + if len(rp.ShardGroups) == 0 { + startTime = time.Unix(0, 0) + } else { + startTime = rp.ShardGroups[len(rp.ShardGroups)-1].StartTime.Add(rp.ShardGroupDuration) + } + endTime = startTime.Add(rp.ShardGroupDuration).Add(-1) + + sh := meta.ShardGroupInfo{ + ID: uint64(len(rp.ShardGroups) + 1), + StartTime: startTime, + EndTime: endTime, + Shards: []meta.ShardInfo{ + meta.ShardInfo{ + ID: nextShardID(), + Owners: owners, + }, + }, + } + rp.ShardGroups = append(rp.ShardGroups, sh) +} + +func nextShardID() uint64 { + return atomic.AddUint64(&shardID, 1) +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc.go new file mode 100644 index 00000000..defbb4fd --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc.go @@ -0,0 +1,213 @@ +package cluster + +import ( + "fmt" + "time" + + "github.com/gogo/protobuf/proto" + "github.com/influxdb/influxdb/cluster/internal" + "github.com/influxdb/influxdb/models" +) + +//go:generate protoc --gogo_out=. internal/data.proto + +// MapShardRequest represents the request to map a remote shard for a query. +type MapShardRequest struct { + pb internal.MapShardRequest +} + +// ShardID of the map request +func (m *MapShardRequest) ShardID() uint64 { return m.pb.GetShardID() } + +// Query returns the Shard map request's query +func (m *MapShardRequest) Query() string { return m.pb.GetQuery() } + +// ChunkSize returns Shard map request's chunk size +func (m *MapShardRequest) ChunkSize() int32 { return m.pb.GetChunkSize() } + +// SetShardID sets the map request's shard id +func (m *MapShardRequest) SetShardID(id uint64) { m.pb.ShardID = &id } + +// SetQuery sets the Shard map request's Query +func (m *MapShardRequest) SetQuery(query string) { m.pb.Query = &query } + +// SetChunkSize sets the Shard map request's chunk size +func (m *MapShardRequest) SetChunkSize(chunkSize int32) { m.pb.ChunkSize = &chunkSize } + +// MarshalBinary encodes the object to a binary format. +func (m *MapShardRequest) MarshalBinary() ([]byte, error) { + return proto.Marshal(&m.pb) +} + +// UnmarshalBinary populates MapShardRequest from a binary format. +func (m *MapShardRequest) UnmarshalBinary(buf []byte) error { + if err := proto.Unmarshal(buf, &m.pb); err != nil { + return err + } + return nil +} + +// MapShardResponse represents the response returned from a remote MapShardRequest call +type MapShardResponse struct { + pb internal.MapShardResponse +} + +// NewMapShardResponse returns the response returned from a remote MapShardRequest call +func NewMapShardResponse(code int, message string) *MapShardResponse { + m := &MapShardResponse{} + m.SetCode(code) + m.SetMessage(message) + return m +} + +// Code returns the Shard map response's code +func (r *MapShardResponse) Code() int { return int(r.pb.GetCode()) } + +// Message returns the the Shard map response's Message +func (r *MapShardResponse) Message() string { return r.pb.GetMessage() } + +// TagSets returns Shard map response's tag sets +func (r *MapShardResponse) TagSets() []string { return r.pb.GetTagSets() } + +// Fields returns the Shard map response's Fields +func (r *MapShardResponse) Fields() []string { return r.pb.GetFields() } + +// Data returns the Shard map response's Data +func (r *MapShardResponse) Data() []byte { return r.pb.GetData() } + +// SetCode sets the Shard map response's code +func (r *MapShardResponse) SetCode(code int) { r.pb.Code = proto.Int32(int32(code)) } + +// SetMessage sets Shard map response's message +func (r *MapShardResponse) SetMessage(message string) { r.pb.Message = &message } + +// SetTagSets sets Shard map response's tagsets +func (r *MapShardResponse) SetTagSets(tagsets []string) { r.pb.TagSets = tagsets } + +// SetFields sets the Shard map response's Fields +func (r *MapShardResponse) SetFields(fields []string) { r.pb.Fields = fields } + +// SetData sets the Shard map response's Data +func (r *MapShardResponse) SetData(data []byte) { r.pb.Data = data } + +// MarshalBinary encodes the object to a binary format. +func (r *MapShardResponse) MarshalBinary() ([]byte, error) { + return proto.Marshal(&r.pb) +} + +// UnmarshalBinary populates WritePointRequest from a binary format. +func (r *MapShardResponse) UnmarshalBinary(buf []byte) error { + if err := proto.Unmarshal(buf, &r.pb); err != nil { + return err + } + return nil +} + +// WritePointsRequest represents a request to write point data to the cluster +type WritePointsRequest struct { + Database string + RetentionPolicy string + ConsistencyLevel ConsistencyLevel + Points []models.Point +} + +// AddPoint adds a point to the WritePointRequest with field key 'value' +func (w *WritePointsRequest) AddPoint(name string, value interface{}, timestamp time.Time, tags map[string]string) { + pt, err := models.NewPoint( + name, tags, map[string]interface{}{"value": value}, timestamp, + ) + if err != nil { + return + } + w.Points = append(w.Points, pt) +} + +// WriteShardRequest represents the a request to write a slice of points to a shard +type WriteShardRequest struct { + pb internal.WriteShardRequest +} + +// WriteShardResponse represents the response returned from a remote WriteShardRequest call +type WriteShardResponse struct { + pb internal.WriteShardResponse +} + +// SetShardID sets the ShardID +func (w *WriteShardRequest) SetShardID(id uint64) { w.pb.ShardID = &id } + +// ShardID gets the ShardID +func (w *WriteShardRequest) ShardID() uint64 { return w.pb.GetShardID() } + +// Points returns the time series Points +func (w *WriteShardRequest) Points() []models.Point { return w.unmarshalPoints() } + +// AddPoint adds a new time series point +func (w *WriteShardRequest) AddPoint(name string, value interface{}, timestamp time.Time, tags map[string]string) { + pt, err := models.NewPoint( + name, tags, map[string]interface{}{"value": value}, timestamp, + ) + if err != nil { + return + } + w.AddPoints([]models.Point{pt}) +} + +// AddPoints adds a new time series point +func (w *WriteShardRequest) AddPoints(points []models.Point) { + for _, p := range points { + w.pb.Points = append(w.pb.Points, []byte(p.String())) + } +} + +// MarshalBinary encodes the object to a binary format. +func (w *WriteShardRequest) MarshalBinary() ([]byte, error) { + return proto.Marshal(&w.pb) +} + +// UnmarshalBinary populates WritePointRequest from a binary format. +func (w *WriteShardRequest) UnmarshalBinary(buf []byte) error { + if err := proto.Unmarshal(buf, &w.pb); err != nil { + return err + } + return nil +} + +func (w *WriteShardRequest) unmarshalPoints() []models.Point { + points := make([]models.Point, len(w.pb.GetPoints())) + for i, p := range w.pb.GetPoints() { + pt, err := models.ParsePoints(p) + if err != nil { + // A error here means that one node parsed the point correctly but sent an + // unparseable version to another node. We could log and drop the point and allow + // anti-entropy to resolve the discrepancy but this shouldn't ever happen. + panic(fmt.Sprintf("failed to parse point: `%v`: %v", string(p), err)) + } + points[i] = pt[0] + } + return points +} + +// SetCode sets the Code +func (w *WriteShardResponse) SetCode(code int) { w.pb.Code = proto.Int32(int32(code)) } + +// SetMessage sets the Message +func (w *WriteShardResponse) SetMessage(message string) { w.pb.Message = &message } + +// Code returns the Code +func (w *WriteShardResponse) Code() int { return int(w.pb.GetCode()) } + +// Message returns the Message +func (w *WriteShardResponse) Message() string { return w.pb.GetMessage() } + +// MarshalBinary encodes the object to a binary format. +func (w *WriteShardResponse) MarshalBinary() ([]byte, error) { + return proto.Marshal(&w.pb) +} + +// UnmarshalBinary populates WritePointRequest from a binary format. +func (w *WriteShardResponse) UnmarshalBinary(buf []byte) error { + if err := proto.Unmarshal(buf, &w.pb); err != nil { + return err + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc_test.go new file mode 100644 index 00000000..4e42cd5d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/rpc_test.go @@ -0,0 +1,110 @@ +package cluster + +import ( + "testing" + "time" +) + +func TestWriteShardRequestBinary(t *testing.T) { + sr := &WriteShardRequest{} + + sr.SetShardID(uint64(1)) + if exp := uint64(1); sr.ShardID() != exp { + t.Fatalf("ShardID mismatch: got %v, exp %v", sr.ShardID(), exp) + } + + sr.AddPoint("cpu", 1.0, time.Unix(0, 0), map[string]string{"host": "serverA"}) + sr.AddPoint("cpu", 2.0, time.Unix(0, 0).Add(time.Hour), nil) + sr.AddPoint("cpu_load", 3.0, time.Unix(0, 0).Add(time.Hour+time.Second), nil) + + b, err := sr.MarshalBinary() + if err != nil { + t.Fatalf("WritePointsRequest.MarshalBinary() failed: %v", err) + } + if len(b) == 0 { + t.Fatalf("WritePointsRequest.MarshalBinary() returned 0 bytes") + } + + got := &WriteShardRequest{} + if err := got.UnmarshalBinary(b); err != nil { + t.Fatalf("WritePointsRequest.UnmarshalMarshalBinary() failed: %v", err) + } + + if got.ShardID() != sr.ShardID() { + t.Errorf("ShardID mismatch: got %v, exp %v", got.ShardID(), sr.ShardID()) + } + + if len(got.Points()) != len(sr.Points()) { + t.Errorf("Points count mismatch: got %v, exp %v", len(got.Points()), len(sr.Points())) + } + + srPoints := sr.Points() + gotPoints := got.Points() + for i, p := range srPoints { + g := gotPoints[i] + + if g.Name() != p.Name() { + t.Errorf("Point %d name mismatch: got %v, exp %v", i, g.Name(), p.Name()) + } + + if !g.Time().Equal(p.Time()) { + t.Errorf("Point %d time mismatch: got %v, exp %v", i, g.Time(), p.Time()) + } + + if g.HashID() != p.HashID() { + t.Errorf("Point #%d HashID() mismatch: got %v, exp %v", i, g.HashID(), p.HashID()) + } + + for k, v := range p.Tags() { + if g.Tags()[k] != v { + t.Errorf("Point #%d tag mismatch: got %v, exp %v", i, k, v) + } + } + + if len(p.Fields()) != len(g.Fields()) { + t.Errorf("Point %d field count mismatch: got %v, exp %v", i, len(g.Fields()), len(p.Fields())) + } + + for j, f := range p.Fields() { + if g.Fields()[j] != f { + t.Errorf("Point %d field mismatch: got %v, exp %v", i, g.Fields()[j], f) + } + } + } +} + +func TestWriteShardResponseBinary(t *testing.T) { + sr := &WriteShardResponse{} + sr.SetCode(10) + sr.SetMessage("foo") + b, err := sr.MarshalBinary() + + if exp := 10; sr.Code() != exp { + t.Fatalf("Code mismatch: got %v, exp %v", sr.Code(), exp) + } + + if exp := "foo"; sr.Message() != exp { + t.Fatalf("Message mismatch: got %v, exp %v", sr.Message(), exp) + } + + if err != nil { + t.Fatalf("WritePointsResponse.MarshalBinary() failed: %v", err) + } + if len(b) == 0 { + t.Fatalf("WritePointsResponse.MarshalBinary() returned 0 bytes") + } + + got := &WriteShardResponse{} + if err := got.UnmarshalBinary(b); err != nil { + t.Fatalf("WritePointsResponse.UnmarshalMarshalBinary() failed: %v", err) + } + + if got.Code() != sr.Code() { + t.Errorf("Code mismatch: got %v, exp %v", got.Code(), sr.Code()) + } + + if got.Message() != sr.Message() { + t.Errorf("Message mismatch: got %v, exp %v", got.Message(), sr.Message()) + } + +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service.go new file mode 100644 index 00000000..5169a6e3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service.go @@ -0,0 +1,371 @@ +package cluster + +import ( + "encoding/binary" + "encoding/json" + "expvar" + "fmt" + "io" + "log" + "net" + "os" + "strings" + "sync" + + "github.com/influxdb/influxdb" + "github.com/influxdb/influxdb/influxql" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/models" + "github.com/influxdb/influxdb/tsdb" +) + +// MaxMessageSize defines how large a message can be before we reject it +const MaxMessageSize = 1024 * 1024 * 1024 // 1GB + +// MuxHeader is the header byte used in the TCP mux. +const MuxHeader = 2 + +// Statistics maintained by the cluster package +const ( + writeShardReq = "writeShardReq" + writeShardPointsReq = "writeShardPointsReq" + writeShardFail = "writeShardFail" + mapShardReq = "mapShardReq" + mapShardResp = "mapShardResp" +) + +// Service processes data received over raw TCP connections. +type Service struct { + mu sync.RWMutex + + wg sync.WaitGroup + closing chan struct{} + + Listener net.Listener + + MetaStore interface { + ShardOwner(shardID uint64) (string, string, *meta.ShardGroupInfo) + } + + TSDBStore interface { + CreateShard(database, policy string, shardID uint64) error + WriteToShard(shardID uint64, points []models.Point) error + CreateMapper(shardID uint64, stmt influxql.Statement, chunkSize int) (tsdb.Mapper, error) + } + + Logger *log.Logger + statMap *expvar.Map +} + +// NewService returns a new instance of Service. +func NewService(c Config) *Service { + return &Service{ + closing: make(chan struct{}), + Logger: log.New(os.Stderr, "[cluster] ", log.LstdFlags), + statMap: influxdb.NewStatistics("cluster", "cluster", nil), + } +} + +// Open opens the network listener and begins serving requests. +func (s *Service) Open() error { + + s.Logger.Println("Starting cluster service") + // Begin serving conections. + s.wg.Add(1) + go s.serve() + + return nil +} + +// SetLogger sets the internal logger to the logger passed in. +func (s *Service) SetLogger(l *log.Logger) { + s.Logger = l +} + +// serve accepts connections from the listener and handles them. +func (s *Service) serve() { + defer s.wg.Done() + + for { + // Check if the service is shutting down. + select { + case <-s.closing: + return + default: + } + + // Accept the next connection. + conn, err := s.Listener.Accept() + if err != nil { + if strings.Contains(err.Error(), "connection closed") { + s.Logger.Printf("cluster service accept error: %s", err) + return + } + s.Logger.Printf("accept error: %s", err) + continue + } + + // Delegate connection handling to a separate goroutine. + s.wg.Add(1) + go func() { + defer s.wg.Done() + s.handleConn(conn) + }() + } +} + +// Close shuts down the listener and waits for all connections to finish. +func (s *Service) Close() error { + if s.Listener != nil { + s.Listener.Close() + } + + // Shut down all handlers. + close(s.closing) + s.wg.Wait() + + return nil +} + +// handleConn services an individual TCP connection. +func (s *Service) handleConn(conn net.Conn) { + // Ensure connection is closed when service is closed. + closing := make(chan struct{}) + defer close(closing) + go func() { + select { + case <-closing: + case <-s.closing: + } + conn.Close() + }() + + s.Logger.Printf("accept remote connection from %v\n", conn.RemoteAddr()) + defer func() { + s.Logger.Printf("close remote connection from %v\n", conn.RemoteAddr()) + }() + for { + // Read type-length-value. + typ, buf, err := ReadTLV(conn) + if err != nil { + if strings.HasSuffix(err.Error(), "EOF") { + return + } + s.Logger.Printf("unable to read type-length-value %s", err) + return + } + + // Delegate message processing by type. + switch typ { + case writeShardRequestMessage: + s.statMap.Add(writeShardReq, 1) + err := s.processWriteShardRequest(buf) + if err != nil { + s.Logger.Printf("process write shard error: %s", err) + } + s.writeShardResponse(conn, err) + case mapShardRequestMessage: + s.statMap.Add(mapShardReq, 1) + err := s.processMapShardRequest(conn, buf) + if err != nil { + s.Logger.Printf("process map shard error: %s", err) + if err := writeMapShardResponseMessage(conn, NewMapShardResponse(1, err.Error())); err != nil { + s.Logger.Printf("process map shard error writing response: %s", err.Error()) + } + } + default: + s.Logger.Printf("cluster service message type not found: %d", typ) + } + } +} + +func (s *Service) processWriteShardRequest(buf []byte) error { + // Build request + var req WriteShardRequest + if err := req.UnmarshalBinary(buf); err != nil { + return err + } + + points := req.Points() + s.statMap.Add(writeShardPointsReq, int64(len(points))) + err := s.TSDBStore.WriteToShard(req.ShardID(), req.Points()) + + // We may have received a write for a shard that we don't have locally because the + // sending node may have just created the shard (via the metastore) and the write + // arrived before the local store could create the shard. In this case, we need + // to check the metastore to determine what database and retention policy this + // shard should reside within. + if err == tsdb.ErrShardNotFound { + + // Query the metastore for the owner of this shard + database, retentionPolicy, sgi := s.MetaStore.ShardOwner(req.ShardID()) + if sgi == nil { + // If we can't find it, then we need to drop this request + // as it is no longer valid. This could happen if writes were queued via + // hinted handoff and delivered after a shard group was deleted. + s.Logger.Printf("drop write request: shard=%d. shard group does not exist or was deleted", req.ShardID()) + return nil + } + + err = s.TSDBStore.CreateShard(database, retentionPolicy, req.ShardID()) + if err != nil { + return err + } + return s.TSDBStore.WriteToShard(req.ShardID(), req.Points()) + } + + if err != nil { + s.statMap.Add(writeShardFail, 1) + return fmt.Errorf("write shard %d: %s", req.ShardID(), err) + } + + return nil +} + +func (s *Service) writeShardResponse(w io.Writer, e error) { + // Build response. + var resp WriteShardResponse + if e != nil { + resp.SetCode(1) + resp.SetMessage(e.Error()) + } else { + resp.SetCode(0) + } + + // Marshal response to binary. + buf, err := resp.MarshalBinary() + if err != nil { + s.Logger.Printf("error marshalling shard response: %s", err) + return + } + + // Write to connection. + if err := WriteTLV(w, writeShardResponseMessage, buf); err != nil { + s.Logger.Printf("write shard response error: %s", err) + } +} + +func (s *Service) processMapShardRequest(w io.Writer, buf []byte) error { + // Decode request + var req MapShardRequest + if err := req.UnmarshalBinary(buf); err != nil { + return err + } + + // Parse the statement. + q, err := influxql.ParseQuery(req.Query()) + if err != nil { + return fmt.Errorf("processing map shard: %s", err) + } else if len(q.Statements) != 1 { + return fmt.Errorf("processing map shard: expected 1 statement but got %d", len(q.Statements)) + } + + m, err := s.TSDBStore.CreateMapper(req.ShardID(), q.Statements[0], int(req.ChunkSize())) + if err != nil { + return fmt.Errorf("create mapper: %s", err) + } + if m == nil { + return writeMapShardResponseMessage(w, NewMapShardResponse(0, "")) + } + + if err := m.Open(); err != nil { + return fmt.Errorf("mapper open: %s", err) + } + defer m.Close() + + var metaSent bool + for { + var resp MapShardResponse + + if !metaSent { + resp.SetTagSets(m.TagSets()) + resp.SetFields(m.Fields()) + metaSent = true + } + + chunk, err := m.NextChunk() + if err != nil { + return fmt.Errorf("next chunk: %s", err) + } + + // NOTE: Even if the chunk is nil, we still need to send one + // empty response to let the other side know we're out of data. + + if chunk != nil { + b, err := json.Marshal(chunk) + if err != nil { + return fmt.Errorf("encoding: %s", err) + } + resp.SetData(b) + } + + // Write to connection. + resp.SetCode(0) + if err := writeMapShardResponseMessage(w, &resp); err != nil { + return err + } + s.statMap.Add(mapShardResp, 1) + + if chunk == nil { + // All mapper data sent. + return nil + } + } +} + +func writeMapShardResponseMessage(w io.Writer, msg *MapShardResponse) error { + buf, err := msg.MarshalBinary() + if err != nil { + return err + } + return WriteTLV(w, mapShardResponseMessage, buf) +} + +// ReadTLV reads a type-length-value record from r. +func ReadTLV(r io.Reader) (byte, []byte, error) { + var typ [1]byte + if _, err := io.ReadFull(r, typ[:]); err != nil { + return 0, nil, fmt.Errorf("read message type: %s", err) + } + + // Read the size of the message. + var sz int64 + if err := binary.Read(r, binary.BigEndian, &sz); err != nil { + return 0, nil, fmt.Errorf("read message size: %s", err) + } + + if sz == 0 { + return 0, nil, fmt.Errorf("invalid message size: %d", sz) + } + + if sz >= MaxMessageSize { + return 0, nil, fmt.Errorf("max message size of %d exceeded: %d", MaxMessageSize, sz) + } + + // Read the value. + buf := make([]byte, sz) + if _, err := io.ReadFull(r, buf); err != nil { + return 0, nil, fmt.Errorf("read message value: %s", err) + } + + return typ[0], buf, nil +} + +// WriteTLV writes a type-length-value record to w. +func WriteTLV(w io.Writer, typ byte, buf []byte) error { + if _, err := w.Write([]byte{typ}); err != nil { + return fmt.Errorf("write message type: %s", err) + } + + // Write the size of the message. + if err := binary.Write(w, binary.BigEndian, int64(len(buf))); err != nil { + return fmt.Errorf("write message size: %s", err) + } + + // Write the value. + if _, err := w.Write(buf); err != nil { + return fmt.Errorf("write message value: %s", err) + } + + return nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service_test.go new file mode 100644 index 00000000..8158c47a --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/service_test.go @@ -0,0 +1,105 @@ +package cluster_test + +import ( + "fmt" + "net" + "time" + + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/influxql" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/models" + "github.com/influxdb/influxdb/tcp" + "github.com/influxdb/influxdb/tsdb" +) + +type metaStore struct { + host string +} + +func (m *metaStore) Node(nodeID uint64) (*meta.NodeInfo, error) { + return &meta.NodeInfo{ + ID: nodeID, + Host: m.host, + }, nil +} + +type testService struct { + nodeID uint64 + ln net.Listener + muxln net.Listener + writeShardFunc func(shardID uint64, points []models.Point) error + createShardFunc func(database, policy string, shardID uint64) error + createMapperFunc func(shardID uint64, stmt influxql.Statement, chunkSize int) (tsdb.Mapper, error) +} + +func newTestWriteService(f func(shardID uint64, points []models.Point) error) testService { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + panic(err) + } + + mux := tcp.NewMux() + muxln := mux.Listen(cluster.MuxHeader) + go mux.Serve(ln) + + return testService{ + writeShardFunc: f, + ln: ln, + muxln: muxln, + } +} + +func (ts *testService) Close() { + if ts.ln != nil { + ts.ln.Close() + } +} + +type serviceResponses []serviceResponse +type serviceResponse struct { + shardID uint64 + ownerID uint64 + points []models.Point +} + +func (t testService) WriteToShard(shardID uint64, points []models.Point) error { + return t.writeShardFunc(shardID, points) +} + +func (t testService) CreateShard(database, policy string, shardID uint64) error { + return t.createShardFunc(database, policy, shardID) +} + +func (t testService) CreateMapper(shardID uint64, stmt influxql.Statement, chunkSize int) (tsdb.Mapper, error) { + return t.createMapperFunc(shardID, stmt, chunkSize) +} + +func writeShardSuccess(shardID uint64, points []models.Point) error { + responses <- &serviceResponse{ + shardID: shardID, + points: points, + } + return nil +} + +func writeShardFail(shardID uint64, points []models.Point) error { + return fmt.Errorf("failed to write") +} + +var responses = make(chan *serviceResponse, 1024) + +func (testService) ResponseN(n int) ([]*serviceResponse, error) { + var a []*serviceResponse + for { + select { + case r := <-responses: + a = append(a, r) + if len(a) == n { + return a, nil + } + case <-time.After(time.Second): + return a, fmt.Errorf("unexpected response count: expected: %d, actual: %d", n, len(a)) + } + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper.go new file mode 100644 index 00000000..b8645f4a --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper.go @@ -0,0 +1,259 @@ +package cluster + +import ( + "encoding/json" + "fmt" + "math/rand" + "net" + "time" + + "github.com/influxdb/influxdb/influxql" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/tsdb" +) + +// ShardMapper is responsible for providing mappers for requested shards. It is +// responsible for creating those mappers from the local store, or reaching +// out to another node on the cluster. +type ShardMapper struct { + ForceRemoteMapping bool // All shards treated as remote. Useful for testing. + + MetaStore interface { + NodeID() uint64 + Node(id uint64) (ni *meta.NodeInfo, err error) + } + + TSDBStore interface { + CreateMapper(shardID uint64, stmt influxql.Statement, chunkSize int) (tsdb.Mapper, error) + } + + timeout time.Duration + pool *clientPool +} + +// NewShardMapper returns a mapper of local and remote shards. +func NewShardMapper(timeout time.Duration) *ShardMapper { + return &ShardMapper{ + pool: newClientPool(), + timeout: timeout, + } +} + +// CreateMapper returns a Mapper for the given shard ID. +func (s *ShardMapper) CreateMapper(sh meta.ShardInfo, stmt influxql.Statement, chunkSize int) (tsdb.Mapper, error) { + // Create a remote mapper if the local node doesn't own the shard. + if !sh.OwnedBy(s.MetaStore.NodeID()) || s.ForceRemoteMapping { + // Pick a node in a pseudo-random manner. + conn, err := s.dial(sh.Owners[rand.Intn(len(sh.Owners))].NodeID) + if err != nil { + return nil, err + } + conn.SetDeadline(time.Now().Add(s.timeout)) + + return NewRemoteMapper(conn, sh.ID, stmt, chunkSize), nil + } + + // If it is local then return the mapper from the store. + m, err := s.TSDBStore.CreateMapper(sh.ID, stmt, chunkSize) + if err != nil { + return nil, err + } + + return m, nil +} + +func (s *ShardMapper) dial(nodeID uint64) (net.Conn, error) { + ni, err := s.MetaStore.Node(nodeID) + if err != nil { + return nil, err + } + conn, err := net.Dial("tcp", ni.Host) + if err != nil { + return nil, err + } + + // Write the cluster multiplexing header byte + conn.Write([]byte{MuxHeader}) + + return conn, nil +} + +// RemoteMapper implements the tsdb.Mapper interface. It connects to a remote node, +// sends a query, and interprets the stream of data that comes back. +type RemoteMapper struct { + shardID uint64 + stmt influxql.Statement + chunkSize int + + tagsets []string + fields []string + + conn net.Conn + bufferedResponse *MapShardResponse + + unmarshallers []tsdb.UnmarshalFunc // Mapping-specific unmarshal functions. +} + +// NewRemoteMapper returns a new remote mapper using the given connection. +func NewRemoteMapper(c net.Conn, shardID uint64, stmt influxql.Statement, chunkSize int) *RemoteMapper { + return &RemoteMapper{ + conn: c, + shardID: shardID, + stmt: stmt, + chunkSize: chunkSize, + } +} + +// Open connects to the remote node and starts receiving data. +func (r *RemoteMapper) Open() (err error) { + defer func() { + if err != nil { + r.conn.Close() + } + }() + + // Build Map request. + var request MapShardRequest + request.SetShardID(r.shardID) + request.SetQuery(r.stmt.String()) + request.SetChunkSize(int32(r.chunkSize)) + + // Marshal into protocol buffers. + buf, err := request.MarshalBinary() + if err != nil { + return err + } + + // Write request. + if err := WriteTLV(r.conn, mapShardRequestMessage, buf); err != nil { + return err + } + + // Read the response. + _, buf, err = ReadTLV(r.conn) + if err != nil { + return err + } + + // Unmarshal response. + r.bufferedResponse = &MapShardResponse{} + if err := r.bufferedResponse.UnmarshalBinary(buf); err != nil { + return err + } + + if r.bufferedResponse.Code() != 0 { + return fmt.Errorf("error code %d: %s", r.bufferedResponse.Code(), r.bufferedResponse.Message()) + } + + // Decode the first response to get the TagSets. + r.tagsets = r.bufferedResponse.TagSets() + r.fields = r.bufferedResponse.Fields() + + // Set up each mapping function for this statement. + if stmt, ok := r.stmt.(*influxql.SelectStatement); ok { + for _, c := range stmt.FunctionCalls() { + fn, err := tsdb.InitializeUnmarshaller(c) + if err != nil { + return err + } + r.unmarshallers = append(r.unmarshallers, fn) + } + } + + return nil +} + +// TagSets returns the TagSets +func (r *RemoteMapper) TagSets() []string { + return r.tagsets +} + +// Fields returns RemoteMapper's Fields +func (r *RemoteMapper) Fields() []string { + return r.fields +} + +// NextChunk returns the next chunk read from the remote node to the client. +func (r *RemoteMapper) NextChunk() (chunk interface{}, err error) { + var response *MapShardResponse + if r.bufferedResponse != nil { + response = r.bufferedResponse + r.bufferedResponse = nil + } else { + response = &MapShardResponse{} + + // Read the response. + _, buf, err := ReadTLV(r.conn) + if err != nil { + return nil, err + } + + // Unmarshal response. + if err := response.UnmarshalBinary(buf); err != nil { + return nil, err + } + + if response.Code() != 0 { + return nil, fmt.Errorf("error code %d: %s", response.Code(), response.Message()) + } + } + + if response.Data() == nil { + return nil, nil + } + + moj := &tsdb.MapperOutputJSON{} + if err := json.Unmarshal(response.Data(), moj); err != nil { + return nil, err + } + mvj := []*tsdb.MapperValueJSON{} + if err := json.Unmarshal(moj.Values, &mvj); err != nil { + return nil, err + } + + // Prep the non-JSON version of Mapper output. + mo := &tsdb.MapperOutput{ + Name: moj.Name, + Tags: moj.Tags, + Fields: moj.Fields, + } + + if len(mvj) == 1 && len(mvj[0].AggData) > 0 { + // The MapperValue is carrying aggregate data, so run it through the + // custom unmarshallers for the map functions through which the data + // was mapped. + aggValues := []interface{}{} + for i, b := range mvj[0].AggData { + v, err := r.unmarshallers[i](b) + if err != nil { + return nil, err + } + aggValues = append(aggValues, v) + } + mo.Values = []*tsdb.MapperValue{&tsdb.MapperValue{ + Value: aggValues, + Tags: mvj[0].Tags, + }} + } else { + // Must be raw data instead. + for _, v := range mvj { + var rawValue interface{} + if err := json.Unmarshal(v.RawData, &rawValue); err != nil { + return nil, err + } + + mo.Values = append(mo.Values, &tsdb.MapperValue{ + Time: v.Time, + Value: rawValue, + Tags: v.Tags, + }) + } + } + + return mo, nil +} + +// Close the Mapper +func (r *RemoteMapper) Close() { + r.conn.Close() +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper_test.go new file mode 100644 index 00000000..3a80f596 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_mapper_test.go @@ -0,0 +1,110 @@ +package cluster + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "testing" + + "github.com/influxdb/influxdb/influxql" + "github.com/influxdb/influxdb/tsdb" +) + +// remoteShardResponder implements the remoteShardConn interface. +type remoteShardResponder struct { + net.Conn + t *testing.T + rxBytes []byte + + buffer *bytes.Buffer +} + +func newRemoteShardResponder(outputs []*tsdb.MapperOutput, tagsets []string) *remoteShardResponder { + r := &remoteShardResponder{} + a := make([]byte, 0, 1024) + r.buffer = bytes.NewBuffer(a) + + // Pump the outputs in the buffer for later reading. + for _, o := range outputs { + resp := &MapShardResponse{} + resp.SetCode(0) + if o != nil { + d, _ := json.Marshal(o) + resp.SetData(d) + resp.SetTagSets(tagsets) + } + + g, _ := resp.MarshalBinary() + WriteTLV(r.buffer, mapShardResponseMessage, g) + } + + return r +} + +func (r remoteShardResponder) Close() error { return nil } +func (r remoteShardResponder) Read(p []byte) (n int, err error) { + return io.ReadFull(r.buffer, p) +} + +func (r remoteShardResponder) Write(p []byte) (n int, err error) { + if r.rxBytes == nil { + r.rxBytes = make([]byte, 0) + } + r.rxBytes = append(r.rxBytes, p...) + return len(p), nil +} + +// Ensure a RemoteMapper can process valid responses from a remote shard. +func TestShardWriter_RemoteMapper_Success(t *testing.T) { + expTagSets := []string{"tagsetA"} + expOutput := &tsdb.MapperOutput{ + Name: "cpu", + Tags: map[string]string{"host": "serverA"}, + } + + c := newRemoteShardResponder([]*tsdb.MapperOutput{expOutput, nil}, expTagSets) + + r := NewRemoteMapper(c, 1234, mustParseStmt("SELECT * FROM CPU"), 10) + if err := r.Open(); err != nil { + t.Fatalf("failed to open remote mapper: %s", err.Error()) + } + + if r.TagSets()[0] != expTagSets[0] { + t.Fatalf("incorrect tagsets received, exp %v, got %v", expTagSets, r.TagSets()) + } + + // Get first chunk from mapper. + chunk, err := r.NextChunk() + if err != nil { + t.Fatalf("failed to get next chunk from mapper: %s", err.Error()) + } + output, ok := chunk.(*tsdb.MapperOutput) + if !ok { + t.Fatal("chunk is not of expected type") + } + if output.Name != "cpu" { + t.Fatalf("received output incorrect, exp: %v, got %v", expOutput, output) + } + + // Next chunk should be nil, indicating no more data. + chunk, err = r.NextChunk() + if err != nil { + t.Fatalf("failed to get next chunk from mapper: %s", err.Error()) + } + if chunk != nil { + t.Fatal("received more chunks when none expected") + } +} + +// mustParseStmt parses a single statement or panics. +func mustParseStmt(stmt string) influxql.Statement { + q, err := influxql.ParseQuery(stmt) + if err != nil { + panic(err) + } else if len(q.Statements) != 1 { + panic(fmt.Sprintf("expected 1 statement but got %d", len(q.Statements))) + } + return q.Statements[0] +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer.go new file mode 100644 index 00000000..f6da1023 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer.go @@ -0,0 +1,165 @@ +package cluster + +import ( + "fmt" + "net" + "time" + + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/models" + "gopkg.in/fatih/pool.v2" +) + +const ( + writeShardRequestMessage byte = iota + 1 + writeShardResponseMessage + mapShardRequestMessage + mapShardResponseMessage +) + +// ShardWriter writes a set of points to a shard. +type ShardWriter struct { + pool *clientPool + timeout time.Duration + + MetaStore interface { + Node(id uint64) (ni *meta.NodeInfo, err error) + } +} + +// NewShardWriter returns a new instance of ShardWriter. +func NewShardWriter(timeout time.Duration) *ShardWriter { + return &ShardWriter{ + pool: newClientPool(), + timeout: timeout, + } +} + +// WriteShard writes time series points to a shard +func (w *ShardWriter) WriteShard(shardID, ownerID uint64, points []models.Point) error { + c, err := w.dial(ownerID) + if err != nil { + return err + } + + conn, ok := c.(*pool.PoolConn) + if !ok { + panic("wrong connection type") + } + defer func(conn net.Conn) { + conn.Close() // return to pool + }(conn) + + // Build write request. + var request WriteShardRequest + request.SetShardID(shardID) + request.AddPoints(points) + + // Marshal into protocol buffers. + buf, err := request.MarshalBinary() + if err != nil { + return err + } + + // Write request. + conn.SetWriteDeadline(time.Now().Add(w.timeout)) + if err := WriteTLV(conn, writeShardRequestMessage, buf); err != nil { + conn.MarkUnusable() + return err + } + + // Read the response. + conn.SetReadDeadline(time.Now().Add(w.timeout)) + _, buf, err = ReadTLV(conn) + if err != nil { + conn.MarkUnusable() + return err + } + + // Unmarshal response. + var response WriteShardResponse + if err := response.UnmarshalBinary(buf); err != nil { + return err + } + + if response.Code() != 0 { + return fmt.Errorf("error code %d: %s", response.Code(), response.Message()) + } + + return nil +} + +func (w *ShardWriter) dial(nodeID uint64) (net.Conn, error) { + // If we don't have a connection pool for that addr yet, create one + _, ok := w.pool.getPool(nodeID) + if !ok { + factory := &connFactory{nodeID: nodeID, clientPool: w.pool, timeout: w.timeout} + factory.metaStore = w.MetaStore + + p, err := pool.NewChannelPool(1, 3, factory.dial) + if err != nil { + return nil, err + } + w.pool.setPool(nodeID, p) + } + return w.pool.conn(nodeID) +} + +// Close closes ShardWriter's pool +func (w *ShardWriter) Close() error { + if w.pool == nil { + return fmt.Errorf("client already closed") + } + w.pool.close() + w.pool = nil + return nil +} + +const ( + maxConnections = 500 + maxRetries = 3 +) + +var errMaxConnectionsExceeded = fmt.Errorf("can not exceed max connections of %d", maxConnections) + +type connFactory struct { + nodeID uint64 + timeout time.Duration + + clientPool interface { + size() int + } + + metaStore interface { + Node(id uint64) (ni *meta.NodeInfo, err error) + } +} + +func (c *connFactory) dial() (net.Conn, error) { + if c.clientPool.size() > maxConnections { + return nil, errMaxConnectionsExceeded + } + + ni, err := c.metaStore.Node(c.nodeID) + if err != nil { + return nil, err + } + + if ni == nil { + return nil, fmt.Errorf("node %d does not exist", c.nodeID) + } + + conn, err := net.DialTimeout("tcp", ni.Host, c.timeout) + if err != nil { + return nil, err + } + + // Write a marker byte for cluster messages. + _, err = conn.Write([]byte{MuxHeader}) + if err != nil { + conn.Close() + return nil, err + } + + return conn, nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer_test.go new file mode 100644 index 00000000..67134234 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cluster/shard_writer_test.go @@ -0,0 +1,186 @@ +package cluster_test + +import ( + "net" + "strings" + "testing" + "time" + + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/models" +) + +// Ensure the shard writer can successful write a single request. +func TestShardWriter_WriteShard_Success(t *testing.T) { + ts := newTestWriteService(writeShardSuccess) + s := cluster.NewService(cluster.Config{}) + s.Listener = ts.muxln + s.TSDBStore = ts + if err := s.Open(); err != nil { + t.Fatal(err) + } + defer s.Close() + defer ts.Close() + + w := cluster.NewShardWriter(time.Minute) + w.MetaStore = &metaStore{host: ts.ln.Addr().String()} + + // Build a single point. + now := time.Now() + var points []models.Point + points = append(points, models.MustNewPoint("cpu", models.Tags{"host": "server01"}, map[string]interface{}{"value": int64(100)}, now)) + + // Write to shard and close. + if err := w.WriteShard(1, 2, points); err != nil { + t.Fatal(err) + } else if err := w.Close(); err != nil { + t.Fatal(err) + } + + // Validate response. + responses, err := ts.ResponseN(1) + if err != nil { + t.Fatal(err) + } else if responses[0].shardID != 1 { + t.Fatalf("unexpected shard id: %d", responses[0].shardID) + } + + // Validate point. + if p := responses[0].points[0]; p.Name() != "cpu" { + t.Fatalf("unexpected name: %s", p.Name()) + } else if p.Fields()["value"] != int64(100) { + t.Fatalf("unexpected 'value' field: %d", p.Fields()["value"]) + } else if p.Tags()["host"] != "server01" { + t.Fatalf("unexpected 'host' tag: %s", p.Tags()["host"]) + } else if p.Time().UnixNano() != now.UnixNano() { + t.Fatalf("unexpected time: %s", p.Time()) + } +} + +// Ensure the shard writer can successful write a multiple requests. +func TestShardWriter_WriteShard_Multiple(t *testing.T) { + ts := newTestWriteService(writeShardSuccess) + s := cluster.NewService(cluster.Config{}) + s.Listener = ts.muxln + s.TSDBStore = ts + if err := s.Open(); err != nil { + t.Fatal(err) + } + defer s.Close() + defer ts.Close() + + w := cluster.NewShardWriter(time.Minute) + w.MetaStore = &metaStore{host: ts.ln.Addr().String()} + + // Build a single point. + now := time.Now() + var points []models.Point + points = append(points, models.MustNewPoint("cpu", models.Tags{"host": "server01"}, map[string]interface{}{"value": int64(100)}, now)) + + // Write to shard twice and close. + if err := w.WriteShard(1, 2, points); err != nil { + t.Fatal(err) + } else if err := w.WriteShard(1, 2, points); err != nil { + t.Fatal(err) + } else if err := w.Close(); err != nil { + t.Fatal(err) + } + + // Validate response. + responses, err := ts.ResponseN(1) + if err != nil { + t.Fatal(err) + } else if responses[0].shardID != 1 { + t.Fatalf("unexpected shard id: %d", responses[0].shardID) + } + + // Validate point. + if p := responses[0].points[0]; p.Name() != "cpu" { + t.Fatalf("unexpected name: %s", p.Name()) + } else if p.Fields()["value"] != int64(100) { + t.Fatalf("unexpected 'value' field: %d", p.Fields()["value"]) + } else if p.Tags()["host"] != "server01" { + t.Fatalf("unexpected 'host' tag: %s", p.Tags()["host"]) + } else if p.Time().UnixNano() != now.UnixNano() { + t.Fatalf("unexpected time: %s", p.Time()) + } +} + +// Ensure the shard writer returns an error when the server fails to accept the write. +func TestShardWriter_WriteShard_Error(t *testing.T) { + ts := newTestWriteService(writeShardFail) + s := cluster.NewService(cluster.Config{}) + s.Listener = ts.muxln + s.TSDBStore = ts + if err := s.Open(); err != nil { + t.Fatal(err) + } + defer s.Close() + defer ts.Close() + + w := cluster.NewShardWriter(time.Minute) + w.MetaStore = &metaStore{host: ts.ln.Addr().String()} + now := time.Now() + + shardID := uint64(1) + ownerID := uint64(2) + var points []models.Point + points = append(points, models.MustNewPoint( + "cpu", models.Tags{"host": "server01"}, map[string]interface{}{"value": int64(100)}, now, + )) + + if err := w.WriteShard(shardID, ownerID, points); err == nil || err.Error() != "error code 1: write shard 1: failed to write" { + t.Fatalf("unexpected error: %v", err) + } +} + +// Ensure the shard writer returns an error when dialing times out. +func TestShardWriter_Write_ErrDialTimeout(t *testing.T) { + ts := newTestWriteService(writeShardSuccess) + s := cluster.NewService(cluster.Config{}) + s.Listener = ts.muxln + s.TSDBStore = ts + if err := s.Open(); err != nil { + t.Fatal(err) + } + defer s.Close() + defer ts.Close() + + w := cluster.NewShardWriter(time.Nanosecond) + w.MetaStore = &metaStore{host: ts.ln.Addr().String()} + now := time.Now() + + shardID := uint64(1) + ownerID := uint64(2) + var points []models.Point + points = append(points, models.MustNewPoint( + "cpu", models.Tags{"host": "server01"}, map[string]interface{}{"value": int64(100)}, now, + )) + + if err, exp := w.WriteShard(shardID, ownerID, points), "i/o timeout"; err == nil || !strings.Contains(err.Error(), exp) { + t.Fatalf("expected error %v, to contain %s", err, exp) + } +} + +// Ensure the shard writer returns an error when reading times out. +func TestShardWriter_Write_ErrReadTimeout(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + w := cluster.NewShardWriter(time.Millisecond) + w.MetaStore = &metaStore{host: ln.Addr().String()} + now := time.Now() + + shardID := uint64(1) + ownerID := uint64(2) + var points []models.Point + points = append(points, models.MustNewPoint( + "cpu", models.Tags{"host": "server01"}, map[string]interface{}{"value": int64(100)}, now, + )) + + if err := w.WriteShard(shardID, ownerID, points); err == nil || !strings.Contains(err.Error(), "i/o timeout") { + t.Fatalf("unexpected error: %s", err) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli.go new file mode 100644 index 00000000..2d126994 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli.go @@ -0,0 +1,786 @@ +package cli + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "fmt" + "io" + "net" + "net/url" + "os" + "os/signal" + "os/user" + "path/filepath" + "sort" + "strconv" + "strings" + "syscall" + "text/tabwriter" + + "github.com/influxdb/influxdb/client" + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/importer/v8" + "github.com/peterh/liner" +) + +const ( + noTokenMsg = "Visit https://enterprise.influxdata.com to register for updates, InfluxDB server management, and monitoring.\n" +) + +// CommandLine holds CLI configuration and state +type CommandLine struct { + Client *client.Client + Line *liner.State + Host string + Port int + Username string + Password string + Database string + Ssl bool + RetentionPolicy string + ClientVersion string + ServerVersion string + Pretty bool // controls pretty print for json + Format string // controls the output format. Valid values are json, csv, or column + Precision string + WriteConsistency string + Execute string + ShowVersion bool + Import bool + PPS int // Controls how many points per second the import will allow via throttling + Path string + Compressed bool + Quit chan struct{} + osSignals chan os.Signal + historyFile *os.File +} + +// New returns an instance of CommandLine +func New(version string) *CommandLine { + return &CommandLine{ + ClientVersion: version, + Quit: make(chan struct{}, 1), + osSignals: make(chan os.Signal, 1), + } +} + +// Run executes the CLI +func (c *CommandLine) Run() { + // register OS signals for graceful termination + signal.Notify(c.osSignals, os.Kill, os.Interrupt, syscall.SIGTERM) + + var promptForPassword bool + // determine if they set the password flag but provided no value + for _, v := range os.Args { + v = strings.ToLower(v) + if (strings.HasPrefix(v, "-password") || strings.HasPrefix(v, "--password")) && c.Password == "" { + promptForPassword = true + break + } + } + + c.Line = liner.NewLiner() + defer c.Line.Close() + + if promptForPassword { + p, e := c.Line.PasswordPrompt("password: ") + if e != nil { + fmt.Println("Unable to parse password.") + } else { + c.Password = p + } + } + + if err := c.Connect(""); err != nil { + fmt.Fprintf(os.Stderr, + "Failed to connect to %s\nPlease check your connection settings and ensure 'influxd' is running.\n", + c.Client.Addr()) + return + } + + if c.Execute == "" && !c.Import { + token, err := c.DatabaseToken() + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to check token: %s\n", err.Error()) + return + } + if token == "" { + fmt.Printf(noTokenMsg) + } + fmt.Printf("Connected to %s version %s\n", c.Client.Addr(), c.ServerVersion) + } + + if c.Execute != "" { + // Modify precision before executing query + c.SetPrecision(c.Precision) + if err := c.ExecuteQuery(c.Execute); err != nil { + c.Line.Close() + os.Exit(1) + } + c.Line.Close() + os.Exit(0) + } + + if c.Import { + path := net.JoinHostPort(c.Host, strconv.Itoa(c.Port)) + u, e := client.ParseConnectionString(path, c.Ssl) + if e != nil { + fmt.Println(e) + return + } + + config := v8.NewConfig() + config.Username = c.Username + config.Password = c.Password + config.Precision = "ns" + config.WriteConsistency = "any" + config.Path = c.Path + config.Version = c.ClientVersion + config.URL = u + config.Compressed = c.Compressed + config.PPS = c.PPS + config.Precision = c.Precision + + i := v8.NewImporter(config) + if err := i.Import(); err != nil { + fmt.Printf("ERROR: %s\n", err) + c.Line.Close() + os.Exit(1) + } + c.Line.Close() + os.Exit(0) + } + + c.Version() + + var historyFilePath string + usr, err := user.Current() + // Only load/write history if we can get the user + if err == nil { + historyFilePath = filepath.Join(usr.HomeDir, ".influx_history") + if c.historyFile, err = os.OpenFile(historyFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640); err == nil { + defer c.historyFile.Close() + c.Line.ReadHistory(c.historyFile) + } + } + + // read from prompt until exit is run + for { + select { + case <-c.osSignals: + close(c.Quit) + case <-c.Quit: + c.exit() + default: + l, e := c.Line.Prompt("> ") + if e != nil { + break + } + if c.ParseCommand(l) { + c.Line.AppendHistory(l) + _, err := c.Line.WriteHistory(c.historyFile) + if err != nil { + fmt.Printf("There was an error writing history file: %s\n", err) + } + } + } + } +} + +// ParseCommand parses an instruction and calls related method, if any +func (c *CommandLine) ParseCommand(cmd string) bool { + lcmd := strings.TrimSpace(strings.ToLower(cmd)) + tokens := strings.Fields(lcmd) + + if len(tokens) > 0 { + switch tokens[0] { + case "exit": + // signal the program to exit + close(c.Quit) + case "gopher": + c.gopher() + case "connect": + c.Connect(cmd) + case "auth": + c.SetAuth(cmd) + case "help": + c.help() + case "history": + c.history() + case "format": + c.SetFormat(cmd) + case "precision": + c.SetPrecision(cmd) + case "consistency": + c.SetWriteConsistency(cmd) + case "settings": + c.Settings() + case "pretty": + c.Pretty = !c.Pretty + if c.Pretty { + fmt.Println("Pretty print enabled") + } else { + fmt.Println("Pretty print disabled") + } + case "use": + c.use(cmd) + case "insert": + c.Insert(cmd) + default: + c.ExecuteQuery(cmd) + } + + return true + } + return false +} + +// Connect connects client to a server +func (c *CommandLine) Connect(cmd string) error { + var cl *client.Client + var u url.URL + + // Remove the "connect" keyword if it exists + path := strings.TrimSpace(strings.Replace(cmd, "connect", "", -1)) + + // If they didn't provide a connection string, use the current settings + if path == "" { + path = net.JoinHostPort(c.Host, strconv.Itoa(c.Port)) + } + + var e error + u, e = client.ParseConnectionString(path, c.Ssl) + if e != nil { + return e + } + + config := client.NewConfig() + config.URL = u + config.Username = c.Username + config.Password = c.Password + config.UserAgent = "InfluxDBShell/" + c.ClientVersion + config.Precision = c.Precision + cl, err := client.NewClient(config) + if err != nil { + return fmt.Errorf("Could not create client %s", err) + } + c.Client = cl + + var v string + if _, v, e = c.Client.Ping(); e != nil { + return fmt.Errorf("Failed to connect to %s\n", c.Client.Addr()) + } + c.ServerVersion = v + + return nil +} + +// SetAuth sets client authentication credentials +func (c *CommandLine) SetAuth(cmd string) { + // If they pass in the entire command, we should parse it + // auth + args := strings.Fields(cmd) + if len(args) == 3 { + args = args[1:] + } else { + args = []string{} + } + + if len(args) == 2 { + c.Username = args[0] + c.Password = args[1] + } else { + u, e := c.Line.Prompt("username: ") + if e != nil { + fmt.Printf("Unable to process input: %s", e) + return + } + c.Username = strings.TrimSpace(u) + p, e := c.Line.PasswordPrompt("password: ") + if e != nil { + fmt.Printf("Unable to process input: %s", e) + return + } + c.Password = p + } + + // Update the client as well + c.Client.SetAuth(c.Username, c.Password) +} + +func (c *CommandLine) use(cmd string) { + args := strings.Split(strings.TrimSuffix(strings.TrimSpace(cmd), ";"), " ") + if len(args) != 2 { + fmt.Printf("Could not parse database name from %q.\n", cmd) + return + } + d := args[1] + c.Database = d + fmt.Printf("Using database %s\n", d) +} + +// SetPrecision sets client precision +func (c *CommandLine) SetPrecision(cmd string) { + // Remove the "precision" keyword if it exists + cmd = strings.TrimSpace(strings.Replace(cmd, "precision", "", -1)) + // normalize cmd + cmd = strings.ToLower(cmd) + + switch cmd { + case "h", "m", "s", "ms", "u", "ns": + c.Precision = cmd + c.Client.SetPrecision(c.Precision) + case "rfc3339": + c.Precision = "" + c.Client.SetPrecision(c.Precision) + default: + fmt.Printf("Unknown precision %q. Please use rfc3339, h, m, s, ms, u or ns.\n", cmd) + } +} + +// SetFormat sets output format +func (c *CommandLine) SetFormat(cmd string) { + // Remove the "format" keyword if it exists + cmd = strings.TrimSpace(strings.Replace(cmd, "format", "", -1)) + // normalize cmd + cmd = strings.ToLower(cmd) + + switch cmd { + case "json", "csv", "column": + c.Format = cmd + default: + fmt.Printf("Unknown format %q. Please use json, csv, or column.\n", cmd) + } +} + +// SetWriteConsistency sets cluster consistency level +func (c *CommandLine) SetWriteConsistency(cmd string) { + // Remove the "consistency" keyword if it exists + cmd = strings.TrimSpace(strings.Replace(cmd, "consistency", "", -1)) + // normalize cmd + cmd = strings.ToLower(cmd) + + _, err := cluster.ParseConsistencyLevel(cmd) + if err != nil { + fmt.Printf("Unknown consistency level %q. Please use any, one, quorum, or all.\n", cmd) + return + } + c.WriteConsistency = cmd +} + +// isWhitespace returns true if the rune is a space, tab, or newline. +func isWhitespace(ch rune) bool { return ch == ' ' || ch == '\t' || ch == '\n' } + +// isLetter returns true if the rune is a letter. +func isLetter(ch rune) bool { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') } + +// isDigit returns true if the rune is a digit. +func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') } + +// isIdentFirstChar returns true if the rune can be used as the first char in an unquoted identifer. +func isIdentFirstChar(ch rune) bool { return isLetter(ch) || ch == '_' } + +// isIdentChar returns true if the rune can be used in an unquoted identifier. +func isNotIdentChar(ch rune) bool { return !(isLetter(ch) || isDigit(ch) || ch == '_') } + +func parseUnquotedIdentifier(stmt string) (string, string) { + if fields := strings.FieldsFunc(stmt, isNotIdentChar); len(fields) > 0 { + return fields[0], strings.TrimPrefix(stmt, fields[0]) + } + return "", stmt +} + +func parseDoubleQuotedIdentifier(stmt string) (string, string) { + escapeNext := false + fields := strings.FieldsFunc(stmt, func(ch rune) bool { + if ch == '\\' { + escapeNext = true + } else if ch == '"' { + if !escapeNext { + return true + } + escapeNext = false + } + return false + }) + if len(fields) > 0 { + return fields[0], strings.TrimPrefix(stmt, "\""+fields[0]+"\"") + } + return "", stmt +} + +func parseNextIdentifier(stmt string) (ident, remainder string) { + if len(stmt) > 0 { + switch { + case isWhitespace(rune(stmt[0])): + return parseNextIdentifier(stmt[1:]) + case isIdentFirstChar(rune(stmt[0])): + return parseUnquotedIdentifier(stmt) + case stmt[0] == '"': + return parseDoubleQuotedIdentifier(stmt) + } + } + return "", stmt +} + +func (c *CommandLine) parseInto(stmt string) string { + ident, stmt := parseNextIdentifier(stmt) + if strings.HasPrefix(stmt, ".") { + c.Database = ident + fmt.Printf("Using database %s\n", c.Database) + ident, stmt = parseNextIdentifier(stmt[1:]) + } + if strings.HasPrefix(stmt, " ") { + c.RetentionPolicy = ident + fmt.Printf("Using retention policy %s\n", c.RetentionPolicy) + return stmt[1:] + } + return stmt +} + +// Insert runs an INSERT statement +func (c *CommandLine) Insert(stmt string) error { + i, point := parseNextIdentifier(stmt) + if !strings.EqualFold(i, "insert") { + fmt.Printf("ERR: found %s, expected INSERT\n", i) + return nil + } + if i, r := parseNextIdentifier(point); strings.EqualFold(i, "into") { + point = c.parseInto(r) + } + _, err := c.Client.Write(client.BatchPoints{ + Points: []client.Point{ + client.Point{Raw: point}, + }, + Database: c.Database, + RetentionPolicy: c.RetentionPolicy, + Precision: "n", + WriteConsistency: c.WriteConsistency, + }) + if err != nil { + fmt.Printf("ERR: %s\n", err) + if c.Database == "" { + fmt.Println("Note: error may be due to not setting a database or retention policy.") + fmt.Println(`Please set a database with the command "use " or`) + fmt.Println("INSERT INTO . ") + } + return err + } + return nil +} + +// ExecuteQuery runs any query statement +func (c *CommandLine) ExecuteQuery(query string) error { + response, err := c.Client.Query(client.Query{Command: query, Database: c.Database}) + if err != nil { + fmt.Printf("ERR: %s\n", err) + return err + } + c.FormatResponse(response, os.Stdout) + if err := response.Error(); err != nil { + fmt.Printf("ERR: %s\n", response.Error()) + if c.Database == "" { + fmt.Println("Warning: It is possible this error is due to not setting a database.") + fmt.Println(`Please set a database with the command "use ".`) + } + return err + } + return nil +} + +// DatabaseToken retrieves database token +func (c *CommandLine) DatabaseToken() (string, error) { + response, err := c.Client.Query(client.Query{Command: "SHOW DIAGNOSTICS for 'registration'"}) + if err != nil { + return "", err + } + if response.Error() != nil || len((*response).Results[0].Series) == 0 { + return "", nil + } + + // Look for position of "token" column. + for i, s := range (*response).Results[0].Series[0].Columns { + if s == "token" { + return (*response).Results[0].Series[0].Values[0][i].(string), nil + } + } + return "", nil +} + +// FormatResponse formats output to previsouly chosen format +func (c *CommandLine) FormatResponse(response *client.Response, w io.Writer) { + switch c.Format { + case "json": + c.writeJSON(response, w) + case "csv": + c.writeCSV(response, w) + case "column": + c.writeColumns(response, w) + default: + fmt.Fprintf(w, "Unknown output format %q.\n", c.Format) + } +} + +func (c *CommandLine) writeJSON(response *client.Response, w io.Writer) { + var data []byte + var err error + if c.Pretty { + data, err = json.MarshalIndent(response, "", " ") + } else { + data, err = json.Marshal(response) + } + if err != nil { + fmt.Fprintf(w, "Unable to parse json: %s\n", err) + return + } + fmt.Fprintln(w, string(data)) +} + +func (c *CommandLine) writeCSV(response *client.Response, w io.Writer) { + csvw := csv.NewWriter(w) + for _, result := range response.Results { + // Create a tabbed writer for each result as they won't always line up + rows := c.formatResults(result, "\t") + for _, r := range rows { + csvw.Write(strings.Split(r, "\t")) + } + csvw.Flush() + } +} + +func (c *CommandLine) writeColumns(response *client.Response, w io.Writer) { + for _, result := range response.Results { + // Create a tabbed writer for each result a they won't always line up + w := new(tabwriter.Writer) + w.Init(os.Stdout, 0, 8, 1, '\t', 0) + csv := c.formatResults(result, "\t") + for _, r := range csv { + fmt.Fprintln(w, r) + } + w.Flush() + } +} + +// formatResults will behave differently if you are formatting for columns or csv +func (c *CommandLine) formatResults(result client.Result, separator string) []string { + rows := []string{} + // Create a tabbed writer for each result a they won't always line up + for i, row := range result.Series { + // gather tags + tags := []string{} + for k, v := range row.Tags { + tags = append(tags, fmt.Sprintf("%s=%s", k, v)) + sort.Strings(tags) + } + + columnNames := []string{} + + // Only put name/tags in a column if format is csv + if c.Format == "csv" { + if len(tags) > 0 { + columnNames = append([]string{"tags"}, columnNames...) + } + + if row.Name != "" { + columnNames = append([]string{"name"}, columnNames...) + } + } + + for _, column := range row.Columns { + columnNames = append(columnNames, column) + } + + // Output a line separator if we have more than one set or results and format is column + if i > 0 && c.Format == "column" { + rows = append(rows, "") + } + + // If we are column format, we break out the name/tag to seperate lines + if c.Format == "column" { + if row.Name != "" { + n := fmt.Sprintf("name: %s", row.Name) + rows = append(rows, n) + if len(tags) == 0 { + l := strings.Repeat("-", len(n)) + rows = append(rows, l) + } + } + if len(tags) > 0 { + t := fmt.Sprintf("tags: %s", (strings.Join(tags, ", "))) + rows = append(rows, t) + } + } + + rows = append(rows, strings.Join(columnNames, separator)) + + // if format is column, break tags to their own line/format + if c.Format == "column" && len(tags) > 0 { + lines := []string{} + for _, columnName := range columnNames { + lines = append(lines, strings.Repeat("-", len(columnName))) + } + rows = append(rows, strings.Join(lines, separator)) + } + + for _, v := range row.Values { + var values []string + if c.Format == "csv" { + if row.Name != "" { + values = append(values, row.Name) + } + if len(tags) > 0 { + values = append(values, strings.Join(tags, ",")) + } + } + + for _, vv := range v { + values = append(values, interfaceToString(vv)) + } + rows = append(rows, strings.Join(values, separator)) + } + // Outout a line separator if in column format + if c.Format == "column" { + rows = append(rows, "") + } + } + return rows +} + +func interfaceToString(v interface{}) string { + switch t := v.(type) { + case nil: + return "" + case bool: + return fmt.Sprintf("%v", v) + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr: + return fmt.Sprintf("%d", t) + case float32, float64: + return fmt.Sprintf("%v", t) + default: + return fmt.Sprintf("%v", t) + } +} + +// Settings prints current settings +func (c *CommandLine) Settings() { + w := new(tabwriter.Writer) + w.Init(os.Stdout, 0, 8, 1, '\t', 0) + if c.Port > 0 { + fmt.Fprintf(w, "Host\t%s:%d\n", c.Host, c.Port) + } else { + fmt.Fprintf(w, "Host\t%s\n", c.Host) + } + fmt.Fprintf(w, "Username\t%s\n", c.Username) + fmt.Fprintf(w, "Database\t%s\n", c.Database) + fmt.Fprintf(w, "Pretty\t%v\n", c.Pretty) + fmt.Fprintf(w, "Format\t%s\n", c.Format) + fmt.Fprintf(w, "Write Consistency\t%s\n", c.WriteConsistency) + fmt.Fprintln(w) + w.Flush() +} + +func (c *CommandLine) help() { + fmt.Println(`Usage: + connect connects to another node specified by host:port + auth prompts for username and password + pretty toggles pretty print for the json format + use sets current database + format specifies the format of the server responses: json, csv, or column + precision specifies the format of the timestamp: rfc3339, h, m, s, ms, u or ns + consistency sets write consistency level: any, one, quorum, or all + history displays command history + settings outputs the current settings for the shell + exit quits the influx shell + + show databases show database names + show series show series information + show measurements show measurement information + show tag keys show tag key information + show field keys show field key information + + A full list of influxql commands can be found at: + https://influxdb.com/docs/v0.9/query_language/spec.html +`) +} + +func (c *CommandLine) history() { + var buf bytes.Buffer + c.Line.WriteHistory(&buf) + fmt.Print(buf.String()) +} + +func (c *CommandLine) gopher() { + fmt.Println(` + .-::-::://:-::- .:/++/' + '://:-''/oo+//++o+/.://o- ./+: + .:-. '++- .o/ '+yydhy' o- + .:/. .h: :osoys .smMN- :/ + -/:.' s- /MMMymh. '/y/ s' + -+s:'''' d -mMMms// '-/o: + -/++/++/////:. o: '... s- :s. + :+-+s-' ':/' 's- /+ 'o: + '+-'o: /ydhsh. '//. '-o- o- + .y. o: .MMMdm+y ':+++:::/+:.' s: + .-h/ y- 'sdmds'h -+ydds:::-.' 'h. + .//-.d' o: '.' 'dsNMMMNh:.:++' :y + +y. 'd 's. .s:mddds: ++ o/ + 'N- odd 'o/. './o-s-' .---+++' o- + 'N' yNd .://:/:::::. -s -+/s/./s' 'o/' + so' .h '''' ////s: '+. .s +y' + os/-.y' 's' 'y::+ +d' + '.:o/ -+:-:.' so.---.' + o' 'd-.''/s' + .s' :y.''.y + -s mo:::' + :: yh + // '''' /M' + o+ .s///:/. 'N: + :+ /: -s' ho + 's- -/s/:+/.+h' +h + ys' ':' '-. -d + oh .h + /o .s + s. .h + -y .d + m/ -h + +d /o + 'N- y: + h: m. + s- -d + o- s+ + +- 'm' + s/ oo--. + y- /s ':+' + s' 'od--' .d: + -+ ':o: ':+-/+ + y- .:+- ' + //o- '.:+/. + .-:+/' ''-/+/. + ./:' ''.:o+/-' + .+o:/:/+-' ''.-+ooo/-' + o: -h///++////-. + /: .o/ + //+ 'y + ./sooy. + +`) +} + +// Version prints CLI version +func (c *CommandLine) Version() { + fmt.Println("InfluxDB shell " + c.ClientVersion) +} + +func (c *CommandLine) exit() { + // write to history file + _, err := c.Line.WriteHistory(c.historyFile) + if err != nil { + fmt.Printf("There was an error writing history file: %s\n", err) + } + // release line resources + c.Line.Close() + c.Line = nil + // exit CLI + os.Exit(0) +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli_test.go new file mode 100644 index 00000000..7d476239 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/cli/cli_test.go @@ -0,0 +1,442 @@ +package cli_test + +import ( + "bufio" + "bytes" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + + "github.com/influxdb/influxdb/client" + "github.com/influxdb/influxdb/cmd/influx/cli" + "github.com/peterh/liner" +) + +const ( + CLIENT_VERSION = "y.y" + SERVER_VERSION = "x.x" +) + +func TestNewCLI(t *testing.T) { + t.Parallel() + c := cli.New(CLIENT_VERSION) + + if c == nil { + t.Fatal("CommandLine shouldn't be nil.") + } + + if c.ClientVersion != CLIENT_VERSION { + t.Fatalf("CommandLine version is %s but should be %s", c.ClientVersion, CLIENT_VERSION) + } +} + +func TestRunCLI(t *testing.T) { + t.Parallel() + ts := emptyTestServer() + defer ts.Close() + + u, _ := url.Parse(ts.URL) + h, p, _ := net.SplitHostPort(u.Host) + c := cli.New(CLIENT_VERSION) + c.Host = h + c.Port, _ = strconv.Atoi(p) + c.Run() +} + +func TestConnect(t *testing.T) { + t.Parallel() + ts := emptyTestServer() + defer ts.Close() + + u, _ := url.Parse(ts.URL) + cmd := "connect " + u.Host + c := cli.CommandLine{} + + // assert connection is established + if err := c.Connect(cmd); err != nil { + t.Fatalf("There was an error while connecting to %s: %s", u.Path, err) + } + + // assert server version is populated + if c.ServerVersion != SERVER_VERSION { + t.Fatalf("Server version is %s but should be %s.", c.ServerVersion, SERVER_VERSION) + } +} + +func TestSetAuth(t *testing.T) { + t.Parallel() + c := cli.New(CLIENT_VERSION) + config := client.NewConfig() + client, _ := client.NewClient(config) + c.Client = client + u := "userx" + p := "pwdy" + c.SetAuth("auth " + u + " " + p) + + // validate CLI configuration + if c.Username != u { + t.Fatalf("Username is %s but should be %s", c.Username, u) + } + if c.Password != p { + t.Fatalf("Password is %s but should be %s", c.Password, p) + } +} + +func TestSetPrecision(t *testing.T) { + t.Parallel() + c := cli.New(CLIENT_VERSION) + config := client.NewConfig() + client, _ := client.NewClient(config) + c.Client = client + + // validate set non-default precision + p := "ns" + c.SetPrecision("precision " + p) + if c.Precision != p { + t.Fatalf("Precision is %s but should be %s", c.Precision, p) + } + + // validate set default precision which equals empty string + p = "rfc3339" + c.SetPrecision("precision " + p) + if c.Precision != "" { + t.Fatalf("Precision is %s but should be empty", c.Precision) + } +} + +func TestSetFormat(t *testing.T) { + t.Parallel() + c := cli.New(CLIENT_VERSION) + config := client.NewConfig() + client, _ := client.NewClient(config) + c.Client = client + + // validate set non-default format + f := "json" + c.SetFormat("format " + f) + if c.Format != f { + t.Fatalf("Format is %s but should be %s", c.Format, f) + } +} + +func TestSetWriteConsistency(t *testing.T) { + t.Parallel() + c := cli.New(CLIENT_VERSION) + config := client.NewConfig() + client, _ := client.NewClient(config) + c.Client = client + + // set valid write consistency + consistency := "all" + c.SetWriteConsistency("consistency " + consistency) + if c.WriteConsistency != consistency { + t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) + } + + // set different valid write consistency and validate change + consistency = "quorum" + c.SetWriteConsistency("consistency " + consistency) + if c.WriteConsistency != consistency { + t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) + } + + // set invalid write consistency and verify there was no change + invalidConsistency := "invalid_consistency" + c.SetWriteConsistency("consistency " + invalidConsistency) + if c.WriteConsistency == invalidConsistency { + t.Fatalf("WriteConsistency is %s but should be %s", c.WriteConsistency, consistency) + } +} + +func TestParseCommand_CommandsExist(t *testing.T) { + t.Parallel() + c := cli.CommandLine{} + tests := []struct { + cmd string + }{ + {cmd: "gopher"}, + {cmd: "connect"}, + {cmd: "help"}, + {cmd: "pretty"}, + {cmd: "use"}, + } + for _, test := range tests { + if !c.ParseCommand(test.cmd) { + t.Fatalf(`Command failed for %q.`, test.cmd) + } + } +} + +func TestParseCommand_BlankCommand(t *testing.T) { + t.Parallel() + c := cli.CommandLine{} + tests := []struct { + cmd string + }{ + {cmd: ""}, // test that a blank command doesn't work + } + for _, test := range tests { + if c.ParseCommand(test.cmd) { + t.Fatalf(`Command failed for %q.`, test.cmd) + } + } +} + +func TestParseCommand_TogglePretty(t *testing.T) { + t.Parallel() + c := cli.CommandLine{} + if c.Pretty { + t.Fatalf(`Pretty should be false.`) + } + c.ParseCommand("pretty") + if !c.Pretty { + t.Fatalf(`Pretty should be true.`) + } + c.ParseCommand("pretty") + if c.Pretty { + t.Fatalf(`Pretty should be false.`) + } +} + +func TestParseCommand_Exit(t *testing.T) { + t.Parallel() + tests := []struct { + cmd string + }{ + {cmd: "exit"}, + {cmd: " exit"}, + {cmd: "exit "}, + {cmd: "Exit "}, + } + + for _, test := range tests { + c := cli.CommandLine{Quit: make(chan struct{}, 1)} + c.ParseCommand(test.cmd) + // channel should be closed + if _, ok := <-c.Quit; ok { + t.Fatalf(`Command "exit" failed for %q.`, test.cmd) + } + } +} + +func TestParseCommand_Use(t *testing.T) { + t.Parallel() + c := cli.CommandLine{} + tests := []struct { + cmd string + }{ + {cmd: "use db"}, + {cmd: " use db"}, + {cmd: "use db "}, + {cmd: "use db;"}, + {cmd: "use db; "}, + {cmd: "Use db"}, + } + + for _, test := range tests { + if !c.ParseCommand(test.cmd) { + t.Fatalf(`Command "use" failed for %q.`, test.cmd) + } + + if c.Database != "db" { + t.Fatalf(`Command "use" changed database to %q. Expected db`, c.Database) + } + } +} + +func TestParseCommand_Consistency(t *testing.T) { + t.Parallel() + c := cli.CommandLine{} + tests := []struct { + cmd string + }{ + {cmd: "consistency one"}, + {cmd: " consistency one"}, + {cmd: "consistency one "}, + {cmd: "consistency one;"}, + {cmd: "consistency one; "}, + {cmd: "Consistency one"}, + } + + for _, test := range tests { + if !c.ParseCommand(test.cmd) { + t.Fatalf(`Command "consistency" failed for %q.`, test.cmd) + } + + if c.WriteConsistency != "one" { + t.Fatalf(`Command "consistency" changed consistency to %q. Expected one`, c.WriteConsistency) + } + } +} + +func TestParseCommand_Insert(t *testing.T) { + t.Parallel() + ts := emptyTestServer() + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + m := cli.CommandLine{Client: c} + + tests := []struct { + cmd string + }{ + {cmd: "INSERT cpu,host=serverA,region=us-west value=1.0"}, + {cmd: " INSERT cpu,host=serverA,region=us-west value=1.0"}, + {cmd: "INSERT cpu,host=serverA,region=us-west value=1.0"}, + {cmd: "insert cpu,host=serverA,region=us-west value=1.0 "}, + {cmd: "insert"}, + {cmd: "Insert "}, + {cmd: "insert c"}, + {cmd: "insert int"}, + } + + for _, test := range tests { + if !m.ParseCommand(test.cmd) { + t.Fatalf(`Command "insert" failed for %q.`, test.cmd) + } + } +} + +func TestParseCommand_InsertInto(t *testing.T) { + t.Parallel() + ts := emptyTestServer() + defer ts.Close() + + u, _ := url.Parse(ts.URL) + config := client.Config{URL: *u} + c, err := client.NewClient(config) + if err != nil { + t.Fatalf("unexpected error. expected %v, actual %v", nil, err) + } + m := cli.CommandLine{Client: c} + + tests := []struct { + cmd, db, rp string + }{ + { + cmd: `INSERT INTO test cpu,host=serverA,region=us-west value=1.0`, + db: "", + rp: "test", + }, + { + cmd: ` INSERT INTO .test cpu,host=serverA,region=us-west value=1.0`, + db: "", + rp: "test", + }, + { + cmd: `INSERT INTO "test test" cpu,host=serverA,region=us-west value=1.0`, + db: "", + rp: "test test", + }, + { + cmd: `Insert iNTO test.test cpu,host=serverA,region=us-west value=1.0`, + db: "test", + rp: "test", + }, + { + cmd: `insert into "test test" cpu,host=serverA,region=us-west value=1.0`, + db: "test", + rp: "test test", + }, + { + cmd: `insert into "d b"."test test" cpu,host=serverA,region=us-west value=1.0`, + db: "d b", + rp: "test test", + }, + } + + for _, test := range tests { + if !m.ParseCommand(test.cmd) { + t.Fatalf(`Command "insert into" failed for %q.`, test.cmd) + } + if m.Database != test.db { + t.Fatalf(`Command "insert into" db parsing failed, expected: %q, actual: %q`, test.db, m.Database) + } + if m.RetentionPolicy != test.rp { + t.Fatalf(`Command "insert into" rp parsing failed, expected: %q, actual: %q`, test.rp, m.RetentionPolicy) + } + } +} + +func TestParseCommand_History(t *testing.T) { + t.Parallel() + c := cli.CommandLine{Line: liner.NewLiner()} + defer c.Line.Close() + + // append one entry to history + c.Line.AppendHistory("abc") + + tests := []struct { + cmd string + }{ + {cmd: "history"}, + {cmd: " history"}, + {cmd: "history "}, + {cmd: "History "}, + } + + for _, test := range tests { + if !c.ParseCommand(test.cmd) { + t.Fatalf(`Command "history" failed for %q.`, test.cmd) + } + } + + // buf size should be at least 1 + var buf bytes.Buffer + c.Line.WriteHistory(&buf) + if buf.Len() < 1 { + t.Fatal("History is borked") + } +} + +func TestParseCommand_HistoryWithBlankCommand(t *testing.T) { + t.Parallel() + c := cli.CommandLine{Line: liner.NewLiner()} + defer c.Line.Close() + + // append one entry to history + c.Line.AppendHistory("x") + + tests := []struct { + cmd string + }{ + {cmd: "history"}, + {cmd: " history"}, + {cmd: "history "}, + {cmd: "History "}, + {cmd: ""}, // shouldn't be persisted in history + {cmd: " "}, // shouldn't be persisted in history + } + + // don't validate because blank commands are never executed + for _, test := range tests { + c.ParseCommand(test.cmd) + } + + // buf shall not contain empty commands + var buf bytes.Buffer + c.Line.WriteHistory(&buf) + scanner := bufio.NewScanner(&buf) + for scanner.Scan() { + if scanner.Text() == "" || scanner.Text() == " " { + t.Fatal("Empty commands should not be persisted in history.") + } + } +} + +// helper methods + +func emptyTestServer() *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Influxdb-Version", SERVER_VERSION) + return + })) +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/main.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/main.go new file mode 100644 index 00000000..debaccb1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx/main.go @@ -0,0 +1,103 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/influxdb/influxdb/client" + "github.com/influxdb/influxdb/cmd/influx/cli" +) + +// These variables are populated via the Go linker. +var ( + version = "0.9" +) + +const ( + // defaultFormat is the default format of the results when issuing queries + defaultFormat = "column" + + // defaultPrecision is the default timestamp format of the results when issuing queries + defaultPrecision = "ns" + + // defaultPPS is the default points per second that the import will throttle at + // by default it's 0, which means it will not throttle + defaultPPS = 0 +) + +func main() { + c := cli.New(version) + + fs := flag.NewFlagSet("InfluxDB shell version "+version, flag.ExitOnError) + fs.StringVar(&c.Host, "host", client.DefaultHost, "Influxdb host to connect to.") + fs.IntVar(&c.Port, "port", client.DefaultPort, "Influxdb port to connect to.") + fs.StringVar(&c.Username, "username", c.Username, "Username to connect to the server.") + fs.StringVar(&c.Password, "password", c.Password, `Password to connect to the server. Leaving blank will prompt for password (--password="").`) + fs.StringVar(&c.Database, "database", c.Database, "Database to connect to the server.") + fs.BoolVar(&c.Ssl, "ssl", false, "Use https for connecting to cluster.") + fs.StringVar(&c.Format, "format", defaultFormat, "Format specifies the format of the server responses: json, csv, or column.") + fs.StringVar(&c.Precision, "precision", defaultPrecision, "Precision specifies the format of the timestamp: rfc3339,h,m,s,ms,u or ns.") + fs.StringVar(&c.WriteConsistency, "consistency", "any", "Set write consistency level: any, one, quorum, or all.") + fs.BoolVar(&c.Pretty, "pretty", false, "Turns on pretty print for the json format.") + fs.StringVar(&c.Execute, "execute", c.Execute, "Execute command and quit.") + fs.BoolVar(&c.ShowVersion, "version", false, "Displays the InfluxDB version.") + fs.BoolVar(&c.Import, "import", false, "Import a previous database.") + fs.IntVar(&c.PPS, "pps", defaultPPS, "How many points per second the import will allow. By default it is zero and will not throttle importing.") + fs.StringVar(&c.Path, "path", "", "path to the file to import") + fs.BoolVar(&c.Compressed, "compressed", false, "set to true if the import file is compressed") + + // Define our own custom usage to print + fs.Usage = func() { + fmt.Println(`Usage of influx: + -version + Display the version and exit. + -host 'host name' + Host to connect to. + -port 'port #' + Port to connect to. + -database 'database name' + Database to connect to the server. + -password 'password' + Password to connect to the server. Leaving blank will prompt for password (--password ''). + -username 'username' + Username to connect to the server. + -ssl + Use https for requests. + -execute 'command' + Execute command and quit. + -format 'json|csv|column' + Format specifies the format of the server responses: json, csv, or column. + -precision 'rfc3339|h|m|s|ms|u|ns' + Precision specifies the format of the timestamp: rfc3339, h, m, s, ms, u or ns. + -consistency 'any|one|quorum|all' + Set write consistency level: any, one, quorum, or all + -pretty + Turns on pretty print for the json format. + -import + Import a previous database export from file + -pps + How many points per second the import will allow. By default it is zero and will not throttle importing. + -path + Path to file to import + -compressed + Set to true if the import file is compressed + +Examples: + + # Use influx in a non-interactive mode to query the database "metrics" and pretty print json: + $ influx -database 'metrics' -execute 'select * from cpu' -format 'json' -pretty + + # Connect to a specific database on startup and set database context: + $ influx -database 'metrics' -host 'localhost' -port '8086' +`) + } + fs.Parse(os.Args[1:]) + + if c.ShowVersion { + c.Version() + os.Exit(0) + } + + c.Run() +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/info.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/info.go new file mode 100644 index 00000000..381486b3 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/info.go @@ -0,0 +1,109 @@ +package main + +import ( + "encoding/binary" + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + "sort" + "strings" + "text/tabwriter" + + "github.com/influxdb/influxdb/tsdb" +) + +func cmdInfo(path string) { + tstore := tsdb.NewStore(filepath.Join(path, "data")) + tstore.Logger = log.New(ioutil.Discard, "", log.LstdFlags) + tstore.EngineOptions.Config.Dir = filepath.Join(path, "data") + tstore.EngineOptions.Config.WALLoggingEnabled = false + tstore.EngineOptions.Config.WALDir = filepath.Join(path, "wal") + if err := tstore.Open(); err != nil { + fmt.Printf("Failed to open dir: %v\n", err) + os.Exit(1) + } + + size, err := tstore.DiskSize() + if err != nil { + fmt.Printf("Failed to determine disk usage: %v\n", err) + } + + // Summary stats + fmt.Printf("Shards: %d, Indexes: %d, Databases: %d, Disk Size: %d, Series: %d\n\n", + tstore.ShardN(), tstore.DatabaseIndexN(), len(tstore.Databases()), size, countSeries(tstore)) + + tw := tabwriter.NewWriter(os.Stdout, 16, 8, 0, '\t', 0) + + fmt.Fprintln(tw, strings.Join([]string{"Shard", "DB", "Measurement", "Tags [#K/#V]", "Fields [Name:Type]", "Series"}, "\t")) + + shardIDs := tstore.ShardIDs() + + databases := tstore.Databases() + sort.Strings(databases) + + for _, db := range databases { + index := tstore.DatabaseIndex(db) + measurements := index.Measurements() + sort.Sort(measurements) + for _, m := range measurements { + tags := m.TagKeys() + tagValues := 0 + for _, tag := range tags { + tagValues += len(m.TagValues(tag)) + } + fields := m.FieldNames() + sort.Strings(fields) + series := m.SeriesKeys() + sort.Strings(series) + sort.Sort(ShardIDs(shardIDs)) + + // Sample a point from each measurement to determine the field types + for _, shardID := range shardIDs { + shard := tstore.Shard(shardID) + codec := shard.FieldCodec(m.Name) + for _, field := range codec.Fields() { + ft := fmt.Sprintf("%s:%s", field.Name, field.Type) + fmt.Fprintf(tw, "%d\t%s\t%s\t%d/%d\t%d [%s]\t%d\n", shardID, db, m.Name, len(tags), tagValues, + len(fields), ft, len(series)) + + } + + } + } + } + tw.Flush() +} + +func countSeries(tstore *tsdb.Store) int { + var count int + for _, shardID := range tstore.ShardIDs() { + shard := tstore.Shard(shardID) + cnt, err := shard.SeriesCount() + if err != nil { + fmt.Printf("series count failed: %v\n", err) + continue + } + count += cnt + } + return count +} + +func btou64(b []byte) uint64 { + return binary.BigEndian.Uint64(b) +} + +// u64tob converts a uint64 into an 8-byte slice. +func u64tob(v uint64) []byte { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, v) + return b +} + +// ShardIDs is a collection of UINT 64 that represent shard ids. +type ShardIDs []uint64 + +func (a ShardIDs) Len() int { return len(a) } +func (a ShardIDs) Less(i, j int) bool { return a[i] < a[j] } +func (a ShardIDs) Swap(i, j int) { a[i], a[j] = a[j], a[i] } diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/main.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/main.go new file mode 100644 index 00000000..647376b8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/main.go @@ -0,0 +1,87 @@ +package main + +import ( + "flag" + "fmt" + "os" + + _ "github.com/influxdb/influxdb/tsdb/engine" +) + +func usage() { + println(`Usage: influx_inspect [options] + +Displays detailed information about InfluxDB data files. +`) + + println(`Commands: + info - displays series meta-data for all shards. Default location [$HOME/.influxdb] + dumptsm - dumps low-level details about tsm1 files.`) + println() +} + +func main() { + + flag.Usage = usage + flag.Parse() + + if len(flag.Args()) == 0 { + flag.Usage() + os.Exit(0) + } + + switch flag.Args()[0] { + case "info": + var path string + fs := flag.NewFlagSet("info", flag.ExitOnError) + fs.StringVar(&path, "dir", os.Getenv("HOME")+"/.influxdb", "Root storage path. [$HOME/.influxdb]") + + fs.Usage = func() { + println("Usage: influx_inspect info [options]\n\n Displays series meta-data for all shards..") + println() + println("Options:") + fs.PrintDefaults() + } + + if err := fs.Parse(flag.Args()[1:]); err != nil { + fmt.Printf("%v", err) + os.Exit(1) + } + cmdInfo(path) + case "dumptsm": + var dumpAll bool + opts := &tsdmDumpOpts{} + fs := flag.NewFlagSet("file", flag.ExitOnError) + fs.BoolVar(&opts.dumpIndex, "index", false, "Dump raw index data") + fs.BoolVar(&opts.dumpBlocks, "blocks", false, "Dump raw block data") + fs.BoolVar(&dumpAll, "all", false, "Dump all data. Caution: This may print a lot of information") + fs.StringVar(&opts.filterKey, "filter-key", "", "Only display index and block data match this key substring") + + fs.Usage = func() { + println("Usage: influx_inspect dumptsm [options] \n\n Dumps low-level details about tsm1 files.") + println() + println("Options:") + fs.PrintDefaults() + os.Exit(0) + } + + if err := fs.Parse(flag.Args()[1:]); err != nil { + fmt.Printf("%v", err) + os.Exit(1) + } + + if len(fs.Args()) == 0 || fs.Args()[0] == "" { + fmt.Printf("TSM file not specified\n\n") + fs.Usage() + fs.PrintDefaults() + os.Exit(1) + } + opts.path = fs.Args()[0] + opts.dumpBlocks = opts.dumpBlocks || dumpAll || opts.filterKey != "" + opts.dumpIndex = opts.dumpIndex || dumpAll || opts.filterKey != "" + cmdDumpTsm1(opts) + default: + flag.Usage() + os.Exit(1) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/tsm.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/tsm.go new file mode 100644 index 00000000..66788b87 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_inspect/tsm.go @@ -0,0 +1,443 @@ +package main + +import ( + "encoding/binary" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "strings" + "text/tabwriter" + "time" + + "github.com/golang/snappy" + "github.com/influxdb/influxdb/tsdb" + "github.com/influxdb/influxdb/tsdb/engine/tsm1" +) + +type tsdmDumpOpts struct { + dumpIndex bool + dumpBlocks bool + filterKey string + path string +} + +type tsmIndex struct { + series int + offset int64 + minTime time.Time + maxTime time.Time + blocks []*block +} + +type block struct { + id uint64 + offset int64 +} + +type blockStats struct { + min, max int + counts [][]int +} + +func (b *blockStats) inc(typ int, enc byte) { + for len(b.counts) <= typ { + b.counts = append(b.counts, []int{}) + } + for len(b.counts[typ]) <= int(enc) { + b.counts[typ] = append(b.counts[typ], 0) + } + b.counts[typ][enc]++ +} + +func (b *blockStats) size(sz int) { + if b.min == 0 || sz < b.min { + b.min = sz + } + if b.min == 0 || sz > b.max { + b.max = sz + } +} + +var ( + fieldType = []string{ + "timestamp", "float", "int", "bool", "string", + } + blockTypes = []string{ + "float64", "int64", "bool", "string", + } + timeEnc = []string{ + "none", "s8b", "rle", + } + floatEnc = []string{ + "none", "gor", + } + intEnc = []string{ + "none", "s8b", "rle", + } + boolEnc = []string{ + "none", "bp", + } + stringEnc = []string{ + "none", "snpy", + } + encDescs = [][]string{ + timeEnc, floatEnc, intEnc, boolEnc, stringEnc, + } +) + +func readFields(path string) (map[string]*tsdb.MeasurementFields, error) { + fields := make(map[string]*tsdb.MeasurementFields) + + f, err := os.OpenFile(filepath.Join(path, tsm1.FieldsFileExtension), os.O_RDONLY, 0666) + if os.IsNotExist(err) { + return fields, nil + } else if err != nil { + return nil, err + } + b, err := ioutil.ReadAll(f) + if err != nil { + return nil, err + } + + data, err := snappy.Decode(nil, b) + if err != nil { + return nil, err + } + + if err := json.Unmarshal(data, &fields); err != nil { + return nil, err + } + return fields, nil +} + +func readSeries(path string) (map[string]*tsdb.Series, error) { + series := make(map[string]*tsdb.Series) + + f, err := os.OpenFile(filepath.Join(path, tsm1.SeriesFileExtension), os.O_RDONLY, 0666) + if os.IsNotExist(err) { + return series, nil + } else if err != nil { + return nil, err + } + defer f.Close() + b, err := ioutil.ReadAll(f) + if err != nil { + return nil, err + } + + data, err := snappy.Decode(nil, b) + if err != nil { + return nil, err + } + + if err := json.Unmarshal(data, &series); err != nil { + return nil, err + } + + return series, nil +} + +func readIds(path string) (map[string]uint64, error) { + f, err := os.OpenFile(filepath.Join(path, tsm1.IDsFileExtension), os.O_RDONLY, 0666) + if os.IsNotExist(err) { + return nil, nil + } else if err != nil { + return nil, err + } + b, err := ioutil.ReadAll(f) + if err != nil { + return nil, err + } + + b, err = snappy.Decode(nil, b) + if err != nil { + return nil, err + } + + ids := make(map[string]uint64) + if b != nil { + if err := json.Unmarshal(b, &ids); err != nil { + return nil, err + } + } + return ids, err +} +func readIndex(f *os.File) (*tsmIndex, error) { + // Get the file size + stat, err := f.Stat() + if err != nil { + return nil, err + } + + // Seek to the series count + f.Seek(-4, os.SEEK_END) + b := make([]byte, 8) + _, err = f.Read(b[:4]) + if err != nil { + return nil, err + } + + seriesCount := binary.BigEndian.Uint32(b) + + // Get the min time + f.Seek(-20, os.SEEK_END) + f.Read(b) + minTime := time.Unix(0, int64(btou64(b))) + + // Get max time + f.Seek(-12, os.SEEK_END) + f.Read(b) + maxTime := time.Unix(0, int64(btou64(b))) + + // Figure out where the index starts + indexStart := stat.Size() - int64(seriesCount*12+20) + + // Seek to the start of the index + f.Seek(indexStart, os.SEEK_SET) + count := int(seriesCount) + index := &tsmIndex{ + offset: indexStart, + minTime: minTime, + maxTime: maxTime, + series: count, + } + + if indexStart < 0 { + return nil, fmt.Errorf("index corrupt: offset=%d", indexStart) + } + + // Read the index entries + for i := 0; i < count; i++ { + f.Read(b) + id := binary.BigEndian.Uint64(b) + f.Read(b[:4]) + pos := binary.BigEndian.Uint32(b[:4]) + index.blocks = append(index.blocks, &block{id: id, offset: int64(pos)}) + } + + return index, nil +} + +func cmdDumpTsm1(opts *tsdmDumpOpts) { + var errors []error + + f, err := os.Open(opts.path) + if err != nil { + println(err.Error()) + os.Exit(1) + } + + // Get the file size + stat, err := f.Stat() + if err != nil { + println(err.Error()) + os.Exit(1) + } + + b := make([]byte, 8) + f.Read(b[:4]) + + // Verify magic number + if binary.BigEndian.Uint32(b[:4]) != 0x16D116D1 { + println("Not a tsm1 file.") + os.Exit(1) + } + + ids, err := readIds(filepath.Dir(opts.path)) + if err != nil { + println("Failed to read series:", err.Error()) + os.Exit(1) + } + + invIds := map[uint64]string{} + for k, v := range ids { + invIds[v] = k + } + + index, err := readIndex(f) + if err != nil { + println("Failed to readIndex:", err.Error()) + + // Create a stubbed out index so we can still try and read the block data directly + // w/o panicing ourselves. + index = &tsmIndex{ + minTime: time.Unix(0, 0), + maxTime: time.Unix(0, 0), + offset: stat.Size(), + } + } + + blockStats := &blockStats{} + + println("Summary:") + fmt.Printf(" File: %s\n", opts.path) + fmt.Printf(" Time Range: %s - %s\n", + index.minTime.UTC().Format(time.RFC3339Nano), + index.maxTime.UTC().Format(time.RFC3339Nano), + ) + fmt.Printf(" Duration: %s ", index.maxTime.Sub(index.minTime)) + fmt.Printf(" Series: %d ", index.series) + fmt.Printf(" File Size: %d\n", stat.Size()) + println() + + tw := tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\t', 0) + fmt.Fprintln(tw, " "+strings.Join([]string{"Pos", "ID", "Ofs", "Key", "Field"}, "\t")) + for i, block := range index.blocks { + key := invIds[block.id] + split := strings.Split(key, "#!~#") + + // We dont' know know if we have fields so use an informative default + var measurement, field string = "UNKNOWN", "UNKNOWN" + + // We read some IDs from the ids file + if len(invIds) > 0 { + // Change the default to error until we know we have a valid key + measurement = "ERR" + field = "ERR" + + // Possible corruption? Try to read as much as we can and point to the problem. + if key == "" { + errors = append(errors, fmt.Errorf("index pos %d, field id: %d, missing key for id", i, block.id)) + } else if len(split) < 2 { + errors = append(errors, fmt.Errorf("index pos %d, field id: %d, key corrupt: got '%v'", i, block.id, key)) + } else { + measurement = split[0] + field = split[1] + } + } + + if opts.filterKey != "" && !strings.Contains(key, opts.filterKey) { + continue + } + fmt.Fprintln(tw, " "+strings.Join([]string{ + strconv.FormatInt(int64(i), 10), + strconv.FormatUint(block.id, 10), + strconv.FormatInt(int64(block.offset), 10), + measurement, + field, + }, "\t")) + } + + if opts.dumpIndex { + println("Index:") + tw.Flush() + println() + } + + tw = tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\t', 0) + fmt.Fprintln(tw, " "+strings.Join([]string{"Blk", "Ofs", "Len", "ID", "Type", "Min Time", "Points", "Enc [T/V]", "Len [T/V]"}, "\t")) + + // Staring at 4 because the magic number is 4 bytes + i := int64(4) + var blockCount, pointCount, blockSize int64 + indexSize := stat.Size() - index.offset + + // Start at the beginning and read every block + for i < index.offset { + f.Seek(int64(i), 0) + + f.Read(b) + id := btou64(b) + f.Read(b[:4]) + length := binary.BigEndian.Uint32(b[:4]) + buf := make([]byte, length) + f.Read(buf) + + blockSize += int64(len(buf)) + 12 + + startTime := time.Unix(0, int64(btou64(buf[:8]))) + blockType := buf[8] + + encoded := buf[9:] + + var v []tsm1.Value + v, err := tsm1.DecodeBlock(buf, v) + if err != nil { + fmt.Printf("error: %v\n", err.Error()) + os.Exit(1) + } + + pointCount += int64(len(v)) + + // Length of the timestamp block + tsLen, j := binary.Uvarint(encoded) + + // Unpack the timestamp bytes + ts := encoded[int(j) : int(j)+int(tsLen)] + + // Unpack the value bytes + values := encoded[int(j)+int(tsLen):] + + tsEncoding := timeEnc[int(ts[0]>>4)] + vEncoding := encDescs[int(blockType+1)][values[0]>>4] + + typeDesc := blockTypes[blockType] + + blockStats.inc(0, ts[0]>>4) + blockStats.inc(int(blockType+1), values[0]>>4) + blockStats.size(len(buf)) + + if opts.filterKey != "" && !strings.Contains(invIds[id], opts.filterKey) { + i += (12 + int64(length)) + blockCount++ + continue + } + + fmt.Fprintln(tw, " "+strings.Join([]string{ + strconv.FormatInt(blockCount, 10), + strconv.FormatInt(i, 10), + strconv.FormatInt(int64(len(buf)), 10), + strconv.FormatUint(id, 10), + typeDesc, + startTime.UTC().Format(time.RFC3339Nano), + strconv.FormatInt(int64(len(v)), 10), + fmt.Sprintf("%s/%s", tsEncoding, vEncoding), + fmt.Sprintf("%d/%d", len(ts), len(values)), + }, "\t")) + + i += (12 + int64(length)) + blockCount++ + } + if opts.dumpBlocks { + println("Blocks:") + tw.Flush() + println() + } + + fmt.Printf("Statistics\n") + fmt.Printf(" Blocks:\n") + fmt.Printf(" Total: %d Size: %d Min: %d Max: %d Avg: %d\n", + blockCount, blockSize, blockStats.min, blockStats.max, blockSize/blockCount) + fmt.Printf(" Index:\n") + fmt.Printf(" Total: %d Size: %d\n", len(index.blocks), indexSize) + fmt.Printf(" Points:\n") + fmt.Printf(" Total: %d", pointCount) + println() + + println(" Encoding:") + for i, counts := range blockStats.counts { + if len(counts) == 0 { + continue + } + fmt.Printf(" %s: ", strings.Title(fieldType[i])) + for j, v := range counts { + fmt.Printf("\t%s: %d (%d%%) ", encDescs[i][j], v, int(float64(v)/float64(blockCount)*100)) + } + println() + } + fmt.Printf(" Compression:\n") + fmt.Printf(" Per block: %0.2f bytes/point\n", float64(blockSize)/float64(pointCount)) + fmt.Printf(" Total: %0.2f bytes/point\n", float64(stat.Size())/float64(pointCount)) + + if len(errors) > 0 { + println() + fmt.Printf("Errors (%d):\n", len(errors)) + for _, err := range errors { + fmt.Printf(" * %v\n", err) + } + println() + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/examples/template.toml b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/examples/template.toml new file mode 100644 index 00000000..5080dbd1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/examples/template.toml @@ -0,0 +1,92 @@ +# This section can be removed +[provision] + # The basic provisioner simply deletes and creates database. + # If `reset_database` is false, it will not attempt to delete the database + [provision.basic] + # If enabled the provisioner will actually run + enabled = true + # Address of the instance that is to be provisioned + address = "localhost:8086" + # Database the will be created/deleted + database = "stress" + # Attempt to delete database + reset_database = true + +# This section cannot be commented out +# To prevent writes set `enabled=false` +# in [write.influx_client.basic] +[write] + [write.point_generator] + # The basic point generator will generate points of the form + # `cpu,host=server-%v,location=us-west value=234 123456` + [write.point_generator.basic] + # number of points that will be written for each of the series + point_count = 100 + # number of series + series_count = 100000 + # How much time between each timestamp + tick = "10s" + # Randomize timestamp a bit (not functional) + jitter = true + # Precision of points that are being written + precision = "n" + # name of the measurement that will be written + measurement = "cpu" + # The date for the first point that is written into influx + start_date = "2006-Jan-02" + # Defines a tag for a series + [[write.point_generator.basic.tag]] + key = "host" + value = "server" + [[write.point_generator.basic.tag]] + key = "location" + value = "us-west" + # Defines a field for a series + [[write.point_generator.basic.field]] + key = "value" + value = "float64" # supported types: float64, int, bool + + + [write.influx_client] + [write.influx_client.basic] + # If enabled the writer will actually write + enabled = true + # Address of the Influxdb instance + address = "localhost:8086" # stress_test_server runs on port 1234 + # Database that is being written to + database = "stress" + # Precision of points that are being written + precision = "n" + # Size of batches that are sent to db + batch_size = 10000 + # Interval between each batch + batch_interval = "0s" + # How many concurrent writers to the db + concurrency = 10 + # ssl enabled? + ssl = false + # format of points that are written to influxdb + format = "line_http" # line_udp (not supported yet), graphite_tcp (not supported yet), graphite_udp (not supported yet) + +# This section can be removed +[read] + [read.query_generator] + [read.query_generator.basic] + # Template of the query that will be ran against the instance + template = "SELECT count(value) FROM cpu where host='server-%v'" + # How many times the templated query will be ran + query_count = 250 + + [read.query_client] + [read.query_client.basic] + # if enabled the reader will actually read + enabled = true + # Address of the instance that will be queried + address = "localhost:8086" + # Database that will be queried + database = "stress" + # Interval bewteen queries + query_interval = "100ms" + # Number of concurrent queriers + concurrency = 1 + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/influx_stress.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/influx_stress.go new file mode 100644 index 00000000..6eaee05b --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influx_stress/influx_stress.go @@ -0,0 +1,44 @@ +package main + +import ( + "flag" + "fmt" + "os" + "runtime/pprof" + + "github.com/influxdb/influxdb/stress" +) + +var ( + //database = flag.String("database", "", "name of database") + //address = flag.String("addr", "", "IP address and port of database (e.g., localhost:8086)") + + config = flag.String("config", "", "The stress test file") + cpuprofile = flag.String("cpuprofile", "", "Write the cpu profile to `filename`") +) + +func main() { + + flag.Parse() + + if *cpuprofile != "" { + f, err := os.Create(*cpuprofile) + if err != nil { + fmt.Println(err) + return + } + pprof.StartCPUProfile(f) + defer pprof.StopCPUProfile() + } + + c, err := stress.NewConfig(*config) + if err != nil { + fmt.Println(err) + return + } + + stress.Run(c) + + return + +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup.go new file mode 100644 index 00000000..c88652f7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup.go @@ -0,0 +1,170 @@ +package backup + +import ( + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log" + "net" + "os" + + "github.com/influxdb/influxdb/services/snapshotter" + "github.com/influxdb/influxdb/snapshot" +) + +// Suffix is a suffix added to the backup while it's in-process. +const Suffix = ".pending" + +// Command represents the program execution for "influxd backup". +type Command struct { + // The logger passed to the ticker during execution. + Logger *log.Logger + + // Standard input/output, overridden for testing. + Stderr io.Writer +} + +// NewCommand returns a new instance of Command with default settings. +func NewCommand() *Command { + return &Command{ + Stderr: os.Stderr, + } +} + +// Run executes the program. +func (cmd *Command) Run(args ...string) error { + // Set up logger. + cmd.Logger = log.New(cmd.Stderr, "", log.LstdFlags) + cmd.Logger.Printf("influxdb backup") + + // Parse command line arguments. + host, path, err := cmd.parseFlags(args) + if err != nil { + return err + } + + // Retrieve snapshot from local file. + m, err := snapshot.ReadFileManifest(path) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("read file snapshot: %s", err) + } + + // Determine temporary path to download to. + tmppath := path + Suffix + + // Calculate path of next backup file. + // This uses the path if it doesn't exist. + // Otherwise it appends an autoincrementing number. + path, err = cmd.nextPath(path) + if err != nil { + return fmt.Errorf("next path: %s", err) + } + + // Retrieve snapshot. + if err := cmd.download(host, m, tmppath); err != nil { + return fmt.Errorf("download: %s", err) + } + + // Rename temporary file to final path. + if err := os.Rename(tmppath, path); err != nil { + return fmt.Errorf("rename: %s", err) + } + + // TODO: Check file integrity. + + // Notify user of completion. + cmd.Logger.Println("backup complete") + + return nil +} + +// parseFlags parses and validates the command line arguments. +func (cmd *Command) parseFlags(args []string) (host string, path string, err error) { + fs := flag.NewFlagSet("", flag.ContinueOnError) + fs.StringVar(&host, "host", "localhost:8088", "") + fs.SetOutput(cmd.Stderr) + fs.Usage = cmd.printUsage + if err := fs.Parse(args); err != nil { + return "", "", err + } + + // Ensure that only one arg is specified. + if fs.NArg() == 0 { + return "", "", errors.New("snapshot path required") + } else if fs.NArg() != 1 { + return "", "", errors.New("only one snapshot path allowed") + } + path = fs.Arg(0) + + return host, path, nil +} + +// nextPath returns the next file to write to. +func (cmd *Command) nextPath(path string) (string, error) { + // Use base path if it doesn't exist. + if _, err := os.Stat(path); os.IsNotExist(err) { + return path, nil + } else if err != nil { + return "", err + } + + // Otherwise iterate through incremental files until one is available. + for i := 0; ; i++ { + s := fmt.Sprintf(path+".%d", i) + if _, err := os.Stat(s); os.IsNotExist(err) { + return s, nil + } else if err != nil { + return "", err + } + } +} + +// download downloads a snapshot from a host to a given path. +func (cmd *Command) download(host string, m *snapshot.Manifest, path string) error { + // Create local file to write to. + f, err := os.Create(path) + if err != nil { + return fmt.Errorf("open temp file: %s", err) + } + defer f.Close() + + // Connect to snapshotter service. + conn, err := net.Dial("tcp", host) + if err != nil { + return err + } + defer conn.Close() + + // Send snapshotter marker byte. + if _, err := conn.Write([]byte{snapshotter.MuxHeader}); err != nil { + return fmt.Errorf("write snapshot header byte: %s", err) + } + + // Write the manifest we currently have. + if err := json.NewEncoder(conn).Encode(m); err != nil { + return fmt.Errorf("encode snapshot manifest: %s", err) + } + + // Read snapshot from the connection. + if _, err := io.Copy(f, conn); err != nil { + return fmt.Errorf("copy snapshot to file: %s", err) + } + + // FIXME(benbjohnson): Verify integrity of snapshot. + + return nil +} + +// printUsage prints the usage message to STDERR. +func (cmd *Command) printUsage() { + fmt.Fprintf(cmd.Stderr, `usage: influxd backup [flags] PATH + +backup downloads a snapshot of a data node and saves it to disk. + + -host + The host to connect to snapshot. + Defaults to 127.0.0.1:8088. +`) +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup_test.go new file mode 100644 index 00000000..15db9644 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/backup/backup_test.go @@ -0,0 +1,125 @@ +package backup_test + +/* +import ( + "bytes" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/influxdb/influxdb" + "github.com/influxdb/influxdb/cmd/influxd" +) + +// Ensure the backup can download from the server and save to disk. +func TestBackupCommand(t *testing.T) { + // Mock the backup endpoint. + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/data/snapshot" { + t.Fatalf("unexpected url path: %s", r.URL.Path) + } + + // Write a simple snapshot to the buffer. + sw := influxdb.NewSnapshotWriter() + sw.Snapshot = &influxdb.Snapshot{Files: []influxdb.SnapshotFile{ + {Name: "meta", Size: 5, Index: 10}, + }} + sw.FileWriters["meta"] = influxdb.NopWriteToCloser(bytes.NewBufferString("55555")) + if _, err := sw.WriteTo(w); err != nil { + t.Fatal(err) + } + })) + defer s.Close() + + // Create a temp path and remove incremental backups at the end. + path := tempfile() + defer os.Remove(path) + defer os.Remove(path + ".0") + defer os.Remove(path + ".1") + + // Execute the backup against the mock server. + for i := 0; i < 3; i++ { + if err := NewBackupCommand().Run("-host", s.URL, path); err != nil { + t.Fatal(err) + } + } + + // Verify snapshot and two incremental snapshots were written. + if _, err := os.Stat(path); err != nil { + t.Fatalf("snapshot not found: %s", err) + } else if _, err = os.Stat(path + ".0"); err != nil { + t.Fatalf("incremental snapshot(0) not found: %s", err) + } else if _, err = os.Stat(path + ".1"); err != nil { + t.Fatalf("incremental snapshot(1) not found: %s", err) + } +} + +// Ensure the backup command returns an error if flags cannot be parsed. +func TestBackupCommand_ErrFlagParse(t *testing.T) { + cmd := NewBackupCommand() + if err := cmd.Run("-bad-flag"); err == nil || err.Error() != `flag provided but not defined: -bad-flag` { + t.Fatal(err) + } else if !strings.Contains(cmd.Stderr.String(), "usage") { + t.Fatal("usage message not displayed") + } +} + +// Ensure the backup command returns an error if the host cannot be parsed. +func TestBackupCommand_ErrInvalidHostURL(t *testing.T) { + if err := NewBackupCommand().Run("-host", "http://%f"); err == nil || err.Error() != `parse host url: parse http://%f: hexadecimal escape in host` { + t.Fatal(err) + } +} + +// Ensure the backup command returns an error if the output path is not specified. +func TestBackupCommand_ErrPathRequired(t *testing.T) { + if err := NewBackupCommand().Run("-host", "//localhost"); err == nil || err.Error() != `snapshot path required` { + t.Fatal(err) + } +} + +// Ensure the backup returns an error if it cannot connect to the server. +func TestBackupCommand_ErrConnectionRefused(t *testing.T) { + // Start and immediately stop a server so we have a dead port. + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + s.Close() + + // Execute the backup command. + path := tempfile() + defer os.Remove(path) + if err := NewBackupCommand().Run("-host", s.URL, path); err == nil || + !(strings.Contains(err.Error(), `connection refused`) || strings.Contains(err.Error(), `No connection could be made`)) { + t.Fatal(err) + } +} + +// Ensure the backup returns any non-200 status codes. +func TestBackupCommand_ErrServerError(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer s.Close() + + // Execute the backup command. + path := tempfile() + defer os.Remove(path) + if err := NewBackupCommand().Run("-host", s.URL, path); err == nil || err.Error() != `download: snapshot error: status=500` { + t.Fatal(err) + } +} + +// BackupCommand is a test wrapper for main.BackupCommand. +type BackupCommand struct { + *main.BackupCommand + Stderr bytes.Buffer +} + +// NewBackupCommand returns a new instance of BackupCommand. +func NewBackupCommand() *BackupCommand { + cmd := &BackupCommand{BackupCommand: main.NewBackupCommand()} + cmd.BackupCommand.Stderr = &cmd.Stderr + return cmd +} +*/ diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/help/help.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/help/help.go new file mode 100644 index 00000000..3f6bbfb0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/help/help.go @@ -0,0 +1,46 @@ +package help + +import ( + "fmt" + "io" + "os" + "strings" +) + +// Command displays help for command-line sub-commands. +type Command struct { + Stdout io.Writer +} + +// NewCommand returns a new instance of Command. +func NewCommand() *Command { + return &Command{ + Stdout: os.Stdout, + } +} + +// Run executes the command. +func (cmd *Command) Run(args ...string) error { + fmt.Fprintln(cmd.Stdout, strings.TrimSpace(usage)) + return nil +} + +const usage = ` +Configure and start an InfluxDB server. + +Usage: + + influxd [[command] [arguments]] + +The commands are: + + backup downloads a snapshot of a data node and saves it to disk + config display the default configuration + restore uses a snapshot of a data node to rebuild a cluster + run run node with existing configuration + version displays the InfluxDB version + +"run" is the default command. + +Use "influxd help [command]" for more information about a command. +` diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/main.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/main.go new file mode 100644 index 00000000..b528e39d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/main.go @@ -0,0 +1,205 @@ +package main + +import ( + "flag" + "fmt" + "io" + "log" + "math/rand" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/influxdb/influxdb/cmd/influxd/backup" + "github.com/influxdb/influxdb/cmd/influxd/help" + "github.com/influxdb/influxdb/cmd/influxd/restore" + "github.com/influxdb/influxdb/cmd/influxd/run" +) + +// These variables are populated via the Go linker. +var ( + version = "0.9" + commit string + branch string + buildTime string +) + +func init() { + // If commit, branch, or build time are not set, make that clear. + if commit == "" { + commit = "unknown" + } + if branch == "" { + branch = "unknown" + } + if buildTime == "" { + buildTime = "unknown" + } +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + m := NewMain() + if err := m.Run(os.Args[1:]...); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +// Main represents the program execution. +type Main struct { + Logger *log.Logger + + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewMain return a new instance of Main. +func NewMain() *Main { + return &Main{ + Logger: log.New(os.Stderr, "[run] ", log.LstdFlags), + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run determines and runs the command specified by the CLI args. +func (m *Main) Run(args ...string) error { + name, args := ParseCommandName(args) + + // Extract name from args. + switch name { + case "", "run": + cmd := run.NewCommand() + + // Tell the server the build details. + cmd.Version = version + cmd.Commit = commit + cmd.Branch = branch + cmd.BuildTime = buildTime + + if err := cmd.Run(args...); err != nil { + return fmt.Errorf("run: %s", err) + } + + signalCh := make(chan os.Signal, 1) + signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) + m.Logger.Println("Listening for signals") + + // Block until one of the signals above is received + select { + case <-signalCh: + m.Logger.Println("Signal received, initializing clean shutdown...") + go func() { + cmd.Close() + }() + } + + // Block again until another signal is received, a shutdown timeout elapses, + // or the Command is gracefully closed + m.Logger.Println("Waiting for clean shutdown...") + select { + case <-signalCh: + m.Logger.Println("second signal received, initializing hard shutdown") + case <-time.After(time.Second * 30): + m.Logger.Println("time limit reached, initializing hard shutdown") + case <-cmd.Closed: + m.Logger.Println("server shutdown completed") + } + + // goodbye. + + case "backup": + name := backup.NewCommand() + if err := name.Run(args...); err != nil { + return fmt.Errorf("backup: %s", err) + } + case "restore": + name := restore.NewCommand() + if err := name.Run(args...); err != nil { + return fmt.Errorf("restore: %s", err) + } + case "config": + if err := run.NewPrintConfigCommand().Run(args...); err != nil { + return fmt.Errorf("config: %s", err) + } + case "version": + if err := NewVersionCommand().Run(args...); err != nil { + return fmt.Errorf("version: %s", err) + } + case "help": + if err := help.NewCommand().Run(args...); err != nil { + return fmt.Errorf("help: %s", err) + } + default: + return fmt.Errorf(`unknown command "%s"`+"\n"+`Run 'influxd help' for usage`+"\n\n", name) + } + + return nil +} + +// ParseCommandName extracts the command name and args from the args list. +func ParseCommandName(args []string) (string, []string) { + // Retrieve command name as first argument. + var name string + if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + name = args[0] + } + + // Special case -h immediately following binary name + if len(args) > 0 && args[0] == "-h" { + name = "help" + } + + // If command is "help" and has an argument then rewrite args to use "-h". + if name == "help" && len(args) > 1 { + args[0], args[1] = args[1], "-h" + name = args[0] + } + + // If a named command is specified then return it with its arguments. + if name != "" { + return name, args[1:] + } + return "", args +} + +// VersionCommand represents the command executed by "influxd version". +type VersionCommand struct { + Stdout io.Writer + Stderr io.Writer +} + +// NewVersionCommand return a new instance of VersionCommand. +func NewVersionCommand() *VersionCommand { + return &VersionCommand{ + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run prints the current version and commit info. +func (cmd *VersionCommand) Run(args ...string) error { + // Parse flags in case -h is specified. + fs := flag.NewFlagSet("", flag.ContinueOnError) + fs.Usage = func() { fmt.Fprintln(cmd.Stderr, strings.TrimSpace(versionUsage)) } + if err := fs.Parse(args); err != nil { + return err + } + + // Print version info. + fmt.Fprintf(cmd.Stdout, "InfluxDB v%s (git: %s %s, built %s)\n", version, branch, commit, buildTime) + + return nil +} + +var versionUsage = ` +usage: version + + version displays the InfluxDB version, build branch and git commit hash +` diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore.go new file mode 100644 index 00000000..4d22916f --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore.go @@ -0,0 +1,260 @@ +package restore + +import ( + "bytes" + "errors" + "flag" + "fmt" + "io" + "net" + "os" + "path/filepath" + + "github.com/BurntSushi/toml" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/snapshot" + "github.com/influxdb/influxdb/tsdb" +) + +// Command represents the program execution for "influxd restore". +type Command struct { + Stdout io.Writer + Stderr io.Writer +} + +// NewCommand returns a new instance of Command with default settings. +func NewCommand() *Command { + return &Command{ + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run executes the program. +func (cmd *Command) Run(args ...string) error { + config, path, err := cmd.parseFlags(args) + if err != nil { + return err + } + + return cmd.Restore(config, path) +} + +// Restore restores a database snapshot +func (cmd *Command) Restore(config *Config, path string) error { + // Remove meta and data directories. + if err := os.RemoveAll(config.Meta.Dir); err != nil { + return fmt.Errorf("remove meta dir: %s", err) + } else if err := os.RemoveAll(config.Data.Dir); err != nil { + return fmt.Errorf("remove data dir: %s", err) + } + + // Open snapshot file and all incremental backups. + mr, files, err := snapshot.OpenFileMultiReader(path) + if err != nil { + return fmt.Errorf("open multireader: %s", err) + } + defer closeAll(files) + + // Unpack files from archive. + if err := cmd.unpack(mr, config); err != nil { + return fmt.Errorf("unpack: %s", err) + } + + // Notify user of completion. + fmt.Fprintf(os.Stdout, "restore complete using %s", path) + return nil +} + +// parseFlags parses and validates the command line arguments. +func (cmd *Command) parseFlags(args []string) (*Config, string, error) { + fs := flag.NewFlagSet("", flag.ContinueOnError) + configPath := fs.String("config", "", "") + fs.SetOutput(cmd.Stderr) + fs.Usage = cmd.printUsage + if err := fs.Parse(args); err != nil { + return nil, "", err + } + + // Parse configuration file from disk. + if *configPath == "" { + return nil, "", fmt.Errorf("config required") + } + + // Parse config. + config := Config{ + Meta: meta.NewConfig(), + Data: tsdb.NewConfig(), + } + if _, err := toml.DecodeFile(*configPath, &config); err != nil { + return nil, "", err + } + + // Require output path. + path := fs.Arg(0) + if path == "" { + return nil, "", fmt.Errorf("snapshot path required") + } + + return &config, path, nil +} + +func closeAll(a []io.Closer) { + for _, c := range a { + _ = c.Close() + } +} + +// unpack expands the files in the snapshot archive into a directory. +func (cmd *Command) unpack(mr *snapshot.MultiReader, config *Config) error { + // Loop over files and extract. + for { + // Read entry header. + sf, err := mr.Next() + if err == io.EOF { + break + } else if err != nil { + return fmt.Errorf("next: entry=%s, err=%s", sf.Name, err) + } + + // Log progress. + fmt.Fprintf(os.Stdout, "unpacking: %s (%d bytes)\n", sf.Name, sf.Size) + + // Handle meta and tsdb files separately. + switch sf.Name { + case "meta": + if err := cmd.unpackMeta(mr, sf, config); err != nil { + return fmt.Errorf("meta: %s", err) + } + default: + if err := cmd.unpackData(mr, sf, config); err != nil { + return fmt.Errorf("data: %s", err) + } + } + } + + return nil +} + +// unpackMeta reads the metadata from the snapshot and initializes a raft +// cluster and replaces the root metadata. +func (cmd *Command) unpackMeta(mr *snapshot.MultiReader, sf snapshot.File, config *Config) error { + // Read meta into buffer. + var buf bytes.Buffer + if _, err := io.CopyN(&buf, mr, sf.Size); err != nil { + return fmt.Errorf("copy: %s", err) + } + + // Unpack into metadata. + var data meta.Data + if err := data.UnmarshalBinary(buf.Bytes()); err != nil { + return fmt.Errorf("unmarshal: %s", err) + } + + // Copy meta config and remove peers so it starts in single mode. + c := config.Meta + c.Peers = nil + + // Initialize meta store. + store := meta.NewStore(config.Meta) + store.RaftListener = newNopListener() + store.ExecListener = newNopListener() + store.RPCListener = newNopListener() + + // Determine advertised address. + _, port, err := net.SplitHostPort(config.Meta.BindAddress) + if err != nil { + return fmt.Errorf("split bind address: %s", err) + } + hostport := net.JoinHostPort(config.Meta.Hostname, port) + + // Resolve address. + addr, err := net.ResolveTCPAddr("tcp", hostport) + if err != nil { + return fmt.Errorf("resolve tcp: addr=%s, err=%s", hostport, err) + } + store.Addr = addr + store.RemoteAddr = addr + + // Open the meta store. + if err := store.Open(); err != nil { + return fmt.Errorf("open store: %s", err) + } + defer store.Close() + + // Wait for the store to be ready or error. + select { + case <-store.Ready(): + case err := <-store.Err(): + return err + } + + // Force set the full metadata. + if err := store.SetData(&data); err != nil { + return fmt.Errorf("set data: %s", err) + } + + return nil +} + +func (cmd *Command) unpackData(mr *snapshot.MultiReader, sf snapshot.File, config *Config) error { + path := filepath.Join(config.Data.Dir, sf.Name) + // Create parent directory for output file. + if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil { + return fmt.Errorf("mkdir: entry=%s, err=%s", sf.Name, err) + } + + // Create output file. + f, err := os.Create(path) + if err != nil { + return fmt.Errorf("create: entry=%s, err=%s", sf.Name, err) + } + defer f.Close() + + // Copy contents from reader. + if _, err := io.CopyN(f, mr, sf.Size); err != nil { + return fmt.Errorf("copy: entry=%s, err=%s", sf.Name, err) + } + + return nil +} + +// printUsage prints the usage message to STDERR. +func (cmd *Command) printUsage() { + fmt.Fprintf(cmd.Stderr, `usage: influxd restore [flags] PATH + +restore uses a snapshot of a data node to rebuild a cluster. + + -config + Set the path to the configuration file. +`) +} + +// Config represents a partial config for rebuilding the server. +type Config struct { + Meta *meta.Config `toml:"meta"` + Data tsdb.Config `toml:"data"` +} + +type nopListener struct { + closing chan struct{} +} + +func newNopListener() *nopListener { + return &nopListener{make(chan struct{})} +} + +func (ln *nopListener) Accept() (net.Conn, error) { + <-ln.closing + return nil, errors.New("listener closing") +} + +func (ln *nopListener) Close() error { + if ln.closing != nil { + close(ln.closing) + ln.closing = nil + } + return nil +} + +func (ln *nopListener) Addr() net.Addr { return nil } diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore_test.go new file mode 100644 index 00000000..f9d97421 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/restore/restore_test.go @@ -0,0 +1,155 @@ +package restore_test + +/* +import ( + "bytes" + "io/ioutil" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + main "github.com/influxdb/influxdb/cmd/influxd" + "github.com/influxdb/influxdb/tsdb" +) + +func newConfig(path string, port int) main.Config { + config := main.NewConfig() + config.Port = port + config.Broker.Enabled = true + config.Broker.Dir = filepath.Join(path, "broker") + + config.Data.Enabled = true + config.Data.Dir = filepath.Join(path, "data") + return *config +} + +// Ensure the restore command can expand a snapshot and bootstrap a broker. +func TestRestoreCommand(t *testing.T) { + if testing.Short() { + t.Skip("skipping TestRestoreCommand") + } + + now := time.Now() + + // Create root path to server. + path := tempfile() + defer os.Remove(path) + + // Parse configuration. + config := newConfig(path, 8900) + + // Start server. + cmd := main.NewRunCommand() + node := cmd.Open(&config, "") + if node.Broker == nil { + t.Fatal("cannot run broker") + } else if node.DataNode == nil { + t.Fatal("cannot run server") + } + b := node.Broker + s := node.DataNode + + // Create data. + if err := s.CreateDatabase("db"); err != nil { + t.Fatalf("cannot create database: %s", err) + } + if index, err := s.WriteSeries("db", "default", []models.Point{tsdb.NewPoint("cpu", nil, map[string]interface{}{"value": float64(100)}, now)}); err != nil { + t.Fatalf("cannot write series: %s", err) + } else if err = s.Sync(1, index); err != nil { + t.Fatalf("shard sync: %s", err) + } + + // Create snapshot writer. + sw, err := s.CreateSnapshotWriter() + if err != nil { + t.Fatalf("create snapshot writer: %s", err) + } + + // Snapshot to file. + sspath := tempfile() + f, err := os.Create(sspath) + if err != nil { + t.Fatal(err) + } + sw.WriteTo(f) + f.Close() + + // Stop server. + node.Close() + + // Remove data & broker directories. + if err := os.RemoveAll(path); err != nil { + t.Fatalf("remove: %s", err) + } + + // Execute the restore. + if err := NewRestoreCommand().Restore(&config, sspath); err != nil { + t.Fatal(err) + } + + // Rewrite config to a new port and re-parse. + config = newConfig(path, 8910) + + // Restart server. + cmd = main.NewRunCommand() + node = cmd.Open(&config, "") + if b == nil { + t.Fatal("cannot run broker") + } else if s == nil { + t.Fatal("cannot run server") + } + b = node.Broker + s = node.DataNode + + // Write new data. + if err := s.CreateDatabase("newdb"); err != nil { + t.Fatalf("cannot create new database: %s", err) + } + if index, err := s.WriteSeries("newdb", "default", []models.Point{tsdb.NewPoint("mem", nil, map[string]interface{}{"value": float64(1000)}, now)}); err != nil { + t.Fatalf("cannot write new series: %s", err) + } else if err = s.Sync(2, index); err != nil { + t.Fatalf("shard sync: %s", err) + } + + // Read series data. + if v, err := s.ReadSeries("db", "default", "cpu", nil, now); err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(v, map[string]interface{}{"value": float64(100)}) { + t.Fatalf("read series(0) mismatch: %#v", v) + } + + // Read new series data. + if v, err := s.ReadSeries("newdb", "default", "mem", nil, now); err != nil { + t.Fatal(err) + } else if !reflect.DeepEqual(v, map[string]interface{}{"value": float64(1000)}) { + t.Fatalf("read series(1) mismatch: %#v", v) + } + + // Stop server. + node.Close() +} + +// RestoreCommand is a test wrapper for main.RestoreCommand. +type RestoreCommand struct { + *main.RestoreCommand + Stderr bytes.Buffer +} + +// NewRestoreCommand returns a new instance of RestoreCommand. +func NewRestoreCommand() *RestoreCommand { + cmd := &RestoreCommand{RestoreCommand: main.NewRestoreCommand()} + cmd.RestoreCommand.Stderr = &cmd.Stderr + return cmd +} + +// MustReadFile reads data from a file. Panic on error. +func MustReadFile(filename string) []byte { + b, err := ioutil.ReadFile(filename) + if err != nil { + panic(err.Error()) + } + return b +} +*/ diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/command.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/command.go new file mode 100644 index 00000000..f9a4561d --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/command.go @@ -0,0 +1,243 @@ +package run + +import ( + "flag" + "fmt" + "io" + "io/ioutil" + "log" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" + + "github.com/BurntSushi/toml" +) + +const logo = ` + 8888888 .d888 888 8888888b. 888888b. + 888 d88P" 888 888 "Y88b 888 "88b + 888 888 888 888 888 888 .88P + 888 88888b. 888888 888 888 888 888 888 888 888 8888888K. + 888 888 "88b 888 888 888 888 Y8bd8P' 888 888 888 "Y88b + 888 888 888 888 888 888 888 X88K 888 888 888 888 + 888 888 888 888 888 Y88b 888 .d8""8b. 888 .d88P 888 d88P + 8888888 888 888 888 888 "Y88888 888 888 8888888P" 8888888P" + +` + +// Command represents the command executed by "influxd run". +type Command struct { + Version string + Branch string + Commit string + BuildTime string + + closing chan struct{} + Closed chan struct{} + + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer + + Server *Server +} + +// NewCommand return a new instance of Command. +func NewCommand() *Command { + return &Command{ + closing: make(chan struct{}), + Closed: make(chan struct{}), + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run parses the config from args and runs the server. +func (cmd *Command) Run(args ...string) error { + // Parse the command line flags. + options, err := cmd.ParseFlags(args...) + if err != nil { + return err + } + + // Print sweet InfluxDB logo. + fmt.Print(logo) + + // Set parallelism. + runtime.GOMAXPROCS(runtime.NumCPU()) + + // Mark start-up in log. + log.Printf("InfluxDB starting, version %s, branch %s, commit %s, built %s", + cmd.Version, cmd.Branch, cmd.Commit, cmd.BuildTime) + log.Printf("Go version %s, GOMAXPROCS set to %d", runtime.Version(), runtime.GOMAXPROCS(0)) + + // Write the PID file. + if err := cmd.writePIDFile(options.PIDFile); err != nil { + return fmt.Errorf("write pid file: %s", err) + } + + // Turn on block profiling to debug stuck databases + runtime.SetBlockProfileRate(int(1 * time.Second)) + + // Parse config + config, err := cmd.ParseConfig(options.ConfigPath) + if err != nil { + return fmt.Errorf("parse config: %s", err) + } + + // Apply any environment variables on top of the parsed config + if err := config.ApplyEnvOverrides(); err != nil { + return fmt.Errorf("apply env config: %v", err) + } + + // Override config hostname if specified in the command line args. + if options.Hostname != "" { + config.Meta.Hostname = options.Hostname + } + + if options.Join != "" { + config.Meta.Peers = strings.Split(options.Join, ",") + } + + // Validate the configuration. + if err := config.Validate(); err != nil { + return fmt.Errorf("%s. To generate a valid configuration file run `influxd config > influxdb.generated.conf`", err) + } + + // Create server from config and start it. + buildInfo := &BuildInfo{ + Version: cmd.Version, + Commit: cmd.Commit, + Branch: cmd.Branch, + Time: cmd.BuildTime, + } + s, err := NewServer(config, buildInfo) + if err != nil { + return fmt.Errorf("create server: %s", err) + } + s.CPUProfile = options.CPUProfile + s.MemProfile = options.MemProfile + if err := s.Open(); err != nil { + return fmt.Errorf("open server: %s", err) + } + cmd.Server = s + + // Begin monitoring the server's error channel. + go cmd.monitorServerErrors() + + return nil +} + +// Close shuts down the server. +func (cmd *Command) Close() error { + defer close(cmd.Closed) + close(cmd.closing) + if cmd.Server != nil { + return cmd.Server.Close() + } + return nil +} + +func (cmd *Command) monitorServerErrors() { + logger := log.New(cmd.Stderr, "", log.LstdFlags) + for { + select { + case err := <-cmd.Server.Err(): + logger.Println(err) + case <-cmd.closing: + return + } + } +} + +// ParseFlags parses the command line flags from args and returns an options set. +func (cmd *Command) ParseFlags(args ...string) (Options, error) { + var options Options + fs := flag.NewFlagSet("", flag.ContinueOnError) + fs.StringVar(&options.ConfigPath, "config", "", "") + fs.StringVar(&options.PIDFile, "pidfile", "", "") + fs.StringVar(&options.Hostname, "hostname", "", "") + fs.StringVar(&options.Join, "join", "", "") + fs.StringVar(&options.CPUProfile, "cpuprofile", "", "") + fs.StringVar(&options.MemProfile, "memprofile", "", "") + fs.Usage = func() { fmt.Fprintln(cmd.Stderr, usage) } + if err := fs.Parse(args); err != nil { + return Options{}, err + } + return options, nil +} + +// writePIDFile writes the process ID to path. +func (cmd *Command) writePIDFile(path string) error { + // Ignore if path is not set. + if path == "" { + return nil + } + + // Ensure the required directory structure exists. + err := os.MkdirAll(filepath.Dir(path), 0777) + if err != nil { + return fmt.Errorf("mkdir: %s", err) + } + + // Retrieve the PID and write it. + pid := strconv.Itoa(os.Getpid()) + if err := ioutil.WriteFile(path, []byte(pid), 0666); err != nil { + return fmt.Errorf("write file: %s", err) + } + + return nil +} + +// ParseConfig parses the config at path. +// Returns a demo configuration if path is blank. +func (cmd *Command) ParseConfig(path string) (*Config, error) { + // Use demo configuration if no config path is specified. + if path == "" { + log.Println("no configuration provided, using default settings") + return NewDemoConfig() + } + + log.Printf("Using configuration at: %s\n", path) + + config := NewConfig() + if _, err := toml.DecodeFile(path, &config); err != nil { + return nil, err + } + + return config, nil +} + +var usage = `usage: run [flags] + +run starts the broker and data node server. If this is the first time running +the command then a new cluster will be initialized unless the -join argument +is used. + + -config + Set the path to the configuration file. + + -hostname + Override the hostname, the 'hostname' configuration + option will be overridden. + + -join + Joins the server to an existing cluster. + + -pidfile + Write process ID to a file. +` + +// Options represents the command line options that can be parsed. +type Options struct { + ConfigPath string + PIDFile string + Hostname string + Join string + CPUProfile string + MemProfile string +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config.go new file mode 100644 index 00000000..92474baa --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config.go @@ -0,0 +1,233 @@ +package run + +import ( + "errors" + "fmt" + "os" + "os/user" + "path/filepath" + "reflect" + "strconv" + "strings" + "time" + + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/monitor" + "github.com/influxdb/influxdb/services/admin" + "github.com/influxdb/influxdb/services/collectd" + "github.com/influxdb/influxdb/services/continuous_querier" + "github.com/influxdb/influxdb/services/graphite" + "github.com/influxdb/influxdb/services/hh" + "github.com/influxdb/influxdb/services/httpd" + "github.com/influxdb/influxdb/services/opentsdb" + "github.com/influxdb/influxdb/services/precreator" + "github.com/influxdb/influxdb/services/registration" + "github.com/influxdb/influxdb/services/retention" + "github.com/influxdb/influxdb/services/subscriber" + "github.com/influxdb/influxdb/services/udp" + "github.com/influxdb/influxdb/tsdb" +) + +// Config represents the configuration format for the influxd binary. +type Config struct { + Meta *meta.Config `toml:"meta"` + Data tsdb.Config `toml:"data"` + Cluster cluster.Config `toml:"cluster"` + Retention retention.Config `toml:"retention"` + Registration registration.Config `toml:"registration"` + Precreator precreator.Config `toml:"shard-precreation"` + + Admin admin.Config `toml:"admin"` + Monitor monitor.Config `toml:"monitor"` + Subscriber subscriber.Config `toml:"subscriber"` + HTTPD httpd.Config `toml:"http"` + Graphites []graphite.Config `toml:"graphite"` + Collectd collectd.Config `toml:"collectd"` + OpenTSDB opentsdb.Config `toml:"opentsdb"` + UDPs []udp.Config `toml:"udp"` + + // Snapshot SnapshotConfig `toml:"snapshot"` + ContinuousQuery continuous_querier.Config `toml:"continuous_queries"` + + HintedHandoff hh.Config `toml:"hinted-handoff"` + + // Server reporting + ReportingDisabled bool `toml:"reporting-disabled"` +} + +// NewConfig returns an instance of Config with reasonable defaults. +func NewConfig() *Config { + c := &Config{} + c.Meta = meta.NewConfig() + c.Data = tsdb.NewConfig() + c.Cluster = cluster.NewConfig() + c.Registration = registration.NewConfig() + c.Precreator = precreator.NewConfig() + + c.Admin = admin.NewConfig() + c.Monitor = monitor.NewConfig() + c.Subscriber = subscriber.NewConfig() + c.HTTPD = httpd.NewConfig() + c.Collectd = collectd.NewConfig() + c.OpenTSDB = opentsdb.NewConfig() + + c.ContinuousQuery = continuous_querier.NewConfig() + c.Retention = retention.NewConfig() + c.HintedHandoff = hh.NewConfig() + + return c +} + +// NewDemoConfig returns the config that runs when no config is specified. +func NewDemoConfig() (*Config, error) { + c := NewConfig() + + var homeDir string + // By default, store meta and data files in current users home directory + u, err := user.Current() + if err == nil { + homeDir = u.HomeDir + } else if os.Getenv("HOME") != "" { + homeDir = os.Getenv("HOME") + } else { + return nil, fmt.Errorf("failed to determine current user for storage") + } + + c.Meta.Dir = filepath.Join(homeDir, ".influxdb/meta") + c.Data.Dir = filepath.Join(homeDir, ".influxdb/data") + c.HintedHandoff.Dir = filepath.Join(homeDir, ".influxdb/hh") + c.Data.WALDir = filepath.Join(homeDir, ".influxdb/wal") + + c.HintedHandoff.Enabled = true + c.Admin.Enabled = true + + return c, nil +} + +// Validate returns an error if the config is invalid. +func (c *Config) Validate() error { + if c.Meta.Dir == "" { + return errors.New("Meta.Dir must be specified") + } else if c.HintedHandoff.Enabled && c.HintedHandoff.Dir == "" { + return errors.New("HintedHandoff.Dir must be specified") + } + + if err := c.Data.Validate(); err != nil { + return err + } + + for _, g := range c.Graphites { + if err := g.Validate(); err != nil { + return fmt.Errorf("invalid graphite config: %v", err) + } + } + return nil +} + +// ApplyEnvOverrides apply the environment configuration on top of the config. +func (c *Config) ApplyEnvOverrides() error { + return c.applyEnvOverrides("INFLUXDB", reflect.ValueOf(c)) +} + +func (c *Config) applyEnvOverrides(prefix string, spec reflect.Value) error { + // If we have a pointer, dereference it + s := spec + if spec.Kind() == reflect.Ptr { + s = spec.Elem() + } + + // Make sure we have struct + if s.Kind() != reflect.Struct { + return nil + } + + typeOfSpec := s.Type() + for i := 0; i < s.NumField(); i++ { + f := s.Field(i) + // Get the toml tag to determine what env var name to use + configName := typeOfSpec.Field(i).Tag.Get("toml") + // Replace hyphens with underscores to avoid issues with shells + configName = strings.Replace(configName, "-", "_", -1) + fieldKey := typeOfSpec.Field(i).Name + + // Skip any fields that we cannot set + if f.CanSet() || f.Kind() == reflect.Slice { + + // Use the upper-case prefix and toml name for the env var + key := strings.ToUpper(configName) + if prefix != "" { + key = strings.ToUpper(fmt.Sprintf("%s_%s", prefix, configName)) + } + value := os.Getenv(key) + + // If the type is s slice, apply to each using the index as a suffix + // e.g. GRAPHITE_0 + if f.Kind() == reflect.Slice || f.Kind() == reflect.Array { + for i := 0; i < f.Len(); i++ { + if err := c.applyEnvOverrides(fmt.Sprintf("%s_%d", key, i), f.Index(i)); err != nil { + return err + } + } + continue + } + + // If it's a sub-config, recursively apply + if f.Kind() == reflect.Struct || f.Kind() == reflect.Ptr { + if err := c.applyEnvOverrides(key, f); err != nil { + return err + } + continue + } + + // Skip any fields we don't have a value to set + if value == "" { + continue + } + + switch f.Kind() { + case reflect.String: + f.SetString(value) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + + var intValue int64 + + // Handle toml.Duration + if f.Type().Name() == "Duration" { + dur, err := time.ParseDuration(value) + if err != nil { + return fmt.Errorf("failed to apply %v to %v using type %v and value '%v'", key, fieldKey, f.Type().String(), value) + } + intValue = dur.Nanoseconds() + } else { + var err error + intValue, err = strconv.ParseInt(value, 0, f.Type().Bits()) + if err != nil { + return fmt.Errorf("failed to apply %v to %v using type %v and value '%v'", key, fieldKey, f.Type().String(), value) + } + } + + f.SetInt(intValue) + case reflect.Bool: + boolValue, err := strconv.ParseBool(value) + if err != nil { + return fmt.Errorf("failed to apply %v to %v using type %v and value '%v'", key, fieldKey, f.Type().String(), value) + + } + f.SetBool(boolValue) + case reflect.Float32, reflect.Float64: + floatValue, err := strconv.ParseFloat(value, f.Type().Bits()) + if err != nil { + return fmt.Errorf("failed to apply %v to %v using type %v and value '%v'", key, fieldKey, f.Type().String(), value) + + } + f.SetFloat(floatValue) + default: + if err := c.applyEnvOverrides(key, f); err != nil { + return err + } + } + } + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_command.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_command.go new file mode 100644 index 00000000..7bb0d4e5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_command.go @@ -0,0 +1,83 @@ +package run + +import ( + "flag" + "fmt" + "io" + "os" + + "github.com/BurntSushi/toml" +) + +// PrintConfigCommand represents the command executed by "influxd config". +type PrintConfigCommand struct { + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// NewPrintConfigCommand return a new instance of PrintConfigCommand. +func NewPrintConfigCommand() *PrintConfigCommand { + return &PrintConfigCommand{ + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + } +} + +// Run parses and prints the current config loaded. +func (cmd *PrintConfigCommand) Run(args ...string) error { + // Parse command flags. + fs := flag.NewFlagSet("", flag.ContinueOnError) + configPath := fs.String("config", "", "") + hostname := fs.String("hostname", "", "") + fs.Usage = func() { fmt.Fprintln(cmd.Stderr, printConfigUsage) } + if err := fs.Parse(args); err != nil { + return err + } + + // Parse config from path. + config, err := cmd.parseConfig(*configPath) + if err != nil { + return fmt.Errorf("parse config: %s", err) + } + + // Apply any environment variables on top of the parsed config + if err := config.ApplyEnvOverrides(); err != nil { + return fmt.Errorf("apply env config: %v", err) + } + + // Override config properties. + if *hostname != "" { + config.Meta.Hostname = *hostname + } + + // Validate the configuration. + if err := config.Validate(); err != nil { + return fmt.Errorf("%s. To generate a valid configuration file run `influxd config > influxdb.generated.conf`", err) + } + + toml.NewEncoder(cmd.Stdout).Encode(config) + fmt.Fprint(cmd.Stdout, "\n") + + return nil +} + +// ParseConfig parses the config at path. +// Returns a demo configuration if path is blank. +func (cmd *PrintConfigCommand) parseConfig(path string) (*Config, error) { + if path == "" { + return NewDemoConfig() + } + + config := NewConfig() + if _, err := toml.DecodeFile(path, &config); err != nil { + return nil, err + } + return config, nil +} + +var printConfigUsage = `usage: config + + config displays the default configuration +` diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_test.go new file mode 100644 index 00000000..c3312ef9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/config_test.go @@ -0,0 +1,147 @@ +package run_test + +import ( + "os" + "testing" + + "github.com/BurntSushi/toml" + "github.com/influxdb/influxdb/cmd/influxd/run" +) + +// Ensure the configuration can be parsed. +func TestConfig_Parse(t *testing.T) { + // Parse configuration. + var c run.Config + if _, err := toml.Decode(` +[meta] +dir = "/tmp/meta" + +[data] +dir = "/tmp/data" + +[cluster] + +[admin] +bind-address = ":8083" + +[http] +bind-address = ":8087" + +[[graphite]] +protocol = "udp" + +[[graphite]] +protocol = "tcp" + +[collectd] +bind-address = ":1000" + +[opentsdb] +bind-address = ":2000" + +[[udp]] +bind-address = ":4444" + +[monitoring] +enabled = true + +[subscriber] +enabled = true + +[continuous_queries] +enabled = true +`, &c); err != nil { + t.Fatal(err) + } + + // Validate configuration. + if c.Meta.Dir != "/tmp/meta" { + t.Fatalf("unexpected meta dir: %s", c.Meta.Dir) + } else if c.Data.Dir != "/tmp/data" { + t.Fatalf("unexpected data dir: %s", c.Data.Dir) + } else if c.Admin.BindAddress != ":8083" { + t.Fatalf("unexpected admin bind address: %s", c.Admin.BindAddress) + } else if c.HTTPD.BindAddress != ":8087" { + t.Fatalf("unexpected api bind address: %s", c.HTTPD.BindAddress) + } else if len(c.Graphites) != 2 { + t.Fatalf("unexpected graphites count: %d", len(c.Graphites)) + } else if c.Graphites[0].Protocol != "udp" { + t.Fatalf("unexpected graphite protocol(0): %s", c.Graphites[0].Protocol) + } else if c.Graphites[1].Protocol != "tcp" { + t.Fatalf("unexpected graphite protocol(1): %s", c.Graphites[1].Protocol) + } else if c.Collectd.BindAddress != ":1000" { + t.Fatalf("unexpected collectd bind address: %s", c.Collectd.BindAddress) + } else if c.OpenTSDB.BindAddress != ":2000" { + t.Fatalf("unexpected opentsdb bind address: %s", c.OpenTSDB.BindAddress) + } else if c.UDPs[0].BindAddress != ":4444" { + t.Fatalf("unexpected udp bind address: %s", c.UDPs[0].BindAddress) + } else if c.Subscriber.Enabled != true { + t.Fatalf("unexpected subscriber enabled: %v", c.Subscriber.Enabled) + } else if c.ContinuousQuery.Enabled != true { + t.Fatalf("unexpected continuous query enabled: %v", c.ContinuousQuery.Enabled) + } +} + +// Ensure the configuration can be parsed. +func TestConfig_Parse_EnvOverride(t *testing.T) { + // Parse configuration. + var c run.Config + if _, err := toml.Decode(` +[meta] +dir = "/tmp/meta" + +[data] +dir = "/tmp/data" + +[cluster] + +[admin] +bind-address = ":8083" + +[http] +bind-address = ":8087" + +[[graphite]] +protocol = "udp" + +[[graphite]] +protocol = "tcp" + +[collectd] +bind-address = ":1000" + +[opentsdb] +bind-address = ":2000" + +[[udp]] +bind-address = ":4444" + +[monitoring] +enabled = true + +[continuous_queries] +enabled = true +`, &c); err != nil { + t.Fatal(err) + } + + if err := os.Setenv("INFLUXDB_UDP_BIND_ADDRESS", ":1234"); err != nil { + t.Fatalf("failed to set env var: %v", err) + } + + if err := os.Setenv("INFLUXDB_GRAPHITE_1_PROTOCOL", "udp"); err != nil { + t.Fatalf("failed to set env var: %v", err) + } + + if err := c.ApplyEnvOverrides(); err != nil { + t.Fatalf("failed to apply env overrides: %v", err) + } + + if c.UDPs[0].BindAddress != ":4444" { + t.Fatalf("unexpected udp bind address: %s", c.UDPs[0].BindAddress) + } + + if c.Graphites[1].Protocol != "udp" { + t.Fatalf("unexpected graphite protocol(0): %s", c.Graphites[0].Protocol) + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server.go new file mode 100644 index 00000000..e19b29cd --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server.go @@ -0,0 +1,646 @@ +package run + +import ( + "fmt" + "log" + "net" + "os" + "runtime" + "runtime/pprof" + "strings" + "time" + + "github.com/influxdb/enterprise-client/v1" + "github.com/influxdb/influxdb/cluster" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/monitor" + "github.com/influxdb/influxdb/services/admin" + "github.com/influxdb/influxdb/services/collectd" + "github.com/influxdb/influxdb/services/continuous_querier" + "github.com/influxdb/influxdb/services/copier" + "github.com/influxdb/influxdb/services/graphite" + "github.com/influxdb/influxdb/services/hh" + "github.com/influxdb/influxdb/services/httpd" + "github.com/influxdb/influxdb/services/opentsdb" + "github.com/influxdb/influxdb/services/precreator" + "github.com/influxdb/influxdb/services/registration" + "github.com/influxdb/influxdb/services/retention" + "github.com/influxdb/influxdb/services/snapshotter" + "github.com/influxdb/influxdb/services/subscriber" + "github.com/influxdb/influxdb/services/udp" + "github.com/influxdb/influxdb/tcp" + "github.com/influxdb/influxdb/tsdb" + // Initialize the engine packages + _ "github.com/influxdb/influxdb/tsdb/engine" +) + +// BuildInfo represents the build details for the server code. +type BuildInfo struct { + Version string + Commit string + Branch string + Time string +} + +// Server represents a container for the metadata and storage data and services. +// It is built using a Config and it manages the startup and shutdown of all +// services in the proper order. +type Server struct { + buildInfo BuildInfo + + err chan error + closing chan struct{} + + Hostname string + BindAddress string + Listener net.Listener + + MetaStore *meta.Store + TSDBStore *tsdb.Store + QueryExecutor *tsdb.QueryExecutor + PointsWriter *cluster.PointsWriter + ShardWriter *cluster.ShardWriter + ShardMapper *cluster.ShardMapper + HintedHandoff *hh.Service + Subscriber *subscriber.Service + + Services []Service + + // These references are required for the tcp muxer. + ClusterService *cluster.Service + SnapshotterService *snapshotter.Service + CopierService *copier.Service + + Monitor *monitor.Monitor + + // Server reporting and registration + reportingDisabled bool + + // Profiling + CPUProfile string + MemProfile string +} + +// NewServer returns a new instance of Server built from a config. +func NewServer(c *Config, buildInfo *BuildInfo) (*Server, error) { + // Construct base meta store and data store. + tsdbStore := tsdb.NewStore(c.Data.Dir) + tsdbStore.EngineOptions.Config = c.Data + + s := &Server{ + buildInfo: *buildInfo, + err: make(chan error), + closing: make(chan struct{}), + + Hostname: c.Meta.Hostname, + BindAddress: c.Meta.BindAddress, + + MetaStore: meta.NewStore(c.Meta), + TSDBStore: tsdbStore, + + Monitor: monitor.New(c.Monitor), + + reportingDisabled: c.ReportingDisabled, + } + + // Copy TSDB configuration. + s.TSDBStore.EngineOptions.EngineVersion = c.Data.Engine + s.TSDBStore.EngineOptions.MaxWALSize = c.Data.MaxWALSize + s.TSDBStore.EngineOptions.WALFlushInterval = time.Duration(c.Data.WALFlushInterval) + s.TSDBStore.EngineOptions.WALPartitionFlushDelay = time.Duration(c.Data.WALPartitionFlushDelay) + + // Set the shard mapper + s.ShardMapper = cluster.NewShardMapper(time.Duration(c.Cluster.ShardMapperTimeout)) + s.ShardMapper.ForceRemoteMapping = c.Cluster.ForceRemoteShardMapping + s.ShardMapper.MetaStore = s.MetaStore + s.ShardMapper.TSDBStore = s.TSDBStore + + // Initialize query executor. + s.QueryExecutor = tsdb.NewQueryExecutor(s.TSDBStore) + s.QueryExecutor.MetaStore = s.MetaStore + s.QueryExecutor.MetaStatementExecutor = &meta.StatementExecutor{Store: s.MetaStore} + s.QueryExecutor.MonitorStatementExecutor = &monitor.StatementExecutor{Monitor: s.Monitor} + s.QueryExecutor.ShardMapper = s.ShardMapper + s.QueryExecutor.QueryLogEnabled = c.Data.QueryLogEnabled + + // Set the shard writer + s.ShardWriter = cluster.NewShardWriter(time.Duration(c.Cluster.ShardWriterTimeout)) + s.ShardWriter.MetaStore = s.MetaStore + + // Create the hinted handoff service + s.HintedHandoff = hh.NewService(c.HintedHandoff, s.ShardWriter, s.MetaStore) + s.HintedHandoff.Monitor = s.Monitor + + // Create the Subscriber service + s.Subscriber = subscriber.NewService(c.Subscriber) + s.Subscriber.MetaStore = s.MetaStore + + // Initialize points writer. + s.PointsWriter = cluster.NewPointsWriter() + s.PointsWriter.WriteTimeout = time.Duration(c.Cluster.WriteTimeout) + s.PointsWriter.MetaStore = s.MetaStore + s.PointsWriter.TSDBStore = s.TSDBStore + s.PointsWriter.ShardWriter = s.ShardWriter + s.PointsWriter.HintedHandoff = s.HintedHandoff + s.PointsWriter.Subscriber = s.Subscriber + + // needed for executing INTO queries. + s.QueryExecutor.IntoWriter = s.PointsWriter + + // Initialize the monitor + s.Monitor.Version = s.buildInfo.Version + s.Monitor.Commit = s.buildInfo.Commit + s.Monitor.Branch = s.buildInfo.Branch + s.Monitor.BuildTime = s.buildInfo.Time + s.Monitor.MetaStore = s.MetaStore + s.Monitor.PointsWriter = s.PointsWriter + + // Append services. + s.appendClusterService(c.Cluster) + s.appendPrecreatorService(c.Precreator) + s.appendRegistrationService(c.Registration) + s.appendSnapshotterService() + s.appendCopierService() + s.appendAdminService(c.Admin) + s.appendContinuousQueryService(c.ContinuousQuery) + s.appendHTTPDService(c.HTTPD) + s.appendCollectdService(c.Collectd) + if err := s.appendOpenTSDBService(c.OpenTSDB); err != nil { + return nil, err + } + for _, g := range c.UDPs { + s.appendUDPService(g) + } + s.appendRetentionPolicyService(c.Retention) + for _, g := range c.Graphites { + if err := s.appendGraphiteService(g); err != nil { + return nil, err + } + } + + return s, nil +} + +func (s *Server) appendClusterService(c cluster.Config) { + srv := cluster.NewService(c) + srv.TSDBStore = s.TSDBStore + srv.MetaStore = s.MetaStore + s.Services = append(s.Services, srv) + s.ClusterService = srv +} + +func (s *Server) appendSnapshotterService() { + srv := snapshotter.NewService() + srv.TSDBStore = s.TSDBStore + srv.MetaStore = s.MetaStore + s.Services = append(s.Services, srv) + s.SnapshotterService = srv +} + +func (s *Server) appendCopierService() { + srv := copier.NewService() + srv.TSDBStore = s.TSDBStore + s.Services = append(s.Services, srv) + s.CopierService = srv +} + +func (s *Server) appendRetentionPolicyService(c retention.Config) { + if !c.Enabled { + return + } + srv := retention.NewService(c) + srv.MetaStore = s.MetaStore + srv.TSDBStore = s.TSDBStore + s.Services = append(s.Services, srv) +} + +func (s *Server) appendAdminService(c admin.Config) { + if !c.Enabled { + return + } + srv := admin.NewService(c) + s.Services = append(s.Services, srv) +} + +func (s *Server) appendHTTPDService(c httpd.Config) { + if !c.Enabled { + return + } + srv := httpd.NewService(c) + srv.Handler.MetaStore = s.MetaStore + srv.Handler.QueryExecutor = s.QueryExecutor + srv.Handler.PointsWriter = s.PointsWriter + srv.Handler.Version = s.buildInfo.Version + + // If a ContinuousQuerier service has been started, attach it. + for _, srvc := range s.Services { + if cqsrvc, ok := srvc.(continuous_querier.ContinuousQuerier); ok { + srv.Handler.ContinuousQuerier = cqsrvc + } + } + + s.Services = append(s.Services, srv) +} + +func (s *Server) appendCollectdService(c collectd.Config) { + if !c.Enabled { + return + } + srv := collectd.NewService(c) + srv.MetaStore = s.MetaStore + srv.PointsWriter = s.PointsWriter + s.Services = append(s.Services, srv) +} + +func (s *Server) appendOpenTSDBService(c opentsdb.Config) error { + if !c.Enabled { + return nil + } + srv, err := opentsdb.NewService(c) + if err != nil { + return err + } + srv.PointsWriter = s.PointsWriter + srv.MetaStore = s.MetaStore + s.Services = append(s.Services, srv) + return nil +} + +func (s *Server) appendGraphiteService(c graphite.Config) error { + if !c.Enabled { + return nil + } + srv, err := graphite.NewService(c) + if err != nil { + return err + } + + srv.PointsWriter = s.PointsWriter + srv.MetaStore = s.MetaStore + srv.Monitor = s.Monitor + s.Services = append(s.Services, srv) + return nil +} + +func (s *Server) appendPrecreatorService(c precreator.Config) error { + if !c.Enabled { + return nil + } + srv, err := precreator.NewService(c) + if err != nil { + return err + } + + srv.MetaStore = s.MetaStore + s.Services = append(s.Services, srv) + return nil +} + +func (s *Server) appendRegistrationService(c registration.Config) error { + if !c.Enabled { + return nil + } + srv, err := registration.NewService(c, s.buildInfo.Version) + if err != nil { + return err + } + + srv.MetaStore = s.MetaStore + srv.Monitor = s.Monitor + s.Services = append(s.Services, srv) + return nil +} + +func (s *Server) appendUDPService(c udp.Config) { + if !c.Enabled { + return + } + srv := udp.NewService(c) + srv.PointsWriter = s.PointsWriter + srv.MetaStore = s.MetaStore + s.Services = append(s.Services, srv) +} + +func (s *Server) appendContinuousQueryService(c continuous_querier.Config) { + if !c.Enabled { + return + } + srv := continuous_querier.NewService(c) + srv.MetaStore = s.MetaStore + srv.QueryExecutor = s.QueryExecutor + s.Services = append(s.Services, srv) +} + +// Err returns an error channel that multiplexes all out of band errors received from all services. +func (s *Server) Err() <-chan error { return s.err } + +// Open opens the meta and data store and all services. +func (s *Server) Open() error { + if err := func() error { + // Start profiling, if set. + startProfile(s.CPUProfile, s.MemProfile) + + host, port, err := s.hostAddr() + if err != nil { + return err + } + + hostport := net.JoinHostPort(host, port) + addr, err := net.ResolveTCPAddr("tcp", hostport) + if err != nil { + return fmt.Errorf("resolve tcp: addr=%s, err=%s", hostport, err) + } + s.MetaStore.Addr = addr + s.MetaStore.RemoteAddr = &tcpaddr{hostport} + + // Open shared TCP connection. + ln, err := net.Listen("tcp", s.BindAddress) + if err != nil { + return fmt.Errorf("listen: %s", err) + } + s.Listener = ln + + // The port 0 is used, we need to retrieve the port assigned by the kernel + if strings.HasSuffix(s.BindAddress, ":0") { + s.MetaStore.Addr = ln.Addr() + } + + // Multiplex listener. + mux := tcp.NewMux() + s.MetaStore.RaftListener = mux.Listen(meta.MuxRaftHeader) + s.MetaStore.ExecListener = mux.Listen(meta.MuxExecHeader) + s.MetaStore.RPCListener = mux.Listen(meta.MuxRPCHeader) + + s.ClusterService.Listener = mux.Listen(cluster.MuxHeader) + s.SnapshotterService.Listener = mux.Listen(snapshotter.MuxHeader) + s.CopierService.Listener = mux.Listen(copier.MuxHeader) + go mux.Serve(ln) + + // Open meta store. + if err := s.MetaStore.Open(); err != nil { + return fmt.Errorf("open meta store: %s", err) + } + go s.monitorErrorChan(s.MetaStore.Err()) + + // Wait for the store to initialize. + <-s.MetaStore.Ready() + + // Open TSDB store. + if err := s.TSDBStore.Open(); err != nil { + return fmt.Errorf("open tsdb store: %s", err) + } + + // Open the hinted handoff service + if err := s.HintedHandoff.Open(); err != nil { + return fmt.Errorf("open hinted handoff: %s", err) + } + + // Open the subcriber service + if err := s.Subscriber.Open(); err != nil { + return fmt.Errorf("open subscriber: %s", err) + } + + // Open the points writer service + if err := s.PointsWriter.Open(); err != nil { + return fmt.Errorf("open points writer: %s", err) + } + + // Open the monitor service + if err := s.Monitor.Open(); err != nil { + return fmt.Errorf("open monitor: %v", err) + } + + for _, service := range s.Services { + if err := service.Open(); err != nil { + return fmt.Errorf("open service: %s", err) + } + } + + // Start the reporting service, if not disabled. + if !s.reportingDisabled { + go s.startServerReporting() + } + + return nil + + }(); err != nil { + s.Close() + return err + } + + return nil +} + +// Close shuts down the meta and data stores and all services. +func (s *Server) Close() error { + stopProfile() + + // Close the listener first to stop any new connections + if s.Listener != nil { + s.Listener.Close() + } + + // Close services to allow any inflight requests to complete + // and prevent new requests from being accepted. + for _, service := range s.Services { + service.Close() + } + + if s.Monitor != nil { + s.Monitor.Close() + } + + if s.PointsWriter != nil { + s.PointsWriter.Close() + } + + if s.HintedHandoff != nil { + s.HintedHandoff.Close() + } + + // Close the TSDBStore, no more reads or writes at this point + if s.TSDBStore != nil { + s.TSDBStore.Close() + } + + if s.Subscriber != nil { + s.Subscriber.Close() + } + + // Finally close the meta-store since everything else depends on it + if s.MetaStore != nil { + s.MetaStore.Close() + } + + close(s.closing) + return nil +} + +// startServerReporting starts periodic server reporting. +func (s *Server) startServerReporting() { + for { + select { + case <-s.closing: + return + default: + } + if err := s.MetaStore.WaitForLeader(30 * time.Second); err != nil { + log.Printf("no leader available for reporting: %s", err.Error()) + time.Sleep(time.Second) + continue + } + s.reportServer() + <-time.After(24 * time.Hour) + } +} + +// reportServer reports anonymous statistics about the system. +func (s *Server) reportServer() { + dis, err := s.MetaStore.Databases() + if err != nil { + log.Printf("failed to retrieve databases for reporting: %s", err.Error()) + return + } + numDatabases := len(dis) + + numMeasurements := 0 + numSeries := 0 + for _, di := range dis { + d := s.TSDBStore.DatabaseIndex(di.Name) + if d == nil { + // No data in this store for this database. + continue + } + m, s := d.MeasurementSeriesCounts() + numMeasurements += m + numSeries += s + } + + clusterID, err := s.MetaStore.ClusterID() + if err != nil { + log.Printf("failed to retrieve cluster ID for reporting: %s", err.Error()) + return + } + + cl := client.New("") + usage := client.Usage{ + Product: "influxdb", + Data: []client.UsageData{ + { + Values: client.Values{ + "os": runtime.GOOS, + "arch": runtime.GOARCH, + "version": s.buildInfo.Version, + "server_id": s.MetaStore.NodeID(), + "cluster_id": clusterID, + "num_series": numSeries, + "num_measurements": numMeasurements, + "num_databases": numDatabases, + }, + }, + }, + } + + log.Printf("Sending anonymous usage statistics to m.influxdb.com") + + go cl.Save(usage) +} + +// monitorErrorChan reads an error channel and resends it through the server. +func (s *Server) monitorErrorChan(ch <-chan error) { + for { + select { + case err, ok := <-ch: + if !ok { + return + } + s.err <- err + case <-s.closing: + return + } + } +} + +// hostAddr returns the host and port that remote nodes will use to reach this +// node. +func (s *Server) hostAddr() (string, string, error) { + // Resolve host to address. + _, port, err := net.SplitHostPort(s.BindAddress) + if err != nil { + return "", "", fmt.Errorf("split bind address: %s", err) + } + + host := s.Hostname + + // See if we might have a port that will override the BindAddress port + if host != "" && host[len(host)-1] >= '0' && host[len(host)-1] <= '9' && strings.Contains(host, ":") { + hostArg, portArg, err := net.SplitHostPort(s.Hostname) + if err != nil { + return "", "", err + } + + if hostArg != "" { + host = hostArg + } + + if portArg != "" { + port = portArg + } + } + return host, port, nil +} + +// Service represents a service attached to the server. +type Service interface { + Open() error + Close() error +} + +// prof stores the file locations of active profiles. +var prof struct { + cpu *os.File + mem *os.File +} + +// StartProfile initializes the cpu and memory profile, if specified. +func startProfile(cpuprofile, memprofile string) { + if cpuprofile != "" { + f, err := os.Create(cpuprofile) + if err != nil { + log.Fatalf("cpuprofile: %v", err) + } + log.Printf("writing CPU profile to: %s\n", cpuprofile) + prof.cpu = f + pprof.StartCPUProfile(prof.cpu) + } + + if memprofile != "" { + f, err := os.Create(memprofile) + if err != nil { + log.Fatalf("memprofile: %v", err) + } + log.Printf("writing mem profile to: %s\n", memprofile) + prof.mem = f + runtime.MemProfileRate = 4096 + } + +} + +// StopProfile closes the cpu and memory profiles if they are running. +func stopProfile() { + if prof.cpu != nil { + pprof.StopCPUProfile() + prof.cpu.Close() + log.Println("CPU profile stopped") + } + if prof.mem != nil { + pprof.Lookup("heap").WriteTo(prof.mem, 0) + prof.mem.Close() + log.Println("mem profile stopped") + } +} + +type tcpaddr struct{ host string } + +func (a *tcpaddr) Network() string { return "tcp" } +func (a *tcpaddr) String() string { return a.host } diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_helpers_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_helpers_test.go new file mode 100644 index 00000000..620a48f8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_helpers_test.go @@ -0,0 +1,377 @@ +// This package is a set of convenience helpers and structs to make integration testing easier +package run_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" + "math" + "net/http" + "net/url" + "os" + "regexp" + "strings" + "testing" + "time" + + "github.com/influxdb/influxdb/cmd/influxd/run" + "github.com/influxdb/influxdb/meta" + "github.com/influxdb/influxdb/services/httpd" + "github.com/influxdb/influxdb/toml" +) + +// Server represents a test wrapper for run.Server. +type Server struct { + *run.Server + Config *run.Config +} + +// NewServer returns a new instance of Server. +func NewServer(c *run.Config) *Server { + buildInfo := &run.BuildInfo{ + Version: "testServer", + Commit: "testCommit", + Branch: "testBranch", + } + srv, _ := run.NewServer(c, buildInfo) + s := Server{ + Server: srv, + Config: c, + } + s.TSDBStore.EngineOptions.Config = c.Data + configureLogging(&s) + return &s +} + +// OpenServer opens a test server. +func OpenServer(c *run.Config, joinURLs string) *Server { + s := NewServer(c) + configureLogging(s) + if err := s.Open(); err != nil { + panic(err.Error()) + } + return s +} + +// OpenServerWithVersion opens a test server with a specific version. +func OpenServerWithVersion(c *run.Config, version string) *Server { + buildInfo := &run.BuildInfo{ + Version: version, + Commit: "", + Branch: "", + } + srv, _ := run.NewServer(c, buildInfo) + s := Server{ + Server: srv, + Config: c, + } + configureLogging(&s) + if err := s.Open(); err != nil { + panic(err.Error()) + } + + return &s +} + +// OpenDefaultServer opens a test server with a default database & retention policy. +func OpenDefaultServer(c *run.Config, joinURLs string) *Server { + s := OpenServer(c, joinURLs) + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + panic(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + panic(err) + } + return s +} + +// Close shuts down the server and removes all temporary paths. +func (s *Server) Close() { + s.Server.Close() + os.RemoveAll(s.Config.Meta.Dir) + os.RemoveAll(s.Config.Data.Dir) + os.RemoveAll(s.Config.HintedHandoff.Dir) +} + +// URL returns the base URL for the httpd endpoint. +func (s *Server) URL() string { + for _, service := range s.Services { + if service, ok := service.(*httpd.Service); ok { + return "http://" + service.Addr().String() + } + } + panic("httpd server not found in services") +} + +// CreateDatabaseAndRetentionPolicy will create the database and retention policy. +func (s *Server) CreateDatabaseAndRetentionPolicy(db string, rp *meta.RetentionPolicyInfo) error { + if _, err := s.MetaStore.CreateDatabase(db); err != nil { + return err + } else if _, err := s.MetaStore.CreateRetentionPolicy(db, rp); err != nil { + return err + } + return nil +} + +// Query executes a query against the server and returns the results. +func (s *Server) Query(query string) (results string, err error) { + return s.QueryWithParams(query, nil) +} + +// Query executes a query against the server and returns the results. +func (s *Server) QueryWithParams(query string, values url.Values) (results string, err error) { + if values == nil { + values = url.Values{} + } + values.Set("q", query) + return s.HTTPGet(s.URL() + "/query?" + values.Encode()) +} + +// HTTPGet makes an HTTP GET request to the server and returns the response. +func (s *Server) HTTPGet(url string) (results string, err error) { + resp, err := http.Get(url) + if err != nil { + return "", err + } + body := string(MustReadAll(resp.Body)) + switch resp.StatusCode { + case http.StatusBadRequest: + if !expectPattern(".*error parsing query*.", body) { + return "", fmt.Errorf("unexpected status code: code=%d, body=%s", resp.StatusCode, body) + } + return body, nil + case http.StatusOK: + return body, nil + default: + return "", fmt.Errorf("unexpected status code: code=%d, body=%s", resp.StatusCode, body) + } +} + +// HTTPPost makes an HTTP POST request to the server and returns the response. +func (s *Server) HTTPPost(url string, content []byte) (results string, err error) { + buf := bytes.NewBuffer(content) + resp, err := http.Post(url, "application/json", buf) + if err != nil { + return "", err + } + body := string(MustReadAll(resp.Body)) + switch resp.StatusCode { + case http.StatusBadRequest: + if !expectPattern(".*error parsing query*.", body) { + return "", fmt.Errorf("unexpected status code: code=%d, body=%s", resp.StatusCode, body) + } + return body, nil + case http.StatusOK, http.StatusNoContent: + return body, nil + default: + return "", fmt.Errorf("unexpected status code: code=%d, body=%s", resp.StatusCode, body) + } +} + +// Write executes a write against the server and returns the results. +func (s *Server) Write(db, rp, body string, params url.Values) (results string, err error) { + if params == nil { + params = url.Values{} + } + if params.Get("db") == "" { + params.Set("db", db) + } + if params.Get("rp") == "" { + params.Set("rp", rp) + } + resp, err := http.Post(s.URL()+"/write?"+params.Encode(), "", strings.NewReader(body)) + if err != nil { + return "", err + } else if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + return "", fmt.Errorf("invalid status code: code=%d, body=%s", resp.StatusCode, MustReadAll(resp.Body)) + } + return string(MustReadAll(resp.Body)), nil +} + +// MustWrite executes a write to the server. Panic on error. +func (s *Server) MustWrite(db, rp, body string, params url.Values) string { + results, err := s.Write(db, rp, body, params) + if err != nil { + panic(err) + } + return results +} + +// NewConfig returns the default config with temporary paths. +func NewConfig() *run.Config { + c := run.NewConfig() + c.ReportingDisabled = true + c.Cluster.ShardWriterTimeout = toml.Duration(30 * time.Second) + c.Cluster.WriteTimeout = toml.Duration(30 * time.Second) + c.Meta.Dir = MustTempFile() + c.Meta.BindAddress = "127.0.0.1:0" + c.Meta.HeartbeatTimeout = toml.Duration(50 * time.Millisecond) + c.Meta.ElectionTimeout = toml.Duration(50 * time.Millisecond) + c.Meta.LeaderLeaseTimeout = toml.Duration(50 * time.Millisecond) + c.Meta.CommitTimeout = toml.Duration(5 * time.Millisecond) + + c.Data.Dir = MustTempFile() + c.Data.WALDir = MustTempFile() + c.Data.WALLoggingEnabled = false + + c.HintedHandoff.Dir = MustTempFile() + + c.HTTPD.Enabled = true + c.HTTPD.BindAddress = "127.0.0.1:0" + c.HTTPD.LogEnabled = testing.Verbose() + + c.Monitor.StoreEnabled = false + + return c +} + +func newRetentionPolicyInfo(name string, rf int, duration time.Duration) *meta.RetentionPolicyInfo { + return &meta.RetentionPolicyInfo{Name: name, ReplicaN: rf, Duration: duration} +} + +func maxFloat64() string { + maxFloat64, _ := json.Marshal(math.MaxFloat64) + return string(maxFloat64) +} + +func maxInt64() string { + maxInt64, _ := json.Marshal(^int64(0)) + return string(maxInt64) +} + +func now() time.Time { + return time.Now().UTC() +} + +func yesterday() time.Time { + return now().Add(-1 * time.Hour * 24) +} + +func mustParseTime(layout, value string) time.Time { + tm, err := time.Parse(layout, value) + if err != nil { + panic(err) + } + return tm +} + +// MustReadAll reads r. Panic on error. +func MustReadAll(r io.Reader) []byte { + b, err := ioutil.ReadAll(r) + if err != nil { + panic(err) + } + return b +} + +// MustTempFile returns a path to a temporary file. +func MustTempFile() string { + f, err := ioutil.TempFile("", "influxd-") + if err != nil { + panic(err) + } + f.Close() + os.Remove(f.Name()) + return f.Name() +} + +func expectPattern(exp, act string) bool { + re := regexp.MustCompile(exp) + if !re.MatchString(act) { + return false + } + return true +} + +type Query struct { + name string + command string + params url.Values + exp, act string + pattern bool + skip bool + repeat int +} + +// Execute runs the command and returns an err if it fails +func (q *Query) Execute(s *Server) (err error) { + if q.params == nil { + q.act, err = s.Query(q.command) + return + } + q.act, err = s.QueryWithParams(q.command, q.params) + return +} + +func (q *Query) success() bool { + if q.pattern { + return expectPattern(q.exp, q.act) + } + return q.exp == q.act +} + +func (q *Query) Error(err error) string { + return fmt.Sprintf("%s: %v", q.name, err) +} + +func (q *Query) failureMessage() string { + return fmt.Sprintf("%s: unexpected results\nquery: %s\nexp: %s\nactual: %s\n", q.name, q.command, q.exp, q.act) +} + +type Test struct { + initialized bool + write string + params url.Values + db string + rp string + exp string + queries []*Query +} + +func NewTest(db, rp string) Test { + return Test{ + db: db, + rp: rp, + } +} + +func (t *Test) addQueries(q ...*Query) { + t.queries = append(t.queries, q...) +} + +func (t *Test) init(s *Server) error { + if t.write == "" || t.initialized { + return nil + } + t.initialized = true + if res, err := s.Write(t.db, t.rp, t.write, t.params); err != nil { + return err + } else if t.exp != res { + return fmt.Errorf("unexpected results\nexp: %s\ngot: %s\n", t.exp, res) + } + return nil +} + +func configureLogging(s *Server) { + // Set the logger to discard unless verbose is on + if !testing.Verbose() { + type logSetter interface { + SetLogger(*log.Logger) + } + nullLogger := log.New(ioutil.Discard, "", 0) + s.MetaStore.Logger = nullLogger + s.TSDBStore.Logger = nullLogger + s.HintedHandoff.SetLogger(nullLogger) + s.Monitor.SetLogger(nullLogger) + s.QueryExecutor.SetLogger(nullLogger) + s.Subscriber.SetLogger(nullLogger) + for _, service := range s.Services { + if service, ok := service.(logSetter); ok { + service.SetLogger(nullLogger) + } + } + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.go new file mode 100644 index 00000000..8a25d3c7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.go @@ -0,0 +1,5460 @@ +package run_test + +import ( + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/influxdb/influxdb/cluster" +) + +// Ensure that HTTP responses include the InfluxDB version. +func TestServer_HTTPResponseVersion(t *testing.T) { + version := "v1234" + s := OpenServerWithVersion(NewConfig(), version) + defer s.Close() + + resp, _ := http.Get(s.URL() + "/query") + got := resp.Header.Get("X-Influxdb-Version") + if got != version { + t.Errorf("Server responded with incorrect version, exp %s, got %s", version, got) + } +} + +// Ensure the database commands work. +func TestServer_DatabaseCommands(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + test := Test{ + queries: []*Query{ + &Query{ + name: "create database should succeed", + command: `CREATE DATABASE db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "create database should error with bad name", + command: `CREATE DATABASE 0xdb0`, + exp: `{"error":"error parsing query: found 0, expected identifier at line 1, char 17"}`, + }, + &Query{ + name: "show database should succeed", + command: `SHOW DATABASES`, + exp: `{"results":[{"series":[{"name":"databases","columns":["name"],"values":[["db0"]]}]}]}`, + }, + &Query{ + name: "create database should error if it already exists", + command: `CREATE DATABASE db0`, + exp: `{"results":[{"error":"database already exists"}]}`, + }, + &Query{ + name: "create database should not error with existing database with IF NOT EXISTS", + command: `CREATE DATABASE IF NOT EXISTS db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "create database should create non-existing database with IF NOT EXISTS", + command: `CREATE DATABASE IF NOT EXISTS db1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show database should succeed", + command: `SHOW DATABASES`, + exp: `{"results":[{"series":[{"name":"databases","columns":["name"],"values":[["db0"],["db1"]]}]}]}`, + }, + &Query{ + name: "drop database db0 should succeed", + command: `DROP DATABASE db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "drop database db1 should succeed", + command: `DROP DATABASE db1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "drop database should error if it does not exists", + command: `DROP DATABASE db1`, + exp: `{"results":[{"error":"database not found: db1"}]}`, + }, + &Query{ + name: "drop database should not error with non-existing database db1 WITH IF EXISTS", + command: `DROP DATABASE IF EXISTS db1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show database should have no results", + command: `SHOW DATABASES`, + exp: `{"results":[{"series":[{"name":"databases","columns":["name"]}]}]}`, + }, + &Query{ + name: "drop database should error if it doesn't exist", + command: `DROP DATABASE db0`, + exp: `{"results":[{"error":"database not found: db0"}]}`, + }, + }, + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_DropAndRecreateDatabase(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "Drop database after data write", + command: `DROP DATABASE db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "Recreate database", + command: `CREATE DATABASE db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "Recreate retention policy", + command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 365d REPLICATION 1 DEFAULT`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "Show measurements after recreate", + command: `SHOW MEASUREMENTS`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Query data after recreate", + command: `SELECT * FROM cpu`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_DropDatabaseIsolated(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + if err := s.CreateDatabaseAndRetentionPolicy("db1", newRetentionPolicyInfo("rp1", 1, 0)); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "Query data from 1st database", + command: `SELECT * FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Query data from 1st database with GROUP BY *", + command: `SELECT * FROM cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop other database", + command: `DROP DATABASE db1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "Query data from 1st database and ensure it's still there", + command: `SELECT * FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Query data from 1st database and ensure it's still there with GROUP BY *", + command: `SELECT * FROM cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_DropAndRecreateSeries(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "Show series is present", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop series after data write", + command: `DROP SERIES FROM cpu`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Show series is gone", + command: `SHOW SERIES`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + + // Re-write data and test again. + reTest := NewTest("db0", "rp0") + reTest.write = strings.Join(writes, "\n") + + reTest.addQueries([]*Query{ + &Query{ + name: "Show series is present again after re-write", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range reTest.queries { + if i == 0 { + if err := reTest.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_DropSeriesFromRegex(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`a,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`aa,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`b,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`c,host=serverA,region=uswest val=30.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "Show series is present", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"a","columns":["_key","host","region"],"values":[["a,host=serverA,region=uswest","serverA","uswest"]]},{"name":"aa","columns":["_key","host","region"],"values":[["aa,host=serverA,region=uswest","serverA","uswest"]]},{"name":"b","columns":["_key","host","region"],"values":[["b,host=serverA,region=uswest","serverA","uswest"]]},{"name":"c","columns":["_key","host","region"],"values":[["c,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop series after data write", + command: `DROP SERIES FROM /a.*/`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Show series is gone", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"b","columns":["_key","host","region"],"values":[["b,host=serverA,region=uswest","serverA","uswest"]]},{"name":"c","columns":["_key","host","region"],"values":[["c,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop series from regex that matches no measurements", + command: `DROP SERIES FROM /a.*/`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "make sure DROP SERIES doesn't delete anything when regex doesn't match", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"b","columns":["_key","host","region"],"values":[["b,host=serverA,region=uswest","serverA","uswest"]]},{"name":"c","columns":["_key","host","region"],"values":[["c,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop series with WHERE field should error", + command: `DROP SERIES FROM c WHERE val > 50.0`, + exp: `{"results":[{"error":"DROP SERIES doesn't support fields in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "make sure DROP SERIES with field in WHERE didn't delete data", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"b","columns":["_key","host","region"],"values":[["b,host=serverA,region=uswest","serverA","uswest"]]},{"name":"c","columns":["_key","host","region"],"values":[["c,host=serverA,region=uswest","serverA","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop series with WHERE time should error", + command: `DROP SERIES FROM c WHERE time > now() - 1d`, + exp: `{"results":[{"error":"DROP SERIES doesn't support time in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure retention policy commands work. +func TestServer_RetentionPolicyCommands(t *testing.T) { + t.Parallel() + c := NewConfig() + c.Meta.RetentionAutoCreate = false + s := OpenServer(c, "") + defer s.Close() + + // Create a database. + if _, err := s.MetaStore.CreateDatabase("db0"); err != nil { + t.Fatal(err) + } + + test := Test{ + queries: []*Query{ + &Query{ + name: "create retention policy should succeed", + command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 1h REPLICATION 1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "create retention policy should error if it already exists", + command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 1h REPLICATION 1`, + exp: `{"results":[{"error":"retention policy already exists"}]}`, + }, + &Query{ + name: "show retention policy should succeed", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["rp0","1h0m0s",1,false]]}]}]}`, + }, + &Query{ + name: "alter retention policy should succeed", + command: `ALTER RETENTION POLICY rp0 ON db0 DURATION 2h REPLICATION 3 DEFAULT`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show retention policy should have new altered information", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["rp0","2h0m0s",3,true]]}]}]}`, + }, + &Query{ + name: "dropping default retention policy should not succeed", + command: `DROP RETENTION POLICY rp0 ON db0`, + exp: `{"results":[{"error":"retention policy is default"}]}`, + }, + &Query{ + name: "show retention policy should still show policy", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["rp0","2h0m0s",3,true]]}]}]}`, + }, + &Query{ + name: "create a second non-default retention policy", + command: `CREATE RETENTION POLICY rp2 ON db0 DURATION 1h REPLICATION 1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show retention policy should show both", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["rp0","2h0m0s",3,true],["rp2","1h0m0s",1,false]]}]}]}`, + }, + &Query{ + name: "dropping non-default retention policy succeed", + command: `DROP RETENTION POLICY rp2 ON db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show retention policy should show just default", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["rp0","2h0m0s",3,true]]}]}]}`, + }, + &Query{ + name: "Ensure retention policy with unacceptable retention cannot be created", + command: `CREATE RETENTION POLICY rp3 ON db0 DURATION 1s REPLICATION 1`, + exp: `{"results":[{"error":"retention policy duration must be at least 1h0m0s"}]}`, + }, + &Query{ + name: "Check error when deleting retention policy on non-existent database", + command: `DROP RETENTION POLICY rp1 ON mydatabase`, + exp: `{"results":[{"error":"database not found"}]}`, + }, + }, + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the autocreation of retention policy works. +func TestServer_DatabaseRetentionPolicyAutoCreate(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + test := Test{ + queries: []*Query{ + &Query{ + name: "create database should succeed", + command: `CREATE DATABASE db0`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show retention policies should return auto-created policy", + command: `SHOW RETENTION POLICIES ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["default","0",1,true]]}]}]}`, + }, + }, + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure user commands work. +func TestServer_UserCommands(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + // Create a database. + if _, err := s.MetaStore.CreateDatabase("db0"); err != nil { + t.Fatal(err) + } + + test := Test{ + queries: []*Query{ + &Query{ + name: "show users, no actual users", + command: `SHOW USERS`, + exp: `{"results":[{"series":[{"columns":["user","admin"]}]}]}`, + }, + &Query{ + name: `create user`, + command: "CREATE USER jdoe WITH PASSWORD '1337'", + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show users, 1 existing user", + command: `SHOW USERS`, + exp: `{"results":[{"series":[{"columns":["user","admin"],"values":[["jdoe",false]]}]}]}`, + }, + &Query{ + name: "grant all priviledges to jdoe", + command: `GRANT ALL PRIVILEGES TO jdoe`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "show users, existing user as admin", + command: `SHOW USERS`, + exp: `{"results":[{"series":[{"columns":["user","admin"],"values":[["jdoe",true]]}]}]}`, + }, + &Query{ + name: "grant DB privileges to user", + command: `GRANT READ ON db0 TO jdoe`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "revoke all privileges", + command: `REVOKE ALL PRIVILEGES FROM jdoe`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "bad create user request", + command: `CREATE USER 0xBAD WITH PASSWORD pwd1337`, + exp: `{"error":"error parsing query: found 0, expected identifier at line 1, char 13"}`, + }, + &Query{ + name: "bad create user request, no name", + command: `CREATE USER WITH PASSWORD pwd1337`, + exp: `{"error":"error parsing query: found WITH, expected identifier at line 1, char 13"}`, + }, + &Query{ + name: "bad create user request, no password", + command: `CREATE USER jdoe`, + exp: `{"error":"error parsing query: found EOF, expected WITH at line 1, char 18"}`, + }, + &Query{ + name: "drop user", + command: `DROP USER jdoe`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "make sure user was dropped", + command: `SHOW USERS`, + exp: `{"results":[{"series":[{"columns":["user","admin"]}]}]}`, + }, + &Query{ + name: "delete non existing user", + command: `DROP USER noone`, + exp: `{"results":[{"error":"user not found"}]}`, + }, + }, + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(fmt.Sprintf("command: %s - err: %s", query.command, query.Error(err))) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can create a single point via json protocol and read it back. +func TestServer_Write_JSON(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + if res, err := s.Write("", "", fmt.Sprintf(`{"database" : "db0", "retentionPolicy" : "rp0", "points": [{"measurement": "cpu", "tags": {"host": "server02"},"fields": {"value": 1.0}}],"time":"%s"} `, now.Format(time.RFC3339Nano)), nil); err != nil { + t.Fatal(err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server02"},"columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server can create a single point via line protocol with float type and read it back. +func TestServer_Write_LineProtocol_Float(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + if res, err := s.Write("db0", "rp0", `cpu,host=server01 value=1.0 `+strconv.FormatInt(now.UnixNano(), 10), nil); err != nil { + t.Fatal(err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server can create a single point via line protocol with bool type and read it back. +func TestServer_Write_LineProtocol_Bool(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + if res, err := s.Write("db0", "rp0", `cpu,host=server01 value=true `+strconv.FormatInt(now.UnixNano(), 10), nil); err != nil { + t.Fatal(err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",true]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server can create a single point via line protocol with string type and read it back. +func TestServer_Write_LineProtocol_String(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + if res, err := s.Write("db0", "rp0", `cpu,host=server01 value="disk full" `+strconv.FormatInt(now.UnixNano(), 10), nil); err != nil { + t.Fatal(err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s","disk full"]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server can create a single point via line protocol with integer type and read it back. +func TestServer_Write_LineProtocol_Integer(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + if res, err := s.Write("db0", "rp0", `cpu,host=server01 value=100 `+strconv.FormatInt(now.UnixNano(), 10), nil); err != nil { + t.Fatal(err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",100]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server returns a partial write response when some points fail to parse. Also validate that +// the successfully parsed points can be queried. +func TestServer_Write_LineProtocol_Partial(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + points := []string{ + "cpu,host=server01 value=100 " + strconv.FormatInt(now.UnixNano(), 10), + "cpu,host=server01 value=NaN " + strconv.FormatInt(now.UnixNano(), 20), + "cpu,host=server01 value=NaN " + strconv.FormatInt(now.UnixNano(), 30), + } + if res, err := s.Write("db0", "rp0", strings.Join(points, "\n"), nil); err == nil { + t.Fatal("expected error. got nil", err) + } else if exp := ``; exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } else if exp := "partial write"; !strings.Contains(err.Error(), exp) { + t.Fatalf("unexpected error: exp\nexp: %v\ngot: %v", exp, err) + } + + // Verify the data was written. + if res, err := s.Query(`SELECT * FROM db0.rp0.cpu GROUP BY *`); err != nil { + t.Fatal(err) + } else if exp := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",100]]}]}]}`, now.Format(time.RFC3339Nano)); exp != res { + t.Fatalf("unexpected results\nexp: %s\ngot: %s\n", exp, res) + } +} + +// Ensure the server can query with default databases (via param) and default retention policy +func TestServer_Query_DefaultDBAndRP(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf(`cpu value=1.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()) + + test.addQueries([]*Query{ + &Query{ + name: "default db and rp", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T01:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "default rp exists", + command: `show retention policies ON db0`, + exp: `{"results":[{"series":[{"columns":["name","duration","replicaN","default"],"values":[["default","0",1,false],["rp0","1h0m0s",1,true]]}]}]}`, + }, + &Query{ + name: "default rp", + command: `SELECT * FROM db0..cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T01:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "default dp", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM rp0.cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T01:00:00Z",1]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can have a database with multiple measurements. +func TestServer_Query_Multiple_Measurements(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + // Make sure we do writes for measurements that will span across shards + writes := []string{ + fmt.Sprintf("cpu,host=server01 value=100,core=4 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf("cpu1,host=server02 value=50,core=2 %d", mustParseTime(time.RFC3339Nano, "2015-01-01T00:00:00Z").UnixNano()), + } + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "measurement in one shard but not another shouldn't panic server", + command: `SELECT host,value FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","host","value"],"values":[["2000-01-01T00:00:00Z","server01",100]]}]}]}`, + }, + &Query{ + name: "measurement in one shard but not another shouldn't panic server", + command: `SELECT host,value FROM db0.rp0.cpu GROUP BY host`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["2000-01-01T00:00:00Z",100]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server correctly supports data with identical tag values. +func TestServer_Query_IdenticalTagValues(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf("cpu,t1=val1 value=1 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf("cpu,t2=val2 value=2 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf("cpu,t1=val2 value=3 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:02:00Z").UnixNano()), + } + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "measurements with identical tag values - SELECT *, no GROUP BY", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"t1":"val1","t2":""},"columns":["time","value"],"values":[["2000-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"t1":"val2","t2":""},"columns":["time","value"],"values":[["2000-01-01T00:02:00Z",3]]},{"name":"cpu","tags":{"t1":"","t2":"val2"},"columns":["time","value"],"values":[["2000-01-01T00:01:00Z",2]]}]}]}`, + }, + &Query{ + name: "measurements with identical tag values - SELECT *, with GROUP BY", + command: `SELECT value FROM db0.rp0.cpu GROUP BY t1,t2`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"t1":"val1","t2":""},"columns":["time","value"],"values":[["2000-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"t1":"val2","t2":""},"columns":["time","value"],"values":[["2000-01-01T00:02:00Z",3]]},{"name":"cpu","tags":{"t1":"","t2":"val2"},"columns":["time","value"],"values":[["2000-01-01T00:01:00Z",2]]}]}]}`, + }, + &Query{ + name: "measurements with identical tag values - SELECT value no GROUP BY", + command: `SELECT value FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:00Z",1],["2000-01-01T00:01:00Z",2],["2000-01-01T00:02:00Z",3]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can handle a query that involves accessing no shards. +func TestServer_Query_NoShards(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = `cpu,host=server01 value=1 ` + strconv.FormatInt(now.UnixNano(), 10) + + test.addQueries([]*Query{ + &Query{ + name: "selecting value should succeed", + command: `SELECT value FROM db0.rp0.cpu WHERE time < now() - 1d`, + exp: `{"results":[{}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query a non-existent field +func TestServer_Query_NonExistent(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = `cpu,host=server01 value=1 ` + strconv.FormatInt(now.UnixNano(), 10) + + test.addQueries([]*Query{ + &Query{ + name: "selecting value should succeed", + command: `SELECT value FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting non-existent should succeed", + command: `SELECT foo FROM db0.rp0.cpu`, + exp: `{"results":[{}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can perform basic math +func TestServer_Query_Math(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db", newRetentionPolicyInfo("rp", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + writes := []string{ + "float value=42 " + strconv.FormatInt(now.UnixNano(), 10), + "integer value=42i " + strconv.FormatInt(now.UnixNano(), 10), + } + + test := NewTest("db", "rp") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "SELECT multiple of float value", + command: `SELECT value * 2 from db.rp.float`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"float","columns":["time",""],"values":[["%s",84]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "SELECT multiple of float value", + command: `SELECT 2 * value from db.rp.float`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"float","columns":["time",""],"values":[["%s",84]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "SELECT multiple of integer value", + command: `SELECT value * 2 from db.rp.integer`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"integer","columns":["time",""],"values":[["%s",84]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "SELECT float multiple of integer value", + command: `SELECT value * 2.0 from db.rp.integer`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"integer","columns":["time",""],"values":[["%s",84]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query with the count aggregate function +func TestServer_Query_Count(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + writes := []string{ + `cpu,host=server01 value=1.0 ` + strconv.FormatInt(now.UnixNano(), 10), + `ram value1=1.0,value2=2.0 ` + strconv.FormatInt(now.UnixNano(), 10), + } + + test.write = strings.Join(writes, "\n") + + hour_ago := now.Add(-time.Hour).UTC() + + test.addQueries([]*Query{ + &Query{ + name: "selecting count(value) should succeed", + command: `SELECT count(value) FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "selecting count(value) with where time should return result", + command: fmt.Sprintf(`SELECT count(value) FROM db0.rp0.cpu WHERE time >= '%s'`, hour_ago.Format(time.RFC3339Nano)), + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","count"],"values":[["%s",1]]}]}]}`, hour_ago.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting count(value) with filter that excludes all results should return 0", + command: fmt.Sprintf(`SELECT count(value) FROM db0.rp0.cpu WHERE value=100 AND time >= '%s'`, hour_ago.Format(time.RFC3339Nano)), + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","count"],"values":[["%s",0]]}]}]}`, hour_ago.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting count(value1) with matching filter against value2 should return correct result", + command: fmt.Sprintf(`SELECT count(value1) FROM db0.rp0.ram WHERE value2=2 AND time >= '%s'`, hour_ago.Format(time.RFC3339Nano)), + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"ram","columns":["time","count"],"values":[["%s",1]]}]}]}`, hour_ago.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting count(value1) with non-matching filter against value2 should return correct result", + command: fmt.Sprintf(`SELECT count(value1) FROM db0.rp0.ram WHERE value2=3 AND time >= '%s'`, hour_ago.Format(time.RFC3339Nano)), + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"ram","columns":["time","count"],"values":[["%s",0]]}]}]}`, hour_ago.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting count(*) should error", + command: `SELECT count(*) FROM db0.rp0.cpu`, + exp: `{"error":"error parsing query: expected field argument in count()"}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query with Now(). +func TestServer_Query_Now(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = `cpu,host=server01 value=1.0 ` + strconv.FormatInt(now.UnixNano(), 10) + + test.addQueries([]*Query{ + &Query{ + name: "where with time < now() should work", + command: `SELECT * FROM db0.rp0.cpu where time < now()`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","host","value"],"values":[["%s","server01",1]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "where with time < now() and GROUP BY * should work", + command: `SELECT * FROM db0.rp0.cpu where time < now() GROUP BY *`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "where with time > now() should return an empty result", + command: `SELECT * FROM db0.rp0.cpu where time > now()`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "where with time > now() with GROUP BY * should return an empty result", + command: `SELECT * FROM db0.rp0.cpu where time > now() GROUP BY *`, + exp: `{"results":[{}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query with epoch precisions. +func TestServer_Query_EpochPrecision(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = `cpu,host=server01 value=1.0 ` + strconv.FormatInt(now.UnixNano(), 10) + + test.addQueries([]*Query{ + &Query{ + name: "nanosecond precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"n"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()), + }, + &Query{ + name: "microsecond precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"u"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()/int64(time.Microsecond)), + }, + &Query{ + name: "millisecond precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"ms"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()/int64(time.Millisecond)), + }, + &Query{ + name: "second precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"s"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()/int64(time.Second)), + }, + &Query{ + name: "minute precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"m"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()/int64(time.Minute)), + }, + &Query{ + name: "hour precision", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + params: url.Values{"epoch": []string{"h"}}, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[[%d,1]]}]}]}`, now.UnixNano()/int64(time.Hour)), + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server works with tag queries. +func TestServer_Query_Tags(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + writes := []string{ + fmt.Sprintf("cpu,host=server01 value=100,core=4 %d", now.UnixNano()), + fmt.Sprintf("cpu,host=server02 value=50,core=2 %d", now.Add(1).UnixNano()), + + fmt.Sprintf("cpu1,host=server01,region=us-west value=100 %d", mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf("cpu1,host=server02 value=200 %d", mustParseTime(time.RFC3339Nano, "2010-02-28T01:03:37.703820946Z").UnixNano()), + fmt.Sprintf("cpu1,host=server03 value=300 %d", mustParseTime(time.RFC3339Nano, "2012-02-28T01:03:38.703820946Z").UnixNano()), + + fmt.Sprintf("cpu2,host=server01 value=100 %d", mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf("cpu2 value=200 %d", mustParseTime(time.RFC3339Nano, "2012-02-28T01:03:38.703820946Z").UnixNano()), + + fmt.Sprintf("cpu3,company=acme01 value=100 %d", mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf("cpu3 value=200 %d", mustParseTime(time.RFC3339Nano, "2012-02-28T01:03:38.703820946Z").UnixNano()), + + fmt.Sprintf("status_code,url=http://www.example.com value=404 %d", mustParseTime(time.RFC3339Nano, "2015-07-22T08:13:54.929026672Z").UnixNano()), + fmt.Sprintf("status_code,url=https://influxdb.com value=418 %d", mustParseTime(time.RFC3339Nano, "2015-07-22T09:52:24.914395083Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "tag without field should return error", + command: `SELECT host FROM db0.rp0.cpu`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + &Query{ + name: "field with tag should succeed", + command: `SELECT host, value FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","host","value"],"values":[["%s","server01",100],["%s","server02",50]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "field with tag and GROUP BY should succeed", + command: `SELECT host, value FROM db0.rp0.cpu GROUP BY host`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",100]]},{"name":"cpu","tags":{"host":"server02"},"columns":["time","value"],"values":[["%s",50]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "field with two tags should succeed", + command: `SELECT host, value, core FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","host","value","core"],"values":[["%s","server01",100,4],["%s","server02",50,2]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "field with two tags and GROUP BY should succeed", + command: `SELECT host, value, core FROM db0.rp0.cpu GROUP BY host`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value","core"],"values":[["%s",100,4]]},{"name":"cpu","tags":{"host":"server02"},"columns":["time","value","core"],"values":[["%s",50,2]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "select * with tags should succeed", + command: `SELECT * FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","core","host","value"],"values":[["%s",4,"server01",100],["%s",2,"server02",50]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "select * with tags with GROUP BY * should succeed", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","core","value"],"values":[["%s",4,100]]},{"name":"cpu","tags":{"host":"server02"},"columns":["time","core","value"],"values":[["%s",2,50]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "group by tag", + command: `SELECT value FROM db0.rp0.cpu GROUP by host`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",100]]},{"name":"cpu","tags":{"host":"server02"},"columns":["time","value"],"values":[["%s",50]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "single field (EQ tag value1)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server01'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (2 EQ tags)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server01' AND region = 'us-west'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (OR different tags)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server03' OR region = 'us-west'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2012-02-28T01:03:38.703820946Z",300],["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (OR with non-existent tag value)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server01' OR host = 'server66'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (OR with all tag values)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server01' OR host = 'server02' OR host = 'server03'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2010-02-28T01:03:37.703820946Z",200],["2012-02-28T01:03:38.703820946Z",300],["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (1 EQ and 1 NEQ tag)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server01' AND region != 'us-west'`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "single field (EQ tag value2)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host = 'server02'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2010-02-28T01:03:37.703820946Z",200]]}]}]}`, + }, + &Query{ + name: "single field (NEQ tag value1)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host != 'server01'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2010-02-28T01:03:37.703820946Z",200],["2012-02-28T01:03:38.703820946Z",300]]}]}]}`, + }, + &Query{ + name: "single field (NEQ tag value1 AND NEQ tag value2)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host != 'server01' AND host != 'server02'`, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2012-02-28T01:03:38.703820946Z",300]]}]}]}`, + }, + &Query{ + name: "single field (NEQ tag value1 OR NEQ tag value2)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host != 'server01' OR host != 'server02'`, // Yes, this is always true, but that's the point. + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","value"],"values":[["2010-02-28T01:03:37.703820946Z",200],["2012-02-28T01:03:38.703820946Z",300],["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (NEQ tag value1 AND NEQ tag value2 AND NEQ tag value3)", + command: `SELECT value FROM db0.rp0.cpu1 WHERE host != 'server01' AND host != 'server02' AND host != 'server03'`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "single field (NEQ tag value1, point without any tags)", + command: `SELECT value FROM db0.rp0.cpu2 WHERE host != 'server01'`, + exp: `{"results":[{"series":[{"name":"cpu2","columns":["time","value"],"values":[["2012-02-28T01:03:38.703820946Z",200]]}]}]}`, + }, + &Query{ + name: "single field (NEQ tag value1, point without any tags)", + command: `SELECT value FROM db0.rp0.cpu3 WHERE company !~ /acme01/`, + exp: `{"results":[{"series":[{"name":"cpu3","columns":["time","value"],"values":[["2012-02-28T01:03:38.703820946Z",200]]}]}]}`, + }, + &Query{ + name: "single field (regex tag match)", + command: `SELECT value FROM db0.rp0.cpu3 WHERE company =~ /acme01/`, + exp: `{"results":[{"series":[{"name":"cpu3","columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (regex tag match)", + command: `SELECT value FROM db0.rp0.cpu3 WHERE company !~ /acme[23]/`, + exp: `{"results":[{"series":[{"name":"cpu3","columns":["time","value"],"values":[["2012-02-28T01:03:38.703820946Z",200],["2015-02-28T01:03:36.703820946Z",100]]}]}]}`, + }, + &Query{ + name: "single field (regex tag match with escaping)", + command: `SELECT value FROM db0.rp0.status_code WHERE url !~ /https\:\/\/influxdb\.com/`, + exp: `{"results":[{"series":[{"name":"status_code","columns":["time","value"],"values":[["2015-07-22T08:13:54.929026672Z",404]]}]}]}`, + }, + &Query{ + name: "single field (regex tag match with escaping)", + command: `SELECT value FROM db0.rp0.status_code WHERE url =~ /https\:\/\/influxdb\.com/`, + exp: `{"results":[{"series":[{"name":"status_code","columns":["time","value"],"values":[["2015-07-22T09:52:24.914395083Z",418]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server correctly queries with an alias. +func TestServer_Query_Alias(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf("cpu value=1i,steps=3i %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf("cpu value=2i,steps=4i %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + } + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "baseline query - SELECT * FROM db0.rp0.cpu", + command: `SELECT * FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","steps","value"],"values":[["2000-01-01T00:00:00Z",3,1],["2000-01-01T00:01:00Z",4,2]]}]}]}`, + }, + &Query{ + name: "basic query with alias - SELECT steps, value as v FROM db0.rp0.cpu", + command: `SELECT steps, value as v FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","steps","v"],"values":[["2000-01-01T00:00:00Z",3,1],["2000-01-01T00:01:00Z",4,2]]}]}]}`, + }, + &Query{ + name: "double aggregate sum - SELECT sum(value), sum(steps) FROM db0.rp0.cpu", + command: `SELECT sum(value), sum(steps) FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum","sum"],"values":[["1970-01-01T00:00:00Z",3,7]]}]}]}`, + }, + &Query{ + name: "double aggregate sum reverse order - SELECT sum(steps), sum(value) FROM db0.rp0.cpu", + command: `SELECT sum(steps), sum(value) FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum","sum"],"values":[["1970-01-01T00:00:00Z",7,3]]}]}]}`, + }, + &Query{ + name: "double aggregate sum with alias - SELECT sum(value) as sumv, sum(steps) as sums FROM db0.rp0.cpu", + command: `SELECT sum(value) as sumv, sum(steps) as sums FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sumv","sums"],"values":[["1970-01-01T00:00:00Z",3,7]]}]}]}`, + }, + &Query{ + name: "double aggregate with same value - SELECT sum(value), mean(value) FROM db0.rp0.cpu", + command: `SELECT sum(value), mean(value) FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum","mean"],"values":[["1970-01-01T00:00:00Z",3,1.5]]}]}]}`, + }, + &Query{ + name: "double aggregate with same value and same alias - SELECT mean(value) as mv, max(value) as mv FROM db0.rp0.cpu", + command: `SELECT mean(value) as mv, max(value) as mv FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","mv","mv"],"values":[["1970-01-01T00:00:00Z",1.5,2]]}]}]}`, + }, + &Query{ + name: "double aggregate with non-existent field - SELECT mean(value), max(foo) FROM db0.rp0.cpu", + command: `SELECT mean(value), max(foo) FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","mean","max"],"values":[["1970-01-01T00:00:00Z",1.5,null]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server will succeed and error for common scenarios. +func TestServer_Query_Common(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu,host=server01 value=1 %s", strconv.FormatInt(now.UnixNano(), 10)) + + test.addQueries([]*Query{ + &Query{ + name: "selecting a from a non-existent database should error", + command: `SELECT value FROM db1.rp0.cpu`, + exp: `{"results":[{"error":"database not found: db1"}]}`, + }, + &Query{ + name: "selecting a from a non-existent retention policy should error", + command: `SELECT value FROM db0.rp1.cpu`, + exp: `{"results":[{"error":"retention policy not found"}]}`, + }, + &Query{ + name: "selecting a valid measurement and field should succeed", + command: `SELECT value FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "explicitly selecting time and a valid measurement and field should succeed", + command: `SELECT time,value FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",1]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting a measurement that doesn't exist should result in empty set", + command: `SELECT value FROM db0.rp0.idontexist`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "selecting a field that doesn't exist should result in empty set", + command: `SELECT idontexist FROM db0.rp0.cpu`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "selecting wildcard without specifying a database should error", + command: `SELECT * FROM cpu`, + exp: `{"results":[{"error":"database name required"}]}`, + }, + &Query{ + name: "selecting explicit field without specifying a database should error", + command: `SELECT value FROM cpu`, + exp: `{"results":[{"error":"database name required"}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query two points. +func TestServer_Query_SelectTwoPoints(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu value=100 %s\ncpu value=200 %s", strconv.FormatInt(now.UnixNano(), 10), strconv.FormatInt(now.Add(1).UnixNano(), 10)) + + test.addQueries( + &Query{ + name: "selecting two points should result in two points", + command: `SELECT * FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",100],["%s",200]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + &Query{ + name: "selecting two points with GROUP BY * should result in two points", + command: `SELECT * FROM db0.rp0.cpu GROUP BY *`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",100],["%s",200]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }, + ) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query two negative points. +func TestServer_Query_SelectTwoNegativePoints(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu value=-100 %s\ncpu value=-200 %s", strconv.FormatInt(now.UnixNano(), 10), strconv.FormatInt(now.Add(1).UnixNano(), 10)) + + test.addQueries(&Query{ + name: "selecting two negative points should succeed", + command: `SELECT * FROM db0.rp0.cpu`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["%s",-100],["%s",-200]]}]}]}`, now.Format(time.RFC3339Nano), now.Add(1).Format(time.RFC3339Nano)), + }) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can query with relative time. +func TestServer_Query_SelectRelativeTime(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + now := now() + yesterday := yesterday() + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu,host=server01 value=100 %s\ncpu,host=server01 value=200 %s", strconv.FormatInt(yesterday.UnixNano(), 10), strconv.FormatInt(now.UnixNano(), 10)) + + test.addQueries([]*Query{ + &Query{ + name: "single point with time pre-calculated for past time queries yesterday", + command: `SELECT * FROM db0.rp0.cpu where time >= '` + yesterday.Add(-1*time.Minute).Format(time.RFC3339Nano) + `' GROUP BY *`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",100],["%s",200]]}]}]}`, yesterday.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)), + }, + &Query{ + name: "single point with time pre-calculated for relative time queries now", + command: `SELECT * FROM db0.rp0.cpu where time >= now() - 1m GROUP BY *`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["%s",200]]}]}]}`, now.Format(time.RFC3339Nano)), + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Ensure the server can handle various simple calculus queries. +func TestServer_Query_SelectRawCalculus(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu value=210 1278010021000000000\ncpu value=10 1278010022000000000") + + test.addQueries([]*Query{ + &Query{ + name: "calculate single derivate", + command: `SELECT derivative(value) from db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","derivative"],"values":[["2010-07-01T18:47:02Z",-200]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// mergeMany ensures that when merging many series together and some of them have a different number +// of points than others in a group by interval the results are correct +func TestServer_Query_MergeMany(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + // set infinite retention policy as we are inserting data in the past and don't want retention policy enforcement to make this test racy + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + + writes := []string{} + for i := 1; i < 11; i++ { + for j := 1; j < 5+i%3; j++ { + data := fmt.Sprintf(`cpu,host=server_%d value=22 %d`, i, time.Unix(int64(j), int64(0)).UTC().UnixNano()) + writes = append(writes, data) + } + } + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "GROUP by time", + command: `SELECT count(value) FROM db0.rp0.cpu WHERE time >= '1970-01-01T00:00:01Z' AND time <= '1970-01-01T00:00:06Z' GROUP BY time(1s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","count"],"values":[["1970-01-01T00:00:01Z",10],["1970-01-01T00:00:02Z",10],["1970-01-01T00:00:03Z",10],["1970-01-01T00:00:04Z",10],["1970-01-01T00:00:05Z",7],["1970-01-01T00:00:06Z",3]]}]}]}`, + }, + &Query{ + skip: true, + name: "GROUP by tag - FIXME issue #2875", + command: `SELECT count(value) FROM db0.rp0.cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:00Z' group by host`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","count"],"values":[["2000-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"host":"server02"},"columns":["time","count"],"values":[["2000-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"host":"server03"},"columns":["time","count"],"values":[["2000-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "GROUP by field", + command: `SELECT count(value) FROM db0.rp0.cpu group by value`, + exp: `{"results":[{"error":"can not use field in GROUP BY clause: value"}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_SLimitAndSOffset(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + // set infinite retention policy as we are inserting data in the past and don't want retention policy enforcement to make this test racy + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + + writes := []string{} + for i := 1; i < 10; i++ { + data := fmt.Sprintf(`cpu,region=us-east,host=server-%d value=%d %d`, i, i, time.Unix(int64(i), int64(0)).UnixNano()) + writes = append(writes, data) + } + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "SLIMIT 2 SOFFSET 1", + command: `SELECT count(value) FROM db0.rp0.cpu GROUP BY * SLIMIT 2 SOFFSET 1`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server-2","region":"us-east"},"columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"host":"server-3","region":"us-east"},"columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "SLIMIT 2 SOFFSET 3", + command: `SELECT count(value) FROM db0.rp0.cpu GROUP BY * SLIMIT 2 SOFFSET 3`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server-4","region":"us-east"},"columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]},{"name":"cpu","tags":{"host":"server-5","region":"us-east"},"columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "SLIMIT 3 SOFFSET 8", + command: `SELECT count(value) FROM db0.rp0.cpu GROUP BY * SLIMIT 3 SOFFSET 8`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server-9","region":"us-east"},"columns":["time","count"],"values":[["1970-01-01T00:00:00Z",1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Regex(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu1,host=server01 value=10 %d`, mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf(`cpu2,host=server01 value=20 %d`, mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf(`cpu3,host=server01 value=30 %d`, mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "default db and rp", + command: `SELECT * FROM /cpu[13]/`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu1","columns":["time","host","value"],"values":[["2015-02-28T01:03:36.703820946Z","server01",10]]},{"name":"cpu3","columns":["time","host","value"],"values":[["2015-02-28T01:03:36.703820946Z","server01",30]]}]}]}`, + }, + &Query{ + name: "default db and rp with GROUP BY *", + command: `SELECT * FROM /cpu[13]/ GROUP BY *`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu1","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",10]]},{"name":"cpu3","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",30]]}]}]}`, + }, + &Query{ + name: "specifying db and rp", + command: `SELECT * FROM db0.rp0./cpu[13]/ GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu1","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",10]]},{"name":"cpu3","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",30]]}]}]}`, + }, + &Query{ + name: "default db and specified rp", + command: `SELECT * FROM rp0./cpu[13]/ GROUP BY *`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu1","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",10]]},{"name":"cpu3","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",30]]}]}]}`, + }, + &Query{ + name: "specified db and default rp", + command: `SELECT * FROM db0../cpu[13]/ GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu1","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",10]]},{"name":"cpu3","tags":{"host":"server01"},"columns":["time","value"],"values":[["2015-02-28T01:03:36.703820946Z",30]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_Int(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`int value=45 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + // int64 + &Query{ + name: "stddev with just one point - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT STDDEV(value) FROM int`, + exp: `{"results":[{"series":[{"name":"int","columns":["time","stddev"],"values":[["1970-01-01T00:00:00Z",null]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_IntMax(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`intmax value=%s %d`, maxInt64(), mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intmax value=%s %d`, maxInt64(), mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "large mean and stddev - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEAN(value), STDDEV(value) FROM intmax`, + exp: `{"results":[{"series":[{"name":"intmax","columns":["time","mean","stddev"],"values":[["1970-01-01T00:00:00Z",` + maxInt64() + `,0]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_IntMany(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`intmany,host=server01 value=2.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server02 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`intmany,host=server03 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`intmany,host=server04 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`intmany,host=server05 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + fmt.Sprintf(`intmany,host=server06 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:50Z").UnixNano()), + fmt.Sprintf(`intmany,host=server07 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server08 value=9.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:10Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "mean and stddev - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEAN(value), STDDEV(value) FROM intmany WHERE time >= '2000-01-01' AND time < '2000-01-01T00:02:00Z' GROUP BY time(10m)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","mean","stddev"],"values":[["2000-01-01T00:00:00Z",5,2.138089935299395]]}]}]}`, + }, + &Query{ + name: "first - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT FIRST(value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",2]]}]}]}`, + }, + &Query{ + name: "first - int - epoch ms", + params: url.Values{"db": []string{"db0"}, "epoch": []string{"ms"}}, + command: `SELECT FIRST(value) FROM intmany`, + exp: fmt.Sprintf(`{"results":[{"series":[{"name":"intmany","columns":["time","first"],"values":[[%d,2]]}]}]}`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()/int64(time.Millisecond)), + }, + &Query{ + name: "last - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT LAST(value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","last"],"values":[["2000-01-01T00:01:10Z",9]]}]}]}`, + }, + &Query{ + name: "spread - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SPREAD(value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","spread"],"values":[["1970-01-01T00:00:00Z",7]]}]}]}`, + }, + &Query{ + name: "median - even count - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEDIAN(value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","median"],"values":[["1970-01-01T00:00:00Z",4.5]]}]}]}`, + }, + &Query{ + name: "median - odd count - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEDIAN(value) FROM intmany where time < '2000-01-01T00:01:10Z'`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","median"],"values":[["1970-01-01T00:00:00Z",4]]}]}]}`, + }, + &Query{ + name: "distinct as call - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT(value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","distinct"],"values":[["1970-01-01T00:00:00Z",[2,4,5,7,9]]]}]}]}`, + }, + &Query{ + name: "distinct alt syntax - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT value FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","distinct"],"values":[["1970-01-01T00:00:00Z",[2,4,5,7,9]]]}]}]}`, + }, + &Query{ + name: "distinct select tag - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT(host) FROM intmany`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + &Query{ + name: "distinct alt select tag - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT host FROM intmany`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + &Query{ + name: "count distinct - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT value) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",5]]}]}]}`, + }, + &Query{ + name: "count distinct as call - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT(value)) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",5]]}]}]}`, + }, + &Query{ + name: "count distinct select tag - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT host) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",0]]}]}]}`, + }, + &Query{ + name: "count distinct as call select tag - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT host) FROM intmany`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",0]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_IntMany_GroupBy(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`intmany,host=server01 value=2.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server02 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`intmany,host=server03 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`intmany,host=server04 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`intmany,host=server05 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + fmt.Sprintf(`intmany,host=server06 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:50Z").UnixNano()), + fmt.Sprintf(`intmany,host=server07 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server08 value=9.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:10Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "max order by time with time specified group by 10s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, max(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(10s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","max"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:10Z",4],["2000-01-01T00:00:20Z",4],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:40Z",5],["2000-01-01T00:00:50Z",5],["2000-01-01T00:01:00Z",7],["2000-01-01T00:01:10Z",9]]}]}]}`, + }, + &Query{ + name: "max order by time without time specified group by 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT max(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","max"],"values":[["2000-01-01T00:00:00Z",4],["2000-01-01T00:00:30Z",5],["2000-01-01T00:01:00Z",9]]}]}]}`, + }, + &Query{ + name: "max order by time with time specified group by 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, max(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","max"],"values":[["2000-01-01T00:00:10Z",4],["2000-01-01T00:00:40Z",5],["2000-01-01T00:01:10Z",9]]}]}]}`, + }, + &Query{ + name: "min order by time without time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT min(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","min"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:15Z",4],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:45Z",5],["2000-01-01T00:01:00Z",7]]}]}]}`, + }, + &Query{ + name: "min order by time with time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, min(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","min"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:20Z",4],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:50Z",5],["2000-01-01T00:01:00Z",7]]}]}]}`, + }, + &Query{ + name: "first order by time without time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT first(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:15Z",4],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:45Z",5],["2000-01-01T00:01:00Z",7]]}]}]}`, + }, + &Query{ + name: "first order by time with time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, first(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:20Z",4],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:50Z",5],["2000-01-01T00:01:00Z",7]]}]}]}`, + }, + &Query{ + name: "last order by time without time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT last(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","last"],"values":[["2000-01-01T00:00:00Z",4],["2000-01-01T00:00:15Z",4],["2000-01-01T00:00:30Z",5],["2000-01-01T00:00:45Z",5],["2000-01-01T00:01:00Z",9]]}]}]}`, + }, + &Query{ + name: "last order by time with time specified group by 15s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, last(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:14Z' group by time(15s)`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","last"],"values":[["2000-01-01T00:00:10Z",4],["2000-01-01T00:00:20Z",4],["2000-01-01T00:00:40Z",5],["2000-01-01T00:00:50Z",5],["2000-01-01T00:01:10Z",9]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_IntMany_OrderByDesc(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`intmany,host=server01 value=2.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server02 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`intmany,host=server03 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`intmany,host=server04 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`intmany,host=server05 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + fmt.Sprintf(`intmany,host=server06 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:50Z").UnixNano()), + fmt.Sprintf(`intmany,host=server07 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf(`intmany,host=server08 value=9.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:10Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "aggregate order by time desc", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT max(value) FROM intmany where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:00Z' group by time(10s) order by time desc`, + exp: `{"results":[{"series":[{"name":"intmany","columns":["time","max"],"values":[["2000-01-01T00:01:00Z",7],["2000-01-01T00:00:50Z",5],["2000-01-01T00:00:40Z",5],["2000-01-01T00:00:30Z",4],["2000-01-01T00:00:20Z",4],["2000-01-01T00:00:10Z",4],["2000-01-01T00:00:00Z",2]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_IntOverlap(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`intoverlap,region=us-east value=20 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intoverlap,region=us-east value=30 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`intoverlap,region=us-west value=100 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`intoverlap,region=us-east otherVal=20 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "aggregation with no interval - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT count(value) FROM intoverlap WHERE time = '2000-01-01 00:00:00'`, + exp: `{"results":[{"series":[{"name":"intoverlap","columns":["time","count"],"values":[["2000-01-01T00:00:00Z",2]]}]}]}`, + }, + &Query{ + name: "sum - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM intoverlap WHERE time >= '2000-01-01 00:00:05' AND time <= '2000-01-01T00:00:10Z' GROUP BY time(10s), region`, + exp: `{"results":[{"series":[{"name":"intoverlap","tags":{"region":"us-east"},"columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",null],["2000-01-01T00:00:10Z",30]]}]}]}`, + }, + &Query{ + name: "aggregation with a null field value - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM intoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"intoverlap","tags":{"region":"us-east"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",50]]},{"name":"intoverlap","tags":{"region":"us-west"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",100]]}]}]}`, + }, + &Query{ + name: "multiple aggregations - int", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value), MEAN(value) FROM intoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"intoverlap","tags":{"region":"us-east"},"columns":["time","sum","mean"],"values":[["1970-01-01T00:00:00Z",50,25]]},{"name":"intoverlap","tags":{"region":"us-west"},"columns":["time","sum","mean"],"values":[["1970-01-01T00:00:00Z",100,100]]}]}]}`, + }, + &Query{ + skip: true, + name: "multiple aggregations with division - int FIXME issue #2879", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value), mean(value), sum(value) / mean(value) as div FROM intoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"intoverlap","tags":{"region":"us-east"},"columns":["time","sum","mean","div"],"values":[["1970-01-01T00:00:00Z",50,25,2]]},{"name":"intoverlap","tags":{"region":"us-west"},"columns":["time","div"],"values":[["1970-01-01T00:00:00Z",100,100,1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_FloatSingle(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`floatsingle value=45.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "stddev with just one point - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT STDDEV(value) FROM floatsingle`, + exp: `{"results":[{"series":[{"name":"floatsingle","columns":["time","stddev"],"values":[["1970-01-01T00:00:00Z",null]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_FloatMany(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`floatmany,host=server01 value=2.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server02 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server03 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server04 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server05 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server06 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:50Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server07 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf(`floatmany,host=server08 value=9.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:10Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "mean and stddev - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEAN(value), STDDEV(value) FROM floatmany WHERE time >= '2000-01-01' AND time < '2000-01-01T00:02:00Z' GROUP BY time(10m)`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","mean","stddev"],"values":[["2000-01-01T00:00:00Z",5,2.138089935299395]]}]}]}`, + }, + &Query{ + name: "first - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT FIRST(value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",2]]}]}]}`, + }, + &Query{ + name: "last - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT LAST(value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","last"],"values":[["2000-01-01T00:01:10Z",9]]}]}]}`, + }, + &Query{ + name: "spread - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SPREAD(value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","spread"],"values":[["1970-01-01T00:00:00Z",7]]}]}]}`, + }, + &Query{ + name: "median - even count - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEDIAN(value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","median"],"values":[["1970-01-01T00:00:00Z",4.5]]}]}]}`, + }, + &Query{ + name: "median - odd count - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEDIAN(value) FROM floatmany where time < '2000-01-01T00:01:10Z'`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","median"],"values":[["1970-01-01T00:00:00Z",4]]}]}]}`, + }, + &Query{ + name: "distinct as call - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT(value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","distinct"],"values":[["1970-01-01T00:00:00Z",[2,4,5,7,9]]]}]}]}`, + }, + &Query{ + name: "distinct alt syntax - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT value FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","distinct"],"values":[["1970-01-01T00:00:00Z",[2,4,5,7,9]]]}]}]}`, + }, + &Query{ + name: "distinct select tag - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT(host) FROM floatmany`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + &Query{ + name: "distinct alt select tag - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT DISTINCT host FROM floatmany`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + &Query{ + name: "count distinct - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT value) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",5]]}]}]}`, + }, + &Query{ + name: "count distinct as call - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT(value)) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",5]]}]}]}`, + }, + &Query{ + name: "count distinct select tag - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT host) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",0]]}]}]}`, + }, + &Query{ + name: "count distinct as call select tag - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(DISTINCT host) FROM floatmany`, + exp: `{"results":[{"series":[{"name":"floatmany","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",0]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_FloatOverlap(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`floatoverlap,region=us-east value=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`floatoverlap,region=us-east value=30.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`floatoverlap,region=us-west value=100.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`floatoverlap,region=us-east otherVal=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "aggregation with no interval - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT count(value) FROM floatoverlap WHERE time = '2000-01-01 00:00:00'`, + exp: `{"results":[{"series":[{"name":"floatoverlap","columns":["time","count"],"values":[["2000-01-01T00:00:00Z",2]]}]}]}`, + }, + &Query{ + name: "sum - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM floatoverlap WHERE time >= '2000-01-01 00:00:05' AND time <= '2000-01-01T00:00:10Z' GROUP BY time(10s), region`, + exp: `{"results":[{"series":[{"name":"floatoverlap","tags":{"region":"us-east"},"columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",null],["2000-01-01T00:00:10Z",30]]}]}]}`, + }, + &Query{ + name: "aggregation with a null field value - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM floatoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"floatoverlap","tags":{"region":"us-east"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",50]]},{"name":"floatoverlap","tags":{"region":"us-west"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",100]]}]}]}`, + }, + &Query{ + name: "multiple aggregations - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value), MEAN(value) FROM floatoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"floatoverlap","tags":{"region":"us-east"},"columns":["time","sum","mean"],"values":[["1970-01-01T00:00:00Z",50,25]]},{"name":"floatoverlap","tags":{"region":"us-west"},"columns":["time","sum","mean"],"values":[["1970-01-01T00:00:00Z",100,100]]}]}]}`, + }, + &Query{ + name: "multiple aggregations with division - float", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value) / mean(value) as div FROM floatoverlap GROUP BY region`, + exp: `{"results":[{"series":[{"name":"floatoverlap","tags":{"region":"us-east"},"columns":["time","div"],"values":[["1970-01-01T00:00:00Z",2]]},{"name":"floatoverlap","tags":{"region":"us-west"},"columns":["time","div"],"values":[["1970-01-01T00:00:00Z",1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_Load(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`load,region=us-east,host=serverA value=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`load,region=us-east,host=serverB value=30.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`load,region=us-west,host=serverC value=100.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "group by multiple dimensions", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value) FROM load GROUP BY region, host`, + exp: `{"results":[{"series":[{"name":"load","tags":{"host":"serverA","region":"us-east"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",20]]},{"name":"load","tags":{"host":"serverB","region":"us-east"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",30]]},{"name":"load","tags":{"host":"serverC","region":"us-west"},"columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",100]]}]}]}`, + }, + &Query{ + name: "group by multiple dimensions", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value)*2 FROM load`, + exp: `{"results":[{"series":[{"name":"load","columns":["time",""],"values":[["1970-01-01T00:00:00Z",300]]}]}]}`, + }, + &Query{ + name: "group by multiple dimensions", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value)/2 FROM load`, + exp: `{"results":[{"series":[{"name":"load","columns":["time",""],"values":[["1970-01-01T00:00:00Z",75]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_CPU(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`cpu,region=uk,host=serverZ,service=redis value=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + fmt.Sprintf(`cpu,region=uk,host=serverZ,service=mysql value=30.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "aggregation with WHERE and AND", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT sum(value) FROM cpu WHERE region='uk' AND host='serverZ'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",50]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Aggregates_String(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + test := NewTest("db0", "rp0") + test.write = strings.Join([]string{ + fmt.Sprintf(`stringdata value="first" %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + fmt.Sprintf(`stringdata value="last" %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:04Z").UnixNano()), + }, "\n") + + test.addQueries([]*Query{ + // strings + &Query{ + name: "STDDEV on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT STDDEV(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","stddev"],"values":[["1970-01-01T00:00:00Z",null]]}]}]}`, + }, + &Query{ + name: "MEAN on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEAN(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","mean"],"values":[["1970-01-01T00:00:00Z",0]]}]}]}`, + }, + &Query{ + name: "MEDIAN on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT MEDIAN(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","median"],"values":[["1970-01-01T00:00:00Z",null]]}]}]}`, + }, + &Query{ + name: "COUNT on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT COUNT(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","count"],"values":[["1970-01-01T00:00:00Z",2]]}]}]}`, + }, + &Query{ + name: "FIRST on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT FIRST(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","first"],"values":[["2000-01-01T00:00:03Z","first"]]}]}]}`, + }, + &Query{ + name: "LAST on string data - string", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT LAST(value) FROM stringdata`, + exp: `{"results":[{"series":[{"name":"stringdata","columns":["time","last"],"values":[["2000-01-01T00:00:04Z","last"]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_AggregateSelectors(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`network,host=server01,region=west,core=1 rx=10i,tx=20i,core=2i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`network,host=server02,region=west,core=2 rx=40i,tx=50i,core=3i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`network,host=server03,region=east,core=3 rx=40i,tx=55i,core=4i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`network,host=server04,region=east,core=4 rx=40i,tx=60i,core=1i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`network,host=server05,region=west,core=1 rx=50i,tx=70i,core=2i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + fmt.Sprintf(`network,host=server06,region=east,core=2 rx=50i,tx=40i,core=3i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:50Z").UnixNano()), + fmt.Sprintf(`network,host=server07,region=west,core=3 rx=70i,tx=30i,core=4i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()), + fmt.Sprintf(`network,host=server08,region=east,core=4 rx=90i,tx=10i,core=1i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:10Z").UnixNano()), + fmt.Sprintf(`network,host=server09,region=east,core=1 rx=5i,tx=4i,core=2i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:20Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "baseline", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM network`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","core","host","region","rx","tx"],"values":[["2000-01-01T00:00:00Z",2,"server01","west",10,20],["2000-01-01T00:00:10Z",3,"server02","west",40,50],["2000-01-01T00:00:20Z",4,"server03","east",40,55],["2000-01-01T00:00:30Z",1,"server04","east",40,60],["2000-01-01T00:00:40Z",2,"server05","west",50,70],["2000-01-01T00:00:50Z",3,"server06","east",50,40],["2000-01-01T00:01:00Z",4,"server07","west",70,30],["2000-01-01T00:01:10Z",1,"server08","east",90,10],["2000-01-01T00:01:20Z",2,"server09","east",5,4]]}]}]}`, + }, + &Query{ + name: "max - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT max(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","max"],"values":[["2000-01-01T00:00:00Z",40],["2000-01-01T00:00:30Z",50],["2000-01-01T00:01:00Z",90]]}]}]}`, + }, + &Query{ + name: "max - baseline 30s - epoch ms", + params: url.Values{"db": []string{"db0"}, "epoch": []string{"ms"}}, + command: `SELECT max(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: fmt.Sprintf( + `{"results":[{"series":[{"name":"network","columns":["time","max"],"values":[[%d,40],[%d,50],[%d,90]]}]}]}`, + mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()/int64(time.Millisecond), + mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()/int64(time.Millisecond), + mustParseTime(time.RFC3339Nano, "2000-01-01T00:01:00Z").UnixNano()/int64(time.Millisecond), + ), + }, + &Query{ + name: "max - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, max(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","max"],"values":[["2000-01-01T00:00:00Z",50,40],["2000-01-01T00:00:30Z",70,50],["2000-01-01T00:01:00Z",10,90]]}]}]}`, + }, + &Query{ + name: "max - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, max(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","max"],"values":[["2000-01-01T00:00:10Z",40],["2000-01-01T00:00:40Z",50],["2000-01-01T00:01:10Z",90]]}]}]}`, + }, + &Query{ + name: "max - time and tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, tx, max(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","max"],"values":[["2000-01-01T00:00:10Z",50,40],["2000-01-01T00:00:40Z",70,50],["2000-01-01T00:01:10Z",10,90]]}]}]}`, + }, + &Query{ + name: "min - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT min(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","min"],"values":[["2000-01-01T00:00:00Z",10],["2000-01-01T00:00:30Z",40],["2000-01-01T00:01:00Z",5]]}]}]}`, + }, + &Query{ + name: "min - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, min(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","min"],"values":[["2000-01-01T00:00:00Z",20,10],["2000-01-01T00:00:30Z",60,40],["2000-01-01T00:01:00Z",4,5]]}]}]}`, + }, + &Query{ + name: "min - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, min(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","min"],"values":[["2000-01-01T00:00:00Z",10],["2000-01-01T00:00:30Z",40],["2000-01-01T00:01:20Z",5]]}]}]}`, + }, + &Query{ + name: "min - time and tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, tx, min(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","min"],"values":[["2000-01-01T00:00:00Z",20,10],["2000-01-01T00:00:30Z",60,40],["2000-01-01T00:01:20Z",4,5]]}]}]}`, + }, + &Query{ + name: "max,min - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT max(rx), min(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","max","min"],"values":[["2000-01-01T00:00:00Z",40,10],["2000-01-01T00:00:30Z",50,40],["2000-01-01T00:01:00Z",90,5]]}]}]}`, + }, + &Query{ + name: "first - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT first(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",10],["2000-01-01T00:00:30Z",40],["2000-01-01T00:01:00Z",70]]}]}]}`, + }, + &Query{ + name: "first - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, tx, first(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","first"],"values":[["2000-01-01T00:00:00Z",20,10],["2000-01-01T00:00:30Z",60,40],["2000-01-01T00:01:00Z",30,70]]}]}]}`, + }, + &Query{ + name: "first - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, first(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",10],["2000-01-01T00:00:30Z",40],["2000-01-01T00:01:00Z",70]]}]}]}`, + }, + &Query{ + name: "first - time and tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, tx, first(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","first"],"values":[["2000-01-01T00:00:00Z",20,10],["2000-01-01T00:00:30Z",60,40],["2000-01-01T00:01:00Z",30,70]]}]}]}`, + }, + &Query{ + name: "last - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT last(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","last"],"values":[["2000-01-01T00:00:00Z",40],["2000-01-01T00:00:30Z",50],["2000-01-01T00:01:00Z",5]]}]}]}`, + }, + &Query{ + name: "last - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, last(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","last"],"values":[["2000-01-01T00:00:00Z",55,40],["2000-01-01T00:00:30Z",40,50],["2000-01-01T00:01:00Z",4,5]]}]}]}`, + }, + &Query{ + name: "last - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, last(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","last"],"values":[["2000-01-01T00:00:20Z",40],["2000-01-01T00:00:50Z",50],["2000-01-01T00:01:20Z",5]]}]}]}`, + }, + &Query{ + name: "last - time and tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, tx, last(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","tx","last"],"values":[["2000-01-01T00:00:20Z",55,40],["2000-01-01T00:00:50Z",40,50],["2000-01-01T00:01:20Z",4,5]]}]}]}`, + }, + &Query{ + name: "count - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT count(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","count"],"values":[["2000-01-01T00:00:00Z",3],["2000-01-01T00:00:30Z",3],["2000-01-01T00:01:00Z",3]]}]}]}`, + }, + &Query{ + name: "count - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, count(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "count - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, count(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "distinct - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT distinct(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","distinct"],"values":[["2000-01-01T00:00:00Z",[10,40]],["2000-01-01T00:00:30Z",[40,50]],["2000-01-01T00:01:00Z",[5,70,90]]]}]}]}`, + }, + &Query{ + name: "distinct - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, distinct(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: aggregate function distinct() can not be combined with other functions or fields"}`, + }, + &Query{ + name: "distinct - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, distinct(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: aggregate function distinct() can not be combined with other functions or fields"}`, + }, + &Query{ + name: "mean - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT mean(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","mean"],"values":[["2000-01-01T00:00:00Z",30],["2000-01-01T00:00:30Z",46.666666666666664],["2000-01-01T00:01:00Z",55]]}]}]}`, + }, + &Query{ + name: "mean - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, mean(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "mean - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, mean(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "median - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT median(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","median"],"values":[["2000-01-01T00:00:00Z",40],["2000-01-01T00:00:30Z",50],["2000-01-01T00:01:00Z",70]]}]}]}`, + }, + &Query{ + name: "median - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, median(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "median - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, median(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "spread - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT spread(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","spread"],"values":[["2000-01-01T00:00:00Z",30],["2000-01-01T00:00:30Z",10],["2000-01-01T00:01:00Z",85]]}]}]}`, + }, + &Query{ + name: "spread - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, spread(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "spread - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, spread(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "stddev - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT stddev(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","stddev"],"values":[["2000-01-01T00:00:00Z",17.320508075688775],["2000-01-01T00:00:30Z",5.773502691896258],["2000-01-01T00:01:00Z",44.44097208657794]]}]}]}`, + }, + &Query{ + name: "stddev - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, stddev(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "stddev - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, stddev(rx) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "percentile - baseline 30s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT percentile(rx, 75) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"results":[{"series":[{"name":"network","columns":["time","percentile"],"values":[["2000-01-01T00:00:00Z",40],["2000-01-01T00:00:30Z",50],["2000-01-01T00:01:00Z",70]]}]}]}`, + }, + &Query{ + name: "percentile - time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, percentile(rx, 75) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + &Query{ + name: "percentile - tx", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT tx, percentile(rx, 75) FROM network where time >= '2000-01-01T00:00:00Z' AND time <= '2000-01-01T00:01:29Z' group by time(30s)`, + exp: `{"error":"error parsing query: mixing aggregate and non-aggregate queries is not supported"}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_TopInt(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + // cpu data with overlapping duplicate values + // hour 0 + fmt.Sprintf(`cpu,host=server01 value=2.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server02 value=3.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`cpu,host=server03 value=4.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + // hour 1 + fmt.Sprintf(`cpu,host=server04 value=5.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server05 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:10Z").UnixNano()), + fmt.Sprintf(`cpu,host=server06 value=6.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:20Z").UnixNano()), + // hour 2 + fmt.Sprintf(`cpu,host=server07 value=7.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server08 value=9.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:10Z").UnixNano()), + + // memory data + // hour 0 + fmt.Sprintf(`memory,host=a,service=redis value=1000i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=mysql value=2000i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=redis value=1500i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + // hour 1 + fmt.Sprintf(`memory,host=a,service=redis value=1001i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=mysql value=2001i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=redis value=1501i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:00Z").UnixNano()), + // hour 2 + fmt.Sprintf(`memory,host=a,service=redis value=1002i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=mysql value=2002i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=b,service=redis value=1502i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "top - cpu", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 1) FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - 2 values", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 2) FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T01:00:10Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - 3 values - sorts on tie properly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 3) FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T01:00:10Z",7],["2000-01-01T02:00:00Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - with tag", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, 2) FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top","host"],"values":[["2000-01-01T01:00:10Z",7,"server05"],["2000-01-01T02:00:10Z",9,"server08"]]}]}]}`, + }, + &Query{ + name: "top - cpu - 3 values with limit 2", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 3) FROM cpu limit 2`, + exp: `{"error":"error parsing query: limit (3) in top function can not be larger than the LIMIT (2) in the select statement"}`, + }, + &Query{ + name: "top - cpu - hourly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 1) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:00Z",4],["2000-01-01T01:00:00Z",7],["2000-01-01T02:00:00Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - time specified - hourly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT time, TOP(value, 1) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:20Z",4],["2000-01-01T01:00:10Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - time specified - hourly - epoch ms", + params: url.Values{"db": []string{"db0"}, "epoch": []string{"ms"}}, + command: `SELECT time, TOP(value, 1) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: fmt.Sprintf( + `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[[%d,4],[%d,7],[%d,9]]}]}]}`, + mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()/int64(time.Millisecond), + mustParseTime(time.RFC3339Nano, "2000-01-01T01:00:10Z").UnixNano()/int64(time.Millisecond), + mustParseTime(time.RFC3339Nano, "2000-01-01T02:00:10Z").UnixNano()/int64(time.Millisecond), + ), + }, + &Query{ + name: "top - cpu - time specified (not first) - hourly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 1), time FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:20Z",4],["2000-01-01T01:00:10Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - 2 values hourly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 2) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:00Z",4],["2000-01-01T00:00:00Z",3],["2000-01-01T01:00:00Z",7],["2000-01-01T01:00:00Z",6],["2000-01-01T02:00:00Z",9],["2000-01-01T02:00:00Z",7]]}]}]}`, + }, + &Query{ + name: "top - cpu - time specified - 2 values hourly", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 2), time FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:10Z",3],["2000-01-01T00:00:20Z",4],["2000-01-01T01:00:10Z",7],["2000-01-01T01:00:20Z",6],["2000-01-01T02:00:00Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - cpu - 3 values hourly - validates that a bucket can have less than limit if no values exist in that time bucket", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 3) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:00Z",4],["2000-01-01T00:00:00Z",3],["2000-01-01T00:00:00Z",2],["2000-01-01T01:00:00Z",7],["2000-01-01T01:00:00Z",6],["2000-01-01T01:00:00Z",5],["2000-01-01T02:00:00Z",9],["2000-01-01T02:00:00Z",7]]}]}]}`, + }, + &Query{ + name: "top - cpu - time specified - 3 values hourly - validates that a bucket can have less than limit if no values exist in that time bucket", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 3), time FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T02:00:10Z' group by time(1h)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","top"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:10Z",3],["2000-01-01T00:00:20Z",4],["2000-01-01T01:00:00Z",5],["2000-01-01T01:00:10Z",7],["2000-01-01T01:00:20Z",6],["2000-01-01T02:00:00Z",7],["2000-01-01T02:00:10Z",9]]}]}]}`, + }, + &Query{ + name: "top - memory - 2 values, two tags", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, 2), host, service FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host","service"],"values":[["2000-01-01T01:00:00Z",2001,"b","mysql"],["2000-01-01T02:00:00Z",2002,"b","mysql"]]}]}]}`, + }, + &Query{ + name: "top - memory - host tag with limit 2", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, 2) FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host"],"values":[["2000-01-01T02:00:00Z",2002,"b"],["2000-01-01T02:00:00Z",1002,"a"]]}]}]}`, + }, + &Query{ + name: "top - memory - host tag with limit 2, service tag in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, 2), service FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host","service"],"values":[["2000-01-01T02:00:00Z",2002,"b","mysql"],["2000-01-01T02:00:00Z",1002,"a","redis"]]}]}]}`, + }, + &Query{ + name: "top - memory - service tag with limit 2, host tag in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, service, 2), host FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","service","host"],"values":[["2000-01-01T02:00:00Z",2002,"mysql","b"],["2000-01-01T02:00:00Z",1502,"redis","b"]]}]}]}`, + }, + &Query{ + name: "top - memory - host and service tag with limit 2", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, service, 2) FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host","service"],"values":[["2000-01-01T02:00:00Z",2002,"b","mysql"],["2000-01-01T02:00:00Z",1502,"b","redis"]]}]}]}`, + }, + &Query{ + name: "top - memory - host tag with limit 2 with service tag in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, 2), service FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host","service"],"values":[["2000-01-01T02:00:00Z",2002,"b","mysql"],["2000-01-01T02:00:00Z",1002,"a","redis"]]}]}]}`, + }, + &Query{ + name: "top - memory - host and service tag with limit 3", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT TOP(value, host, service, 3) FROM memory`, + exp: `{"results":[{"series":[{"name":"memory","columns":["time","top","host","service"],"values":[["2000-01-01T02:00:00Z",2002,"b","mysql"],["2000-01-01T02:00:00Z",1502,"b","redis"],["2000-01-01T02:00:00Z",1002,"a","redis"]]}]}]}`, + }, + + // TODO + // - Test that specifiying fields or tags in the function will rewrite the query to expand them to the fields + // - Test that a field can be used in the top function + // - Test that asking for a field will come back before a tag if they have the same name for a tag and a field + // - Test that `select top(value, host, 2)` when there is only one value for `host` it will only bring back one value + // - Test that `select top(value, host, 4) from foo where time > now() - 1d and time < now() group by time(1h)` and host is unique in some time buckets that it returns only the unique ones, and not always 4 values + + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP: %s", query.name) + continue + } + + println(">>>>", query.name) + if query.name != `top - memory - host tag with limit 2` { // FIXME: temporary + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// Test various aggregates when different series only have data for the same timestamp. +func TestServer_Query_Aggregates_IdenticalTime(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`series,host=a value=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=b value=2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=c value=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=d value=4 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=e value=5 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=f value=5 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=g value=5 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=h value=5 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`series,host=i value=5 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "last from multiple series with identical timestamp", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT last(value) FROM "series"`, + exp: `{"results":[{"series":[{"name":"series","columns":["time","last"],"values":[["2000-01-01T00:00:00Z",5]]}]}]}`, + repeat: 100, + }, + &Query{ + name: "first from multiple series with identical timestamp", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT first(value) FROM "series"`, + exp: `{"results":[{"series":[{"name":"series","columns":["time","first"],"values":[["2000-01-01T00:00:00Z",5]]}]}]}`, + repeat: 100, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + for n := 0; n <= query.repeat; n++ { + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + } +} + +// This will test that when using a group by, that it observes the time you asked for +// but will only put the values in the bucket that match the time range +func TestServer_Query_GroupByTimeCutoffs(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu value=1i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`cpu value=2i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + fmt.Sprintf(`cpu value=3i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:05Z").UnixNano()), + fmt.Sprintf(`cpu value=4i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:08Z").UnixNano()), + fmt.Sprintf(`cpu value=5i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:09Z").UnixNano()), + fmt.Sprintf(`cpu value=6i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + } + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "sum all time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["1970-01-01T00:00:00Z",21]]}]}]}`, + }, + &Query{ + name: "sum all time grouped by time 5s", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T00:00:10Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",3],["2000-01-01T00:00:05Z",12],["2000-01-01T00:00:10Z",6]]}]}]}`, + }, + &Query{ + name: "sum all time grouped by time 5s missing first point", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu where time >= '2000-01-01T00:00:01Z' and time <= '2000-01-01T00:00:10Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",2],["2000-01-01T00:00:05Z",12],["2000-01-01T00:00:10Z",6]]}]}]}`, + }, + &Query{ + name: "sum all time grouped by time 5s missing first points (null for bucket)", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu where time >= '2000-01-01T00:00:02Z' and time <= '2000-01-01T00:00:10Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",null],["2000-01-01T00:00:05Z",12],["2000-01-01T00:00:10Z",6]]}]}]}`, + }, + &Query{ + name: "sum all time grouped by time 5s missing last point - 2 time intervals", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T00:00:09Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",3],["2000-01-01T00:00:05Z",12]]}]}]}`, + }, + &Query{ + name: "sum all time grouped by time 5s missing last 2 points - 2 time intervals", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT SUM(value) FROM cpu where time >= '2000-01-01T00:00:00Z' and time <= '2000-01-01T00:00:08Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","sum"],"values":[["2000-01-01T00:00:00Z",3],["2000-01-01T00:00:05Z",7]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Write_Precision(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []struct { + write string + params url.Values + }{ + { + write: fmt.Sprintf("cpu_n0_precision value=1 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").UnixNano()), + }, + { + write: fmt.Sprintf("cpu_n1_precision value=1.1 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").UnixNano()), + params: url.Values{"precision": []string{"n"}}, + }, + { + write: fmt.Sprintf("cpu_u_precision value=100 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").Truncate(time.Microsecond).UnixNano()/int64(time.Microsecond)), + params: url.Values{"precision": []string{"u"}}, + }, + { + write: fmt.Sprintf("cpu_ms_precision value=200 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").Truncate(time.Millisecond).UnixNano()/int64(time.Millisecond)), + params: url.Values{"precision": []string{"ms"}}, + }, + { + write: fmt.Sprintf("cpu_s_precision value=300 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").Truncate(time.Second).UnixNano()/int64(time.Second)), + params: url.Values{"precision": []string{"s"}}, + }, + { + write: fmt.Sprintf("cpu_m_precision value=400 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").Truncate(time.Minute).UnixNano()/int64(time.Minute)), + params: url.Values{"precision": []string{"m"}}, + }, + { + write: fmt.Sprintf("cpu_h_precision value=500 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z").Truncate(time.Hour).UnixNano()/int64(time.Hour)), + params: url.Values{"precision": []string{"h"}}, + }, + } + + test := NewTest("db0", "rp0") + + test.addQueries([]*Query{ + &Query{ + name: "point with nanosecond precision time - no precision specified on write", + command: `SELECT * FROM cpu_n0_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_n0_precision","columns":["time","value"],"values":[["2000-01-01T12:34:56.789012345Z",1]]}]}]}`, + }, + &Query{ + name: "point with nanosecond precision time", + command: `SELECT * FROM cpu_n1_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_n1_precision","columns":["time","value"],"values":[["2000-01-01T12:34:56.789012345Z",1.1]]}]}]}`, + }, + &Query{ + name: "point with microsecond precision time", + command: `SELECT * FROM cpu_u_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_u_precision","columns":["time","value"],"values":[["2000-01-01T12:34:56.789012Z",100]]}]}]}`, + }, + &Query{ + name: "point with millisecond precision time", + command: `SELECT * FROM cpu_ms_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_ms_precision","columns":["time","value"],"values":[["2000-01-01T12:34:56.789Z",200]]}]}]}`, + }, + &Query{ + name: "point with second precision time", + command: `SELECT * FROM cpu_s_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_s_precision","columns":["time","value"],"values":[["2000-01-01T12:34:56Z",300]]}]}]}`, + }, + &Query{ + name: "point with minute precision time", + command: `SELECT * FROM cpu_m_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_m_precision","columns":["time","value"],"values":[["2000-01-01T12:34:00Z",400]]}]}]}`, + }, + &Query{ + name: "point with hour precision time", + command: `SELECT * FROM cpu_h_precision`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"cpu_h_precision","columns":["time","value"],"values":[["2000-01-01T12:00:00Z",500]]}]}]}`, + }, + }...) + + // we are doing writes that require parameter changes, so we are fighting the test harness a little to make this happen properly + for _, w := range writes { + test.write = w.write + test.params = w.params + test.initialized = false + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Wildcards(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`wildcard,region=us-east value=10 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`wildcard,region=us-east valx=20 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`wildcard,region=us-east value=30,valx=40 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + + fmt.Sprintf(`wgroup,region=us-east value=10.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`wgroup,region=us-east value=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`wgroup,region=us-west value=30.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + + fmt.Sprintf(`m1,region=us-east value=10.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`m2,host=server01 field=20.0 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "wildcard", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","region","value","valx"],"values":[["2000-01-01T00:00:00Z","us-east",10,null],["2000-01-01T00:00:10Z","us-east",null,20],["2000-01-01T00:00:20Z","us-east",30,40]]}]}]}`, + }, + &Query{ + name: "wildcard with group by", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM wildcard GROUP BY *`, + exp: `{"results":[{"series":[{"name":"wildcard","tags":{"region":"us-east"},"columns":["time","value","valx"],"values":[["2000-01-01T00:00:00Z",10,null],["2000-01-01T00:00:10Z",null,20],["2000-01-01T00:00:20Z",30,40]]}]}]}`, + }, + &Query{ + name: "GROUP BY queries", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT mean(value) FROM wgroup GROUP BY *`, + exp: `{"results":[{"series":[{"name":"wgroup","tags":{"region":"us-east"},"columns":["time","mean"],"values":[["1970-01-01T00:00:00Z",15]]},{"name":"wgroup","tags":{"region":"us-west"},"columns":["time","mean"],"values":[["1970-01-01T00:00:00Z",30]]}]}]}`, + }, + &Query{ + name: "GROUP BY queries with time", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT mean(value) FROM wgroup WHERE time >= '2000-01-01T00:00:00Z' AND time < '2000-01-01T00:01:00Z' GROUP BY *,TIME(1m)`, + exp: `{"results":[{"series":[{"name":"wgroup","tags":{"region":"us-east"},"columns":["time","mean"],"values":[["2000-01-01T00:00:00Z",15]]},{"name":"wgroup","tags":{"region":"us-west"},"columns":["time","mean"],"values":[["2000-01-01T00:00:00Z",30]]}]}]}`, + }, + &Query{ + name: "wildcard and field in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT value, * FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","region","value","valx"],"values":[["2000-01-01T00:00:00Z","us-east",10,null],["2000-01-01T00:00:10Z","us-east",null,20],["2000-01-01T00:00:20Z","us-east",30,40]]}]}]}`, + }, + &Query{ + name: "field and wildcard in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT value, * FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","region","value","valx"],"values":[["2000-01-01T00:00:00Z","us-east",10,null],["2000-01-01T00:00:10Z","us-east",null,20],["2000-01-01T00:00:20Z","us-east",30,40]]}]}]}`, + }, + &Query{ + name: "field and wildcard in group by", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM wildcard GROUP BY region, *`, + exp: `{"results":[{"series":[{"name":"wildcard","tags":{"region":"us-east"},"columns":["time","value","valx"],"values":[["2000-01-01T00:00:00Z",10,null],["2000-01-01T00:00:10Z",null,20],["2000-01-01T00:00:20Z",30,40]]}]}]}`, + }, + &Query{ + name: "wildcard and field in group by", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM wildcard GROUP BY *, region`, + exp: `{"results":[{"series":[{"name":"wildcard","tags":{"region":"us-east"},"columns":["time","value","valx"],"values":[["2000-01-01T00:00:00Z",10,null],["2000-01-01T00:00:10Z",null,20],["2000-01-01T00:00:20Z",30,40]]}]}]}`, + }, + &Query{ + name: "wildcard with multiple measurements", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM m1, m2`, + exp: `{"results":[{"series":[{"name":"m1","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:00Z",null,null,"us-east",10]]},{"name":"m2","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:01Z",20,"server01",null,null]]}]}]}`, + }, + &Query{ + name: "wildcard with multiple measurements via regex", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM /^m.*/`, + exp: `{"results":[{"series":[{"name":"m1","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:00Z",null,null,"us-east",10]]},{"name":"m2","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:01Z",20,"server01",null,null]]}]}]}`, + }, + &Query{ + name: "wildcard with multiple measurements via regex and limit", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM db0../^m.*/ LIMIT 2`, + exp: `{"results":[{"series":[{"name":"m1","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:00Z",null,null,"us-east",10]]},{"name":"m2","columns":["time","field","host","region","value"],"values":[["2000-01-01T00:00:01Z",20,"server01",null,null]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_WildcardExpansion(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`wildcard,region=us-east,host=A value=10,cpu=80 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`wildcard,region=us-east,host=B value=20,cpu=90 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`wildcard,region=us-west,host=B value=30,cpu=70 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`wildcard,region=us-east,host=A value=40,cpu=60 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + + fmt.Sprintf(`dupnames,region=us-east,day=1 value=10,day=3i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`dupnames,region=us-east,day=2 value=20,day=2i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`dupnames,region=us-west,day=3 value=30,day=1i %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "wildcard", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","cpu","host","region","value"],"values":[["2000-01-01T00:00:00Z",80,"A","us-east",10],["2000-01-01T00:00:10Z",90,"B","us-east",20],["2000-01-01T00:00:20Z",70,"B","us-west",30],["2000-01-01T00:00:30Z",60,"A","us-east",40]]}]}]}`, + }, + &Query{ + name: "no wildcard in select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT cpu, host, region, value FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","cpu","host","region","value"],"values":[["2000-01-01T00:00:00Z",80,"A","us-east",10],["2000-01-01T00:00:10Z",90,"B","us-east",20],["2000-01-01T00:00:20Z",70,"B","us-west",30],["2000-01-01T00:00:30Z",60,"A","us-east",40]]}]}]}`, + }, + &Query{ + name: "no wildcard in select, preserve column order", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT host, cpu, region, value FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","host","cpu","region","value"],"values":[["2000-01-01T00:00:00Z","A",80,"us-east",10],["2000-01-01T00:00:10Z","B",90,"us-east",20],["2000-01-01T00:00:20Z","B",70,"us-west",30],["2000-01-01T00:00:30Z","A",60,"us-east",40]]}]}]}`, + }, + + &Query{ + name: "only tags, no fields", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT host, region FROM wildcard`, + exp: `{"results":[{"error":"statement must have at least one field in select clause"}]}`, + }, + + &Query{ + name: "no wildcard with alias", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT cpu as c, host as h, region, value FROM wildcard`, + exp: `{"results":[{"series":[{"name":"wildcard","columns":["time","c","h","region","value"],"values":[["2000-01-01T00:00:00Z",80,"A","us-east",10],["2000-01-01T00:00:10Z",90,"B","us-east",20],["2000-01-01T00:00:20Z",70,"B","us-west",30],["2000-01-01T00:00:30Z",60,"A","us-east",40]]}]}]}`, + }, + &Query{ + name: "duplicate tag and field key, always favor field over tag", + command: `SELECT * FROM dupnames`, + params: url.Values{"db": []string{"db0"}}, + exp: `{"results":[{"series":[{"name":"dupnames","columns":["time","day","region","value"],"values":[["2000-01-01T00:00:00Z",3,"us-east",10],["2000-01-01T00:00:10Z",2,"us-east",20],["2000-01-01T00:00:20Z",1,"us-west",30]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_AcrossShardsAndFields(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu load=100 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`cpu load=200 %d`, mustParseTime(time.RFC3339Nano, "2010-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`cpu core=4 %d`, mustParseTime(time.RFC3339Nano, "2015-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "two results for cpu", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT load FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2000-01-01T00:00:00Z",100],["2010-01-01T00:00:00Z",200]]}]}]}`, + }, + &Query{ + name: "two results for cpu, multi-select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT core,load FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core","load"],"values":[["2000-01-01T00:00:00Z",null,100],["2010-01-01T00:00:00Z",null,200],["2015-01-01T00:00:00Z",4,null]]}]}]}`, + }, + &Query{ + name: "two results for cpu, wildcard select", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core","load"],"values":[["2000-01-01T00:00:00Z",null,100],["2010-01-01T00:00:00Z",null,200],["2015-01-01T00:00:00Z",4,null]]}]}]}`, + }, + &Query{ + name: "one result for core", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT core FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2015-01-01T00:00:00Z",4]]}]}]}`, + }, + &Query{ + name: "empty result set from non-existent field", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT foo FROM cpu`, + exp: `{"results":[{}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Where_Fields(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu alert_id="alert",tenant_id="tenant",_cust="johnson brothers" %d`, mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + fmt.Sprintf(`cpu alert_id="alert",tenant_id="tenant",_cust="johnson brothers" %d`, mustParseTime(time.RFC3339Nano, "2015-02-28T01:03:36.703820946Z").UnixNano()), + + fmt.Sprintf(`cpu load=100.0,core=4 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:02Z").UnixNano()), + fmt.Sprintf(`cpu load=80.0,core=2 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:01:02Z").UnixNano()), + + fmt.Sprintf(`clicks local=true %d`, mustParseTime(time.RFC3339Nano, "2014-11-10T23:00:01Z").UnixNano()), + fmt.Sprintf(`clicks local=false %d`, mustParseTime(time.RFC3339Nano, "2014-11-10T23:00:02Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + // non type specific + &Query{ + name: "missing measurement with group by", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT load from missing group by *`, + exp: `{"results":[{}]}`, + }, + + // string + &Query{ + name: "single string field", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT alert_id FROM cpu WHERE alert_id='alert'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","alert_id"],"values":[["2015-02-28T01:03:36.703820946Z","alert"]]}]}]}`, + }, + &Query{ + name: "string AND query, all fields in SELECT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT alert_id,tenant_id,_cust FROM cpu WHERE alert_id='alert' AND tenant_id='tenant'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","alert_id","tenant_id","_cust"],"values":[["2015-02-28T01:03:36.703820946Z","alert","tenant","johnson brothers"]]}]}]}`, + }, + &Query{ + name: "string AND query, all fields in SELECT, one in parenthesis", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT alert_id,tenant_id FROM cpu WHERE alert_id='alert' AND (tenant_id='tenant')`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","alert_id","tenant_id"],"values":[["2015-02-28T01:03:36.703820946Z","alert","tenant"]]}]}]}`, + }, + &Query{ + name: "string underscored field", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT alert_id FROM cpu WHERE _cust='johnson brothers'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","alert_id"],"values":[["2015-02-28T01:03:36.703820946Z","alert"]]}]}]}`, + }, + &Query{ + name: "string no match", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT alert_id FROM cpu WHERE _cust='acme'`, + exp: `{"results":[{}]}`, + }, + + // float64 + &Query{ + name: "float64 GT no match", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load > 100`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "float64 GTE match one", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load >= 100`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:00:02Z",100]]}]}]}`, + }, + &Query{ + name: "float64 EQ match upper bound", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load = 100`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:00:02Z",100]]}]}]}`, + }, + &Query{ + name: "float64 LTE match two", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load <= 100`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:00:02Z",100],["2009-11-10T23:01:02Z",80]]}]}]}`, + }, + &Query{ + name: "float64 GT match one", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load > 99`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:00:02Z",100]]}]}]}`, + }, + &Query{ + name: "float64 EQ no match", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load = 99`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "float64 LT match one", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load < 99`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:01:02Z",80]]}]}]}`, + }, + &Query{ + name: "float64 LT no match", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load < 80`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "float64 NE match one", + params: url.Values{"db": []string{"db0"}}, + command: `select load from cpu where load != 100`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","load"],"values":[["2009-11-10T23:01:02Z",80]]}]}]}`, + }, + + // int64 + &Query{ + name: "int64 GT no match", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core > 4`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "int64 GTE match one", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core >= 4`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:00:02Z",4]]}]}]}`, + }, + &Query{ + name: "int64 EQ match upper bound", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core = 4`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:00:02Z",4]]}]}]}`, + }, + &Query{ + name: "int64 LTE match two ", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core <= 4`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:00:02Z",4],["2009-11-10T23:01:02Z",2]]}]}]}`, + }, + &Query{ + name: "int64 GT match one", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core > 3`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:00:02Z",4]]}]}]}`, + }, + &Query{ + name: "int64 EQ no match", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core = 3`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "int64 LT match one", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core < 3`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:01:02Z",2]]}]}]}`, + }, + &Query{ + name: "int64 LT no match", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core < 2`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "int64 NE match one", + params: url.Values{"db": []string{"db0"}}, + command: `select core from cpu where core != 4`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","core"],"values":[["2009-11-10T23:01:02Z",2]]}]}]}`, + }, + + // bool + &Query{ + name: "bool EQ match true", + params: url.Values{"db": []string{"db0"}}, + command: `select local from clicks where local = true`, + exp: `{"results":[{"series":[{"name":"clicks","columns":["time","local"],"values":[["2014-11-10T23:00:01Z",true]]}]}]}`, + }, + &Query{ + name: "bool EQ match false", + params: url.Values{"db": []string{"db0"}}, + command: `select local from clicks where local = false`, + exp: `{"results":[{"series":[{"name":"clicks","columns":["time","local"],"values":[["2014-11-10T23:00:02Z",false]]}]}]}`, + }, + + &Query{ + name: "bool NE match one", + params: url.Values{"db": []string{"db0"}}, + command: `select local from clicks where local != true`, + exp: `{"results":[{"series":[{"name":"clicks","columns":["time","local"],"values":[["2014-11-10T23:00:02Z",false]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Where_With_Tags(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`where_events,tennant=paul foo="bar" %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:02Z").UnixNano()), + fmt.Sprintf(`where_events,tennant=paul foo="baz" %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:03Z").UnixNano()), + fmt.Sprintf(`where_events,tennant=paul foo="bat" %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:04Z").UnixNano()), + fmt.Sprintf(`where_events,tennant=todd foo="bar" %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:05Z").UnixNano()), + fmt.Sprintf(`where_events,tennant=david foo="bap" %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:06Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "tag field and time", + params: url.Values{"db": []string{"db0"}}, + command: `select foo from where_events where (tennant = 'paul' OR tennant = 'david') AND time > 1s AND (foo = 'bar' OR foo = 'baz' OR foo = 'bap')`, + exp: `{"results":[{"series":[{"name":"where_events","columns":["time","foo"],"values":[["2009-11-10T23:00:02Z","bar"],["2009-11-10T23:00:03Z","baz"],["2009-11-10T23:00:06Z","bap"]]}]}]}`, + }, + &Query{ + name: "where on tag that should be double quoted but isn't", + params: url.Values{"db": []string{"db0"}}, + command: `show series where data-center = 'foo'`, + exp: `{"results":[{"error":"invalid expression: data - center = 'foo'"}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_LimitAndOffset(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`limited,tennant=paul foo=2 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:02Z").UnixNano()), + fmt.Sprintf(`limited,tennant=paul foo=3 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:03Z").UnixNano()), + fmt.Sprintf(`limited,tennant=paul foo=4 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:04Z").UnixNano()), + fmt.Sprintf(`limited,tennant=todd foo=5 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:05Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "limit on points", + params: url.Values{"db": []string{"db0"}}, + command: `select foo from "limited" LIMIT 2`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","foo"],"values":[["2009-11-10T23:00:02Z",2],["2009-11-10T23:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "limit higher than the number of data points", + params: url.Values{"db": []string{"db0"}}, + command: `select foo from "limited" LIMIT 20`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","foo"],"values":[["2009-11-10T23:00:02Z",2],["2009-11-10T23:00:03Z",3],["2009-11-10T23:00:04Z",4],["2009-11-10T23:00:05Z",5]]}]}]}`, + }, + &Query{ + name: "limit and offset", + params: url.Values{"db": []string{"db0"}}, + command: `select foo from "limited" LIMIT 2 OFFSET 1`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","foo"],"values":[["2009-11-10T23:00:03Z",3],["2009-11-10T23:00:04Z",4]]}]}]}`, + }, + &Query{ + name: "limit + offset equal to total number of points", + params: url.Values{"db": []string{"db0"}}, + command: `select foo from "limited" LIMIT 3 OFFSET 3`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","foo"],"values":[["2009-11-10T23:00:05Z",5]]}]}]}`, + }, + &Query{ + name: "limit - offset higher than number of points", + command: `select foo from "limited" LIMIT 2 OFFSET 20`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","foo"]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit on points with group by time", + command: `select mean(foo) from "limited" WHERE time >= '2009-11-10T23:00:02Z' AND time < '2009-11-10T23:00:06Z' GROUP BY TIME(1s) LIMIT 2`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","mean"],"values":[["2009-11-10T23:00:02Z",2],["2009-11-10T23:00:03Z",3]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit higher than the number of data points with group by time", + command: `select mean(foo) from "limited" WHERE time >= '2009-11-10T23:00:02Z' AND time < '2009-11-10T23:00:06Z' GROUP BY TIME(1s) LIMIT 20`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","mean"],"values":[["2009-11-10T23:00:02Z",2],["2009-11-10T23:00:03Z",3],["2009-11-10T23:00:04Z",4],["2009-11-10T23:00:05Z",5]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit and offset with group by time", + command: `select mean(foo) from "limited" WHERE time >= '2009-11-10T23:00:02Z' AND time < '2009-11-10T23:00:06Z' GROUP BY TIME(1s) LIMIT 2 OFFSET 1`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","mean"],"values":[["2009-11-10T23:00:03Z",3],["2009-11-10T23:00:04Z",4]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit + offset equal to the number of points with group by time", + command: `select mean(foo) from "limited" WHERE time >= '2009-11-10T23:00:02Z' AND time < '2009-11-10T23:00:06Z' GROUP BY TIME(1s) LIMIT 3 OFFSET 3`, + exp: `{"results":[{"series":[{"name":"limited","columns":["time","mean"],"values":[["2009-11-10T23:00:05Z",5]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit - offset higher than number of points with group by time", + command: `select mean(foo) from "limited" WHERE time >= '2009-11-10T23:00:02Z' AND time < '2009-11-10T23:00:06Z' GROUP BY TIME(1s) LIMIT 2 OFFSET 20`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit higher than the number of data points should error", + command: `select mean(foo) from "limited" where time > '2000-01-01T00:00:00Z' group by time(1s), * fill(0) limit 2147483647`, + exp: `{"results":[{"error":"too many points in the group by interval. maybe you forgot to specify a where time clause?"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "limit1 higher than MaxGroupBy but the number of data points is less than MaxGroupBy", + command: `select mean(foo) from "limited" where time >= '2009-11-10T23:00:02Z' and time < '2009-11-10T23:00:03Z' group by time(1s), * fill(0) limit 2147483647`, + exp: `{"results":[{"series":[{"name":"limited","tags":{"tennant":"paul"},"columns":["time","mean"],"values":[["2009-11-10T23:00:02Z",2]]},{"name":"limited","tags":{"tennant":"todd"},"columns":["time","mean"],"values":[["2009-11-10T23:00:02Z",0]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Fill(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`fills val=3 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:02Z").UnixNano()), + fmt.Sprintf(`fills val=5 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:03Z").UnixNano()), + fmt.Sprintf(`fills val=4 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:06Z").UnixNano()), + fmt.Sprintf(`fills val=10 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:16Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "fill with value", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' group by time(5s) FILL(1)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",4],["2009-11-10T23:00:05Z",4],["2009-11-10T23:00:10Z",1],["2009-11-10T23:00:15Z",10]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "fill with value, WHERE all values match condition", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' and val < 50 group by time(5s) FILL(1)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",4],["2009-11-10T23:00:05Z",4],["2009-11-10T23:00:10Z",1],["2009-11-10T23:00:15Z",10]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "fill with value, WHERE no values match condition", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' and val > 50 group by time(5s) FILL(1)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",1],["2009-11-10T23:00:05Z",1],["2009-11-10T23:00:10Z",1],["2009-11-10T23:00:15Z",1]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "fill with previous", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' group by time(5s) FILL(previous)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",4],["2009-11-10T23:00:05Z",4],["2009-11-10T23:00:10Z",4],["2009-11-10T23:00:15Z",10]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "fill with none, i.e. clear out nulls", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' group by time(5s) FILL(none)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",4],["2009-11-10T23:00:05Z",4],["2009-11-10T23:00:15Z",10]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "fill defaults to null", + command: `select mean(val) from fills where time >= '2009-11-10T23:00:00Z' and time < '2009-11-10T23:00:20Z' group by time(5s)`, + exp: `{"results":[{"series":[{"name":"fills","columns":["time","mean"],"values":[["2009-11-10T23:00:00Z",4],["2009-11-10T23:00:05Z",4],["2009-11-10T23:00:10Z",null],["2009-11-10T23:00:15Z",10]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_Chunk(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := make([]string, 10001) // 10,000 is the default chunking size, even when no chunking requested. + expectedValues := make([]string, len(writes)) + for i := 0; i < len(writes); i++ { + writes[i] = fmt.Sprintf(`cpu value=%d %d`, i, time.Unix(0, int64(i)).UnixNano()) + expectedValues[i] = fmt.Sprintf(`["%s",%d]`, time.Unix(0, int64(i)).UTC().Format(time.RFC3339Nano), i) + } + expected := fmt.Sprintf(`{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[%s]}]}]}`, strings.Join(expectedValues, ",")) + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "SELECT all values, no chunking", + command: `SELECT value FROM cpu`, + exp: expected, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + +} + +func TestServer_Query_DropAndRecreateMeasurement(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`memory,host=serverB,region=uswest val=33.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "Drop Measurement, series tags preserved tests", + command: `SHOW MEASUREMENTS`, + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"],["memory"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show series", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=serverA,region=uswest","serverA","uswest"]]},{"name":"memory","columns":["_key","host","region"],"values":[["memory,host=serverB,region=uswest","serverB","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "ensure we can query for memory with both tags", + command: `SELECT * FROM memory where region='uswest' and host='serverB' GROUP BY *`, + exp: `{"results":[{"series":[{"name":"memory","tags":{"host":"serverB","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:01Z",33.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "drop measurement cpu", + command: `DROP MEASUREMENT cpu`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify measurements", + command: `SHOW MEASUREMENTS`, + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["memory"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify series", + command: `SHOW SERIES`, + exp: `{"results":[{"series":[{"name":"memory","columns":["_key","host","region"],"values":[["memory,host=serverB,region=uswest","serverB","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify cpu measurement is gone", + command: `SELECT * FROM cpu`, + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify selecting from a tag 'host' still works", + command: `SELECT * FROM memory where host='serverB' GROUP BY *`, + exp: `{"results":[{"series":[{"name":"memory","tags":{"host":"serverB","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:01Z",33.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify selecting from a tag 'region' still works", + command: `SELECT * FROM memory where region='uswest' GROUP BY *`, + exp: `{"results":[{"series":[{"name":"memory","tags":{"host":"serverB","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:01Z",33.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify selecting from a tag 'host' and 'region' still works", + command: `SELECT * FROM memory where region='uswest' and host='serverB' GROUP BY *`, + exp: `{"results":[{"series":[{"name":"memory","tags":{"host":"serverB","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:01Z",33.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "Drop non-existant measurement", + command: `DROP MEASUREMENT doesntexist`, + exp: `{"results":[{"error":"measurement not found: doesntexist"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + // Test that re-inserting the measurement works fine. + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + + test = NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "verify measurements after recreation", + command: `SHOW MEASUREMENTS`, + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"],["memory"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "verify cpu measurement has been re-inserted", + command: `SELECT * FROM cpu GROUP BY *`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_ShowSeries(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=server01 value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:01Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=uswest value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:02Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:03Z").UnixNano()), + fmt.Sprintf(`cpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:04Z").UnixNano()), + fmt.Sprintf(`gpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:05Z").UnixNano()), + fmt.Sprintf(`gpu,host=server03,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:06Z").UnixNano()), + fmt.Sprintf(`disk,host=server03,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:07Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: `show series`, + command: "SHOW SERIES", + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=server01","server01",""],["cpu,host=server01,region=uswest","server01","uswest"],["cpu,host=server01,region=useast","server01","useast"],["cpu,host=server02,region=useast","server02","useast"]]},{"name":"disk","columns":["_key","host","region"],"values":[["disk,host=server03,region=caeast","server03","caeast"]]},{"name":"gpu","columns":["_key","host","region"],"values":[["gpu,host=server02,region=useast","server02","useast"],["gpu,host=server03,region=caeast","server03","caeast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series from measurement`, + command: "SHOW SERIES FROM cpu", + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=server01","server01",""],["cpu,host=server01,region=uswest","server01","uswest"],["cpu,host=server01,region=useast","server01","useast"],["cpu,host=server02,region=useast","server02","useast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series from regular expression`, + command: "SHOW SERIES FROM /[cg]pu/", + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=server01","server01",""],["cpu,host=server01,region=uswest","server01","uswest"],["cpu,host=server01,region=useast","server01","useast"],["cpu,host=server02,region=useast","server02","useast"]]},{"name":"gpu","columns":["_key","host","region"],"values":[["gpu,host=server02,region=useast","server02","useast"],["gpu,host=server03,region=caeast","server03","caeast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series with where tag`, + command: "SHOW SERIES WHERE region = 'uswest'", + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=server01,region=uswest","server01","uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series where tag matches regular expression`, + command: "SHOW SERIES WHERE region =~ /ca.*/", + exp: `{"results":[{"series":[{"name":"disk","columns":["_key","host","region"],"values":[["disk,host=server03,region=caeast","server03","caeast"]]},{"name":"gpu","columns":["_key","host","region"],"values":[["gpu,host=server03,region=caeast","server03","caeast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series`, + command: "SHOW SERIES WHERE host !~ /server0[12]/", + exp: `{"results":[{"series":[{"name":"disk","columns":["_key","host","region"],"values":[["disk,host=server03,region=caeast","server03","caeast"]]},{"name":"gpu","columns":["_key","host","region"],"values":[["gpu,host=server03,region=caeast","server03","caeast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series with from and where`, + command: "SHOW SERIES FROM cpu WHERE region = 'useast'", + exp: `{"results":[{"series":[{"name":"cpu","columns":["_key","host","region"],"values":[["cpu,host=server01,region=useast","server01","useast"],["cpu,host=server02,region=useast","server02","useast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series with WHERE time should fail`, + command: "SHOW SERIES WHERE time > now() - 1h", + exp: `{"results":[{"error":"SHOW SERIES doesn't support time in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show series with WHERE field should fail`, + command: "SHOW SERIES WHERE value > 10.0", + exp: `{"results":[{"error":"SHOW SERIES doesn't support fields in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_ShowMeasurements(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=server01 value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=uswest value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server02,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`other,host=server03,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: `show measurements with limit 2`, + command: "SHOW MEASUREMENTS LIMIT 2", + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"],["gpu"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements using WITH`, + command: "SHOW MEASUREMENTS WITH MEASUREMENT = cpu", + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements using WITH and regex`, + command: "SHOW MEASUREMENTS WITH MEASUREMENT =~ /[cg]pu/", + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"],["gpu"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements using WITH and regex - no matches`, + command: "SHOW MEASUREMENTS WITH MEASUREMENT =~ /.*zzzzz.*/", + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements where tag matches regular expression`, + command: "SHOW MEASUREMENTS WHERE region =~ /ca.*/", + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["gpu"],["other"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements where tag does not match a regular expression`, + command: "SHOW MEASUREMENTS WHERE region !~ /ca.*/", + exp: `{"results":[{"series":[{"name":"measurements","columns":["name"],"values":[["cpu"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show measurements with time in WHERE clauses errors`, + command: `SHOW MEASUREMENTS WHERE time > now() - 1h`, + exp: `{"results":[{"error":"SHOW MEASUREMENTS doesn't support time in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_ShowTagKeys(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=server01 value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=uswest value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server02,region=useast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server03,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`disk,host=server03,region=caeast value=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: `show tag keys`, + command: "SHOW TAG KEYS", + exp: `{"results":[{"series":[{"name":"cpu","columns":["tagKey"],"values":[["host"],["region"]]},{"name":"disk","columns":["tagKey"],"values":[["host"],["region"]]},{"name":"gpu","columns":["tagKey"],"values":[["host"],["region"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show tag keys from", + command: "SHOW TAG KEYS FROM cpu", + exp: `{"results":[{"series":[{"name":"cpu","columns":["tagKey"],"values":[["host"],["region"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show tag keys from regex", + command: "SHOW TAG KEYS FROM /[cg]pu/", + exp: `{"results":[{"series":[{"name":"cpu","columns":["tagKey"],"values":[["host"],["region"]]},{"name":"gpu","columns":["tagKey"],"values":[["host"],["region"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show tag keys measurement not found", + command: "SHOW TAG KEYS FROM doesntexist", + exp: `{"results":[{}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show tag keys with time in WHERE clause errors", + command: "SHOW TAG KEYS FROM cpu WHERE time > now() - 1h", + exp: `{"results":[{"error":"SHOW TAG KEYS doesn't support time in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: "show tag values with key", + command: "SHOW TAG VALUES WITH KEY = host", + exp: `{"results":[{"series":[{"name":"hostTagValues","columns":["host"],"values":[["server01"],["server02"],["server03"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key and where`, + command: `SHOW TAG VALUES FROM cpu WITH KEY = host WHERE region = 'uswest'`, + exp: `{"results":[{"series":[{"name":"hostTagValues","columns":["host"],"values":[["server01"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key and where matches regular expression`, + command: `SHOW TAG VALUES WITH KEY = host WHERE region =~ /ca.*/`, + exp: `{"results":[{"series":[{"name":"hostTagValues","columns":["host"],"values":[["server03"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key and where does not matche regular expression`, + command: `SHOW TAG VALUES WITH KEY = region WHERE host !~ /server0[12]/`, + exp: `{"results":[{"series":[{"name":"regionTagValues","columns":["region"],"values":[["caeast"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key in and where does not matche regular expression`, + command: `SHOW TAG VALUES FROM cpu WITH KEY IN (host, region) WHERE region = 'uswest'`, + exp: `{"results":[{"series":[{"name":"hostTagValues","columns":["host"],"values":[["server01"]]},{"name":"regionTagValues","columns":["region"],"values":[["uswest"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key and measurement matches regular expression`, + command: `SHOW TAG VALUES FROM /[cg]pu/ WITH KEY = host`, + exp: `{"results":[{"series":[{"name":"hostTagValues","columns":["host"],"values":[["server01"],["server02"],["server03"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show tag values with key and time in WHERE clause should error`, + command: `SHOW TAG VALUES WITH KEY = host WHERE time > now() - 1h`, + exp: `{"results":[{"error":"SHOW TAG VALUES doesn't support time in WHERE clause"}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_ShowFieldKeys(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=server01 field1=100 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=uswest field1=200,field2=300,field3=400 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=useast field1=200,field2=300,field3=400 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`cpu,host=server02,region=useast field1=200,field2=300,field3=400 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server01,region=useast field4=200,field5=300 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`gpu,host=server03,region=caeast field6=200,field7=300 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + fmt.Sprintf(`disk,host=server03,region=caeast field8=200,field9=300 %d`, mustParseTime(time.RFC3339Nano, "2009-11-10T23:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: `show field keys`, + command: `SHOW FIELD KEYS`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["fieldKey"],"values":[["field1"],["field2"],["field3"]]},{"name":"disk","columns":["fieldKey"],"values":[["field8"],["field9"]]},{"name":"gpu","columns":["fieldKey"],"values":[["field4"],["field5"],["field6"],["field7"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show field keys from measurement`, + command: `SHOW FIELD KEYS FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["fieldKey"],"values":[["field1"],["field2"],["field3"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + &Query{ + name: `show field keys measurement with regex`, + command: `SHOW FIELD KEYS FROM /[cg]pu/`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["fieldKey"],"values":[["field1"],["field2"],["field3"]]},{"name":"gpu","columns":["fieldKey"],"values":[["field4"],["field5"],["field6"],["field7"]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_ContinuousQuery(t *testing.T) { + t.Skip() + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + runTest := func(test *Test, t *testing.T) { + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + } + + // Start times of CQ intervals. + interval0 := time.Now().Add(-time.Second).Round(time.Second * 5) + interval1 := interval0.Add(-time.Second * 5) + interval2 := interval0.Add(-time.Second * 10) + interval3 := interval0.Add(-time.Second * 15) + + writes := []string{ + // Point too far in the past for CQ to pick up. + fmt.Sprintf(`cpu,host=server01,region=uswest value=100 %d`, interval3.Add(time.Second).UnixNano()), + + // Points two intervals ago. + fmt.Sprintf(`cpu,host=server01 value=100 %d`, interval2.Add(time.Second).UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=uswest value=100 %d`, interval2.Add(time.Second*2).UnixNano()), + fmt.Sprintf(`cpu,host=server01,region=useast value=100 %d`, interval2.Add(time.Second*3).UnixNano()), + + // Points one interval ago. + fmt.Sprintf(`gpu,host=server02,region=useast value=100 %d`, interval1.Add(time.Second).UnixNano()), + fmt.Sprintf(`gpu,host=server03,region=caeast value=100 %d`, interval1.Add(time.Second*2).UnixNano()), + + // Points in the current interval. + fmt.Sprintf(`gpu,host=server03,region=caeast value=100 %d`, interval0.Add(time.Second).UnixNano()), + fmt.Sprintf(`disk,host=server03,region=caeast value=100 %d`, interval0.Add(time.Second*2).UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + test.addQueries([]*Query{ + &Query{ + name: `create another retention policy for CQ to write into`, + command: `CREATE RETENTION POLICY rp1 ON db0 DURATION 1h REPLICATION 1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "create continuous query with backreference", + command: `CREATE CONTINUOUS QUERY "cq1" ON db0 BEGIN SELECT count(value) INTO "rp1".:MEASUREMENT FROM /[cg]pu/ GROUP BY time(5s) END`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: `create another retention policy for CQ to write into`, + command: `CREATE RETENTION POLICY rp2 ON db0 DURATION 1h REPLICATION 1`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "create continuous query with backreference and group by time", + command: `CREATE CONTINUOUS QUERY "cq2" ON db0 BEGIN SELECT count(value) INTO "rp2".:MEASUREMENT FROM /[cg]pu/ GROUP BY time(5s), * END`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: `show continuous queries`, + command: `SHOW CONTINUOUS QUERIES`, + exp: `{"results":[{"series":[{"name":"db0","columns":["name","query"],"values":[["cq1","CREATE CONTINUOUS QUERY cq1 ON db0 BEGIN SELECT count(value) INTO \"db0\".\"rp1\".:MEASUREMENT FROM \"db0\".\"rp0\"./[cg]pu/ GROUP BY time(5s) END"],["cq2","CREATE CONTINUOUS QUERY cq2 ON db0 BEGIN SELECT count(value) INTO \"db0\".\"rp2\".:MEASUREMENT FROM \"db0\".\"rp0\"./[cg]pu/ GROUP BY time(5s), * END"]]}]}]}`, + }, + }...) + + // Run first test to create CQs. + runTest(&test, t) + + // Trigger CQs to run. + u := fmt.Sprintf("%s/data/process_continuous_queries?time=%d", s.URL(), interval0.UnixNano()) + if _, err := s.HTTPPost(u, nil); err != nil { + t.Fatal(err) + } + + // Wait for CQs to run. TODO: fix this ugly hack + time.Sleep(time.Second * 5) + + // Setup tests to check the CQ results. + test2 := NewTest("db0", "rp1") + test2.addQueries([]*Query{ + &Query{ + name: "check results of cq1", + command: `SELECT * FROM "rp1"./[cg]pu/`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","count","host","region","value"],"values":[["` + interval2.UTC().Format(time.RFC3339Nano) + `",3,null,null,null]]},{"name":"gpu","columns":["time","count","host","region","value"],"values":[["` + interval1.UTC().Format(time.RFC3339Nano) + `",2,null,null,null],["` + interval0.UTC().Format(time.RFC3339Nano) + `",1,null,null,null]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + // TODO: restore this test once this is fixed: https://github.com/influxdb/influxdb/issues/3968 + &Query{ + skip: true, + name: "check results of cq2", + command: `SELECT * FROM "rp2"./[cg]pu/`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","count","host","region","value"],"values":[["` + interval2.UTC().Format(time.RFC3339Nano) + `",1,"server01","uswest",null],["` + interval2.UTC().Format(time.RFC3339Nano) + `",1,"server01","",null],["` + interval2.UTC().Format(time.RFC3339Nano) + `",1,"server01","useast",null]]},{"name":"gpu","columns":["time","count","host","region","value"],"values":[["` + interval1.UTC().Format(time.RFC3339Nano) + `",1,"server02","useast",null],["` + interval1.UTC().Format(time.RFC3339Nano) + `",1,"server03","caeast",null],["` + interval0.UTC().Format(time.RFC3339Nano) + `",1,"server03","caeast",null]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + // Run second test to check CQ results. + runTest(&test2, t) +} + +// Tests that a known CQ query with concurrent writes does not deadlock the server +func TestServer_ContinuousQuery_Deadlock(t *testing.T) { + + // Skip until #3517 & #3522 are merged + t.Skip("Skipping CQ deadlock test") + if testing.Short() { + t.Skip("skipping CQ deadlock test") + } + t.Parallel() + s := OpenServer(NewConfig(), "") + defer func() { + s.Close() + // Nil the server so our deadlock detector goroutine can determine if we completed writes + // without timing out + s.Server = nil + }() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + + test.addQueries([]*Query{ + &Query{ + name: "create continuous query", + command: `CREATE CONTINUOUS QUERY "my.query" ON db0 BEGIN SELECT sum(visits) as visits INTO test_1m FROM myseries GROUP BY time(1m), host END`, + exp: `{"results":[{}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } + + // Deadlock detector. If the deadlock is fixed, this test should complete all the writes in ~2.5s seconds (with artifical delays + // added). After 10 seconds, if the server has not been closed then we hit the deadlock bug. + iterations := 0 + go func(s *Server) { + <-time.After(10 * time.Second) + + // If the server is not nil then the test is still running and stuck. We panic to avoid + // having the whole test suite hang indefinitely. + if s.Server != nil { + panic("possible deadlock. writes did not complete in time") + } + }(s) + + for { + + // After the second write, if the deadlock exists, we'll get a write timeout and + // all subsequent writes will timeout + if iterations > 5 { + break + } + writes := []string{} + for i := 0; i < 1000; i++ { + writes = append(writes, fmt.Sprintf(`myseries,host=host-%d visits=1i`, i)) + } + write := strings.Join(writes, "\n") + + if _, err := s.Write(test.db, test.rp, write, test.params); err != nil { + t.Fatal(err) + } + iterations += 1 + time.Sleep(500 * time.Millisecond) + } +} + +func TestServer_Query_EvilIdentifiers(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + test := NewTest("db0", "rp0") + test.write = fmt.Sprintf("cpu select=1,in-bytes=2 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()) + + test.addQueries([]*Query{ + &Query{ + name: `query evil identifiers`, + command: `SELECT "select", "in-bytes" FROM cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","select","in-bytes"],"values":[["2000-01-01T00:00:00Z",1,2]]}]}]}`, + params: url.Values{"db": []string{"db0"}}, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_OrderByTime(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu,host=server1 value=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + fmt.Sprintf(`cpu,host=server1 value=2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:02Z").UnixNano()), + fmt.Sprintf(`cpu,host=server1 value=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + + fmt.Sprintf(`power,presence=true value=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + fmt.Sprintf(`power,presence=true value=2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:02Z").UnixNano()), + fmt.Sprintf(`power,presence=true value=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + fmt.Sprintf(`power,presence=false value=4 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:04Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "order on points", + params: url.Values{"db": []string{"db0"}}, + command: `select value from "cpu" ORDER BY time DESC`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:03Z",3],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:01Z",1]]}]}]}`, + }, + + &Query{ + name: "order desc with tags", + params: url.Values{"db": []string{"db0"}}, + command: `select value from "power" ORDER BY time DESC`, + exp: `{"results":[{"series":[{"name":"power","columns":["time","value"],"values":[["2000-01-01T00:00:04Z",4],["2000-01-01T00:00:03Z",3],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:01Z",1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_FieldWithMultiplePeriods(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu foo.bar.baz=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "baseline", + params: url.Values{"db": []string{"db0"}}, + command: `select * from cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","foo.bar.baz"],"values":[["2000-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "select field with periods", + params: url.Values{"db": []string{"db0"}}, + command: `select "foo.bar.baz" from cpu`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","foo.bar.baz"],"values":[["2000-01-01T00:00:00Z",1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_FieldWithMultiplePeriodsMeasurementPrefixMatch(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`foo foo.bar.baz=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "baseline", + params: url.Values{"db": []string{"db0"}}, + command: `select * from foo`, + exp: `{"results":[{"series":[{"name":"foo","columns":["time","foo.bar.baz"],"values":[["2000-01-01T00:00:00Z",1]]}]}]}`, + }, + &Query{ + name: "select field with periods", + params: url.Values{"db": []string{"db0"}}, + command: `select "foo.bar.baz" from foo`, + exp: `{"results":[{"series":[{"name":"foo","columns":["time","foo.bar.baz"],"values":[["2000-01-01T00:00:00Z",1]]}]}]}`, + }, + }...) + + for i, query := range test.queries { + if i == 0 { + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + } + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +func TestServer_Query_IntoTarget(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`foo value=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf(`foo value=2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:10Z").UnixNano()), + fmt.Sprintf(`foo value=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:20Z").UnixNano()), + fmt.Sprintf(`foo value=4 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:30Z").UnixNano()), + fmt.Sprintf(`foo value=4,foobar=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:40Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "into", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * INTO baz FROM foo`, + exp: `{"results":[{"series":[{"name":"result","columns":["time","written"],"values":[["1970-01-01T00:00:00Z",5]]}]}]}`, + }, + &Query{ + name: "confirm results", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * FROM baz`, + exp: `{"results":[{"series":[{"name":"baz","columns":["time","foobar","value"],"values":[["2000-01-01T00:00:00Z",null,1],["2000-01-01T00:00:10Z",null,2],["2000-01-01T00:00:20Z",null,3],["2000-01-01T00:00:30Z",null,4],["2000-01-01T00:00:40Z",3,4]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} + +// This test reproduced a data race with closing the +// Subscriber points channel while writes were in-flight in the PointsWriter. +func TestServer_ConcurrentPointsWriter_Subscriber(t *testing.T) { + t.Parallel() + s := OpenDefaultServer(NewConfig(), "") + defer s.Close() + + // goroutine to write points + done := make(chan struct{}) + go func() { + for { + select { + case <-done: + return + default: + wpr := &cluster.WritePointsRequest{ + Database: "db0", + RetentionPolicy: "rp0", + } + s.PointsWriter.WritePoints(wpr) + } + } + }() + + time.Sleep(10 * time.Millisecond) + + close(done) + // Race occurs on s.Close() +} + +// Ensure time in where clause is inclusive +func TestServer_WhereTimeInclusive(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 0)); err != nil { + t.Fatal(err) + } + if err := s.MetaStore.SetDefaultRetentionPolicy("db0", "rp0"); err != nil { + t.Fatal(err) + } + + writes := []string{ + fmt.Sprintf(`cpu value=1 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:01Z").UnixNano()), + fmt.Sprintf(`cpu value=2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:02Z").UnixNano()), + fmt.Sprintf(`cpu value=3 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:03Z").UnixNano()), + } + + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "all GTE/LTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time >= '2000-01-01T00:00:01Z' and time <= '2000-01-01T00:00:03Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "all GTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time >= '2000-01-01T00:00:01Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "all LTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time <= '2000-01-01T00:00:03Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "first GTE/LTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time >= '2000-01-01T00:00:01Z' and time <= '2000-01-01T00:00:01Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1]]}]}]}`, + }, + &Query{ + name: "last GTE/LTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time >= '2000-01-01T00:00:03Z' and time <= '2000-01-01T00:00:03Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "before GTE/LTE", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time <= '2000-01-01T00:00:00Z'`, + exp: `{"results":[{}]}`, + }, + &Query{ + name: "all GT/LT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time > '2000-01-01T00:00:00Z' and time < '2000-01-01T00:00:04Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "first GT/LT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time > '2000-01-01T00:00:00Z' and time < '2000-01-01T00:00:02Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1]]}]}]}`, + }, + &Query{ + name: "last GT/LT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time > '2000-01-01T00:00:02Z' and time < '2000-01-01T00:00:04Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "all GT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time > '2000-01-01T00:00:00Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + &Query{ + name: "all LT", + params: url.Values{"db": []string{"db0"}}, + command: `SELECT * from cpu where time < '2000-01-01T00:00:04Z'`, + exp: `{"results":[{"series":[{"name":"cpu","columns":["time","value"],"values":[["2000-01-01T00:00:01Z",1],["2000-01-01T00:00:02Z",2],["2000-01-01T00:00:03Z",3]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.md new file mode 100644 index 00000000..8df37e33 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/cmd/influxd/run/server_test.md @@ -0,0 +1,150 @@ +# Server Integration Tests + +Currently, the file `server_test.go` has integration tests for single node scenarios. +At some point we'll need to add cluster tests, and may add them in a different file, or +rename `server_test.go` to `server_single_node_test.go` or something like that. + +## What is in a test? + +Each test is broken apart effectively into the following areas: + +- Write sample data +- Use cases for table driven test, that include a command (typically a query) and an expected result. + +When each test runs it does the following: + +- init: determines if there are any writes and if so, writes them to the in-memory database +- queries: iterate through each query, executing the command, and comparing the results to the expected result. + +## Idempotent - Allows for parallel tests + +Each test should be `idempotent`, meaning that its data will not be affected by other tests, or use cases within the table tests themselves. +This allows for parallel testing, keeping the test suite total execution time very low. + +### Basic sample test + +```go +// Ensure the server can have a database with multiple measurements. +func TestServer_Query_Multiple_Measurements(t *testing.T) { + t.Parallel() + s := OpenServer(NewConfig(), "") + defer s.Close() + + if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) + } + + // Make sure we do writes for measurements that will span across shards + writes := []string{ + fmt.Sprintf("cpu,host=server01 value=100,core=4 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf("cpu1,host=server02 value=50,core=2 %d", mustParseTime(time.RFC3339Nano, "2015-01-01T00:00:00Z").UnixNano()), + } + test := NewTest("db0", "rp0") + test.write = strings.Join(writes, "\n") + + test.addQueries([]*Query{ + &Query{ + name: "measurement in one shard but not another shouldn't panic server", + command: `SELECT host,value FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["2000-01-01T00:00:00Z",100]]}]}]}`, + }, + }...) + + if err := test.init(s); err != nil { + t.Fatalf("test init failed: %s", err) + } + + for _, query := range test.queries { + if query.skip { + t.Logf("SKIP:: %s", query.name) + continue + } + if err := query.Execute(s); err != nil { + t.Error(query.Error(err)) + } else if !query.success() { + t.Error(query.failureMessage()) + } + } +} +``` + +Let's break this down: + +In this test, we first tell it to run in parallel with the `t.Parallel()` call. + +We then open a new server with: + +```go +s := OpenServer(NewConfig(), "") +defer s.Close() +``` + +If needed, we create a database and default retention policy. This is usually needed +when inserting and querying data. This is not needed if you are testing commands like `CREATE DATABASE`, `SHOW DIAGNOSTICS`, etc. + +```go +if err := s.CreateDatabaseAndRetentionPolicy("db0", newRetentionPolicyInfo("rp0", 1, 1*time.Hour)); err != nil { + t.Fatal(err) +} +``` + +Next, set up the write data you need: + +```go +writes := []string{ + fmt.Sprintf("cpu,host=server01 value=100,core=4 %d", mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), + fmt.Sprintf("cpu1,host=server02 value=50,core=2 %d", mustParseTime(time.RFC3339Nano, "2015-01-01T00:00:00Z").UnixNano()), +} +``` +Create a new test with the database and retention policy: + +```go +test := NewTest("db0", "rp0") +``` + +Send in the writes: +```go +test.write = strings.Join(writes, "\n") +``` + +Add some queries (the second one is mocked out to show how to add more than one): + +```go +test.addQueries([]*Query{ + &Query{ + name: "measurement in one shard but not another shouldn't panic server", + command: `SELECT host,value FROM db0.rp0.cpu`, + exp: `{"results":[{"series":[{"name":"cpu","tags":{"host":"server01"},"columns":["time","value"],"values":[["2000-01-01T00:00:00Z",100]]}]}]}`, + }, + &Query{ + name: "another test here...", + command: `Some query command`, + exp: `the expected results`, + }, +}...) +``` + +The rest of the code is boilerplate execution code. It is purposefully not refactored out to a helper +to make sure the test failure reports the proper lines for debugging purposes. + +#### Running the tests + +To run the tests: + +```sh +go test ./cmd/influxd/run -parallel 500 -timeout 10s +``` + +#### Running a specific test + +```sh +go test ./cmd/influxd/run -parallel 500 -timeout 10s -run TestServer_Query_Fill +``` + +#### Verbose feedback + +By default, all logs are silenced when testing. If you pass in the `-v` flag, the test suite becomes verbose, and enables all logging in the system + +```sh +go test ./cmd/influxd/run -parallel 500 -timeout 10s -run TestServer_Query_Fill -v +``` diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/errors.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/errors.go new file mode 100644 index 00000000..7627ee2f --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/errors.go @@ -0,0 +1,45 @@ +package influxdb + +import ( + "errors" + "fmt" + "strings" +) + +var ( + // ErrFieldsRequired is returned when a point does not any fields. + ErrFieldsRequired = errors.New("fields required") + + // ErrFieldTypeConflict is returned when a new field already exists with a different type. + ErrFieldTypeConflict = errors.New("field type conflict") +) + +// ErrDatabaseNotFound indicates that a database operation failed on the +// specified database because the specified database does not exist. +func ErrDatabaseNotFound(name string) error { return fmt.Errorf("database not found: %s", name) } + +// ErrRetentionPolicyNotFound indicates that the named retention policy could +// not be found in the database. +func ErrRetentionPolicyNotFound(name string) error { + return fmt.Errorf("retention policy not found: %s", name) +} + +// IsClientError indicates whether an error is a known client error. +func IsClientError(err error) bool { + if err == nil { + return false + } + + if err == ErrFieldsRequired { + return true + } + if err == ErrFieldTypeConflict { + return true + } + + if strings.Contains(err.Error(), ErrFieldTypeConflict.Error()) { + return true + } + + return false +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/.rvmrc b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/.rvmrc new file mode 100644 index 00000000..a9c1a9ca --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/.rvmrc @@ -0,0 +1 @@ +rvm use ruby-2.1.0@burn-in --create diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile new file mode 100644 index 00000000..b1816e8b --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile @@ -0,0 +1,4 @@ +source 'https://rubygems.org' + +gem "colorize" +gem "influxdb" diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile.lock b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile.lock new file mode 100644 index 00000000..9e721c3a --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/Gemfile.lock @@ -0,0 +1,14 @@ +GEM + remote: https://rubygems.org/ + specs: + colorize (0.6.0) + influxdb (0.0.16) + json + json (1.8.1) + +PLATFORMS + ruby + +DEPENDENCIES + colorize + influxdb diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/burn-in.rb b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/burn-in.rb new file mode 100644 index 00000000..1d44bc2c --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/burn-in.rb @@ -0,0 +1,79 @@ +require "influxdb" +require "colorize" +require "benchmark" + +require_relative "log" +require_relative "random_gaussian" + +BATCH_SIZE = 10_000 + +Log.info "Starting burn-in suite" +master = InfluxDB::Client.new +master.delete_database("burn-in") rescue nil +master.create_database("burn-in") +master.create_database_user("burn-in", "user", "pass") + +master.database = "burn-in" +# master.query "select * from test1 into test2;" +# master.query "select count(value) from test1 group by time(1m) into test2;" + +influxdb = InfluxDB::Client.new "burn-in", username: "user", password: "pass" + +Log.success "Connected to server #{influxdb.host}:#{influxdb.port}" + +Log.log "Creating RandomGaussian(500, 25)" +gaussian = RandomGaussian.new(500, 25) +point_count = 0 + +while true + Log.log "Generating 10,000 points.." + points = [] + BATCH_SIZE.times do |n| + points << {value: gaussian.rand.to_i.abs} + end + point_count += points.length + + Log.info "Sending points to server.." + begin + st = Time.now + foo = influxdb.write_point("test1", points) + et = Time.now + Log.log foo.inspect + Log.log "#{et-st} seconds elapsed" + Log.success "Write successful." + rescue => e + Log.failure "Write failed:" + Log.log e + end + sleep 0.5 + + Log.info "Checking regular points" + st = Time.now + response = influxdb.query("select count(value) from test1;") + et = Time.now + + Log.log "#{et-st} seconds elapsed" + + response_count = response["test1"].first["count"] + if point_count == response_count + Log.success "Point counts match: #{point_count} == #{response_count}" + else + Log.failure "Point counts don't match: #{point_count} != #{response_count}" + end + + # Log.info "Checking continuous query points for test2" + # st = Time.now + # response = influxdb.query("select count(value) from test2;") + # et = Time.now + + # Log.log "#{et-st} seconds elapsed" + + # response_count = response["test2"].first["count"] + # if point_count == response_count + # Log.success "Point counts match: #{point_count} == #{response_count}" + # else + # Log.failure "Point counts don't match: #{point_count} != #{response_count}" + # end +end + + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/log.rb b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/log.rb new file mode 100644 index 00000000..0f70d763 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/log.rb @@ -0,0 +1,23 @@ +module Log + def self.info(msg) + print Time.now.strftime("%r") + " | " + puts msg.to_s.colorize(:yellow) + end + + def self.success(msg) + print Time.now.strftime("%r") + " | " + puts msg.to_s.colorize(:green) + end + + def self.failure(msg) + print Time.now.strftime("%r") + " | " + puts msg.to_s.colorize(:red) + end + + def self.log(msg) + print Time.now.strftime("%r") + " | " + puts msg.to_s + end +end + + diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_gaussian.rb b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_gaussian.rb new file mode 100644 index 00000000..51d6c3c0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_gaussian.rb @@ -0,0 +1,31 @@ +class RandomGaussian + def initialize(mean, stddev, rand_helper = lambda { Kernel.rand }) + @rand_helper = rand_helper + @mean = mean + @stddev = stddev + @valid = false + @next = 0 + end + + def rand + if @valid then + @valid = false + return @next + else + @valid = true + x, y = self.class.gaussian(@mean, @stddev, @rand_helper) + @next = y + return x + end + end + + private + def self.gaussian(mean, stddev, rand) + theta = 2 * Math::PI * rand.call + rho = Math.sqrt(-2 * Math.log(1 - rand.call)) + scale = stddev * rho + x = mean + scale * Math.cos(theta) + y = mean + scale * Math.sin(theta) + return x, y + end +end diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_points.rb b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_points.rb new file mode 100644 index 00000000..93bc8314 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/burn-in/random_points.rb @@ -0,0 +1,29 @@ +require "influxdb" + +ONE_WEEK_IN_SECONDS = 7*24*60*60 +NUM_POINTS = 10_000 +BATCHES = 100 + +master = InfluxDB::Client.new +master.delete_database("ctx") rescue nil +master.create_database("ctx") + +influxdb = InfluxDB::Client.new "ctx" +influxdb.time_precision = "s" + +names = ["foo", "bar", "baz", "quu", "qux"] + +st = Time.now +BATCHES.times do |m| + points = [] + + puts "Writing #{NUM_POINTS} points, time ##{m}.." + NUM_POINTS.times do |n| + timestamp = Time.now.to_i - rand(ONE_WEEK_IN_SECONDS) + points << {value: names.sample, time: timestamp} + end + + influxdb.write_point("ct1", points) +end +puts st +puts Time.now diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/config.sample.toml b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/config.sample.toml new file mode 100644 index 00000000..90e3cee7 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/etc/config.sample.toml @@ -0,0 +1,323 @@ +### Welcome to the InfluxDB configuration file. + +# Once every 24 hours InfluxDB will report anonymous data to m.influxdb.com +# The data includes raft id (random 8 bytes), os, arch, version, and metadata. +# We don't track ip addresses of servers reporting. This is only used +# to track the number of instances running and the versions, which +# is very helpful for us. +# Change this option to true to disable reporting. +reporting-disabled = false + +### +### Enterprise registration control +### + +[registration] +# enabled = true +# url = "https://enterprise.influxdata.com" # The Enterprise server URL +# token = "" # Registration token for Enterprise server + +### +### [meta] +### +### Controls the parameters for the Raft consensus group that stores metadata +### about the InfluxDB cluster. +### + +[meta] + dir = "/var/lib/influxdb/meta" + hostname = "localhost" + bind-address = ":8088" + retention-autocreate = true + election-timeout = "1s" + heartbeat-timeout = "1s" + leader-lease-timeout = "500ms" + commit-timeout = "50ms" + cluster-tracing = false + + # If enabled, when a Raft cluster loses a peer due to a `DROP SERVER` command, + # the leader will automatically ask a non-raft peer node to promote to a raft + # peer. This only happens if there is a non-raft peer node available to promote. + # This setting only affects the local node, so to ensure if operates correctly, be sure to set + # it in the config of every node. + raft-promotion-enabled = true + +### +### [data] +### +### Controls where the actual shard data for InfluxDB lives and how it is +### flushed from the WAL. "dir" may need to be changed to a suitable place +### for your system, but the WAL settings are an advanced configuration. The +### defaults should work for most systems. +### + +[data] + dir = "/var/lib/influxdb/data" + + # Controls the engine type for new shards. Options are b1, bz1, or tsm1. + # b1 is the 0.9.2 storage engine, bz1 is the 0.9.3 and 0.9.4 engine. + # tsm1 is the 0.9.5 engine and is currenly EXPERIMENTAL. Until 0.9.5 is + # actually released data written into a tsm1 engine may be need to be wiped + # between upgrades. + # engine ="bz1" + + # The following WAL settings are for the b1 storage engine used in 0.9.2. They won't + # apply to any new shards created after upgrading to a version > 0.9.3. + max-wal-size = 104857600 # Maximum size the WAL can reach before a flush. Defaults to 100MB. + wal-flush-interval = "10m" # Maximum time data can sit in WAL before a flush. + wal-partition-flush-delay = "2s" # The delay time between each WAL partition being flushed. + + # These are the WAL settings for the storage engine >= 0.9.3 + wal-dir = "/var/lib/influxdb/wal" + wal-logging-enabled = true + + # When a series in the WAL in-memory cache reaches this size in bytes it is marked as ready to + # flush to the index + # wal-ready-series-size = 25600 + + # Flush and compact a partition once this ratio of series are over the ready size + # wal-compaction-threshold = 0.6 + + # Force a flush and compaction if any series in a partition gets above this size in bytes + # wal-max-series-size = 2097152 + + # Force a flush of all series and full compaction if there have been no writes in this + # amount of time. This is useful for ensuring that shards that are cold for writes don't + # keep a bunch of data cached in memory and in the WAL. + # wal-flush-cold-interval = "10m" + + # Force a partition to flush its largest series if it reaches this approximate size in + # bytes. Remember there are 5 partitions so you'll need at least 5x this amount of memory. + # The more memory you have, the bigger this can be. + # wal-partition-size-threshold = 20971520 + + # Whether queries should be logged before execution. Very useful for troubleshooting, but will + # log any sensitive data contained within a query. + # query-log-enabled = true + +### +### [hinted-handoff] +### +### Controls the hinted handoff feature, which allows nodes to temporarily +### store queued data when one node of a cluster is down for a short period +### of time. +### + +[hinted-handoff] + enabled = true + dir = "/var/lib/influxdb/hh" + max-size = 1073741824 + max-age = "168h" + retry-rate-limit = 0 + + # Hinted handoff will start retrying writes to down nodes at a rate of once per second. + # If any error occurs, it will backoff in an exponential manner, until the interval + # reaches retry-max-interval. Once writes to all nodes are successfully completed the + # interval will reset to retry-interval. + retry-interval = "1s" + retry-max-interval = "1m" + + # Interval between running checks for data that should be purged. Data is purged from + # hinted-handoff queues for two reasons. 1) The data is older than the max age, or + # 2) the target node has been dropped from the cluster. Data is never dropped until + # it has reached max-age however, for a dropped node or not. + purge-interval = "1h" + +### +### [cluster] +### +### Controls non-Raft cluster behavior, which generally includes how data is +### shared across shards. +### + +[cluster] + shard-writer-timeout = "10s" # The time within which a shard must respond to write. + write-timeout = "5s" # The time within which a write operation must complete on the cluster. + +### +### [retention] +### +### Controls the enforcement of retention policies for evicting old data. +### + +[retention] + enabled = true + check-interval = "30m" + +### +### [shard-precreation] +### +### Controls the precreation of shards, so they are created before data arrives. +### Only shards that will exist in the future, at time of creation, are precreated. + +[shard-precreation] + enabled = true + check-interval = "10m" + advance-period = "30m" + +### +### Controls the system self-monitoring, statistics and diagnostics. +### +### The internal database for monitoring data is created automatically if +### if it does not already exist. The target retention within this database +### is called 'monitor' and is also created with a retention period of 7 days +### and a replication factor of 1, if it does not exist. In all cases the +### this retention policy is configured as the default for the database. + +[monitor] + store-enabled = true # Whether to record statistics internally. + store-database = "_internal" # The destination database for recorded statistics + store-interval = "10s" # The interval at which to record statistics + +### +### [admin] +### +### Controls the availability of the built-in, web-based admin interface. If HTTPS is +### enabled for the admin interface, HTTPS must also be enabled on the [http] service. +### + +[admin] + enabled = true + bind-address = ":8083" + https-enabled = false + https-certificate = "/etc/ssl/influxdb.pem" + +### +### [http] +### +### Controls how the HTTP endpoints are configured. These are the primary +### mechanism for getting data into and out of InfluxDB. +### + +[http] + enabled = true + bind-address = ":8086" + auth-enabled = false + log-enabled = true + write-tracing = false + pprof-enabled = false + https-enabled = false + https-certificate = "/etc/ssl/influxdb.pem" + +### +### [[graphite]] +### +### Controls one or many listeners for Graphite data. +### + +[[graphite]] + enabled = false + # database = "graphite" + # bind-address = ":2003" + # protocol = "tcp" + # consistency-level = "one" + # name-separator = "." + + # These next lines control how batching works. You should have this enabled + # otherwise you could get dropped metrics or poor performance. Batching + # will buffer points in memory if you have many coming in. + + # batch-size = 1000 # will flush if this many points get buffered + # batch-pending = 5 # number of batches that may be pending in memory + # batch-timeout = "1s" # will flush at least this often even if we haven't hit buffer limit + # udp-read-buffer = 0 # UDP Read buffer size, 0 means OS default. UDP listener will fail if set above OS max. + + ## "name-schema" configures tag names for parsing the metric name from graphite protocol; + ## separated by `name-separator`. + ## The "measurement" tag is special and the corresponding field will become + ## the name of the metric. + ## e.g. "type.host.measurement.device" will parse "server.localhost.cpu.cpu0" as + ## { + ## measurement: "cpu", + ## tags: { + ## "type": "server", + ## "host": "localhost, + ## "device": "cpu0" + ## } + ## } + # name-schema = "type.host.measurement.device" + + ## If set to true, when the input metric name has more fields than `name-schema` specified, + ## the extra fields will be ignored. + ## Otherwise an error will be logged and the metric rejected. + # ignore-unnamed = true + +### +### [collectd] +### +### Controls the listener for collectd data. +### + +[collectd] + enabled = false + # bind-address = "" + # database = "" + # typesdb = "" + + # These next lines control how batching works. You should have this enabled + # otherwise you could get dropped metrics or poor performance. Batching + # will buffer points in memory if you have many coming in. + + # batch-size = 1000 # will flush if this many points get buffered + # batch-pending = 5 # number of batches that may be pending in memory + # batch-timeout = "1s" # will flush at least this often even if we haven't hit buffer limit + # read-buffer = 0 # UDP Read buffer size, 0 means OS default. UDP listener will fail if set above OS max. + +### +### [opentsdb] +### +### Controls the listener for OpenTSDB data. +### + +[opentsdb] + enabled = false + # bind-address = ":4242" + # database = "opentsdb" + # retention-policy = "" + # consistency-level = "one" + # tls-enabled = false + # certificate= "" + # log-point-errors = true # Log an error for every malformed point. + + # These next lines control how batching works. You should have this enabled + # otherwise you could get dropped metrics or poor performance. Only points + # metrics received over the telnet protocol undergo batching. + + # batch-size = 1000 # will flush if this many points get buffered + # batch-pending = 5 # number of batches that may be pending in memory + # batch-timeout = "1s" # will flush at least this often even if we haven't hit buffer limit + +### +### [[udp]] +### +### Controls the listeners for InfluxDB line protocol data via UDP. +### + +[[udp]] + enabled = false + # bind-address = "" + # database = "udp" + # retention-policy = "" + + # These next lines control how batching works. You should have this enabled + # otherwise you could get dropped metrics or poor performance. Batching + # will buffer points in memory if you have many coming in. + + # batch-size = 1000 # will flush if this many points get buffered + # batch-pending = 5 # number of batches that may be pending in memory + # batch-timeout = "1s" # will flush at least this often even if we haven't hit buffer limit + # read-buffer = 0 # UDP Read buffer size, 0 means OS default. UDP listener will fail if set above OS max. + +### +### [continuous_queries] +### +### Controls how continuous queries are run within InfluxDB. +### + +[continuous_queries] + log-enabled = true + enabled = true + recompute-previous-n = 2 + recompute-no-older-than = "10m" + compute-runs-per-interval = 10 + compute-no-more-than = "2m" diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/README.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/README.md new file mode 100644 index 00000000..b8cd9ad8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/README.md @@ -0,0 +1,193 @@ +# Import/Export + +## Exporting from 0.8.9 + +Version `0.8.9` of InfluxDB adds support to export your data to a format that can be imported into `0.9.3` and later. + +Note that `0.8.9` can be found here: + +``` +http://get.influxdb.org.s3.amazonaws.com/influxdb_0.8.9_amd64.deb +http://get.influxdb.org.s3.amazonaws.com/influxdb-0.8.9-1.x86_64.rpm +``` + +### Design + +`0.8.9` exports raw data to a flat file that includes two sections, `DDL` and `DML`. You can choose to export them independently (see below). + +The `DDL` section contains the sql commands to create databases and retention policies. the `DML` section is [line protocol](https://github.com/influxdb/influxdb/blob/master/tsdb/README.md) and can be directly posted to the [http endpoint](https://influxdb.com/docs/v0.9/guides/writing_data.html) in `0.9`. Remember that batching is important and we don't recommend batch sizes over 5k. + +You need to specify a database and shard group when you export. + +To list out your shards, use the following http endpoint: + +`/cluster/shard_spaces` + +example: +```sh +http://username:password@localhost:8086/cluster/shard_spaces +``` + +Then, to export a database with then name "metrics" and a shard space with the name "default", issue the following curl command: + +```sh +curl -o export http://username:password@http://localhost:8086/export/metrics/default +``` + +Compression is supported, and will result in a significantly smaller file size. + +Use the following command for compression: +```sh +curl -o export.gz --compressed http://username:password@http://localhost:8086/export/metrics/default +``` + +You can also export just the `DDL` with this option: + +```sh +curl -o export.ddl http://username:password@http://localhost:8086/export/metrics/default?l=ddl +``` + +Or just the `DML` with this option: + +```sh +curl -o export.dml.gz --compressed http://username:password@http://localhost:8086/export/metrics/default?l=dml +``` + +### Assumptions + +- Series name mapping follows these [guidelines](https://influxdb.com/docs/v0.8/advanced_topics/schema_design.html) +- Database name will map directly from `0.8` to `0.9` +- Shard Spaces map to Retention Policies +- Shard Space Duration is ignored, as in `0.9` we determine shard size automatically +- Regex is used to match the correct series names and only exports that data for the database +- Duration becomes the new Retention Policy duration + +- Users are not migrated due to inability to get passwords. Anyone using users will need to manually set these back up in `0.9` + +### Upgrade Recommendations + +It's recommended that you upgrade to `0.9.3` first and have all your writes going there. Then, on the `0.8.X` instances, upgrade to `0.8.9`. + +It is important that when exporting you change your config to allow for the http endpoints not timing out. To do so, make this change in your config: + +```toml +# Configure the http api +[api] +read-timeout = "0s" +``` + +### Exceptions + +If a series can't be exported to tags based on the guidelines mentioned above, +we will insert the entire series name as the measurement name. You can either +allow that to import into the new InfluxDB instance, or you can do your own +data massage on it prior to importing it. + +For example, if you have the following series name: + +``` +metric.disk.c.host.server01.single +``` + +It will export as exactly thta as the measurement name and no tags: + +``` +metric.disk.c.host.server01.single +``` + +### Export Metrics + +When you export, you will now get comments inline in the `DML`: + +`# Found 999 Series for export` + +As well as count totals for each series exported: + +`# Series FOO - Points Exported: 999` + +With a total at the bottom: + +`# Points Exported: 999` + +You can grep the file that was exported at the end to get all the export metrics: + +`cat myexport | grep Exported` + +## Importing + +Version `0.9.3` of InfluxDB adds support to import your data from version `0.8.9`. + +## Caveats + +For the export/import to work, all requisites have to be met. For export, all series names in `0.8` should be in the following format: + +``` +.... +``` +for example: +``` +az.us-west-1.host.serverA.cpu +``` +or any number of tags +``` +building.2.temperature +``` + +Additionally, the fields need to have a consistent type (all float64, int64, etc) for every write in `0.8`. Otherwise they have the potential to fail writes in the import. +See below for more information. + +## Running the import command + + To import via the cli, you can specify the following command: + + ```sh + influx -import -path=metrics-default.gz -compressed + ``` + + If the file is not compressed you can issue it without the `-compressed` flag: + + ```sh + influx -import -path=metrics-default + ``` + + To redirect failed import lines to another file, run this command: + + ```sh + influx -import -path=metrics-default.gz -compressed > failures + ``` + + The import will use the line protocol in batches of 5,000 lines per batch when sending data to the server. + +### Throttiling the import + + If you need to throttle the import so the database has time to ingest, you can use the `-pps` flag. This will limit the points per second that will be sent to the server. + + ```sh + influx -import -path=metrics-default.gz -compressed -pps 50000 > failures + ``` + + Which is stating that you don't want MORE than 50,000 points per second to write to the database. Due to the processing that is taking place however, you will likely never get exactly 50,000 pps, more like 35,000 pps, etc. + +## Understanding the results of the import + +During the import, a status message will write out for every 100,000 points imported and report stats on the progress of the import: + +``` +2015/08/21 14:48:01 Processed 3100000 lines. Time elapsed: 56.740578415s. Points per second (PPS): 54634 +``` + + The batch will give some basic stats when finished: + + ```sh + 2015/07/29 23:15:20 Processed 2 commands + 2015/07/29 23:15:20 Processed 70207923 inserts + 2015/07/29 23:15:20 Failed 29785000 inserts + ``` + + Most inserts fail due to the following types of error: + + ```sh + 2015/07/29 22:18:28 error writing batch: write failed: field type conflict: input field "value" on measurement "metric" is type float64, already exists as type integer + ``` + + This is due to the fact that in `0.8` a field could get created and saved as int or float types for independent writes. In `0.9` the field has to have a consistent type. diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/v8/importer.go b/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/v8/importer.go new file mode 100644 index 00000000..86e998fc --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/importer/v8/importer.go @@ -0,0 +1,248 @@ +package v8 + +import ( + "bufio" + "compress/gzip" + "fmt" + "io" + "log" + "net/url" + "os" + "strings" + "time" + + "github.com/influxdb/influxdb/client" +) + +const batchSize = 5000 + +// Config is the config used to initialize a Importer importer +type Config struct { + Username string + Password string + URL url.URL + Precision string + WriteConsistency string + Path string + Version string + Compressed bool + PPS int +} + +// NewConfig returns an initialized *Config +func NewConfig() *Config { + return &Config{} +} + +// Importer is the importer used for importing 0.8 data +type Importer struct { + client *client.Client + database string + retentionPolicy string + config *Config + batch []string + totalInserts int + failedInserts int + totalCommands int + throttlePointsWritten int + lastWrite time.Time + throttle *time.Ticker +} + +// NewImporter will return an intialized Importer struct +func NewImporter(config *Config) *Importer { + return &Importer{ + config: config, + batch: make([]string, 0, batchSize), + } +} + +// Import processes the specified file in the Config and writes the data to the databases in chunks specified by batchSize +func (i *Importer) Import() error { + // Create a client and try to connect + config := client.NewConfig() + config.URL = i.config.URL + config.Username = i.config.Username + config.Password = i.config.Password + config.UserAgent = fmt.Sprintf("influxDB importer/%s", i.config.Version) + cl, err := client.NewClient(config) + if err != nil { + return fmt.Errorf("could not create client %s", err) + } + i.client = cl + if _, _, e := i.client.Ping(); e != nil { + return fmt.Errorf("failed to connect to %s\n", i.client.Addr()) + } + + // Validate args + if i.config.Path == "" { + return fmt.Errorf("file argument required") + } + + defer func() { + if i.totalInserts > 0 { + log.Printf("Processed %d commands\n", i.totalCommands) + log.Printf("Processed %d inserts\n", i.totalInserts) + log.Printf("Failed %d inserts\n", i.failedInserts) + } + }() + + // Open the file + f, err := os.Open(i.config.Path) + if err != nil { + return err + } + defer f.Close() + + var r io.Reader + + // If gzipped, wrap in a gzip reader + if i.config.Compressed { + gr, err := gzip.NewReader(f) + if err != nil { + return err + } + defer gr.Close() + // Set the reader to the gzip reader + r = gr + } else { + // Standard text file so our reader can just be the file + r = f + } + + // Get our reader + scanner := bufio.NewScanner(r) + + // Process the DDL + i.processDDL(scanner) + + // Set up our throttle channel. Since there is effectively no other activity at this point + // the smaller resolution gets us much closer to the requested PPS + i.throttle = time.NewTicker(time.Microsecond) + defer i.throttle.Stop() + + // Prime the last write + i.lastWrite = time.Now() + + // Process the DML + i.processDML(scanner) + + // Check if we had any errors scanning the file + if err := scanner.Err(); err != nil { + return fmt.Errorf("reading standard input: %s", err) + } + + return nil +} + +func (i *Importer) processDDL(scanner *bufio.Scanner) { + for scanner.Scan() { + line := scanner.Text() + // If we find the DML token, we are done with DDL + if strings.HasPrefix(line, "# DML") { + return + } + if strings.HasPrefix(line, "#") { + continue + } + // Skip blank lines + if strings.TrimSpace(line) == "" { + continue + } + i.queryExecutor(line) + } +} + +func (i *Importer) processDML(scanner *bufio.Scanner) { + start := time.Now() + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "# CONTEXT-DATABASE:") { + i.database = strings.TrimSpace(strings.Split(line, ":")[1]) + } + if strings.HasPrefix(line, "# CONTEXT-RETENTION-POLICY:") { + i.retentionPolicy = strings.TrimSpace(strings.Split(line, ":")[1]) + } + if strings.HasPrefix(line, "#") { + continue + } + // Skip blank lines + if strings.TrimSpace(line) == "" { + continue + } + i.batchAccumulator(line, start) + } + // Call batchWrite one last time to flush anything out in the batch + i.batchWrite() +} + +func (i *Importer) execute(command string) { + response, err := i.client.Query(client.Query{Command: command, Database: i.database}) + if err != nil { + log.Printf("error: %s\n", err) + return + } + if err := response.Error(); err != nil { + log.Printf("error: %s\n", response.Error()) + } +} + +func (i *Importer) queryExecutor(command string) { + i.totalCommands++ + i.execute(command) +} + +func (i *Importer) batchAccumulator(line string, start time.Time) { + i.batch = append(i.batch, line) + if len(i.batch) == batchSize { + i.batchWrite() + i.batch = i.batch[:0] + // Give some status feedback every 100000 lines processed + processed := i.totalInserts + i.failedInserts + if processed%100000 == 0 { + since := time.Since(start) + pps := float64(processed) / since.Seconds() + log.Printf("Processed %d lines. Time elapsed: %s. Points per second (PPS): %d", processed, since.String(), int64(pps)) + } + } +} + +func (i *Importer) batchWrite() { + // Accumulate the batch size to see how many points we have written this second + i.throttlePointsWritten += len(i.batch) + + // Find out when we last wrote data + since := time.Since(i.lastWrite) + + // Check to see if we've exceeded our points per second for the current timeframe + var currentPPS int + if since.Seconds() > 0 { + currentPPS = int(float64(i.throttlePointsWritten) / since.Seconds()) + } else { + currentPPS = i.throttlePointsWritten + } + + // If our currentPPS is greater than the PPS specified, then we wait and retry + if int(currentPPS) > i.config.PPS && i.config.PPS != 0 { + // Wait for the next tick + <-i.throttle.C + + // Decrement the batch size back out as it is going to get called again + i.throttlePointsWritten -= len(i.batch) + i.batchWrite() + return + } + + _, e := i.client.WriteLineProtocol(strings.Join(i.batch, "\n"), i.database, i.retentionPolicy, i.config.Precision, i.config.WriteConsistency) + if e != nil { + log.Println("error writing batch: ", e) + // Output failed lines to STDOUT so users can capture lines that failed to import + fmt.Println(strings.Join(i.batch, "\n")) + i.failedInserts += len(i.batch) + } else { + i.totalInserts += len(i.batch) + } + i.throttlePointsWritten = 0 + i.lastWrite = time.Now() + return +} diff --git a/Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/INFLUXQL.md b/Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/INFLUXQL.md new file mode 100644 index 00000000..106b8023 --- /dev/null +++ b/Godeps/_workspace/src/github.com/influxdb/influxdb/influxql/INFLUXQL.md @@ -0,0 +1,707 @@ +# The Influx Query Language Specification + +## Introduction + +This is a reference for the Influx Query Language ("InfluxQL"). + +InfluxQL is a SQL-like query language for interacting with InfluxDB. It has been lovingly crafted to feel familiar to those coming from other SQL or SQL-like environments while providing features specific to storing and analyzing time series data. + +## Notation + +The syntax is specified using Extended Backus-Naur Form ("EBNF"). EBNF is the same notation used in the [Go](http://golang.org) programming language specification, which can be found [here](https://golang.org/ref/spec). Not so coincidentally, InfluxDB is written in Go. + +``` +Production = production_name "=" [ Expression ] "." . +Expression = Alternative { "|" Alternative } . +Alternative = Term { Term } . +Term = production_name | token [ "…" token ] | Group | Option | Repetition . +Group = "(" Expression ")" . +Option = "[" Expression "]" . +Repetition = "{" Expression "}" . +``` + +Notation operators in order of increasing precedence: + +``` +| alternation +() grouping +[] option (0 or 1 times) +{} repetition (0 to n times) +``` + +## Query representation + +### Characters + +InfluxQL is Unicode text encoded in [UTF-8](http://en.wikipedia.org/wiki/UTF-8). + +``` +newline = /* the Unicode code point U+000A */ . +unicode_char = /* an arbitrary Unicode code point except newline */ . +``` + +## Letters and digits + +Letters are the set of ASCII characters plus the underscore character _ (U+005F) is considered a letter. + +Only decimal digits are supported. + +``` +letter = ascii_letter | "_" . +ascii_letter = "A" … "Z" | "a" … "z" . +digit = "0" … "9" . +``` + +## Identifiers + +Identifiers are tokens which refer to database names, retention policy names, user names, measurement names, tag keys, and field keys. + +The rules: + +- double quoted identifiers can contain any unicode character other than a new line +- double quoted identifiers can contain escaped `"` characters (i.e., `\"`) +- unquoted identifiers must start with an upper or lowercase ASCII character or "_" +- unquoted identifiers may contain only ASCII letters, decimal digits, and "_" + +``` +identifier = unquoted_identifier | quoted_identifier . +unquoted_identifier = ( letter ) { letter | digit } . +quoted_identifier = `"` unicode_char { unicode_char } `"` . +``` + +#### Examples: + +``` +cpu +_cpu_stats +"1h" +"anything really" +"1_Crazy-1337.identifier>NAME👍" +``` + +## Keywords + +``` +ALL ALTER ANY AS ASC BEGIN +BY CREATE CONTINUOUS DATABASE DATABASES DEFAULT +DELETE DESC DESTINATIONS DIAGNOSTICS DISTINCT DROP +DURATION END EXISTS EXPLAIN FIELD FOR +FORCE FROM GRANT GRANTS GROUP IF +IN INF INNER INSERT INTO KEY +KEYS LIMIT SHOW MEASUREMENT MEASUREMENTS NOT +OFFSET ON ORDER PASSWORD POLICY POLICIES +PRIVILEGES QUERIES QUERY READ REPLICATION RETENTION +REVOKE SELECT SERIES SERVER SERVERS SET +SHARDS SLIMIT SOFFSET STATS SUBSCRIPTION SUBSCRIPTIONS +TAG TO USER USERS VALUES WHERE +WITH WRITE +``` + +## Literals + +### Integers + +InfluxQL supports decimal integer literals. Hexadecimal and octal literals are not currently supported. + +``` +int_lit = ( "1" … "9" ) { digit } . +``` + +### Floats + +InfluxQL supports floating-point literals. Exponents are not currently supported. + +``` +float_lit = int_lit "." int_lit . +``` + +### Strings + +String literals must be surrounded by single quotes. Strings may contain `'` characters as long as they are escaped (i.e., `\'`). + +``` +string_lit = `'` { unicode_char } `'`' . +``` + +### Durations + +Duration literals specify a length of time. An integer literal followed immediately (with no spaces) by a duration unit listed below is interpreted as a duration literal. + +### Duration units +| Units | Meaning | +|--------|-----------------------------------------| +| u or µ | microseconds (1 millionth of a second) | +| ms | milliseconds (1 thousandth of a second) | +| s | second | +| m | minute | +| h | hour | +| d | day | +| w | week | + +``` +duration_lit = int_lit duration_unit . +duration_unit = "u" | "µ" | "s" | "h" | "d" | "w" | "ms" . +``` + +### Dates & Times + +The date and time literal format is not specified in EBNF like the rest of this document. It is specified using Go's date / time parsing format, which is a reference date written in the format required by InfluxQL. The reference date time is: + +InfluxQL reference date time: January 2nd, 2006 at 3:04:05 PM + +``` +time_lit = "2006-01-02 15:04:05.999999" | "2006-01-02" +``` + +### Booleans + +``` +bool_lit = TRUE | FALSE . +``` + +### Regular Expressions + +``` +regex_lit = "/" { unicode_char } "/" . +``` + +## Queries + +A query is composed of one or more statements separated by a semicolon. + +``` +query = statement { ; statement } . + +statement = alter_retention_policy_stmt | + create_continuous_query_stmt | + create_database_stmt | + create_retention_policy_stmt | + create_user_stmt | + create_subscription_stmt | + delete_stmt | + drop_continuous_query_stmt | + drop_database_stmt | + drop_measurement_stmt | + drop_retention_policy_stmt | + drop_series_stmt | + drop_subscription_stmt | + drop_user_stmt | + grant_stmt | + show_continuous_queries_stmt | + show_databases_stmt | + show_field_keys_stmt | + show_measurements_stmt | + show_retention_policies | + show_series_stmt | + show_shards_stmt | + show_subscriptions_stmt| + show_tag_keys_stmt | + show_tag_values_stmt | + show_users_stmt | + revoke_stmt | + select_stmt . +``` + +## Statements + +### ALTER RETENTION POLICY + +``` +alter_retention_policy_stmt = "ALTER RETENTION POLICY" policy_name "ON" + db_name retention_policy_option + [ retention_policy_option ] + [ retention_policy_option ] . + +db_name = identifier . + +policy_name = identifier . + +retention_policy_option = retention_policy_duration | + retention_policy_replication | + "DEFAULT" . + +retention_policy_duration = "DURATION" duration_lit . +retention_policy_replication = "REPLICATION" int_lit +``` + +#### Examples: + +```sql +-- Set default retention policy for mydb to 1h.cpu. +ALTER RETENTION POLICY "1h.cpu" ON mydb DEFAULT; + +-- Change duration and replication factor. +ALTER RETENTION POLICY policy1 ON somedb DURATION 1h REPLICATION 4 +``` + +### CREATE CONTINUOUS QUERY + +``` +create_continuous_query_stmt = "CREATE CONTINUOUS QUERY" query_name "ON" db_name + "BEGIN" select_stmt "END" . + +query_name = identifier . +``` + +#### Examples: + +```sql +-- selects from default retention policy and writes into 6_months retention policy +CREATE CONTINUOUS QUERY "10m_event_count" +ON db_name +BEGIN + SELECT count(value) + INTO "6_months".events + FROM events + GROUP BY time(10m) +END; + +-- this selects from the output of one continuous query in one retention policy and outputs to another series in another retention policy +CREATE CONTINUOUS QUERY "1h_event_count" +ON db_name +BEGIN + SELECT sum(count) as count + INTO "2_years".events + FROM "6_months".events + GROUP BY time(1h) +END; +``` + +### CREATE DATABASE + +``` +create_database_stmt = "CREATE DATABASE" db_name +``` + +#### Example: + +```sql +CREATE DATABASE foo +``` + +### CREATE RETENTION POLICY + +``` +create_retention_policy_stmt = "CREATE RETENTION POLICY" policy_name "ON" + db_name retention_policy_duration + retention_policy_replication + [ "DEFAULT" ] . +``` + +#### Examples + +```sql +-- Create a retention policy. +CREATE RETENTION POLICY "10m.events" ON somedb DURATION 10m REPLICATION 2; + +-- Create a retention policy and set it as the default. +CREATE RETENTION POLICY "10m.events" ON somedb DURATION 10m REPLICATION 2 DEFAULT; +``` + +### CREATE SUBSCRIPTION + +``` +create_subscription_stmt = "CREATE SUBSCRIPTION" subscription_name "ON" db_name "." retention_policy "DESTINATIONS" ("ANY"|"ALL") host { "," host} . +``` + +#### Examples: + +```sql +-- Create a SUBSCRIPTION on database 'mydb' and retention policy 'default' that send data to 'example.com:9090' via UDP. +CREATE SUBSCRIPTION sub0 ON "mydb"."default" DESTINATIONS ALL 'udp://example.com:9090' ; + +-- Create a SUBSCRIPTION on database 'mydb' and retention policy 'default' that round robins the data to 'h1.example.com:9090' and 'h2.example.com:9090'. +CREATE SUBSCRIPTION sub0 ON "mydb"."default" DESTINATIONS ANY 'udp://h1.example.com:9090', 'udp://h2.example.com:9090'; +``` + +### CREATE USER + +``` +create_user_stmt = "CREATE USER" user_name "WITH PASSWORD" password + [ "WITH ALL PRIVILEGES" ] . +``` + +#### Examples: + +```sql +-- Create a normal database user. +CREATE USER jdoe WITH PASSWORD '1337password'; + +-- Create a cluster admin. +-- Note: Unlike the GRANT statement, the "PRIVILEGES" keyword is required here. +CREATE USER jdoe WITH PASSWORD '1337password' WITH ALL PRIVILEGES; +``` + +### DELETE + +``` +delete_stmt = "DELETE" from_clause where_clause . +``` + +#### Example: + +```sql +-- delete data points from the cpu measurement where the region tag +-- equals 'uswest' +DELETE FROM cpu WHERE region = 'uswest'; +``` + +### DROP CONTINUOUS QUERY + +drop_continuous_query_stmt = "DROP CONTINUOUS QUERY" query_name . + +#### Example: + +```sql +DROP CONTINUOUS QUERY myquery; +``` + +### DROP DATABASE + +drop_database_stmt = "DROP DATABASE" db_name . + +#### Example: + +```sql +DROP DATABASE mydb; +``` + +### DROP MEASUREMENT + +``` +drop_measurement_stmt = "DROP MEASUREMENT" measurement . +``` + +#### Examples: + +```sql +-- drop the cpu measurement +DROP MEASUREMENT cpu; +``` + +### DROP RETENTION POLICY + +``` +drop_retention_policy_stmt = "DROP RETENTION POLICY" policy_name "ON" db_name . +``` + +#### Example: + +```sql +-- drop the retention policy named 1h.cpu from mydb +DROP RETENTION POLICY "1h.cpu" ON mydb; +``` + +### DROP SERIES + +``` +drop_series_stmt = "DROP SERIES" [ from_clause ] [ where_clause ] +``` + +#### Example: + +```sql + +``` + +### DROP SUBSCRIPTION + +``` +drop_subscription_stmt = "DROP SUBSCRIPTION" subscription_name "ON" db_name "." retention_policy . +``` + +#### Example: + +```sql +DROP SUBSCRIPTION sub0 ON "mydb"."default"; + +``` + +### DROP USER + +``` +drop_user_stmt = "DROP USER" user_name . +``` + +#### Example: + +```sql +DROP USER jdoe; + +``` + +### GRANT + +NOTE: Users can be granted privileges on databases that do not exist. + +``` +grant_stmt = "GRANT" privilege [ on_clause ] to_clause +``` + +#### Examples: + +```sql +-- grant cluster admin privileges +GRANT ALL TO jdoe; + +-- grant read access to a database +GRANT READ ON mydb TO jdoe; +``` + +### SHOW CONTINUOUS QUERIES + +show_continuous_queries_stmt = "SHOW CONTINUOUS QUERIES" + +#### Example: + +```sql +-- show all continuous queries +SHOW CONTINUOUS QUERIES; +``` + +### SHOW DATABASES + +``` +show_databases_stmt = "SHOW DATABASES" . +``` + +#### Example: + +```sql +-- show all databases +SHOW DATABASES; +``` + +### SHOW FIELD + +show_field_keys_stmt = "SHOW FIELD KEYS" [ from_clause ] . + +#### Examples: + +```sql +-- show field keys from all measurements +SHOW FIELD KEYS; + +-- show field keys from specified measurement +SHOW FIELD KEYS FROM cpu; +``` + +### SHOW MEASUREMENTS + +show_measurements_stmt = "SHOW MEASUREMENTS" [ where_clause ] [ group_by_clause ] [ limit_clause ] + [ offset_clause ] . + +```sql +-- show all measurements +SHOW MEASUREMENTS; + +-- show measurements where region tag = 'uswest' AND host tag = 'serverA' +SHOW MEASUREMENTS WHERE region = 'uswest' AND host = 'serverA'; +``` + +### SHOW RETENTION POLICIES + +``` +show_retention_policies = "SHOW RETENTION POLICIES ON" db_name . +``` + +#### Example: + +```sql +-- show all retention policies on a database +SHOW RETENTION POLICIES ON mydb; +``` + +### SHOW SERIES + +``` +show_series_stmt = "SHOW SERIES" [ from_clause ] [ where_clause ] [ group_by_clause ] + [ limit_clause ] [ offset_clause ] . +``` + +#### Example: + +```sql + +``` + +### SHOW SHARDS + +``` +show_shards_stmt = "SHOW SHARDS" . +``` + +#### Example: + +```sql +SHOW SHARDS; +``` + +### SHOW SUBSCRIPTIONS + +``` +show_subscriptions_stmt = "SHOW SUBSCRIPTIONS" . +``` + +#### Example: + +```sql +SHOW SUBSCRIPTIONS; +``` + +### SHOW TAG KEYS + +``` +show_tag_keys_stmt = "SHOW TAG KEYS" [ from_clause ] [ where_clause ] [ group_by_clause ] + [ limit_clause ] [ offset_clause ] . +``` + +#### Examples: + +```sql +-- show all tag keys +SHOW TAG KEYS; + +-- show all tag keys from the cpu measurement +SHOW TAG KEYS FROM cpu; + +-- show all tag keys from the cpu measurement where the region key = 'uswest' +SHOW TAG KEYS FROM cpu WHERE region = 'uswest'; + +-- show all tag keys where the host key = 'serverA' +SHOW TAG KEYS WHERE host = 'serverA'; +``` + +### SHOW TAG VALUES + +``` +show_tag_values_stmt = "SHOW TAG VALUES" [ from_clause ] with_tag_clause [ where_clause ] + [ group_by_clause ] [ limit_clause ] [ offset_clause ] . +``` + +#### Examples: + +```sql +-- show all tag values across all measurements for the region tag +SHOW TAG VALUES WITH TAG = 'region'; + +-- show tag values from the cpu measurement for the region tag +SHOW TAG VALUES FROM cpu WITH TAG = 'region'; + +-- show tag values from the cpu measurement for region & host tag keys where service = 'redis' +SHOW TAG VALUES FROM cpu WITH TAG IN (region, host) WHERE service = 'redis'; +``` + +### SHOW USERS + +``` +show_users_stmt = "SHOW USERS" . +``` + +#### Example: + +```sql +-- show all users +SHOW USERS; +``` + +### REVOKE + +``` +revoke_stmt = "REVOKE" privilege [ "ON" db_name ] "FROM" user_name +``` + +#### Examples: + +```sql +-- revoke cluster admin from jdoe +REVOKE ALL PRIVILEGES FROM jdoe; + +-- revoke read privileges from jdoe on mydb +REVOKE READ ON mydb FROM jdoe; +``` + +### SELECT + +``` +select_stmt = "SELECT" fields from_clause [ into_clause ] [ where_clause ] + [ group_by_clause ] [ order_by_clause ] [ limit_clause ] + [ offset_clause ] [ slimit_clause ] [ soffset_clause ]. +``` + +#### Examples: + +```sql +-- select mean value from the cpu measurement where region = 'uswest' grouped by 10 minute intervals +SELECT mean(value) FROM cpu WHERE region = 'uswest' GROUP BY time(10m) fill(0); +``` + +## Clauses + +``` +from_clause = "FROM" measurements . + +group_by_clause = "GROUP BY" dimensions fill(