Browse Source

Merge remote-tracking branch 'origin/master' into panelbase

Torkel Ödegaard 10 years ago
parent
commit
57d22fb93f
42 changed files with 894 additions and 766 deletions
  1. 9 0
      circle.yml
  2. 1 0
      docker/blocks/elastic/elasticsearch/config/.placeholder
  3. 6 0
      docker/blocks/elastic/fig
  4. 0 16
      docker/blocks/influxdb/Dockerfile
  5. 1 1
      docker/blocks/influxdb/fig
  6. 28 0
      docs/sources/reference/http_api.md
  7. 1 1
      docs/sources/reference/singlestat.md
  8. 14 0
      pkg/api/admin.go
  9. 2 0
      pkg/api/api.go
  10. 1 0
      pkg/metrics/report_usage.go
  11. 17 0
      pkg/models/stats.go
  12. 57 1
      pkg/services/sqlstore/stats.go
  13. 18 21
      public/app/core/components/search/search.html
  14. 150 0
      public/app/core/components/search/search.ts
  15. 7 0
      public/app/core/components/sidemenu/sidemenu.ts
  16. 0 1
      public/app/core/controllers/all.js
  17. 0 127
      public/app/core/controllers/search_ctrl.js
  18. 2 1
      public/app/core/core.ts
  19. 5 0
      public/app/core/routes/all.js
  20. 1 0
      public/app/core/time_series2.ts
  21. 18 0
      public/app/features/admin/adminStatsCtrl.ts
  22. 1 0
      public/app/features/admin/all.js
  23. 60 0
      public/app/features/admin/partials/stats.html
  24. 19 2
      public/app/features/dashboard/dashboardSrv.js
  25. 1 1
      public/app/features/dashboard/directives/dashSearchView.js
  26. 1 1
      public/app/plugins/datasource/elasticsearch/datasource.js
  27. 2 2
      public/app/plugins/datasource/opentsdb/specs/datasource-specs.ts
  28. 8 5
      public/app/plugins/panel/graph/graph.js
  29. 3 9
      public/app/plugins/panel/graph/graph_tooltip.js
  30. 32 4
      public/app/plugins/panel/graph/specs/graph_specs.ts
  31. 18 21
      public/app/plugins/panel/singlestat/controller.ts
  32. 2 2
      public/app/plugins/panel/singlestat/editor.html
  33. 0 235
      public/app/plugins/panel/singlestat/module.js
  34. 232 0
      public/app/plugins/panel/singlestat/module.ts
  35. 0 221
      public/app/plugins/panel/singlestat/singleStatPanel.js
  36. 88 0
      public/app/plugins/panel/singlestat/specs/singlestat-specs.ts
  37. 58 0
      public/app/plugins/panel/singlestat/specs/singlestat_panel_spec.ts
  38. 1 5
      public/less/login.less
  39. 11 1
      public/test/specs/dashboardSrv-specs.js
  40. 0 88
      public/test/specs/singlestat-specs.js
  41. 10 0
      trigger_grafana_packer.sh
  42. 9 0
      vendor/phantomjs/render.js

+ 9 - 0
circle.yml

@@ -12,6 +12,8 @@ dependencies:
     - mkdir -p ${GOPATH}/src/${ORG_PATH}
     - ln -s ~/grafana ${GOPATH}/src/${ORG_PATH}
     - go get github.com/tools/godep
+    - rm -rf node_modules
+    - npm install -g npm
     - npm install
 
 test:
@@ -25,3 +27,10 @@ test:
      # js tests
      - ./node_modules/grunt-cli/bin/grunt test
      - npm run coveralls
+
+deployment:
+  master:
+    branch: master
+    owner: grafana
+    commands: 
+      - ./trigger_grafana_packer.sh ${TRIGGER_GRAFANA_PACKER_CIRCLECI_TOKEN}

+ 1 - 0
docker/blocks/elastic/elasticsearch/config/.placeholder

@@ -0,0 +1 @@
+Ensure the existence of the parent folder.

+ 6 - 0
docker/blocks/elastic/fig

@@ -0,0 +1,6 @@
+elasticsearch:
+  image: elasticsearch:latest
+  command: elasticsearch -Des.network.host=0.0.0.0
+  ports:
+    - "9200:9200"
+    - "9300:9300"

+ 0 - 16
docker/blocks/influxdb/Dockerfile

@@ -1,16 +0,0 @@
-# influxdb
-
-FROM ubuntu
-
-RUN mkdir -p /opt/influxdb/shared/data
-
-ADD http://s3.amazonaws.com/influxdb/influxdb_0.8.8_amd64.deb /influx88.deb
-RUN dpkg -i /influx88.deb
-RUN rm -rf /opt/influxdb/shared/data
-
-ADD config.toml /opt/influxdb/shared/config.toml
-
-EXPOSE 8083 8086 2004
-
-ENTRYPOINT ["/usr/bin/influxdb"]
-CMD ["-config=/opt/influxdb/shared/config.toml"]

+ 1 - 1
docker/blocks/influxdb/fig

@@ -1,5 +1,5 @@
 influxdb:
-  build: blocks/influxdb
+  image: tutum/influxdb:latest
   ports:
     - "2004:2004"
     - "8083:8083"

+ 28 - 0
docs/sources/reference/http_api.md

@@ -1422,6 +1422,34 @@ Keys:
       }
     }
 
+### Grafana Stats
+
+`GET /api/admin/stats`
+
+**Example Request**:
+
+    GET /api/admin/stats
+    Accept: application/json
+    Content-Type: application/json
+    Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk
+
+**Example Response**:
+
+    HTTP/1.1 200
+    Content-Type: application/json
+
+    {
+      "user_count":2,
+      "org_count":1,
+      "dashboard_count":4,
+      "db_snapshot_count":2,
+      "db_tag_count":6,
+      "data_source_count":1,
+      "playlist_count":1,
+      "starred_db_count":2,
+      "grafana_admin_count":2
+    }
+
 ### Global Users
 
 `POST /api/admin/users`

+ 1 - 1
docs/sources/reference/singlestat.md

@@ -31,7 +31,7 @@ The coloring options of the Singlestat Panel config allow you to dynamically cha
 
 1. `Background`: This checkbox applies the configured thresholds and colors to the entirety of the Singlestat Panel background.
 2. `Value`: This checkbox applies the configured thresholds and colors to the summary stat.
-3. `Thresholds`: Change the background and value colors dynamically within the panel, depending on the Singlestat value. The threshold field accepts **3 comma-separated** values, corresponding to the three colors directly to the right.
+3. `Thresholds`: Change the background and value colors dynamically within the panel, depending on the Singlestat value. The threshold field accepts **2 comma-separated** values which represent 3 ranges that correspond to the three colors directly to the right. For example: if the thresholds are 70, 90 then the first color represents < 70, the second color represents between 70 and 90 and the third color represents > 90.
 4. `Colors`: Select a color and opacity
 5. `Invert order`: This link toggles the threshold color order.</br>For example: Green, Orange, Red (<img class="no-shadow" src="/img/v1/gyr.png">) will become Red, Orange, Green (<img class="no-shadow" src="/img/v1/ryg.png">).
 

+ 14 - 0
pkg/api/admin_settings.go → pkg/api/admin.go

@@ -3,7 +3,9 @@ package api
 import (
 	"strings"
 
+	"github.com/grafana/grafana/pkg/bus"
 	"github.com/grafana/grafana/pkg/middleware"
+	m "github.com/grafana/grafana/pkg/models"
 	"github.com/grafana/grafana/pkg/setting"
 )
 
@@ -27,3 +29,15 @@ func AdminGetSettings(c *middleware.Context) {
 
 	c.JSON(200, settings)
 }
+
+func AdminGetStats(c *middleware.Context) {
+
+	statsQuery := m.GetAdminStatsQuery{}
+
+	if err := bus.Dispatch(&statsQuery); err != nil {
+		c.JsonApiErr(500, "Failed to get admin stats from database", err)
+		return
+	}
+
+	c.JSON(200, statsQuery.Result)
+}

+ 2 - 0
pkg/api/api.go

@@ -40,6 +40,7 @@ func Register(r *macaron.Macaron) {
 	r.Get("/admin/users/edit/:id", reqGrafanaAdmin, Index)
 	r.Get("/admin/orgs", reqGrafanaAdmin, Index)
 	r.Get("/admin/orgs/edit/:id", reqGrafanaAdmin, Index)
+	r.Get("/admin/stats", reqGrafanaAdmin, Index)
 
 	r.Get("/apps", reqSignedIn, Index)
 	r.Get("/apps/edit/*", reqSignedIn, Index)
@@ -210,6 +211,7 @@ func Register(r *macaron.Macaron) {
 		r.Delete("/users/:id", AdminDeleteUser)
 		r.Get("/users/:id/quotas", wrap(GetUserQuotas))
 		r.Put("/users/:id/quotas/:target", bind(m.UpdateUserQuotaCmd{}), wrap(UpdateUserQuota))
+		r.Get("/stats", AdminGetStats)
 	}, reqGrafanaAdmin)
 
 	// rendering

+ 1 - 0
pkg/metrics/report_usage.go

@@ -55,6 +55,7 @@ func sendUsageStats() {
 	metrics["stats.dashboards.count"] = statsQuery.Result.DashboardCount
 	metrics["stats.users.count"] = statsQuery.Result.UserCount
 	metrics["stats.orgs.count"] = statsQuery.Result.OrgCount
+	metrics["stats.playlist.count"] = statsQuery.Result.PlaylistCount
 
 	dsStats := m.GetDataSourceStatsQuery{}
 	if err := bus.Dispatch(&dsStats); err != nil {

+ 17 - 0
pkg/models/stats.go

@@ -4,6 +4,7 @@ type SystemStats struct {
 	DashboardCount int
 	UserCount      int
 	OrgCount       int
+	PlaylistCount  int
 }
 
 type DataSourceStats struct {
@@ -18,3 +19,19 @@ type GetSystemStatsQuery struct {
 type GetDataSourceStatsQuery struct {
 	Result []*DataSourceStats
 }
+
+type AdminStats struct {
+	UserCount         int `json:"user_count"`
+	OrgCount          int `json:"org_count"`
+	DashboardCount    int `json:"dashboard_count"`
+	DbSnapshotCount   int `json:"db_snapshot_count"`
+	DbTagCount        int `json:"db_tag_count"`
+	DataSourceCount   int `json:"data_source_count"`
+	PlaylistCount     int `json:"playlist_count"`
+	StarredDbCount    int `json:"starred_db_count"`
+	GrafanaAdminCount int `json:"grafana_admin_count"`
+}
+
+type GetAdminStatsQuery struct {
+	Result *AdminStats
+}

+ 57 - 1
pkg/services/sqlstore/stats.go

@@ -8,6 +8,7 @@ import (
 func init() {
 	bus.AddHandler("sql", GetSystemStats)
 	bus.AddHandler("sql", GetDataSourceStats)
+	bus.AddHandler("sql", GetAdminStats)
 }
 
 func GetDataSourceStats(query *m.GetDataSourceStatsQuery) error {
@@ -34,7 +35,11 @@ func GetSystemStats(query *m.GetSystemStatsQuery) error {
       (
         SELECT COUNT(*)
         FROM ` + dialect.Quote("dashboard") + `
-      ) AS dashboard_count
+      ) AS dashboard_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("playlist") + `
+      ) AS playlist_count
 			`
 
 	var stats m.SystemStats
@@ -46,3 +51,54 @@ func GetSystemStats(query *m.GetSystemStatsQuery) error {
 	query.Result = &stats
 	return err
 }
+
+func GetAdminStats(query *m.GetAdminStatsQuery) error {
+	var rawSql = `SELECT
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("user") + `
+      ) AS user_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("org") + `
+      ) AS org_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("dashboard") + `
+      ) AS dashboard_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("dashboard_snapshot") + `
+      ) AS db_snapshot_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("dashboard_tag") + `
+      ) AS db_tag_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("data_source") + `
+      ) AS data_source_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("playlist") + `
+      ) AS playlist_count,
+      (
+        SELECT COUNT (DISTINCT ` + dialect.Quote("dashboard_id") + ` )
+        FROM ` + dialect.Quote("star") + `
+      ) AS starred_db_count,
+      (
+        SELECT COUNT(*)
+        FROM ` + dialect.Quote("user") + `
+        WHERE ` + dialect.Quote("is_admin") + ` = 1
+      ) AS grafana_admin_count
+      `
+
+	var stats m.AdminStats
+	_, err := x.Sql(rawSql).Get(&stats)
+	if err != nil {
+		return err
+	}
+
+	query.Result = &stats
+	return err
+}

+ 18 - 21
public/app/partials/search.html → public/app/core/components/search/search.html

@@ -1,24 +1,22 @@
-<div ng-controller="SearchCtrl" ng-init="init()" class="search-box">
-
 	<div class="search-field-wrapper">
 		<span style="position: relative;">
-			<input  type="text" placeholder="Find dashboards by name" give-focus="giveSearchFocus" tabindex="1"
-			ng-keydown="keyDown($event)" ng-model="query.query" ng-model-options="{ debounce: 500 }" spellcheck='false' ng-change="search()" />
+			<input  type="text" placeholder="Find dashboards by name" give-focus="ctrl.giveSearchFocus" tabindex="1"
+			ng-keydown="ctrl.keyDown($event)" ng-model="ctrl.query.query" ng-model-options="{ debounce: 500 }" spellcheck='false' ng-change="ctrl.search()" />
 		</span>
 		<div class="search-switches">
 			<i class="fa fa-filter"></i>
-			<a class="pointer" href="javascript:void 0;" ng-click="showStarred()" tabindex="2">
-				<i class="fa fa-remove" ng-show="query.starred"></i>
+			<a class="pointer" href="javascript:void 0;" ng-click="ctrl.showStarred()" tabindex="2">
+				<i class="fa fa-remove" ng-show="ctrl.query.starred"></i>
 				starred
 			</a> |
-			<a class="pointer" href="javascript:void 0;" ng-click="getTags()" tabindex="3">
-				<i class="fa fa-remove" ng-show="tagsMode"></i>
+			<a class="pointer" href="javascript:void 0;" ng-click="ctrl.getTags()" tabindex="3">
+				<i class="fa fa-remove" ng-show="ctrl.tagsMode"></i>
 				tags
 			</a>
-			<span ng-if="query.tag.length">
+			<span ng-if="ctrl.query.tag.length">
 				|
-				<span ng-repeat="tagName in query.tag">
-					<a ng-click="removeTag(tagName, $event)" tag-color-from-name="tagName" class="label label-tag">
+				<span ng-repeat="tagName in ctrl.query.tag">
+					<a ng-click="ctrl.removeTag(tagName, $event)" tag-color-from-name="tagName" class="label label-tag">
 						<i class="fa fa-remove"></i>
 						{{tagName}}
 					</a>
@@ -27,12 +25,12 @@
 		</div>
 	</div>
 
-	<div class="search-results-container" ng-if="tagsMode">
+	<div class="search-results-container" ng-if="ctrl.tagsMode">
 		<div class="row">
 			<div class="span6 offset1">
-				<div ng-repeat="tag in results" class="pointer" style="width: 180px; float: left;"
+				<div ng-repeat="tag in ctrl.results" class="pointer" style="width: 180px; float: left;"
 					ng-class="{'selected': $index === selectedIndex }"
-					ng-click="filterByTag(tag.term, $event)">
+					ng-click="ctrl.filterByTag(tag.term, $event)">
 					<a class="search-result-tag label label-tag" tag-color-from-name="tag.term">
 						<i class="fa fa-tag"></i>
 						<span>{{tag.term}} &nbsp;({{tag.count}})</span>
@@ -42,14 +40,14 @@
 		</div>
 	</div>
 
-	<div class="search-results-container" ng-if="!tagsMode">
-		<h6 ng-hide="results.length">No dashboards matching your query were found.</h6>
+	<div class="search-results-container" ng-if="!ctrl.tagsMode">
+		<h6 ng-hide="ctrl.results.length">No dashboards matching your query were found.</h6>
 
-		<a class="search-item pointer search-item-{{row.type}}" bindonce ng-repeat="row in results"
+		<a class="search-item pointer search-item-{{row.type}}" bindonce ng-repeat="row in ctrl.results"
 			ng-class="{'selected': $index == selectedIndex}" ng-href="{{row.url}}">
 
 			<span class="search-result-tags">
-				<span ng-click="filterByTag(tag, $event)" ng-repeat="tag in row.tags" tag-color-from-name="tag"  class="label label-tag">
+				<span ng-click="ctrl.filterByTag(tag, $event)" ng-repeat="tag in row.tags" tag-color-from-name="tag"  class="label label-tag">
 					{{tag}}
 				</span>
 				<i class="fa" ng-class="{'fa-star': row.isStarred, 'fa-star-o': !row.isStarred}"></i>
@@ -63,15 +61,14 @@
 	</div>
 
 	<div class="search-button-row">
-		<button class="btn btn-inverse pull-left" ng-click="newDashboard()" ng-show="contextSrv.isEditor">
+		<button class="btn btn-inverse pull-left" ng-click="ctrl.newDashboard()" ng-show="ctrl.contextSrv.isEditor">
 			<i class="fa fa-plus"></i>
 			New
 		</button>
-		<a class="btn btn-inverse pull-left" href="import/dashboard" ng-show="contextSrv.isEditor">
+		<a class="btn btn-inverse pull-left" href="import/dashboard" ng-show="ctrl.contextSrv.isEditor">
 			<i class="fa fa-download"></i>
 			Import
 		</a>
 		<div class="clearfix"></div>
 	</div>
 
-</div>

+ 150 - 0
public/app/core/components/search/search.ts

@@ -0,0 +1,150 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import angular from 'angular';
+import config from 'app/core/config';
+import _ from 'lodash';
+import $ from 'jquery';
+import coreModule from '../../core_module';
+
+export class SearchCtrl {
+  query: any;
+  giveSearchFocus: number;
+  selectedIndex: number;
+  results: any;
+  currentSearchId: number;
+  tagsMode: boolean;
+  showImport: boolean;
+  dismiss: any;
+
+  /** @ngInject */
+  constructor(private $scope, private $location, private $timeout, private backendSrv, private contextSrv) {
+    this.giveSearchFocus = 0;
+    this.selectedIndex = -1;
+    this.results = [];
+    this.query = { query: '', tag: [], starred: false };
+    this.currentSearchId = 0;
+
+    $timeout(() => {
+      this.giveSearchFocus = this.giveSearchFocus + 1;
+      this.query.query = '';
+      this.search();
+    }, 100);
+  }
+
+  keyDown(evt) {
+    if (evt.keyCode === 27) {
+      this.dismiss();
+    }
+    if (evt.keyCode === 40) {
+      this.moveSelection(1);
+    }
+    if (evt.keyCode === 38) {
+      this.moveSelection(-1);
+    }
+    if (evt.keyCode === 13) {
+      if (this.$scope.tagMode) {
+        var tag = this.results[this.selectedIndex];
+        if (tag) {
+          this.filterByTag(tag.term, null);
+        }
+        return;
+      }
+
+      var selectedDash = this.results[this.selectedIndex];
+      if (selectedDash) {
+        this.$location.search({});
+        this.$location.path(selectedDash.url);
+      }
+    }
+  }
+
+  moveSelection(direction) {
+    var max = (this.results || []).length;
+    var newIndex = this.selectedIndex + direction;
+    this.selectedIndex = ((newIndex %= max) < 0) ? newIndex + max : newIndex;
+  }
+
+  searchDashboards() {
+    this.tagsMode = false;
+    this.currentSearchId = this.currentSearchId + 1;
+    var localSearchId = this.currentSearchId;
+
+    return this.backendSrv.search(this.query).then((results) => {
+      if (localSearchId < this.currentSearchId) { return; }
+
+      this.results = _.map(results, function(dash) {
+        dash.url = 'dashboard/' + dash.uri;
+        return dash;
+      });
+
+      if (this.queryHasNoFilters()) {
+        this.results.unshift({ title: 'Home', url: config.appSubUrl + '/', type: 'dash-home' });
+      }
+    });
+  }
+
+  queryHasNoFilters() {
+    var query = this.query;
+    return query.query === '' && query.starred === false && query.tag.length === 0;
+  };
+
+  filterByTag(tag, evt) {
+    this.query.tag.push(tag);
+    this.search();
+    this.giveSearchFocus = this.giveSearchFocus + 1;
+    if (evt) {
+      evt.stopPropagation();
+      evt.preventDefault();
+    }
+  };
+
+  removeTag(tag, evt) {
+    this.query.tag = _.without(this.query.tag, tag);
+    this.search();
+    this.giveSearchFocus = this.giveSearchFocus + 1;
+    evt.stopPropagation();
+    evt.preventDefault();
+  };
+
+  getTags() {
+    return this.backendSrv.get('/api/dashboards/tags').then((results) => {
+      this.tagsMode = !this.tagsMode;
+      this.results = results;
+      this.giveSearchFocus = this.giveSearchFocus + 1;
+      if ( !this.tagsMode ) {
+        this.search();
+      }
+    });
+  };
+
+  showStarred() {
+    this.query.starred = !this.query.starred;
+    this.giveSearchFocus = this.giveSearchFocus + 1;
+    this.search();
+  };
+
+  search() {
+    this.showImport = false;
+    this.selectedIndex = 0;
+    this.searchDashboards();
+  };
+
+  newDashboard() {
+    this.$location.url('dashboard/new');
+  };
+}
+
+export function searchDirective() {
+  return {
+    restrict: 'E',
+    templateUrl: 'app/core/components/search/search.html',
+    controller: SearchCtrl,
+    bindToController: true,
+    controllerAs: 'ctrl',
+    scope: {
+      dismiss: '&'
+    },
+  };
+}
+
+coreModule.directive('search', searchDirective);

+ 7 - 0
public/app/core/components/sidemenu/sidemenu.ts

@@ -107,6 +107,12 @@ export class SideMenuCtrl {
      url: this.getUrl("/admin/settings"),
    });
 
+   this.mainLinks.push({
+     text: "Grafana stats",
+     icon: "fa fa-fw fa-bar-chart",
+     url: this.getUrl("/admin/stats"),
+   });
+
    this.mainLinks.push({
      text: "Global Users",
      icon: "fa fa-fw fa-user",
@@ -118,6 +124,7 @@ export class SideMenuCtrl {
      icon: "fa fa-fw fa-users",
      url: this.getUrl("/admin/orgs"),
    });
+
  }
 
  updateMenu() {

+ 0 - 1
public/app/core/controllers/all.js

@@ -1,5 +1,4 @@
 define([
-  './search_ctrl',
   './inspect_ctrl',
   './json_editor_ctrl',
   './login_ctrl',

+ 0 - 127
public/app/core/controllers/search_ctrl.js

@@ -1,127 +0,0 @@
-define([
-  'angular',
-  'lodash',
-  '../core_module',
-  'app/core/config',
-],
-function (angular, _, coreModule, config) {
-  'use strict';
-
-  coreModule.default.controller('SearchCtrl', function($scope, $location, $timeout, backendSrv) {
-
-    $scope.init = function() {
-      $scope.giveSearchFocus = 0;
-      $scope.selectedIndex = -1;
-      $scope.results = [];
-      $scope.query = { query: '', tag: [], starred: false };
-      $scope.currentSearchId = 0;
-
-      $timeout(function() {
-        $scope.giveSearchFocus = $scope.giveSearchFocus + 1;
-        $scope.query.query = '';
-        $scope.search();
-      }, 100);
-    };
-
-    $scope.keyDown = function (evt) {
-      if (evt.keyCode === 27) {
-        $scope.dismiss();
-      }
-      if (evt.keyCode === 40) {
-        $scope.moveSelection(1);
-      }
-      if (evt.keyCode === 38) {
-        $scope.moveSelection(-1);
-      }
-      if (evt.keyCode === 13) {
-        if ($scope.tagMode) {
-          var tag = $scope.results[$scope.selectedIndex];
-          if (tag) {
-            $scope.filterByTag(tag.term);
-          }
-          return;
-        }
-
-        var selectedDash = $scope.results[$scope.selectedIndex];
-        if (selectedDash) {
-          $location.search({});
-          $location.path(selectedDash.url);
-        }
-      }
-    };
-
-    $scope.moveSelection = function(direction) {
-      var max = ($scope.results || []).length;
-      var newIndex = $scope.selectedIndex + direction;
-      $scope.selectedIndex = ((newIndex %= max) < 0) ? newIndex + max : newIndex;
-    };
-
-    $scope.searchDashboards = function() {
-      $scope.tagsMode = false;
-      $scope.currentSearchId = $scope.currentSearchId + 1;
-      var localSearchId = $scope.currentSearchId;
-
-      return backendSrv.search($scope.query).then(function(results) {
-        if (localSearchId < $scope.currentSearchId) { return; }
-
-        $scope.results = _.map(results, function(dash) {
-          dash.url = 'dashboard/' + dash.uri;
-          return dash;
-        });
-
-        if ($scope.queryHasNoFilters()) {
-          $scope.results.unshift({ title: 'Home', url: config.appSubUrl + '/', type: 'dash-home' });
-        }
-      });
-    };
-
-    $scope.queryHasNoFilters = function() {
-      var query = $scope.query;
-      return query.query === '' && query.starred === false && query.tag.length === 0;
-    };
-
-    $scope.filterByTag = function(tag, evt) {
-      $scope.query.tag.push(tag);
-      $scope.search();
-      $scope.giveSearchFocus = $scope.giveSearchFocus + 1;
-      if (evt) {
-        evt.stopPropagation();
-        evt.preventDefault();
-      }
-    };
-
-    $scope.removeTag = function(tag, evt) {
-      $scope.query.tag = _.without($scope.query.tag, tag);
-      $scope.search();
-      $scope.giveSearchFocus = $scope.giveSearchFocus + 1;
-      evt.stopPropagation();
-      evt.preventDefault();
-    };
-
-    $scope.getTags = function() {
-      return backendSrv.get('/api/dashboards/tags').then(function(results) {
-        $scope.tagsMode = true;
-        $scope.results = results;
-        $scope.giveSearchFocus = $scope.giveSearchFocus + 1;
-      });
-    };
-
-    $scope.showStarred = function() {
-      $scope.query.starred = !$scope.query.starred;
-      $scope.giveSearchFocus = $scope.giveSearchFocus + 1;
-      $scope.search();
-    };
-
-    $scope.search = function() {
-      $scope.showImport = false;
-      $scope.selectedIndex = 0;
-      $scope.searchDashboards();
-    };
-
-    $scope.newDashboard = function() {
-      $location.url('dashboard/new');
-    };
-
-  });
-
-});

+ 2 - 1
public/app/core/core.ts

@@ -23,6 +23,7 @@ import './partials';
 
 import {grafanaAppDirective} from './components/grafana_app';
 import {sideMenuDirective} from './components/sidemenu/sidemenu';
+import {searchDirective} from './components/search/search';
 import {navbarDirective} from './components/navbar/navbar';
 import {arrayJoin} from './directives/array_join';
 import 'app/core/controllers/all';
@@ -31,4 +32,4 @@ import 'app/core/routes/all';
 import './filters/filters';
 import coreModule from './core_module';
 
-export {arrayJoin, coreModule, grafanaAppDirective, sideMenuDirective, navbarDirective};
+export {arrayJoin, coreModule, grafanaAppDirective, sideMenuDirective, navbarDirective, searchDirective};

+ 5 - 0
public/app/core/routes/all.js

@@ -112,6 +112,11 @@ define([
         templateUrl: 'app/features/admin/partials/edit_org.html',
         controller : 'AdminEditOrgCtrl',
       })
+      .when('/admin/stats', {
+        templateUrl: 'app/features/admin/partials/stats.html',
+        controller : 'AdminStatsCtrl',
+        controllerAs: 'ctrl',
+      })
       .when('/login', {
         templateUrl: 'app/partials/login.html',
         controller : 'LoginCtrl',

+ 1 - 0
public/app/core/time_series2.ts

@@ -41,6 +41,7 @@ export default class TimeSeries {
   nullPointMode: any;
   fillBelowTo: any;
   transform: any;
+  flotpairs: any;
 
   constructor(opts) {
     this.datapoints = opts.datapoints;

+ 18 - 0
public/app/features/admin/adminStatsCtrl.ts

@@ -0,0 +1,18 @@
+///<reference path="../../headers/common.d.ts" />
+
+import angular from 'angular';
+
+export class AdminStatsCtrl {
+  stats: any;
+
+  /** @ngInject */
+  constructor(private backendSrv: any) {}
+
+  init() {
+    this.backendSrv.get('/api/admin/stats').then(stats => {
+      this.stats = stats;
+    });
+  }
+}
+
+angular.module('grafana.controllers').controller('AdminStatsCtrl', AdminStatsCtrl);

+ 1 - 0
public/app/features/admin/all.js

@@ -4,4 +4,5 @@ define([
   './adminEditOrgCtrl',
   './adminEditUserCtrl',
   './adminSettingsCtrl',
+  './adminStatsCtrl',
 ], function () {});

+ 60 - 0
public/app/features/admin/partials/stats.html

@@ -0,0 +1,60 @@
+<topnav icon="fa fa-fw fa-bar-chart" title="Grafana stats"  subnav="true">
+  <ul class="nav">
+    <li class="active"><a href="admin/stats">Overview</a></li>
+  </ul>
+</topnav>
+
+<div class="page-container">
+	<div class="page-wide" ng-init="ctrl.init()">
+		<h1>
+			Overview
+		</h1>
+
+    <table class="filter-table form-inline">
+			<thead>
+				<tr>
+					<th>Name</th>
+					<th>Value</th>
+				</tr>
+			</thead>
+			<tbody>
+        <tr>
+					<td>Total dashboards</td>
+					<td>{{ctrl.stats.dashboard_count}}</td>
+				</tr>
+        <tr>
+          <td>Total users</td>
+          <td>{{ctrl.stats.user_count}}</td>
+        </tr>
+        <tr>
+          <td>Total grafana admins</td>
+          <td>{{ctrl.stats.grafana_admin_count}}</td>
+        </tr>
+        <tr>
+          <td>Total organizations</td>
+          <td>{{ctrl.stats.org_count}}</td>
+        </tr>
+        <tr>
+          <td>Total datasources</td>
+          <td>{{ctrl.stats.data_source_count}}</td>
+        </tr>
+        <tr>
+          <td>Total playlists</td>
+          <td>{{ctrl.stats.playlist_count}}</td>
+        </tr>
+        <tr>
+          <td>Total snapshots</td>
+          <td>{{ctrl.stats.db_snapshot_count}}</td>
+        </tr>
+        <tr>
+          <td>Total dashboard tags</td>
+          <td>{{ctrl.stats.db_tag_count}}</td>
+        </tr>
+        <tr>
+          <td>Total starred dashboards</td>
+          <td>{{ctrl.stats.starred_db_count}}</td>
+        </tr>
+			</tbody>
+		</table>
+	</div>
+</div>

+ 19 - 2
public/app/features/dashboard/dashboardSrv.js

@@ -234,9 +234,9 @@ function (angular, $, _, moment) {
       var i, j, k;
       var oldVersion = this.schemaVersion;
       var panelUpgrades = [];
-      this.schemaVersion = 8;
+      this.schemaVersion = 9;
 
-      if (oldVersion === 8) {
+      if (oldVersion === this.schemaVersion) {
         return;
       }
 
@@ -390,6 +390,23 @@ function (angular, $, _, moment) {
         });
       }
 
+      // schema version 9 changes
+      if (oldVersion < 9) {
+        // move aliasYAxis changes
+        panelUpgrades.push(function(panel) {
+          if (panel.type !== 'singlestat' && panel.thresholds !== "") { return; }
+
+          if (panel.thresholds) {
+            var k = panel.thresholds.split(",");
+
+            if (k.length >= 3) {
+              k.shift();
+              panel.thresholds = k.join(",");
+            }
+          }
+        });
+      }
+
       if (panelUpgrades.length === 0) {
         return;
       }

+ 1 - 1
public/app/features/dashboard/directives/dashSearchView.js

@@ -29,7 +29,7 @@ function (angular, $) {
               editorScope = null;
             };
 
-            var view = $('<div class="search-container" ng-include="\'app/partials/search.html\'"></div>');
+            var view = $('<search class="search-container" dismiss="dismiss()"></search>');
 
             elem.append(view);
             $compile(elem.contents())(editorScope);

+ 1 - 1
public/app/plugins/datasource/elasticsearch/datasource.js

@@ -146,7 +146,7 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
         return { status: "success", message: "Data source is working", title: "Success" };
       }, function(err) {
         if (err.data && err.data.error) {
-          return { status: "error", message: err.data.error, title: "Error" };
+          return { status: "error", message: angular.toJson(err.data.error), title: "Error" };
         } else {
           return { status: "error", message: err.status, title: "Error" };
         }

+ 2 - 2
public/app/plugins/datasource/opentsdb/specs/datasource-specs.ts

@@ -36,14 +36,14 @@ describe('opentsdb', function() {
       expect(requestOptions.params.q).to.be('pew');
     });
 
-    it('tag_names(cpu) should generate looku  query', function() {
+    it('tag_names(cpu) should generate lookup query', function() {
       ctx.ds.metricFindQuery('tag_names(cpu)').then(function(data) { results = data; });
       ctx.$rootScope.$apply();
       expect(requestOptions.url).to.be('/api/search/lookup');
       expect(requestOptions.params.m).to.be('cpu');
     });
 
-    it('tag_values(cpu, test) should generate looku  query', function() {
+    it('tag_values(cpu, test) should generate lookup query', function() {
       ctx.ds.metricFindQuery('tag_values(cpu, hostname)').then(function(data) { results = data; });
       ctx.$rootScope.$apply();
       expect(requestOptions.url).to.be('/api/search/lookup');

+ 8 - 5
public/app/plugins/panel/graph/graph.js

@@ -296,7 +296,7 @@ function (angular, $, moment, _, kbn, GraphTooltip) {
             max: max,
             label: "Datetime",
             ticks: ticks,
-            timeformat: time_format(ctrl.interval, ticks, min, max),
+            timeformat: time_format(ticks, min, max),
           };
         }
 
@@ -436,20 +436,23 @@ function (angular, $, moment, _, kbn, GraphTooltip) {
           };
         }
 
-        function time_format(interval, ticks, min, max) {
+        function time_format(ticks, min, max) {
           if (min && max && ticks) {
-            var secPerTick = ((max - min) / ticks) / 1000;
+            var range = max - min;
+            var secPerTick = (range/ticks) / 1000;
+            var oneDay = 86400000;
+            var oneYear = 31536000000;
 
             if (secPerTick <= 45) {
               return "%H:%M:%S";
             }
-            if (secPerTick <= 7200) {
+            if (secPerTick <= 7200 || range <= oneDay) {
               return "%H:%M";
             }
             if (secPerTick <= 80000) {
               return "%m/%d %H:%M";
             }
-            if (secPerTick <= 2419200) {
+            if (secPerTick <= 2419200 || range <= oneYear) {
               return "%m/%d";
             }
             return "%Y-%m";

+ 3 - 9
public/app/plugins/panel/graph/graph_tooltip.js

@@ -81,9 +81,9 @@ function ($) {
           // Stacked series can increase its length on each new stacked serie if null points found,
           // to speed the index search we begin always on the last found hoverIndex.
           var newhoverIndex = this.findHoverIndexFromDataPoints(pos.x, series, hoverIndex);
-          results.push({ value: value, hoverIndex: newhoverIndex, color: series.color, label: series.label });
+          results.push({ value: value, hoverIndex: newhoverIndex });
         } else {
-          results.push({ value: value, hoverIndex: hoverIndex, color: series.color, label: series.label });
+          results.push({ value: value, hoverIndex: hoverIndex });
         }
       }
 
@@ -128,8 +128,6 @@ function ($) {
         relativeTime = dashboard.getRelativeTime(seriesHoverInfo.time);
         absoluteTime = dashboard.formatDate(seriesHoverInfo.time);
 
-        seriesHoverInfo.sort(byToolTipValue);
-
         for (i = 0; i < seriesHoverInfo.length; i++) {
           hoverInfo = seriesHoverInfo[i];
 
@@ -142,7 +140,7 @@ function ($) {
           value = series.formatValue(hoverInfo.value);
 
           seriesHtml += '<div class="graph-tooltip-list-item"><div class="graph-tooltip-series-name">';
-          seriesHtml += '<i class="fa fa-minus" style="color:' + hoverInfo.color +';"></i> ' + hoverInfo.label + ':</div>';
+          seriesHtml += '<i class="fa fa-minus" style="color:' + series.color +';"></i> ' + series.label + ':</div>';
           seriesHtml += '<div class="graph-tooltip-value">' + value + '</div></div>';
           plot.highlight(i, hoverInfo.hoverIndex);
         }
@@ -178,9 +176,5 @@ function ($) {
     });
   }
 
-  function byToolTipValue(a, b) {
-    return parseFloat(b.value) - parseFloat(a.value);
-  }
-
   return GraphTooltip;
 });

+ 32 - 4
public/app/plugins/panel/graph/specs/graph_specs.ts

@@ -7,12 +7,13 @@ import angular from 'angular';
 import $ from 'jquery';
 import helpers from '../../../../../test/specs/helpers';
 import TimeSeries from '../../../../core/time_series2';
+import moment from 'moment';
 
 describe('grafanaGraph', function() {
 
   beforeEach(angularMocks.module('grafana.directives'));
 
-  function graphScenario(desc, func)  {
+  function graphScenario(desc, func, elementWidth = 500)  {
     describe(desc, function() {
       var ctx: any = {};
 
@@ -26,7 +27,7 @@ describe('grafanaGraph', function() {
           var ctrl: any = {};
           var scope = $rootScope.$new();
           scope.ctrl = ctrl;
-          var element = angular.element("<div style='width:500px' grafana-graph><div>");
+          var element = angular.element("<div style='width:" + elementWidth + "px' grafana-graph><div>");
 
           ctrl.height = '200px';
           ctrl.panel = {
@@ -45,8 +46,8 @@ describe('grafanaGraph', function() {
           ctrl.hiddenSeries = {};
           ctrl.dashboard = { timezone: 'browser' };
           ctrl.range = {
-            from: new Date('2014-08-09 10:00:00'),
-            to: new Date('2014-09-09 13:00:00')
+            from: moment([2015, 1, 1, 10]),
+            to: moment([2015, 1, 1, 22]),
           };
           ctx.data = [];
           ctx.data.push(new TimeSeries({
@@ -229,4 +230,31 @@ describe('grafanaGraph', function() {
       expect(axis.tickFormatter(100, axis)).to.be("100%");
     });
   });
+
+  graphScenario('when panel too narrow to show x-axis dates in same granularity as wide panels', function(ctx) {
+    describe('and the range is less than 24 hours', function() {
+      ctx.setup(function(ctrl) {
+        ctrl.range.from = moment([2015, 1, 1, 10]);
+        ctrl.range.to = moment([2015, 1, 1, 22]);
+      });
+
+      it('should format dates as hours minutes', function() {
+        var axis = ctx.plotOptions.xaxis;
+        expect(axis.timeformat).to.be('%H:%M');
+      });
+    });
+
+    describe('and the range is less than one year', function() {
+      ctx.setup(function(scope) {
+        scope.range.from = moment([2015, 1, 1]);
+        scope.range.to = moment([2015, 11, 20]);
+      });
+
+      it('should format dates as month days', function() {
+        var axis = ctx.plotOptions.xaxis;
+        expect(axis.timeformat).to.be('%m/%d');
+      });
+    });
+
+  }, 10);
 });

+ 18 - 21
public/app/plugins/panel/singlestat/controller.js → public/app/plugins/panel/singlestat/controller.ts

@@ -1,17 +1,15 @@
-define([
-  'angular',
-  'app/app',
-  'lodash',
-  'app/core/utils/kbn',
-  'app/core/time_series',
-  'app/features/panel/panel_meta',
-],
-function (angular, app, _, kbn, TimeSeries, PanelMeta) {
-  'use strict';
+///<reference path="../../../headers/common.d.ts" />
 
-  /** @ngInject */
-  function SingleStatCtrl($scope, panelSrv, panelHelper) {
+import angular from 'angular';
+import _ from 'lodash';
+import kbn from 'app/core/utils/kbn';
+import PanelMeta from 'app/features/panel/panel_meta2';
+import TimeSeries from '../../../core/time_series2';
+
+export class SingleStatCtrl {
 
+  /** @ngInject */
+  constructor($scope, panelSrv, panelHelper) {
     $scope.panelMeta = new PanelMeta({
       panelName: 'Singlestat',
       editIcon:  "fa fa-dashboard",
@@ -57,6 +55,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
     };
 
     _.defaults($scope.panel, _d);
+
     $scope.unitFormats = kbn.getUnitFormats();
 
     $scope.setUnitFormat = function(subItem) {
@@ -104,8 +103,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
       if (options.background) {
         $scope.panel.colorValue = false;
         $scope.panel.colors = ['rgba(71, 212, 59, 0.4)', 'rgba(245, 150, 40, 0.73)', 'rgba(225, 40, 40, 0.59)'];
-      }
-      else {
+      } else {
         $scope.panel.colorBackground = false;
         $scope.panel.colors = ['rgba(50, 172, 45, 0.97)', 'rgba(237, 129, 40, 0.89)', 'rgba(245, 54, 54, 0.9)'];
       }
@@ -151,7 +149,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
       // reduce starting decimals if not needed
       if (Math.floor(value) === value) { dec = 0; }
 
-      var result = {};
+      var result: any = {};
       result.decimals = Math.max(0, dec);
       result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;
 
@@ -159,7 +157,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
     };
 
     $scope.render = function() {
-      var data = {};
+      var data: any = {};
 
       $scope.setValues(data);
 
@@ -176,7 +174,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
     $scope.setValues = function(data) {
       data.flotpairs = [];
 
-      if($scope.series.length > 1) {
+      if ($scope.series.length > 1) {
         $scope.inspector.error = new Error();
         $scope.inspector.error.message = 'Multiple Series Error';
         $scope.inspector.error.data = 'Metric query returns ' + $scope.series.length +
@@ -204,7 +202,7 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
       }
 
       // check value to text mappings
-      for(var i = 0; i < $scope.panel.valueMaps.length; i++) {
+      for (var i = 0; i < $scope.panel.valueMaps.length; i++) {
         var map = $scope.panel.valueMaps[i];
         // special null case
         if (map.value === 'null') {
@@ -239,7 +237,6 @@ function (angular, app, _, kbn, TimeSeries, PanelMeta) {
     };
 
     $scope.init();
-  }
 
-  return SingleStatCtrl;
-});
+  }
+}

+ 2 - 2
public/app/plugins/panel/singlestat/editor.html

@@ -97,10 +97,10 @@
 					<label for="panel.colorValue" class="cr1"></label>
 				</li>
 				<li class="tight-form-item">
-					Thresholds<tip>Comma seperated values</tip>
+					Thresholds<tip>Define two threshold values&lt;br /&gt; 50,80 will produce: &lt;50 = Green, 50:80 = Yellow, &gt;80 = Red</tip>
 				</li>
 				<li>
-					<input type="text" class="input-large tight-form-input" ng-model="panel.thresholds" ng-blur="render()" placeholder="0,50,80"></input>
+					<input type="text" class="input-large tight-form-input" ng-model="panel.thresholds" ng-blur="render()" placeholder="50,80"></input>
 				</li>
 				<li class="tight-form-item">
 					Colors

+ 0 - 235
public/app/plugins/panel/singlestat/module.js

@@ -1,235 +0,0 @@
-define([
-  './controller',
-  'lodash',
-  'jquery',
-  'jquery.flot',
-],
-function (SingleStatCtrl, _, $) {
-  'use strict';
-
-  /** @ngInject */
-  function singleStatPanel($location, linkSrv, $timeout, templateSrv) {
-    return {
-      controller: SingleStatCtrl,
-      templateUrl: 'app/plugins/panel/singlestat/module.html',
-      link: function(scope, elem) {
-        var data, panel, linkInfo, $panelContainer;
-        var firstRender = true;
-
-        scope.$on('render', function() {
-          if (firstRender) {
-            var inner = elem.find('.singlestat-panel');
-            if (inner.length) {
-              elem = inner;
-              $panelContainer = elem.parents('.panel-container');
-              firstRender = false;
-              hookupDrilldownLinkTooltip();
-            }
-          }
-
-          render();
-          scope.panelRenderingComplete();
-        });
-
-        function setElementHeight() {
-          try {
-            var height = scope.height || panel.height || scope.row.height;
-            if (_.isString(height)) {
-              height = parseInt(height.replace('px', ''), 10);
-            }
-
-            height -= 5; // padding
-            height -= panel.title ? 24 : 9; // subtract panel title bar
-
-            elem.css('height', height + 'px');
-
-            return true;
-          } catch(e) { // IE throws errors sometimes
-            return false;
-          }
-        }
-
-        function applyColoringThresholds(value, valueString) {
-          if (!panel.colorValue) {
-            return valueString;
-          }
-
-          var color = getColorForValue(value);
-          if (color) {
-            return '<span style="color:' + color + '">'+ valueString + '</span>';
-          }
-
-          return valueString;
-        }
-
-        function getColorForValue(value) {
-          for (var i = data.thresholds.length - 1; i >= 0 ; i--) {
-            if (value >= data.thresholds[i]) {
-              return data.colorMap[i];
-            }
-          }
-          return null;
-        }
-
-        function getSpan(className, fontSize, value)  {
-          value = templateSrv.replace(value);
-          return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
-            value + '</span>';
-        }
-
-        function getBigValueHtml() {
-          var body = '<div class="singlestat-panel-value-container">';
-
-          if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, scope.panel.prefix); }
-
-          var value = applyColoringThresholds(data.valueRounded, data.valueFormated);
-          body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
-
-          if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
-
-          body += '</div>';
-
-          return body;
-        }
-
-        function addSparkline() {
-          var panel = scope.panel;
-          var width = elem.width() + 20;
-          var height = elem.height() || 100;
-
-          var plotCanvas = $('<div></div>');
-          var plotCss = {};
-          plotCss.position = 'absolute';
-
-          if (panel.sparkline.full) {
-            plotCss.bottom = '5px';
-            plotCss.left = '-5px';
-            plotCss.width = (width - 10) + 'px';
-            var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
-            plotCss.height = (height - dynamicHeightMargin) + 'px';
-          }
-          else {
-            plotCss.bottom = "0px";
-            plotCss.left = "-5px";
-            plotCss.width = (width - 10) + 'px';
-            plotCss.height = Math.floor(height * 0.25) + "px";
-          }
-
-          plotCanvas.css(plotCss);
-
-          var options = {
-            legend: { show: false },
-            series: {
-              lines:  {
-                show: true,
-                fill: 1,
-                lineWidth: 1,
-                fillColor: panel.sparkline.fillColor,
-              },
-            },
-            yaxes: { show: false },
-            xaxis: {
-              show: false,
-              mode: "time",
-              min: scope.range.from.valueOf(),
-              max: scope.range.to.valueOf(),
-            },
-            grid: { hoverable: false, show: false },
-          };
-
-          elem.append(plotCanvas);
-
-          var plotSeries = {
-            data: data.flotpairs,
-            color: panel.sparkline.lineColor
-          };
-
-          $.plot(plotCanvas, [plotSeries], options);
-        }
-
-        function render() {
-          if (!scope.data) { return; }
-
-          data = scope.data;
-          panel = scope.panel;
-
-          setElementHeight();
-
-          var body = getBigValueHtml();
-
-          if (panel.colorBackground && !isNaN(data.valueRounded)) {
-            var color = getColorForValue(data.valueRounded);
-            if (color) {
-              $panelContainer.css('background-color', color);
-              if (scope.fullscreen) {
-                elem.css('background-color', color);
-              } else {
-                elem.css('background-color', '');
-              }
-            }
-          } else {
-            $panelContainer.css('background-color', '');
-            elem.css('background-color', '');
-          }
-
-          elem.html(body);
-
-          if (panel.sparkline.show) {
-            addSparkline();
-          }
-
-          elem.toggleClass('pointer', panel.links.length > 0);
-
-          if (panel.links.length > 0) {
-            linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], scope.panel.scopedVars);
-          } else {
-            linkInfo = null;
-          }
-        }
-
-        function hookupDrilldownLinkTooltip() {
-          // drilldown link tooltip
-          var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
-
-          elem.mouseleave(function() {
-            if (panel.links.length === 0) { return;}
-            drilldownTooltip.detach();
-          });
-
-          elem.click(function(evt) {
-            if (!linkInfo) { return; }
-            // ignore title clicks in title
-            if ($(evt).parents('.panel-header').length > 0) { return; }
-
-            if (linkInfo.target === '_blank') {
-              var redirectWindow = window.open(linkInfo.href, '_blank');
-              redirectWindow.location;
-              return;
-            }
-
-            if (linkInfo.href.indexOf('http') === 0) {
-              window.location.href = linkInfo.href;
-            } else {
-              $timeout(function() {
-                $location.url(linkInfo.href);
-              });
-            }
-
-            drilldownTooltip.detach();
-          });
-
-          elem.mousemove(function(e) {
-            if (!linkInfo) { return;}
-
-            drilldownTooltip.text('click to go to: ' + linkInfo.title);
-            drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
-          });
-        }
-      }
-    };
-  }
-
-  return {
-    panel: singleStatPanel
-  };
-});

+ 232 - 0
public/app/plugins/panel/singlestat/module.ts

@@ -0,0 +1,232 @@
+///<reference path="../../../headers/common.d.ts" />
+
+import _ from 'lodash';
+import $ from 'jquery';
+import angular from 'angular';
+import {SingleStatCtrl} from './controller';
+
+angular.module('grafana.directives').directive('singleStatPanel', singleStatPanel);
+
+function singleStatPanel($location, linkSrv, $timeout, templateSrv) {
+  'use strict';
+  return {
+    controller: SingleStatCtrl,
+    templateUrl: 'app/plugins/panel/singlestat/module.html',
+    link: function(scope, elem) {
+      var data, panel, linkInfo, $panelContainer;
+      var firstRender = true;
+
+      scope.$on('render', function() {
+        if (firstRender) {
+          var inner = elem.find('.singlestat-panel');
+          if (inner.length) {
+            elem = inner;
+            $panelContainer = elem.parents('.panel-container');
+            firstRender = false;
+            hookupDrilldownLinkTooltip();
+          }
+        }
+
+        render();
+        scope.panelRenderingComplete();
+      });
+
+      function setElementHeight() {
+        try {
+          var height = scope.height || panel.height || scope.row.height;
+          if (_.isString(height)) {
+            height = parseInt(height.replace('px', ''), 10);
+          }
+
+          height -= 5; // padding
+          height -= panel.title ? 24 : 9; // subtract panel title bar
+
+          elem.css('height', height + 'px');
+
+          return true;
+        } catch (e) { // IE throws errors sometimes
+          return false;
+        }
+      }
+
+      function applyColoringThresholds(value, valueString) {
+        if (!panel.colorValue) {
+          return valueString;
+        }
+
+        var color = getColorForValue(data, value);
+        if (color) {
+          return '<span style="color:' + color + '">'+ valueString + '</span>';
+        }
+
+        return valueString;
+      }
+
+      function getSpan(className, fontSize, value)  {
+        value = templateSrv.replace(value);
+        return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
+          value + '</span>';
+      }
+
+      function getBigValueHtml() {
+        var body = '<div class="singlestat-panel-value-container">';
+
+        if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, scope.panel.prefix); }
+
+        var value = applyColoringThresholds(data.valueRounded, data.valueFormated);
+        body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
+
+        if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
+
+        body += '</div>';
+
+        return body;
+      }
+
+      function addSparkline() {
+        var panel = scope.panel;
+        var width = elem.width() + 20;
+        var height = elem.height() || 100;
+
+        var plotCanvas = $('<div></div>');
+        var plotCss: any = {};
+        plotCss.position = 'absolute';
+
+        if (panel.sparkline.full) {
+          plotCss.bottom = '5px';
+          plotCss.left = '-5px';
+          plotCss.width = (width - 10) + 'px';
+          var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
+          plotCss.height = (height - dynamicHeightMargin) + 'px';
+        } else {
+          plotCss.bottom = "0px";
+          plotCss.left = "-5px";
+          plotCss.width = (width - 10) + 'px';
+          plotCss.height = Math.floor(height * 0.25) + "px";
+        }
+
+        plotCanvas.css(plotCss);
+
+        var options = {
+          legend: { show: false },
+          series: {
+            lines:  {
+              show: true,
+              fill: 1,
+              lineWidth: 1,
+              fillColor: panel.sparkline.fillColor,
+            },
+          },
+          yaxes: { show: false },
+          xaxis: {
+            show: false,
+            mode: "time",
+            min: scope.range.from.valueOf(),
+            max: scope.range.to.valueOf(),
+          },
+          grid: { hoverable: false, show: false },
+        };
+
+        elem.append(plotCanvas);
+
+        var plotSeries = {
+          data: data.flotpairs,
+          color: panel.sparkline.lineColor
+        };
+
+        $.plot(plotCanvas, [plotSeries], options);
+      }
+
+      function render() {
+        if (!scope.data) { return; }
+
+        data = scope.data;
+        panel = scope.panel;
+
+        setElementHeight();
+
+        var body = getBigValueHtml();
+
+        if (panel.colorBackground && !isNaN(data.valueRounded)) {
+          var color = getColorForValue(data, data.valueRounded);
+          if (color) {
+            $panelContainer.css('background-color', color);
+            if (scope.fullscreen) {
+              elem.css('background-color', color);
+            } else {
+              elem.css('background-color', '');
+            }
+          }
+        } else {
+          $panelContainer.css('background-color', '');
+          elem.css('background-color', '');
+        }
+
+        elem.html(body);
+
+        if (panel.sparkline.show) {
+          addSparkline();
+        }
+
+        elem.toggleClass('pointer', panel.links.length > 0);
+
+        if (panel.links.length > 0) {
+          linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], scope.panel.scopedVars);
+        } else {
+          linkInfo = null;
+        }
+      }
+
+      function hookupDrilldownLinkTooltip() {
+        // drilldown link tooltip
+        var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
+
+        elem.mouseleave(function() {
+          if (panel.links.length === 0) { return;}
+          drilldownTooltip.detach();
+        });
+
+        elem.click(function(evt) {
+          if (!linkInfo) { return; }
+          // ignore title clicks in title
+          if ($(evt).parents('.panel-header').length > 0) { return; }
+
+          if (linkInfo.target === '_blank') {
+            var redirectWindow = window.open(linkInfo.href, '_blank');
+            redirectWindow.location;
+            return;
+          }
+
+          if (linkInfo.href.indexOf('http') === 0) {
+            window.location.href = linkInfo.href;
+          } else {
+            $timeout(function() {
+              $location.url(linkInfo.href);
+            });
+          }
+
+          drilldownTooltip.detach();
+        });
+
+        elem.mousemove(function(e) {
+          if (!linkInfo) { return;}
+
+          drilldownTooltip.text('click to go to: ' + linkInfo.title);
+          drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
+        });
+      }
+    }
+  };
+}
+
+function getColorForValue(data, value) {
+  for (var i = data.thresholds.length; i > 0; i--) {
+    if (value >= data.thresholds[i]) {
+      return data.colorMap[i];
+    }
+  }
+
+  return _.first(data.colorMap);
+}
+
+export {singleStatPanel as panel, getColorForValue};

+ 0 - 221
public/app/plugins/panel/singlestat/singleStatPanel.js

@@ -1,221 +0,0 @@
-define([
-  'angular',
-  'app/app',
-  'lodash',
-  'jquery',
-  'jquery.flot',
-],
-function (angular, app, _, $) {
-  'use strict';
-
-  var module = angular.module('grafana.panels.singlestat', []);
-  app.useModule(module);
-
-  module.directive('singlestatPanel', function($location, linkSrv, $timeout, templateSrv) {
-
-    return {
-      link: function(scope, elem) {
-        var data, panel, linkInfo;
-        var $panelContainer = elem.parents('.panel-container');
-
-        scope.$on('render', function() {
-          render();
-          scope.panelRenderingComplete();
-        });
-
-        function setElementHeight() {
-          try {
-            var height = scope.height || panel.height || scope.row.height;
-            if (_.isString(height)) {
-              height = parseInt(height.replace('px', ''), 10);
-            }
-
-            height -= 5; // padding
-            height -= panel.title ? 24 : 9; // subtract panel title bar
-
-            elem.css('height', height + 'px');
-
-            return true;
-          } catch(e) { // IE throws errors sometimes
-            return false;
-          }
-        }
-
-        function applyColoringThresholds(value, valueString) {
-          if (!panel.colorValue) {
-            return valueString;
-          }
-
-          var color = getColorForValue(value);
-          if (color) {
-            return '<span style="color:' + color + '">'+ valueString + '</span>';
-          }
-
-          return valueString;
-        }
-
-        function getColorForValue(value) {
-          for (var i = data.thresholds.length - 1; i >= 0 ; i--) {
-            if (value >= data.thresholds[i]) {
-              return data.colorMap[i];
-            }
-          }
-          return null;
-        }
-
-        function getSpan(className, fontSize, value)  {
-          value = templateSrv.replace(value);
-          return '<span class="' + className + '" style="font-size:' + fontSize + '">' +
-            value + '</span>';
-        }
-
-        function getBigValueHtml() {
-          var body = '<div class="singlestat-panel-value-container">';
-
-          if (panel.prefix) { body += getSpan('singlestat-panel-prefix', panel.prefixFontSize, scope.panel.prefix); }
-
-          var value = applyColoringThresholds(data.valueRounded, data.valueFormated);
-          body += getSpan('singlestat-panel-value', panel.valueFontSize, value);
-
-          if (panel.postfix) { body += getSpan('singlestat-panel-postfix', panel.postfixFontSize, panel.postfix); }
-
-          body += '</div>';
-
-          return body;
-        }
-
-        function addSparkline() {
-          var panel = scope.panel;
-          var width = elem.width() + 20;
-          var height = elem.height() || 100;
-
-          var plotCanvas = $('<div></div>');
-          var plotCss = {};
-          plotCss.position = 'absolute';
-
-          if (panel.sparkline.full) {
-            plotCss.bottom = '5px';
-            plotCss.left = '-5px';
-            plotCss.width = (width - 10) + 'px';
-            var dynamicHeightMargin = height <= 100 ? 5 : (Math.round((height/100)) * 15) + 5;
-            plotCss.height = (height - dynamicHeightMargin) + 'px';
-          }
-          else {
-            plotCss.bottom = "0px";
-            plotCss.left = "-5px";
-            plotCss.width = (width - 10) + 'px';
-            plotCss.height = Math.floor(height * 0.25) + "px";
-          }
-
-          plotCanvas.css(plotCss);
-
-          var options = {
-            legend: { show: false },
-            series: {
-              lines:  {
-                show: true,
-                fill: 1,
-                lineWidth: 1,
-                fillColor: panel.sparkline.fillColor,
-              },
-            },
-            yaxes: { show: false },
-            xaxis: {
-              show: false,
-              mode: "time",
-              min: scope.range.from.valueOf(),
-              max: scope.range.to.valueOf(),
-            },
-            grid: { hoverable: false, show: false },
-          };
-
-          elem.append(plotCanvas);
-
-          var plotSeries = {
-            data: data.flotpairs,
-            color: panel.sparkline.lineColor
-          };
-
-          $.plot(plotCanvas, [plotSeries], options);
-        }
-
-        function render() {
-          if (!scope.data) { return; }
-
-          data = scope.data;
-          panel = scope.panel;
-
-          setElementHeight();
-
-          var body = getBigValueHtml();
-
-          if (panel.colorBackground && !isNaN(data.valueRounded)) {
-            var color = getColorForValue(data.valueRounded);
-            if (color) {
-              $panelContainer.css('background-color', color);
-              if (scope.fullscreen) {
-                elem.css('background-color', color);
-              } else {
-                elem.css('background-color', '');
-              }
-            }
-          } else {
-            $panelContainer.css('background-color', '');
-            elem.css('background-color', '');
-          }
-
-          elem.html(body);
-
-          if (panel.sparkline.show) {
-            addSparkline();
-          }
-
-          elem.toggleClass('pointer', panel.links.length > 0);
-
-          if (panel.links.length > 0) {
-            linkInfo = linkSrv.getPanelLinkAnchorInfo(panel.links[0], scope.panel.scopedVars);
-          } else {
-            linkInfo = null;
-          }
-        }
-
-        // drilldown link tooltip
-        var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
-
-        elem.mouseleave(function() {
-          if (panel.links.length === 0) { return;}
-          drilldownTooltip.detach();
-        });
-
-        elem.click(function() {
-          if (!linkInfo) { return; }
-
-          if (linkInfo.target === '_blank') {
-            var redirectWindow = window.open(linkInfo.href, '_blank');
-            redirectWindow.location;
-            return;
-          }
-
-          if (linkInfo.href.indexOf('http') === 0) {
-            window.location.href = linkInfo.href;
-          } else {
-            $timeout(function() {
-              $location.url(linkInfo.href);
-            });
-          }
-
-          drilldownTooltip.detach();
-        });
-
-        elem.mousemove(function(e) {
-          if (!linkInfo) { return;}
-
-          drilldownTooltip.text('click to go to: ' + linkInfo.title);
-
-          drilldownTooltip.place_tt(e.pageX+20, e.pageY-15);
-        });
-      }
-    };
-  });
-
-});

+ 88 - 0
public/app/plugins/panel/singlestat/specs/singlestat-specs.ts

@@ -0,0 +1,88 @@
+///<reference path="../../../../headers/common.d.ts" />
+
+import {describe, beforeEach, it, sinon, expect, angularMocks} from '../../../../../test/lib/common';
+
+import 'app/features/panel/panel_srv';
+import 'app/features/panel/panel_helper';
+
+import angular from 'angular';
+import helpers from '../../../../../test/specs/helpers';
+import {SingleStatCtrl} from '../controller';
+
+
+angular.module('grafana.controllers').controller('SingleStatCtrl', SingleStatCtrl);
+
+describe('SingleStatCtrl', function() {
+  var ctx = new helpers.ControllerTestContext();
+
+  function singleStatScenario(desc, func) {
+
+    describe(desc, function() {
+
+      ctx.setup = function (setupFunc) {
+
+        beforeEach(angularMocks.module('grafana.services'));
+        beforeEach(angularMocks.module('grafana.controllers'));
+
+        beforeEach(ctx.providePhase());
+        beforeEach(ctx.createControllerPhase('SingleStatCtrl'));
+
+        beforeEach(function() {
+          setupFunc();
+          ctx.datasource.query = sinon.stub().returns(ctx.$q.when({
+            data: [{target: 'test.cpu1', datapoints: ctx.datapoints}]
+          }));
+
+          ctx.scope.refreshData(ctx.datasource);
+          ctx.scope.$digest();
+          ctx.data = ctx.scope.data;
+        });
+      };
+
+      func(ctx);
+    });
+  }
+
+  singleStatScenario('with defaults', function(ctx) {
+    ctx.setup(function() {
+      ctx.datapoints = [[10,1], [20,2]];
+    });
+
+    it('Should use series avg as default main value', function() {
+      expect(ctx.data.value).to.be(15);
+      expect(ctx.data.valueRounded).to.be(15);
+    });
+
+    it('should set formated falue', function() {
+      expect(ctx.data.valueFormated).to.be('15');
+    });
+  });
+
+  singleStatScenario('MainValue should use same number for decimals as displayed when checking thresholds', function(ctx) {
+    ctx.setup(function() {
+      ctx.datapoints = [[99.999,1], [99.99999,2]];
+    });
+
+    it('Should be rounded', function() {
+      expect(ctx.data.value).to.be(99.999495);
+      expect(ctx.data.valueRounded).to.be(100);
+    });
+
+    it('should set formated falue', function() {
+      expect(ctx.data.valueFormated).to.be('100');
+    });
+  });
+
+  singleStatScenario('When value to text mapping is specified', function(ctx) {
+    ctx.setup(function() {
+      ctx.datapoints = [[10,1]];
+      ctx.scope.panel.valueMaps = [{value: '10', text: 'OK'}];
+    });
+
+    it('Should replace value with text', function() {
+      expect(ctx.data.value).to.be(10);
+      expect(ctx.data.valueFormated).to.be('OK');
+    });
+
+  });
+});

+ 58 - 0
public/app/plugins/panel/singlestat/specs/singlestat_panel_spec.ts

@@ -0,0 +1,58 @@
+import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
+
+import {getColorForValue} from '../module';
+
+describe('grafanaSingleStat', function() {
+  describe('legacy thresholds', () => {
+    describe('positive thresholds', () => {
+      var data: any = {
+        colorMap: ['green', 'yellow', 'red'],
+        thresholds: [0, 20, 50]
+      };
+
+      it('5 should return green', () => {
+        expect(getColorForValue(data, 5)).to.be('green');
+      });
+
+      it('25 should return green', () => {
+        expect(getColorForValue(data, 25)).to.be('yellow');
+      });
+
+      it('55 should return green', () => {
+        expect(getColorForValue(data, 55)).to.be('red');
+      });
+    });
+  });
+
+
+
+  describe('negative thresholds', () => {
+    var data: any = {
+      colorMap: ['green', 'yellow', 'red'],
+      thresholds: [ -20, 0, 20]
+    };
+
+    it('-30 should return green', () => {
+      expect(getColorForValue(data, -30)).to.be('green');
+    });
+
+    it('1 should return green', () => {
+      expect(getColorForValue(data, 1)).to.be('yellow');
+    });
+
+    it('22 should return green', () => {
+      expect(getColorForValue(data, 22)).to.be('red');
+    });
+  });
+
+  describe('negative thresholds', () => {
+    var data: any = {
+      colorMap: ['green', 'yellow', 'red'],
+      thresholds: [ -40, -27, 20]
+    };
+
+    it('-30 should return green', () => {
+      expect(getColorForValue(data, -26)).to.be('yellow');
+    });
+  });
+});

+ 1 - 5
public/less/login.less

@@ -110,13 +110,9 @@
   text-align: center;
   border: 1px solid @grafanaTargetFuncBackground;
 	background-color: @grafanaPanelBackground;
-	position: fixed;
-  max-width: 800px;
-  left: 0;
-  right: 0;
+  width: 800px;
   margin-left: auto;
   margin-right: auto;
-  top: 20%;
 
   .tight-form {
     text-align: left;

+ 11 - 1
public/test/specs/dashboardSrv-specs.js

@@ -141,6 +141,7 @@ define([
     describe('when creating dashboard with old schema', function() {
       var model;
       var graph;
+      var singlestat;
 
       beforeEach(function() {
         model = _dashboardSrv.create({
@@ -155,6 +156,10 @@ define([
                 {
                   type: 'graphite', legend: true, aliasYAxis: { test: 2 }, grid: { min: 1, max: 10 },
                   targets: [{refId: 'A'}, {}],
+                },
+                {
+                  type: 'singlestat', legend: true, thresholds: '10,20,30', aliasYAxis: { test: 2 }, grid: { min: 1, max: 10 },
+                  targets: [{refId: 'A'}, {}],
                 }
               ]
             }
@@ -162,6 +167,7 @@ define([
         });
 
         graph = model.rows[0].panels[0];
+        singlestat = model.rows[0].panels[1];
       });
 
       it('should have title', function() {
@@ -181,6 +187,10 @@ define([
         expect(graph.type).to.be('graph');
       });
 
+      it('single stat panel should have two thresholds', function() {
+        expect(singlestat.thresholds).to.be('20,30');
+      });
+
       it('queries without refId should get it', function() {
         expect(graph.targets[1].refId).to.be('B');
       });
@@ -204,7 +214,7 @@ define([
       });
 
       it('dashboard schema version should be set to latest', function() {
-        expect(model.schemaVersion).to.be(8);
+        expect(model.schemaVersion).to.be(9);
       });
 
     });

+ 0 - 88
public/test/specs/singlestat-specs.js

@@ -1,88 +0,0 @@
-define([
-  'angular',
-  './helpers',
-  'app/plugins/panel/singlestat/controller',
-  'app/features/panel/panel_srv',
-  'app/features/panel/panel_helper',
-], function(angular, helpers, SingleStatCtrl) {
-  'use strict';
-
-  angular.module('grafana.controllers').controller('SingleStatCtrl', SingleStatCtrl);
-
-  describe('SingleStatCtrl', function() {
-    var ctx = new helpers.ControllerTestContext();
-
-    function singleStatScenario(desc, func) {
-
-      describe(desc, function() {
-
-        ctx.setup = function (setupFunc) {
-
-          beforeEach(module('grafana.services'));
-          beforeEach(module('grafana.controllers'));
-
-          beforeEach(ctx.providePhase());
-          beforeEach(ctx.createControllerPhase('SingleStatCtrl'));
-
-          beforeEach(function() {
-            setupFunc();
-            ctx.datasource.query = sinon.stub().returns(ctx.$q.when({
-              data: [{target: 'test.cpu1', datapoints: ctx.datapoints}]
-            }));
-
-            ctx.scope.refreshData(ctx.datasource);
-            ctx.scope.$digest();
-            ctx.data = ctx.scope.data;
-          });
-        };
-
-        func(ctx);
-      });
-    }
-
-    singleStatScenario('with defaults', function(ctx) {
-      ctx.setup(function() {
-        ctx.datapoints = [[10,1], [20,2]];
-      });
-
-      it('Should use series avg as default main value', function() {
-        expect(ctx.data.value).to.be(15);
-        expect(ctx.data.valueRounded).to.be(15);
-      });
-
-      it('should set formated falue', function() {
-        expect(ctx.data.valueFormated).to.be('15');
-      });
-    });
-
-    singleStatScenario('MainValue should use same number for decimals as displayed when checking thresholds', function(ctx) {
-      ctx.setup(function() {
-        ctx.datapoints = [[99.999,1], [99.99999,2]];
-      });
-
-      it('Should be rounded', function() {
-        expect(ctx.data.value).to.be(99.999495);
-        expect(ctx.data.valueRounded).to.be(100);
-      });
-
-      it('should set formated falue', function() {
-        expect(ctx.data.valueFormated).to.be('100');
-      });
-    });
-
-    singleStatScenario('When value to text mapping is specified', function(ctx) {
-      ctx.setup(function() {
-        ctx.datapoints = [[10,1]];
-        ctx.scope.panel.valueMaps = [{value: '10', text: 'OK'}];
-      });
-
-      it('Should replace value with text', function() {
-        expect(ctx.data.value).to.be(10);
-        expect(ctx.data.valueFormated).to.be('OK');
-      });
-
-    });
-
-  });
-});
-

+ 10 - 0
trigger_grafana_packer.sh

@@ -0,0 +1,10 @@
+#!/bin/bash
+
+_circle_token=$1
+
+trigger_build_url=https://circleci.com/api/v1/project/grafana/grafana-packer/tree/master?circle-token=${_circle_token}
+
+curl \
+--header "Accept: application/json" \
+--header "Content-Type: application/json" \
+--request POST ${trigger_build_url}

+ 9 - 0
vendor/phantomjs/render.js

@@ -49,6 +49,15 @@
       });
 
       if (canvas || tries === 1000) {
+        var bb = page.evaluate(function () { 
+          return document.getElementsByClassName("main-view")[0].getBoundingClientRect(); 
+        });
+          page.clipRect = {
+          top:    bb.top,
+          left:   bb.left,
+          width:  bb.width,
+          height: bb.height
+        };
         page.render(params.png);
         phantom.exit();
       }