diff --git a/.circleci/config.yml b/.circleci/config.yml index 28400fc6bd6..60b3ae91ccc 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -319,39 +319,49 @@ jobs: deploy-enterprise-master: docker: - - image: circleci/python:2.7-stretch + - image: grafana/grafana-ci-deploy:1.0.0 steps: - attach_workspace: at: . - run: - name: install awscli - command: 'sudo pip install awscli' + name: gcp credentials + command: 'echo ${GCP_GRAFANA_UPLOAD_KEY} > /tmp/gcpkey.json' + - run: + name: sign in to gcp + command: '/opt/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=/tmp/gcpkey.json' - run: name: deploy to s3 command: 'aws s3 sync ./enterprise-dist s3://$ENTERPRISE_BUCKET_NAME/master' + - run: + name: deploy to gcp + command: '/opt/google-cloud-sdk/bin/gsutil cp ./enterprise-dist/* gs://$GCP_BUCKET_NAME/enterprise/master' + deploy-enterprise-release: docker: - - image: circleci/python:2.7-stretch + - image: grafana/grafana-ci-deploy:1.0.0 steps: - - attach_workspace: - at: . - - run: - name: install awscli - command: 'sudo pip install awscli' - - run: - name: deploy to s3 - command: 'aws s3 sync ./enterprise-dist s3://$ENTERPRISE_BUCKET_NAME/release' + - attach_workspace: + at: . + - run: + name: gcp credentials + command: 'echo ${GCP_GRAFANA_UPLOAD_KEY} > /tmp/gcpkey.json' + - run: + name: sign in to gcp + command: '/opt/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=/tmp/gcpkey.json' + - run: + name: deploy to s3 + command: 'aws s3 sync ./enterprise-dist s3://$ENTERPRISE_BUCKET_NAME/release' + - run: + name: deploy to gcp + command: '/opt/google-cloud-sdk/bin/gsutil cp ./enterprise-dist/* gs://$GCP_BUCKET_NAME/enterprise/release' deploy-master: docker: - - image: circleci/python:2.7-stretch + - image: grafana/grafana-ci-deploy:1.0.0 steps: - attach_workspace: at: . - - run: - name: install awscli - command: 'sudo pip install awscli' - run: name: deploy to s3 command: | @@ -361,6 +371,15 @@ jobs: - run: name: Trigger Windows build command: './scripts/trigger_windows_build.sh ${APPVEYOR_TOKEN} ${CIRCLE_SHA1} master' + - run: + name: gcp credentials + command: 'echo ${GCP_GRAFANA_UPLOAD_KEY} > /tmp/gcpkey.json' + - run: + name: sign in to gcp + command: '/opt/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=/tmp/gcpkey.json' + - run: + name: deploy to gcp + command: '/opt/google-cloud-sdk/bin/gsutil cp ./dist/* gs://$GCP_BUCKET_NAME/oss/master' - run: name: Publish to Grafana.com command: | @@ -369,16 +388,22 @@ jobs: deploy-release: docker: - - image: circleci/python:2.7-stretch + - image: grafana/grafana-ci-deploy:1.0.0 steps: - attach_workspace: at: . - - run: - name: install awscli - command: 'sudo pip install awscli' - run: name: deploy to s3 command: 'aws s3 sync ./dist s3://$BUCKET_NAME/release' + - run: + name: gcp credentials + command: 'echo ${GCP_GRAFANA_UPLOAD_KEY} > /tmp/gcpkey.json' + - run: + name: sign in to gcp + command: '/opt/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=/tmp/gcpkey.json' + - run: + name: deploy to gcp + command: '/opt/google-cloud-sdk/bin/gsutil cp ./dist/* gs://R/oss/release' - run: name: Deploy to Grafana.com command: './scripts/build/publish.sh' diff --git a/.gitignore b/.gitignore index 21083741e14..05ae4907e89 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ awsconfig /dist /public/build /public/views/index.html +/public/views/error.html /emails/dist /public_gen /public/vendor/npm diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b14126e5c1..97537ec34f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,16 +4,20 @@ * **Alerting**: Option to disable OK alert notifications [#12330](https://github.com/grafana/grafana/issues/12330) & [#6696](https://github.com/grafana/grafana/issues/6696), thx [@davewat](https://github.com/davewat) * **Postgres/MySQL/MSSQL**: Adds support for configuration of max open/idle connections and connection max lifetime. Also, panels with multiple SQL queries will now be executed concurrently [#11711](https://github.com/grafana/grafana/issues/11711), thx [@connection-reset](https://github.com/connection-reset) -* **MSSQL**: Add encrypt setting to allow configuration of how data sent between client and server are encrypted [#13629](https://github.com/grafana/grafana/issues/13629), thx [@ramiro](https://github.com/ramiro) +* **MySQL**: Graphical query builder [#13762](https://github.com/grafana/grafana/issues/13762), thx [svenklemm](https://github.com/svenklemm) * **MySQL**: Support connecting thru Unix socket for MySQL datasource [#12342](https://github.com/grafana/grafana/issues/12342), thx [@Yukinoshita-Yukino](https://github.com/Yukinoshita-Yukino) +* **MSSQL**: Add encrypt setting to allow configuration of how data sent between client and server are encrypted [#13629](https://github.com/grafana/grafana/issues/13629), thx [@ramiro](https://github.com/ramiro) * **Stackdriver**: Not possible to authenticate using GCE metadata server [#13669](https://github.com/grafana/grafana/issues/13669) ### Minor * **Cloudwatch**: Show all available CloudWatch regions [#12308](https://github.com/grafana/grafana/issues/12308), thx [@mtanda](https://github.com/mtanda) +* **Postgres**: Add delta window function to postgres query builder [#13925](https://github.com/grafana/grafana/issues/13925), thx [svenklemm](https://github.com/svenklemm) * **Units**: New clock time format, to format ms or second values as for example `01h:59m`, [#13635](https://github.com/grafana/grafana/issues/13635), thx [@franciscocpg](https://github.com/franciscocpg) * **Datasource Proxy**: Keep trailing slash for datasource proxy requests [#13326](https://github.com/grafana/grafana/pull/13326), thx [@ryantxu](https://github.com/ryantxu) * **DingDing**: Can't receive DingDing alert when alert is triggered [#13723](https://github.com/grafana/grafana/issues/13723), thx [@Yukinoshita-Yukino](https://github.com/Yukinoshita-Yukino) +* **Internal metrics**: Renamed `grafana_info` to `grafana_build_info` and added branch, goversion and revision [#13876](https://github.com/grafana/grafana/pull/13876) +* **Alerting**: Increaste default duration for queries [#13945](https://github.com/grafana/grafana/pull/13945) ### Breaking changes diff --git a/Makefile b/Makefile index c9e51d897f3..fcb740d2fac 100644 --- a/Makefile +++ b/Makefile @@ -5,8 +5,7 @@ all: deps build deps-go: go run build.go setup -deps-js: - yarn install --pure-lockfile --no-progress +deps-js: node_modules deps: deps-js @@ -43,3 +42,10 @@ test: test-go test-js run: ./bin/grafana-server + +clean: + rm -rf node_modules + rm -rf public/build + +node_modules: package.json yarn.lock + yarn install --pure-lockfile --no-progress diff --git a/build.go b/build.go index 6fd55da25b6..b136754efbc 100644 --- a/build.go +++ b/build.go @@ -471,6 +471,7 @@ func ldflags() string { b.WriteString(fmt.Sprintf(" -X main.version=%s", version)) b.WriteString(fmt.Sprintf(" -X main.commit=%s", getGitSha())) b.WriteString(fmt.Sprintf(" -X main.buildstamp=%d", buildStamp())) + b.WriteString(fmt.Sprintf(" -X main.buildBranch=%s", getGitBranch())) return b.String() } @@ -518,6 +519,14 @@ func setBuildEnv() { } } +func getGitBranch() string { + v, err := runError("git", "rev-parse", "--abbrev-ref", "HEAD") + if err != nil { + return "master" + } + return string(v) +} + func getGitSha() string { v, err := runError("git", "rev-parse", "--short", "HEAD") if err != nil { diff --git a/conf/defaults.ini b/conf/defaults.ini index 750f06f2f6a..481bb002582 100644 --- a/conf/defaults.ini +++ b/conf/defaults.ini @@ -557,3 +557,7 @@ callback_url = [panels] enable_alpha = false + +[enterprise] +license_path = + diff --git a/conf/sample.ini b/conf/sample.ini index e6a03718d19..61eb1d695e8 100644 --- a/conf/sample.ini +++ b/conf/sample.ini @@ -475,3 +475,8 @@ log_queries = # Options to configure external image rendering server like https://github.com/grafana/grafana-image-renderer ;server_url = ;callback_url = + +[enterprise] +# Path to a valid Grafana Enterprise license.jwt file +;license_path = + diff --git a/docs/sources/features/datasources/cloudwatch.md b/docs/sources/features/datasources/cloudwatch.md index be36d108475..e2bcb50bb1d 100644 --- a/docs/sources/features/datasources/cloudwatch.md +++ b/docs/sources/features/datasources/cloudwatch.md @@ -60,7 +60,8 @@ Here is a minimal policy example: "Effect": "Allow", "Action": [ "cloudwatch:ListMetrics", - "cloudwatch:GetMetricStatistics" + "cloudwatch:GetMetricStatistics", + "cloudwatch:GetMetricData" ], "Resource": "*" }, diff --git a/docs/sources/features/datasources/mysql.md b/docs/sources/features/datasources/mysql.md index 988f632bff3..bc4e4df6cf9 100644 --- a/docs/sources/features/datasources/mysql.md +++ b/docs/sources/features/datasources/mysql.md @@ -73,6 +73,58 @@ Example: You can use wildcards (`*`) in place of database or table if you want to grant access to more databases and tables. +## Query Editor + +> Only available in Grafana v5.4+. + +{{< docs-imagebox img="/img/docs/v54/mysql_query_still.png" class="docs-image--no-shadow" animated-gif="/img/docs/v54/mysql_query.gif" >}} + +You find the MySQL query editor in the metrics tab in a panel's edit mode. You enter edit mode by clicking the +panel title, then edit. + +The query editor has a link named `Generated SQL` that shows up after a query has been executed, while in panel edit mode. Click on it and it will expand and show the raw interpolated SQL string that was executed. + +### Select table, time column and metric column (FROM) + +When you enter edit mode for the first time or add a new query Grafana will try to prefill the query builder with the first table that has a timestamp column and a numeric column. + +In the FROM field, Grafana will suggest tables that are in the configured database. To select a table or view in another database that your database user has access to you can manually enter a fully qualified name (database.table) like `otherDb.metrics`. + +The Time column field refers to the name of the column holding your time values. Selecting a value for the Metric column field is optional. If a value is selected, the Metric column field will be used as the series name. + +The metric column suggestions will only contain columns with a text datatype (text, tinytext, mediumtext, longtext, varchar, char). +If you want to use a column with a different datatype as metric column you may enter the column name with a cast: `CAST(numericColumn as CHAR)`. +You may also enter arbitrary SQL expressions in the metric column field that evaluate to a text datatype like +`CONCAT(column1, " ", CAST(numericColumn as CHAR))`. + +### Columns and Aggregation functions (SELECT) + +In the `SELECT` row you can specify what columns and functions you want to use. +In the column field you may write arbitrary expressions instead of a column name like `column1 * column2 / column3`. + +If you use aggregate functions you need to group your resultset. The editor will automatically add a `GROUP BY time` if you add an aggregate function. + +You may add further value columns by clicking the plus button and selecting `Column` from the menu. Multiple value columns will be plotted as separate series in the graph panel. + +### Filter data (WHERE) +To add a filter click the plus icon to the right of the `WHERE` condition. You can remove filters by clicking on +the filter and selecting `Remove`. A filter for the current selected timerange is automatically added to new queries. + +### Group By +To group by time or any other columns click the plus icon at the end of the GROUP BY row. The suggestion dropdown will only show text columns of your currently selected table but you may manually enter any column. +You can remove the group by clicking on the item and then selecting `Remove`. + +If you add any grouping, all selected columns need to have an aggregate function applied. The query builder will automatically add aggregate functions to all columns without aggregate functions when you add groupings. + +#### Gap Filling + +Grafana can fill in missing values when you group by time. The time function accepts two arguments. The first argument is the time window that you would like to group by, and the second argument is the value you want Grafana to fill missing items with. + +### Text Editor Mode (RAW) +You can switch to the raw query editor mode by clicking the hamburger icon and selecting `Switch editor mode` or by clicking `Edit SQL` below the query. + +> If you use the raw query editor, be sure your query at minimum has `ORDER BY time` and a filter on the returned time range. + ## Macros To simplify syntax and to allow for dynamic parts, like date range filters, the query can contain macros. diff --git a/docs/sources/guides/whats-new-in-v5-3.md b/docs/sources/guides/whats-new-in-v5-3.md index 5dcadc0813d..10592f51648 100644 --- a/docs/sources/guides/whats-new-in-v5-3.md +++ b/docs/sources/guides/whats-new-in-v5-3.md @@ -18,7 +18,7 @@ Grafana v5.3 brings new features, many enhancements and bug fixes. This article - [TV mode]({{< relref "#tv-and-kiosk-mode" >}}) is improved and more accessible - [Alerting]({{< relref "#notification-reminders" >}}) with notification reminders - [Postgres]({{< relref "#postgres-query-builder" >}}) gets a new query builder! -- [OAuth]({{< relref "#improved-oauth-support-for-gitlab" >}}) support for Gitlab is improved +- [OAuth]({{< relref "#improved-oauth-support-for-gitlab" >}}) support for GitLab is improved - [Annotations]({{< relref "#annotations" >}}) with template variable filtering - [Variables]({{< relref "#variables" >}}) with free text support @@ -69,9 +69,9 @@ Grafana 5.3 comes with a new graphical query builder for Postgres. This brings P {{< docs-imagebox img="/img/docs/v53/postgres_query_still.png" class="docs-image--no-shadow" animated-gif="/img/docs/v53/postgres_query.gif" >}} -## Improved OAuth Support for Gitlab +## Improved OAuth Support for GitLab -Grafana 5.3 comes with a new OAuth integration for Gitlab that enables configuration to only allow users that are a member of certain Gitlab groups to authenticate. This makes it possible to use Gitlab OAuth with Grafana in a shared environment without giving everyone access to Grafana. +Grafana 5.3 comes with a new OAuth integration for GitLab that enables configuration to only allow users that are a member of certain GitLab groups to authenticate. This makes it possible to use GitLab OAuth with Grafana in a shared environment without giving everyone access to Grafana. Learn how to enable and configure it in the [documentation](/auth/gitlab/). ## Annotations diff --git a/docs/sources/http_api/alerting.md b/docs/sources/http_api/alerting.md index 103de190793..2d70a6d2017 100644 --- a/docs/sources/http_api/alerting.md +++ b/docs/sources/http_api/alerting.md @@ -290,7 +290,7 @@ Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk "sendReminder": true, "frequency": "15m", "settings": { - "addresses: "carl@grafana.com;dev@grafana.com" + "addresses": "carl@grafana.com;dev@grafana.com" } } ``` diff --git a/package.json b/package.json index b4c70c5b3a8..68b7647fb58 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "grunt-contrib-copy": "~1.0.0", "grunt-contrib-cssmin": "~1.0.2", "grunt-exec": "^1.0.1", + "grunt-newer": "^1.3.0", "grunt-notify": "^0.4.5", "grunt-postcss": "^0.8.0", "grunt-sass": "^2.0.0", diff --git a/packaging/docker/build-enterprise.sh b/packaging/docker/build-enterprise.sh index f716a1f44f1..2f59e436d95 100755 --- a/packaging/docker/build-enterprise.sh +++ b/packaging/docker/build-enterprise.sh @@ -8,3 +8,5 @@ docker build \ --tag "${_docker_repo}:${_grafana_tag}"\ --no-cache=true \ . + +docker push "${_docker_repo}:${_grafana_tag}" diff --git a/packaging/release_process.md b/packaging/release_process.md deleted file mode 100644 index 6037a9c499c..00000000000 --- a/packaging/release_process.md +++ /dev/null @@ -1,29 +0,0 @@ -# New Grafana Release Processes - -## Building release packages - -1) Update package.json so that it has the right version. -2) Create a git tag for the release: `git tag -a v3.0.4 -m "3.0.4 release"` -3) Push branch & tag to github! -2) Packages from master a built automatically by circle CI for this repo [grafana/grafana-packer](https://github.com/grafana/grafana-packer) - -### Non master branch - -When building from non master branch create a new branch in repo [grafana/grafana-packer](https://github.com/grafana/grafana-packer) -and configure circle.yml to deploy that branch as well, https://github.com/grafana/grafana-packer/blob/master/circle.yml#L25, -you also need to update https://github.com/grafana/grafana-packer/blob/v3.1.x/deploy.sh#L7. - -### Windows build - -Sign into ci.appveyor.com and the Grafana project's build history page. Builds for windows take a long time (around 20min) -and fail quite often for random reasons so I usually continue with the release process without a windows build already built. - -1) Click on the green build that has the correct version and tag -2) Click on `DEPLOYMENTS` -3) Click on `NEW DEPLOYMENT` -4) Select GrafanaBuildS3 -4) Select the build you want to deploy. - -The deployment should be quick (just uploads the release zip file to S3) - - diff --git a/pkg/api/dtos/index.go b/pkg/api/dtos/index.go index 77004899fc3..bd3ac76eec8 100644 --- a/pkg/api/dtos/index.go +++ b/pkg/api/dtos/index.go @@ -14,6 +14,7 @@ type IndexViewData struct { NewGrafanaVersionExists bool NewGrafanaVersion string AppName string + AppNameBodyClass string } type PluginCss struct { diff --git a/pkg/api/index.go b/pkg/api/index.go index e61620f9586..fe7c9e79a17 100644 --- a/pkg/api/index.go +++ b/pkg/api/index.go @@ -83,6 +83,7 @@ func (hs *HTTPServer) setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, er NewGrafanaVersion: plugins.GrafanaLatestVersion, NewGrafanaVersionExists: plugins.GrafanaHasUpdate, AppName: setting.ApplicationName, + AppNameBodyClass: getAppNameBodyClass(setting.ApplicationName), } if setting.DisableGravatar { @@ -377,3 +378,14 @@ func (hs *HTTPServer) NotFoundHandler(c *m.ReqContext) { c.HTML(404, "index", data) } + +func getAppNameBodyClass(name string) string { + switch name { + case setting.APP_NAME: + return "app-grafana" + case setting.APP_NAME_ENTERPRISE: + return "app-enterprise" + default: + return "" + } +} diff --git a/pkg/cmd/grafana-server/main.go b/pkg/cmd/grafana-server/main.go index 06c07a2887c..c7c1ff3aff7 100644 --- a/pkg/cmd/grafana-server/main.go +++ b/pkg/cmd/grafana-server/main.go @@ -3,6 +3,8 @@ package main import ( "flag" "fmt" + "net/http" + _ "net/http/pprof" "os" "os/signal" "runtime" @@ -11,16 +13,12 @@ import ( "syscall" "time" - "net/http" - _ "net/http/pprof" - + extensions "github.com/grafana/grafana/pkg/extensions" "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/metrics" - "github.com/grafana/grafana/pkg/setting" - - extensions "github.com/grafana/grafana/pkg/extensions" _ "github.com/grafana/grafana/pkg/services/alerting/conditions" _ "github.com/grafana/grafana/pkg/services/alerting/notifiers" + "github.com/grafana/grafana/pkg/setting" _ "github.com/grafana/grafana/pkg/tsdb/cloudwatch" _ "github.com/grafana/grafana/pkg/tsdb/elasticsearch" _ "github.com/grafana/grafana/pkg/tsdb/graphite" @@ -35,6 +33,7 @@ import ( var version = "5.0.0" var commit = "NA" +var buildBranch = "master" var buildstamp string var configFile = flag.String("config", "", "path to config file") @@ -47,7 +46,7 @@ func main() { profilePort := flag.Int("profile-port", 6060, "Define custom port for profiling") flag.Parse() if *v { - fmt.Printf("Version %s (commit: %s)\n", version, commit) + fmt.Printf("Version %s (commit: %s, branch: %s)\n", version, commit, buildBranch) os.Exit(0) } @@ -78,9 +77,10 @@ func main() { setting.BuildVersion = version setting.BuildCommit = commit setting.BuildStamp = buildstampInt64 + setting.BuildBranch = buildBranch setting.IsEnterprise = extensions.IsEnterprise - metrics.M_Grafana_Version.WithLabelValues(version).Set(1) + metrics.SetBuildInformation(version, commit, buildBranch) server := NewGrafanaServer() diff --git a/pkg/cmd/grafana-server/server.go b/pkg/cmd/grafana-server/server.go index 8794d7d8338..765b8ddf993 100644 --- a/pkg/cmd/grafana-server/server.go +++ b/pkg/cmd/grafana-server/server.go @@ -12,24 +12,16 @@ import ( "time" "github.com/facebookgo/inject" + "github.com/grafana/grafana/pkg/api" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/middleware" - "github.com/grafana/grafana/pkg/registry" - - "golang.org/x/sync/errgroup" - - "github.com/grafana/grafana/pkg/api" + _ "github.com/grafana/grafana/pkg/extensions" "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/login" - "github.com/grafana/grafana/pkg/setting" - - "github.com/grafana/grafana/pkg/social" - - // self registering services - _ "github.com/grafana/grafana/pkg/extensions" _ "github.com/grafana/grafana/pkg/metrics" + "github.com/grafana/grafana/pkg/middleware" _ "github.com/grafana/grafana/pkg/plugins" + "github.com/grafana/grafana/pkg/registry" _ "github.com/grafana/grafana/pkg/services/alerting" _ "github.com/grafana/grafana/pkg/services/cleanup" _ "github.com/grafana/grafana/pkg/services/notifications" @@ -37,7 +29,10 @@ import ( _ "github.com/grafana/grafana/pkg/services/rendering" _ "github.com/grafana/grafana/pkg/services/search" _ "github.com/grafana/grafana/pkg/services/sqlstore" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/social" // self registering services _ "github.com/grafana/grafana/pkg/tracing" + "golang.org/x/sync/errgroup" ) func NewGrafanaServer() *GrafanaServerImpl { @@ -159,7 +154,7 @@ func (g *GrafanaServerImpl) loadConfiguration() { os.Exit(1) } - g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0)) + g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "branch", buildBranch, "compiled", time.Unix(setting.BuildStamp, 0)) g.cfg.LogConfigSources() } diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 9a514fdb6f3..5709e3e3213 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -58,7 +58,14 @@ var ( M_StatActive_Users prometheus.Gauge M_StatTotal_Orgs prometheus.Gauge M_StatTotal_Playlists prometheus.Gauge - M_Grafana_Version *prometheus.GaugeVec + + // M_Grafana_Version is a gauge that contains build info about this binary + // + // Deprecated: use M_Grafana_Build_Version instead. + M_Grafana_Version *prometheus.GaugeVec + + // grafanaBuildVersion is a gauge that contains build info about this binary + grafanaBuildVersion *prometheus.GaugeVec ) func newCounterVecStartingAtZero(opts prometheus.CounterOpts, labels []string, labelValues ...string) *prometheus.CounterVec { @@ -293,9 +300,25 @@ func init() { M_Grafana_Version = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "info", - Help: "Information about the Grafana", + Help: "Information about the Grafana. This metric is deprecated. please use `grafana_build_info`", Namespace: exporterName, }, []string{"version"}) + + grafanaBuildVersion = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Name: "build_info", + Help: "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which Grafana was built.", + Namespace: exporterName, + }, []string{"version", "revision", "branch", "goversion"}) +} + +// SetBuildInformation sets the build information for this binary +func SetBuildInformation(version, revision, branch string) { + // We export this info twice for backwards compability. + // Once this have been released for some time we should be able to remote `M_Grafana_Version` + // The reason we added a new one is that its common practice in the prometheus community + // to name this metric `*_build_info` so its easy to do aggregation on all programs. + M_Grafana_Version.WithLabelValues(version).Set(1) + grafanaBuildVersion.WithLabelValues(version, revision, branch, runtime.Version()).Set(1) } func initMetricVars() { @@ -334,7 +357,8 @@ func initMetricVars() { M_StatActive_Users, M_StatTotal_Orgs, M_StatTotal_Playlists, - M_Grafana_Version) + M_Grafana_Version, + grafanaBuildVersion) } diff --git a/pkg/middleware/middleware_test.go b/pkg/middleware/middleware_test.go index 1830b3eb161..e9a3c8059f8 100644 --- a/pkg/middleware/middleware_test.go +++ b/pkg/middleware/middleware_test.go @@ -18,6 +18,7 @@ import ( ) func TestMiddlewareContext(t *testing.T) { + setting.ERR_TEMPLATE_NAME = "error-template" Convey("Given the grafana middleware", t, func() { middlewareScenario("middleware should add context to injector", func(sc *scenarioContext) { diff --git a/pkg/middleware/recovery.go b/pkg/middleware/recovery.go index 456bc91354e..eef07c8c24a 100644 --- a/pkg/middleware/recovery.go +++ b/pkg/middleware/recovery.go @@ -138,7 +138,7 @@ func Recovery() macaron.Handler { c.JSON(500, resp) } else { - c.HTML(500, "error") + c.HTML(500, setting.ERR_TEMPLATE_NAME) } } }() diff --git a/pkg/middleware/recovery_test.go b/pkg/middleware/recovery_test.go index 4bbedbc3b21..c92150f3b7d 100644 --- a/pkg/middleware/recovery_test.go +++ b/pkg/middleware/recovery_test.go @@ -8,11 +8,14 @@ import ( "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/session" + "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" "gopkg.in/macaron.v1" ) func TestRecoveryMiddleware(t *testing.T) { + setting.ERR_TEMPLATE_NAME = "error-template" + Convey("Given an api route that panics", t, func() { apiURL := "/api/whatever" recoveryScenario("recovery middleware should return json", apiURL, func(sc *scenarioContext) { @@ -50,6 +53,7 @@ func recoveryScenario(desc string, url string, fn scenarioFunc) { sc := &scenarioContext{ url: url, } + viewsPath, _ := filepath.Abs("../../public/views") sc.m = macaron.New() diff --git a/pkg/models/context.go b/pkg/models/context.go index 262f6550954..c78028665a6 100644 --- a/pkg/models/context.go +++ b/pkg/models/context.go @@ -36,7 +36,7 @@ func (ctx *ReqContext) Handle(status int, title string, err error) { ctx.Data["AppSubUrl"] = setting.AppSubUrl ctx.Data["Theme"] = "dark" - ctx.HTML(status, "error") + ctx.HTML(status, setting.ERR_TEMPLATE_NAME) } func (ctx *ReqContext) JsonOK(message string) { diff --git a/pkg/services/alerting/conditions/reducer_test.go b/pkg/services/alerting/conditions/reducer_test.go index 9d4e1462690..7f11fc498bd 100644 --- a/pkg/services/alerting/conditions/reducer_test.go +++ b/pkg/services/alerting/conditions/reducer_test.go @@ -52,6 +52,24 @@ func TestSimpleReducer(t *testing.T) { So(result, ShouldEqual, float64(1)) }) + Convey("median should ignore null values", func() { + reducer := NewSimpleReducer("median") + series := &tsdb.TimeSeries{ + Name: "test time serie", + } + + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 1)) + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 2)) + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 3)) + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(float64(1)), 4)) + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(float64(2)), 5)) + series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(float64(3)), 6)) + + result := reducer.Reduce(series) + So(result.Valid, ShouldEqual, true) + So(result.Float64, ShouldEqual, float64(2)) + }) + Convey("avg", func() { result := testReducer("avg", 1, 2, 3) So(result, ShouldEqual, float64(2)) diff --git a/pkg/services/alerting/notifiers/telegram.go b/pkg/services/alerting/notifiers/telegram.go index 6c47c92972c..4a4a989d873 100644 --- a/pkg/services/alerting/notifiers/telegram.go +++ b/pkg/services/alerting/notifiers/telegram.go @@ -14,7 +14,7 @@ import ( ) const ( - captionLengthLimit = 200 + captionLengthLimit = 1024 ) var ( diff --git a/pkg/services/alerting/notifiers/telegram_test.go b/pkg/services/alerting/notifiers/telegram_test.go index 911323ae9d1..9906a2ffd95 100644 --- a/pkg/services/alerting/notifiers/telegram_test.go +++ b/pkg/services/alerting/notifiers/telegram_test.go @@ -61,7 +61,7 @@ func TestTelegramNotifier(t *testing.T) { }) caption := generateImageCaption(evalContext, "http://grafa.url/abcdef", "") - So(len(caption), ShouldBeLessThanOrEqualTo, 200) + So(len(caption), ShouldBeLessThanOrEqualTo, 1024) So(caption, ShouldContainSubstring, "Some kind of message.") So(caption, ShouldContainSubstring, "[OK] This is an alarm") So(caption, ShouldContainSubstring, "http://grafa.url/abcdef") @@ -78,9 +78,9 @@ func TestTelegramNotifier(t *testing.T) { }) caption := generateImageCaption(evalContext, - "http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "http://grafa.url/abcdefaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "foo bar") - So(len(caption), ShouldBeLessThanOrEqualTo, 200) + So(len(caption), ShouldBeLessThanOrEqualTo, 1024) So(caption, ShouldContainSubstring, "Some kind of message.") So(caption, ShouldContainSubstring, "[OK] This is an alarm") So(caption, ShouldContainSubstring, "foo bar") @@ -91,31 +91,31 @@ func TestTelegramNotifier(t *testing.T) { evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ Name: "This is an alarm", - Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it.", + Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.", State: m.AlertStateOK, }) caption := generateImageCaption(evalContext, "http://grafa.url/foo", "") - So(len(caption), ShouldBeLessThanOrEqualTo, 200) + So(len(caption), ShouldBeLessThanOrEqualTo, 1024) So(caption, ShouldContainSubstring, "[OK] This is an alarm") So(caption, ShouldNotContainSubstring, "http") - So(caption, ShouldContainSubstring, "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise ") + So(caption, ShouldContainSubstring, "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri") }) Convey("Metrics should be skipped if they don't fit", func() { evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ Name: "This is an alarm", - Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I ", + Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri", State: m.AlertStateOK, }) caption := generateImageCaption(evalContext, "http://grafa.url/foo", "foo bar long song") - So(len(caption), ShouldBeLessThanOrEqualTo, 200) + So(len(caption), ShouldBeLessThanOrEqualTo, 1024) So(caption, ShouldContainSubstring, "[OK] This is an alarm") So(caption, ShouldNotContainSubstring, "http") So(caption, ShouldNotContainSubstring, "foo bar") diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go index 16158ded002..afae642f5b3 100644 --- a/pkg/setting/setting.go +++ b/pkg/setting/setting.go @@ -13,15 +13,12 @@ import ( "regexp" "runtime" "strings" - - "gopkg.in/ini.v1" - - "github.com/go-macaron/session" - "time" + "github.com/go-macaron/session" "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/util" + "gopkg.in/ini.v1" ) type Scheme string @@ -34,9 +31,15 @@ const ( ) const ( - DEV string = "development" - PROD string = "production" - TEST string = "test" + DEV = "development" + PROD = "production" + TEST = "test" + APP_NAME = "Grafana" + APP_NAME_ENTERPRISE = "Grafana Enterprise" +) + +var ( + ERR_TEMPLATE_NAME = "error" ) var ( @@ -49,6 +52,7 @@ var ( // build BuildVersion string BuildCommit string + BuildBranch string BuildStamp int64 IsEnterprise bool ApplicationName string @@ -209,12 +213,10 @@ type Cfg struct { RendererLimitAlerting int DisableBruteForceLoginProtection bool - - TempDataLifetime time.Duration - - MetricsEndpointEnabled bool - - EnableAlphaPanels bool + TempDataLifetime time.Duration + MetricsEndpointEnabled bool + EnableAlphaPanels bool + EnterpriseLicensePath string } type CommandLineArgs struct { @@ -533,9 +535,9 @@ func (cfg *Cfg) Load(args *CommandLineArgs) error { // Temporary keep global, to make refactor in steps Raw = cfg.Raw - ApplicationName = "Grafana" + ApplicationName = APP_NAME if IsEnterprise { - ApplicationName += " Enterprise" + ApplicationName = APP_NAME_ENTERPRISE } Env = iniFile.Section("").Key("app_mode").MustString("development") @@ -715,6 +717,10 @@ func (cfg *Cfg) Load(args *CommandLineArgs) error { imageUploadingSection := iniFile.Section("external_image_storage") ImageUploadProvider = imageUploadingSection.Key("provider").MustString("") + + enterprise := iniFile.Section("enterprise") + cfg.EnterpriseLicensePath = enterprise.Key("license_path").MustString(filepath.Join(cfg.DataPath, "license.jwt")) + return nil } diff --git a/public/app/core/actions/user.ts b/public/app/core/actions/user.ts new file mode 100644 index 00000000000..dba0588c058 --- /dev/null +++ b/public/app/core/actions/user.ts @@ -0,0 +1,28 @@ +import { ThunkAction } from 'redux-thunk'; +import { getBackendSrv } from '../services/backend_srv'; +import { DashboardAcl, DashboardSearchHit, StoreState } from '../../types'; + +type ThunkResult = ThunkAction; + +export type Action = LoadStarredDashboardsAction; + +export enum ActionTypes { + LoadStarredDashboards = 'LOAD_STARRED_DASHBOARDS', +} + +interface LoadStarredDashboardsAction { + type: ActionTypes.LoadStarredDashboards; + payload: DashboardSearchHit[]; +} + +const starredDashboardsLoaded = (dashboards: DashboardAcl[]) => ({ + type: ActionTypes.LoadStarredDashboards, + payload: dashboards, +}); + +export function loadStarredDashboards(): ThunkResult { + return async dispatch => { + const starredDashboards = await getBackendSrv().search({ starred: true }); + dispatch(starredDashboardsLoaded(starredDashboards)); + }; +} diff --git a/public/app/core/components/Animations/SlideDown.tsx b/public/app/core/components/Animations/SlideDown.tsx index 4d515f98f16..70dacd73849 100644 --- a/public/app/core/components/Animations/SlideDown.tsx +++ b/public/app/core/components/Animations/SlideDown.tsx @@ -1,15 +1,22 @@ -import React from 'react'; +import React from 'react'; import Transition from 'react-transition-group/Transition'; -const defaultMaxHeight = '200px'; // When animating using max-height we need to use a static value. +interface Style { + transition?: string; + overflow?: string; +} + +// When animating using max-height we need to use a static value. // If this is not enough, pass in
{title}
- + {buttonTitle} diff --git a/public/app/core/components/EmptyListCTA/__snapshots__/EmptyListCTA.test.tsx.snap b/public/app/core/components/EmptyListCTA/__snapshots__/EmptyListCTA.test.tsx.snap index 6d47c984d5e..b85660bcc6f 100644 --- a/public/app/core/components/EmptyListCTA/__snapshots__/EmptyListCTA.test.tsx.snap +++ b/public/app/core/components/EmptyListCTA/__snapshots__/EmptyListCTA.test.tsx.snap @@ -12,6 +12,7 @@ exports[`EmptyListCTA renders correctly 1`] = ` = props => { return ( - + {props.children} {props.tooltip && ( @@ -19,4 +20,3 @@ export const Label: SFC = props => { ); }; - diff --git a/public/app/core/components/Picker/SimplePicker.tsx b/public/app/core/components/Picker/SimplePicker.tsx new file mode 100644 index 00000000000..6c9e8aca199 --- /dev/null +++ b/public/app/core/components/Picker/SimplePicker.tsx @@ -0,0 +1,46 @@ +import React, { SFC } from 'react'; +import Select from 'react-select'; +import DescriptionOption from './DescriptionOption'; +import ResetStyles from './ResetStyles'; + +interface Props { + className?: string; + defaultValue: any; + getOptionLabel: (item: any) => string; + getOptionValue: (item: any) => string; + onSelected: (item: any) => {} | void; + options: any[]; + placeholder?: string; + width: number; +} + +const SimplePicker: SFC = ({ + className, + defaultValue, + getOptionLabel, + getOptionValue, + onSelected, + options, + placeholder, + width, +}) => { + return ( + this.onApiKeyStateUpdate(evt, ApiKeyStateProps.Name)} + /> + +
+ Role + + + +
+
+ +
+ + + +
+ ); + } + + renderApiKeyList() { + const { isAdding } = this.state; + const { apiKeys, searchQuery } = this.props; + + return ( +
+
+
+ +
+ +
+ +
+ + {this.renderAddApiKeyForm()} + +

Existing Keys

+ + + + + + + + {apiKeys.length > 0 ? ( + + {apiKeys.map(key => { + return ( + + + + + + ); + })} + + ) : null} +
NameRole +
{key.name}{key.role} + this.onDeleteApiKey(key)} /> +
+
+ ); } render() { - const { newApiKey, isAdding } = this.state; - const { hasFetched, navModel, searchQuery } = this.props; + const { hasFetched, navModel, apiKeysCount } = this.props; return (
-
-
-
- -
- -
- -
- - -
- -
Add API Key
-
-
-
- Key name - this.onApiKeyStateUpdate(evt, ApiKeyStateProps.Name)} - /> -
-
- Role - - - -
-
- -
-
-
-
-
- {hasFetched ? this.renderTable() : } -
+ {hasFetched ? ( + apiKeysCount > 0 ? ( + this.renderApiKeyList() + ) : ( + this.renderEmptyList() + ) + ) : ( + + )}
); } @@ -220,6 +261,7 @@ function mapStateToProps(state) { navModel: getNavModel(state.navIndex, 'apikeys'), apiKeys: getApiKeys(state.apiKeys), searchQuery: state.apiKeys.searchQuery, + apiKeysCount: getApiKeysCount(state.apiKeys), hasFetched: state.apiKeys.hasFetched, }; } diff --git a/public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap b/public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap index b1cac8469be..7ede9618250 100644 --- a/public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap +++ b/public/app/features/api-keys/__snapshots__/ApiKeysPage.test.tsx.snap @@ -1,276 +1,17 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Render should render API keys table 1`] = ` +exports[`Render should render API keys table if there are any keys 1`] = `
-
-
-
- -
-
- -
- -
- -
- Add API Key -
-
-
-
- - Key name - - -
-
- - Role - - - - -
-
- -
-
-
-
-
-

- Existing Keys -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Name - - Role - -
- test-1 - - Viewer - - - - -
- test-2 - - Viewer - - - - -
- test-3 - - Viewer - - - - -
- test-4 - - Viewer - - - - -
- test-5 - - Viewer - - - - -
-
+
`; -exports[`Render should render component 1`] = ` +exports[`Render should render CTA if there are no API keys 1`] = `
-
-
- -
-
- -
+ @@ -406,9 +127,6 @@ exports[`Render should render component 1`] = `
-
`; diff --git a/public/app/features/api-keys/state/selectors.ts b/public/app/features/api-keys/state/selectors.ts index 8065c252e85..789237ae9a3 100644 --- a/public/app/features/api-keys/state/selectors.ts +++ b/public/app/features/api-keys/state/selectors.ts @@ -1,5 +1,7 @@ import { ApiKeysState } from 'app/types'; +export const getApiKeysCount = (state: ApiKeysState) => state.keys.length; + export const getApiKeys = (state: ApiKeysState) => { const regex = RegExp(state.searchQuery, 'i'); diff --git a/public/app/features/dashboard/panel_model.ts b/public/app/features/dashboard/panel_model.ts index ebf8a6bb224..d82368d8dd7 100644 --- a/public/app/features/dashboard/panel_model.ts +++ b/public/app/features/dashboard/panel_model.ts @@ -133,6 +133,7 @@ export class PanelModel { } destroy() { + this.events.emit('panel-teardown'); this.events.removeAllListeners(); } } diff --git a/public/app/features/dashboard/state/actions.ts b/public/app/features/dashboard/state/actions.ts index 749edef58fb..bc35ff31ff0 100644 --- a/public/app/features/dashboard/state/actions.ts +++ b/public/app/features/dashboard/state/actions.ts @@ -13,6 +13,7 @@ import { export enum ActionTypes { LoadDashboardPermissions = 'LOAD_DASHBOARD_PERMISSIONS', + LoadStarredDashboards = 'LOAD_STARRED_DASHBOARDS', } export interface LoadDashboardPermissionsAction { @@ -20,7 +21,12 @@ export interface LoadDashboardPermissionsAction { payload: DashboardAcl[]; } -export type Action = LoadDashboardPermissionsAction; +export interface LoadStarredDashboardsAction { + type: ActionTypes.LoadStarredDashboards; + payload: DashboardAcl[]; +} + +export type Action = LoadDashboardPermissionsAction | LoadStarredDashboardsAction; type ThunkResult = ThunkAction; diff --git a/public/app/features/dashboard/state/reducers.test.ts b/public/app/features/dashboard/state/reducers.test.ts index c5b67f58ac9..ced8866aad8 100644 --- a/public/app/features/dashboard/state/reducers.test.ts +++ b/public/app/features/dashboard/state/reducers.test.ts @@ -1,6 +1,6 @@ import { Action, ActionTypes } from './actions'; import { OrgRole, PermissionLevel, DashboardState } from 'app/types'; -import { inititalState, dashboardReducer } from './reducers'; +import { initialState, dashboardReducer } from './reducers'; describe('dashboard reducer', () => { describe('loadDashboardPermissions', () => { @@ -14,7 +14,7 @@ describe('dashboard reducer', () => { { id: 3, dashboardId: 1, role: OrgRole.Editor, permission: PermissionLevel.Edit }, ], }; - state = dashboardReducer(inititalState, action); + state = dashboardReducer(initialState, action); }); it('should add permissions to state', async () => { diff --git a/public/app/features/dashboard/state/reducers.ts b/public/app/features/dashboard/state/reducers.ts index 5100529d973..8a79a6c9f77 100644 --- a/public/app/features/dashboard/state/reducers.ts +++ b/public/app/features/dashboard/state/reducers.ts @@ -2,11 +2,11 @@ import { DashboardState } from 'app/types'; import { Action, ActionTypes } from './actions'; import { processAclItems } from 'app/core/utils/acl'; -export const inititalState: DashboardState = { +export const initialState: DashboardState = { permissions: [], }; -export const dashboardReducer = (state = inititalState, action: Action): DashboardState => { +export const dashboardReducer = (state = initialState, action: Action): DashboardState => { switch (action.type) { case ActionTypes.LoadDashboardPermissions: return { diff --git a/public/app/features/explore/ErrorBoundary.tsx b/public/app/features/explore/ErrorBoundary.tsx new file mode 100644 index 00000000000..959d15eea80 --- /dev/null +++ b/public/app/features/explore/ErrorBoundary.tsx @@ -0,0 +1,34 @@ +import React, { Component } from 'react'; + +export default class ErrorBoundary extends Component<{}, any> { + constructor(props) { + super(props); + this.state = { error: null, errorInfo: null }; + } + + componentDidCatch(error, errorInfo) { + // Catch errors in any components below and re-render with error message + this.setState({ + error: error, + errorInfo: errorInfo, + }); + } + + render() { + if (this.state.errorInfo) { + // Error path + return ( +
+

An unexpected error happened.

+
+ {this.state.error && this.state.error.toString()} +
+ {this.state.errorInfo.componentStack} +
+
+ ); + } + // Normally, just render children + return this.props.children; + } +} diff --git a/public/app/features/explore/Explore.tsx b/public/app/features/explore/Explore.tsx index f29d38d283a..af771bad5dd 100644 --- a/public/app/features/explore/Explore.tsx +++ b/public/app/features/explore/Explore.tsx @@ -3,15 +3,8 @@ import { hot } from 'react-hot-loader'; import Select from 'react-select'; import _ from 'lodash'; -import { - ExploreState, - ExploreUrlState, - HistoryItem, - Query, - QueryTransaction, - Range, - ResultType, -} from 'app/types/explore'; +import { ExploreState, ExploreUrlState, HistoryItem, Query, QueryTransaction, ResultType } from 'app/types/explore'; +import { RawTimeRange } from 'app/types/series'; import kbn from 'app/core/utils/kbn'; import colors from 'app/core/utils/colors'; import store from 'app/core/store'; @@ -28,8 +21,11 @@ import QueryRows from './QueryRows'; import Graph from './Graph'; import Logs from './Logs'; import Table from './Table'; +import ErrorBoundary from './ErrorBoundary'; import TimePicker from './TimePicker'; import { ensureQueries, generateQueryKey, hasQuery } from './utils/query'; +import { DataSource } from 'app/types/datasources'; +import { mergeStreams } from 'app/core/logs_model'; const MAX_HISTORY_ITEMS = 100; @@ -154,12 +150,7 @@ export class Explore extends React.PureComponent { } } - componentDidCatch(error) { - this.setState({ datasourceError: error }); - console.error(error); - } - - async setDatasource(datasource) { + async setDatasource(datasource: DataSource) { const supportsGraph = datasource.meta.metrics; const supportsLogs = datasource.meta.logs; const supportsTable = datasource.meta.metrics; @@ -170,7 +161,7 @@ export class Explore extends React.PureComponent { const testResult = await datasource.testDatasource(); datasourceError = testResult.status === 'success' ? null : testResult.message; } catch (error) { - datasourceError = (error && error.statusText) || error; + datasourceError = (error && error.statusText) || 'Network error'; } const historyKey = `grafana.explore.history.${datasourceId}`; @@ -187,8 +178,12 @@ export class Explore extends React.PureComponent { query: this.queryExpressions[i], })); + // Custom components + const StartPage = datasource.pluginExports.ExploreStartPage; + this.setState( { + StartPage, datasource, datasourceError, history, @@ -278,10 +273,9 @@ export class Explore extends React.PureComponent { } }; - onChangeTime = nextRange => { - const range = { - from: nextRange.from, - to: nextRange.to, + onChangeTime = (nextRange: RawTimeRange) => { + const range: RawTimeRange = { + ...nextRange, }; this.setState({ range }, () => this.onSubmit()); }; @@ -342,6 +336,13 @@ export class Explore extends React.PureComponent { ); }; + // Use this in help pages to set page to a single query + onClickQuery = query => { + const nextQueries = [{ query, key: generateQueryKey() }]; + this.queryExpressions = nextQueries.map(q => q.query); + this.setState({ queries: nextQueries }, this.onSubmit); + }; + onClickSplit = () => { const { onChangeSplit } = this.props; if (onChangeSplit) { @@ -471,7 +472,7 @@ export class Explore extends React.PureComponent { ) { const { datasource, range } = this.state; const resolution = this.el.offsetWidth; - const absoluteRange = { + const absoluteRange: RawTimeRange = { from: parseDate(range.from, false), to: parseDate(range.to, true), }; @@ -486,7 +487,7 @@ export class Explore extends React.PureComponent { ]; // Clone range for query request - const queryRange: Range = { ...range }; + const queryRange: RawTimeRange = { ...range }; return { interval, @@ -584,13 +585,28 @@ export class Explore extends React.PureComponent { }); } - failQueryTransaction(transactionId: string, error: string, datasourceId: string) { + failQueryTransaction(transactionId: string, response: any, datasourceId: string) { const { datasource } = this.state; if (datasource.meta.id !== datasourceId) { // Navigated away, queries did not matter return; } + console.error(response); + + let error: string | JSX.Element = response; + if (response.data) { + error = response.data.error; + if (response.data.response) { + error = ( + <> + {response.data.error} +
{response.data.response}
+ + ); + } + } + this.setState(state => { // Transaction might have been discarded if (!state.queryTransactions.find(qt => qt.id === transactionId)) { @@ -637,9 +653,7 @@ export class Explore extends React.PureComponent { this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId); this.setState({ graphRange: transaction.options.range }); } catch (response) { - console.error(response); - const queryError = response.data ? response.data.error : response; - this.failQueryTransaction(transaction.id, queryError, datasourceId); + this.failQueryTransaction(transaction.id, response, datasourceId); } } else { this.discardTransactions(rowIndex); @@ -669,9 +683,7 @@ export class Explore extends React.PureComponent { const results = res.data[0]; this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId); } catch (response) { - console.error(response); - const queryError = response.data ? response.data.error : response; - this.failQueryTransaction(transaction.id, queryError, datasourceId); + this.failQueryTransaction(transaction.id, response, datasourceId); } } else { this.discardTransactions(rowIndex); @@ -697,9 +709,7 @@ export class Explore extends React.PureComponent { const results = res.data; this.completeQueryTransaction(transaction.id, results, latency, queries, datasourceId); } catch (response) { - console.error(response); - const queryError = response.data ? response.data.error : response; - this.failQueryTransaction(transaction.id, queryError, datasourceId); + this.failQueryTransaction(transaction.id, response, datasourceId); } } else { this.discardTransactions(rowIndex); @@ -724,6 +734,7 @@ export class Explore extends React.PureComponent { render() { const { position, split } = this.props; const { + StartPage, datasource, datasourceError, datasourceLoading, @@ -751,17 +762,20 @@ export class Explore extends React.PureComponent { const graphLoading = queryTransactions.some(qt => qt.resultType === 'Graph' && !qt.done); const tableLoading = queryTransactions.some(qt => qt.resultType === 'Table' && !qt.done); const logsLoading = queryTransactions.some(qt => qt.resultType === 'Logs' && !qt.done); + // TODO don't recreate those on each re-render const graphResult = _.flatten( queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result) ); const tableResult = mergeTablesIntoModel( new TableModel(), - ...queryTransactions.filter(qt => qt.resultType === 'Table' && qt.done).map(qt => qt.result) + ...queryTransactions.filter(qt => qt.resultType === 'Table' && qt.done && qt.result).map(qt => qt.result) ); - const logsResult = _.flatten( - queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done).map(qt => qt.result) + const logsResult = mergeStreams( + queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done && qt.result).map(qt => qt.result) ); const loading = queryTransactions.some(qt => !qt.done); + const showStartPages = StartPage && queryTransactions.length === 0; + const viewModeCount = [supportsGraph, supportsLogs, supportsTable].filter(m => m).length; return (
@@ -846,45 +860,53 @@ export class Explore extends React.PureComponent { onClickHintFix={this.onModifyQueries} onExecuteQuery={this.onSubmit} onRemoveQueryRow={this.onRemoveQueryRow} - supportsLogs={supportsLogs} transactions={queryTransactions} /> -
- {supportsGraph ? ( - - ) : null} - {supportsTable ? ( - - ) : null} - {supportsLogs ? ( - - ) : null} -
-
- {supportsGraph && - showingGraph && ( - + + {showStartPages && } + {!showStartPages && ( + <> + {viewModeCount > 1 && ( +
+ {supportsGraph ? ( + + ) : null} + {supportsTable ? ( + + ) : null} + {supportsLogs ? ( + + ) : null} +
+ )} + + {supportsGraph && + showingGraph && ( + + )} + {supportsTable && showingTable ? ( +
+ + + ) : null} + {supportsLogs && showingLogs ? : null} + )} - {supportsTable && showingTable ? ( -
-
- - ) : null} - {supportsLogs && showingLogs ? : null} + ) : null} diff --git a/public/app/features/explore/Graph.tsx b/public/app/features/explore/Graph.tsx index d57f8d49a43..bbb055067a2 100644 --- a/public/app/features/explore/Graph.tsx +++ b/public/app/features/explore/Graph.tsx @@ -6,7 +6,7 @@ import { withSize } from 'react-sizeme'; import 'vendor/flot/jquery.flot'; import 'vendor/flot/jquery.flot.time'; -import { Range } from 'app/types/explore'; +import { RawTimeRange } from 'app/types/series'; import * as dateMath from 'app/core/utils/datemath'; import TimeSeries from 'app/core/time_series2'; @@ -76,7 +76,7 @@ interface GraphProps { height?: string; // e.g., '200px' id?: string; loading?: boolean; - range: Range; + range: RawTimeRange; split?: boolean; size?: { width: number; height: number }; } @@ -169,7 +169,7 @@ export class Graph extends PureComponent { return (
- {loading &&
} + {loading &&
} {this.props.data && this.props.data.length > MAX_NUMBER_OF_TIME_SERIES && !this.state.showAllTimeSeries && ( diff --git a/public/app/features/explore/Logs.tsx b/public/app/features/explore/Logs.tsx index cc8f9be48fd..278c5ee016d 100644 --- a/public/app/features/explore/Logs.tsx +++ b/public/app/features/explore/Logs.tsx @@ -10,37 +10,33 @@ interface LogsProps { loading: boolean; } -const EXAMPLE_QUERY = '{job="default/prometheus"}'; - export default class Logs extends PureComponent { render() { - const { className = '', data } = this.props; + const { className = '', data, loading = false } = this.props; const hasData = data && data.rows && data.rows.length > 0; return (
- {hasData ? ( -
- {data.rows.map(row => ( - -
-
{row.timeLocal}
-
- -
- - ))} +
+ {loading &&
} +
+ {hasData && + data.rows.map(row => ( + +
+
{row.timeLocal}
+
+ +
+ + ))}
- ) : null} - {!hasData ? ( -
- Enter a query like {EXAMPLE_QUERY} -
- ) : null} + {!loading && !hasData && 'No data was returned.'} +
); } diff --git a/public/app/features/explore/QueryField.tsx b/public/app/features/explore/QueryField.tsx index 9350682f1a0..73d743fe8e6 100644 --- a/public/app/features/explore/QueryField.tsx +++ b/public/app/features/explore/QueryField.tsx @@ -27,7 +27,7 @@ function hasSuggestions(suggestions: CompletionItemGroup[]): boolean { return suggestions && suggestions.length > 0; } -interface TypeaheadFieldProps { +interface QueryFieldProps { additionalPlugins?: any[]; cleanText?: (text: string) => string; initialValue: string | null; @@ -35,14 +35,14 @@ interface TypeaheadFieldProps { onFocus?: () => void; onTypeahead?: (typeahead: TypeaheadInput) => TypeaheadOutput; onValueChanged?: (value: Value) => void; - onWillApplySuggestion?: (suggestion: string, state: TypeaheadFieldState) => string; + onWillApplySuggestion?: (suggestion: string, state: QueryFieldState) => string; placeholder?: string; portalOrigin?: string; syntax?: string; syntaxLoaded?: boolean; } -export interface TypeaheadFieldState { +export interface QueryFieldState { suggestions: CompletionItemGroup[]; typeaheadContext: string | null; typeaheadIndex: number; @@ -60,7 +60,7 @@ export interface TypeaheadInput { wrapperNode: Element; } -class QueryField extends React.PureComponent { +export class QueryField extends React.PureComponent { menuEl: HTMLElement | null; placeholdersBuffer: PlaceholdersBuffer; plugins: any[]; @@ -72,7 +72,7 @@ class QueryField extends React.PureComponent p); this.state = { suggestions: [], @@ -102,7 +102,7 @@ class QueryField extends React.PureComponent - {this.renderMenu()} - +
+
+ {this.renderMenu()} + +
); } diff --git a/public/app/features/explore/QueryRows.tsx b/public/app/features/explore/QueryRows.tsx index aaa7dfcd20b..4aacdb22599 100644 --- a/public/app/features/explore/QueryRows.tsx +++ b/public/app/features/explore/QueryRows.tsx @@ -2,9 +2,9 @@ import React, { PureComponent } from 'react'; import { QueryTransaction, HistoryItem, Query, QueryHint } from 'app/types/explore'; -// TODO make this datasource-plugin-dependent -import QueryField from './PromQueryField'; -import QueryTransactions from './QueryTransactions'; +import DefaultQueryField from './QueryField'; +import QueryTransactionStatus from './QueryTransactionStatus'; +import { DataSource } from 'app/types'; function getFirstHintFromTransactions(transactions: QueryTransaction[]): QueryHint { const transaction = transactions.find(qt => qt.hints && qt.hints.length > 0); @@ -24,10 +24,8 @@ interface QueryRowEventHandlers { interface QueryRowCommonProps { className?: string; - datasource: any; + datasource: DataSource; history: HistoryItem[]; - // Temporarily - supportsLogs?: boolean; transactions: QueryTransaction[]; } @@ -78,14 +76,15 @@ class QueryRow extends PureComponent { }; render() { - const { datasource, history, query, supportsLogs, transactions } = this.props; + const { datasource, history, query, transactions } = this.props; const transactionWithError = transactions.find(t => t.error !== undefined); const hint = getFirstHintFromTransactions(transactions); const queryError = transactionWithError ? transactionWithError.error : null; + const QueryField = datasource.pluginExports.ExploreQueryField || DefaultQueryField; return (
- +
{ onClickHintFix={this.onClickHintFix} onPressEnter={this.onPressEnter} onQueryChange={this.onChangeQuery} - supportsLogs={supportsLogs} />
diff --git a/public/app/features/explore/QueryTransactions.tsx b/public/app/features/explore/QueryTransactionStatus.tsx similarity index 60% rename from public/app/features/explore/QueryTransactions.tsx rename to public/app/features/explore/QueryTransactionStatus.tsx index 0ce721f14e7..77a50b7d2ca 100644 --- a/public/app/features/explore/QueryTransactions.tsx +++ b/public/app/features/explore/QueryTransactionStatus.tsx @@ -1,17 +1,17 @@ import React, { PureComponent } from 'react'; -import { QueryTransaction as QueryTransactionModel } from 'app/types/explore'; +import { QueryTransaction } from 'app/types/explore'; import ElapsedTime from './ElapsedTime'; function formatLatency(value) { return `${(value / 1000).toFixed(1)}s`; } -interface QueryTransactionProps { - transaction: QueryTransactionModel; +interface QueryTransactionStatusItemProps { + transaction: QueryTransaction; } -class QueryTransaction extends PureComponent { +class QueryTransactionStatusItem extends PureComponent { render() { const { transaction } = this.props; const className = transaction.done ? 'query-transaction' : 'query-transaction query-transaction--loading'; @@ -26,16 +26,16 @@ class QueryTransaction extends PureComponent { } } -interface QueryTransactionsProps { - transactions: QueryTransactionModel[]; +interface QueryTransactionStatusProps { + transactions: QueryTransaction[]; } -export default class QueryTransactions extends PureComponent { +export default class QueryTransactionStatus extends PureComponent { render() { const { transactions } = this.props; return (
- {transactions.map((t, i) => )} + {transactions.map((t, i) => )}
); } diff --git a/public/app/features/explore/Table.tsx b/public/app/features/explore/Table.tsx index 0264bd3b4cc..4946a6a505d 100644 --- a/public/app/features/explore/Table.tsx +++ b/public/app/features/explore/Table.tsx @@ -21,10 +21,16 @@ function prepareRows(rows, columnNames) { export default class Table extends PureComponent { getCellProps = (state, rowInfo, column) => { return { - onClick: () => { - const columnKey = column.Header; - const rowValue = rowInfo.row[columnKey]; - this.props.onClickCell(columnKey, rowValue); + onClick: (e: React.SyntheticEvent) => { + // Only handle click on link, not the cell + if (e.target) { + const link = e.target as HTMLElement; + if (link.className === 'link') { + const columnKey = column.Header; + const rowValue = rowInfo.row[columnKey]; + this.props.onClickCell(columnKey, rowValue); + } + } }, }; }; diff --git a/public/app/features/explore/TimePicker.test.tsx b/public/app/features/explore/TimePicker.test.tsx index afe6b092901..cadcfbb668c 100644 --- a/public/app/features/explore/TimePicker.test.tsx +++ b/public/app/features/explore/TimePicker.test.tsx @@ -33,8 +33,8 @@ describe('', () => { to: '1000', }; const rangeString = rangeUtil.describeTimeRange({ - from: parseTime(range.from), - to: parseTime(range.to), + from: parseTime(range.from, true), + to: parseTime(range.to, true), }); const wrapper = shallow(); expect(wrapper.state('fromRaw')).toBe('1970-01-01 00:00:00'); @@ -50,8 +50,8 @@ describe('', () => { to: '4000', }; const rangeString = rangeUtil.describeTimeRange({ - from: parseTime(range.from), - to: parseTime(range.to), + from: parseTime(range.from, true), + to: parseTime(range.to, true), }); const onChangeTime = sinon.spy(); diff --git a/public/app/features/explore/TimePicker.tsx b/public/app/features/explore/TimePicker.tsx index f9c740073d0..8955fb4aa9b 100644 --- a/public/app/features/explore/TimePicker.tsx +++ b/public/app/features/explore/TimePicker.tsx @@ -3,6 +3,7 @@ import moment from 'moment'; import * as dateMath from 'app/core/utils/datemath'; import * as rangeUtil from 'app/core/utils/rangeutil'; +import { RawTimeRange } from 'app/types/series'; const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss'; export const DEFAULT_RANGE = { @@ -10,77 +11,104 @@ export const DEFAULT_RANGE = { to: 'now', }; -export function parseTime(value, isUtc = false, asString = false) { +/** + * Return a human-editable string of either relative (inludes "now") or absolute local time (in the shape of DATE_FORMAT). + * @param value Epoch or relative time + */ +export function parseTime(value: string, isUtc = false): string { if (value.indexOf('now') !== -1) { return value; } - if (!isNaN(value)) { - const epoch = parseInt(value, 10); - const m = isUtc ? moment.utc(epoch) : moment(epoch); - return asString ? m.format(DATE_FORMAT) : m; + let time: any = value; + // Possible epoch + if (!isNaN(time)) { + time = parseInt(time, 10); } - return undefined; + time = isUtc ? moment.utc(time) : moment(time); + return time.format(DATE_FORMAT); } -export default class TimePicker extends PureComponent { +interface TimePickerProps { + isOpen?: boolean; + isUtc?: boolean; + range?: RawTimeRange; + onChangeTime?: (Range) => void; +} + +interface TimePickerState { + isOpen: boolean; + isUtc: boolean; + rangeString: string; + refreshInterval: string; + + // Input-controlled text, keep these in a shape that is human-editable + fromRaw: string; + toRaw: string; +} + +export default class TimePicker extends PureComponent { dropdownEl: any; + constructor(props) { super(props); - const fromRaw = props.range ? props.range.from : DEFAULT_RANGE.from; - const toRaw = props.range ? props.range.to : DEFAULT_RANGE.to; + const from = props.range ? props.range.from : DEFAULT_RANGE.from; + const to = props.range ? props.range.to : DEFAULT_RANGE.to; + + // Ensure internal format + const fromRaw = parseTime(from, props.isUtc); + const toRaw = parseTime(to, props.isUtc); const range = { - from: parseTime(fromRaw), - to: parseTime(toRaw), + from: fromRaw, + to: toRaw, }; + this.state = { - fromRaw: parseTime(fromRaw, props.isUtc, true), + fromRaw, + toRaw, isOpen: props.isOpen, isUtc: props.isUtc, rangeString: rangeUtil.describeTimeRange(range), refreshInterval: '', - toRaw: parseTime(toRaw, props.isUtc, true), }; } - move(direction) { + move(direction: number) { const { onChangeTime } = this.props; const { fromRaw, toRaw } = this.state; - const range = { - from: dateMath.parse(fromRaw, false), - to: dateMath.parse(toRaw, true), - }; + const from = dateMath.parse(fromRaw, false); + const to = dateMath.parse(toRaw, true); + const timespan = (to.valueOf() - from.valueOf()) / 2; - const timespan = (range.to.valueOf() - range.from.valueOf()) / 2; - let to, from; + let nextTo, nextFrom; if (direction === -1) { - to = range.to.valueOf() - timespan; - from = range.from.valueOf() - timespan; + nextTo = to.valueOf() - timespan; + nextFrom = from.valueOf() - timespan; } else if (direction === 1) { - to = range.to.valueOf() + timespan; - from = range.from.valueOf() + timespan; - if (to > Date.now() && range.to < Date.now()) { - to = Date.now(); - from = range.from.valueOf(); + nextTo = to.valueOf() + timespan; + nextFrom = from.valueOf() + timespan; + if (nextTo > Date.now() && to < Date.now()) { + nextTo = Date.now(); + nextFrom = from.valueOf(); } } else { - to = range.to.valueOf(); - from = range.from.valueOf(); + nextTo = to.valueOf(); + nextFrom = from.valueOf(); } - const rangeString = rangeUtil.describeTimeRange(range); - // No need to convert to UTC again - to = moment(to); - from = moment(from); + const nextRange = { + from: moment(nextFrom), + to: moment(nextTo), + }; this.setState( { - rangeString, - fromRaw: from.format(DATE_FORMAT), - toRaw: to.format(DATE_FORMAT), + rangeString: rangeUtil.describeTimeRange(nextRange), + fromRaw: nextRange.from.format(DATE_FORMAT), + toRaw: nextRange.to.format(DATE_FORMAT), }, () => { - onChangeTime({ to, from }); + onChangeTime(nextRange); } ); } @@ -99,16 +127,19 @@ export default class TimePicker extends PureComponent { handleClickApply = () => { const { onChangeTime } = this.props; - const { toRaw, fromRaw } = this.state; - const range = { - from: dateMath.parse(fromRaw, false), - to: dateMath.parse(toRaw, true), - }; - const rangeString = rangeUtil.describeTimeRange(range); + let range; this.setState( - { - isOpen: false, - rangeString, + state => { + const { toRaw, fromRaw } = this.state; + range = { + from: dateMath.parse(fromRaw, false), + to: dateMath.parse(toRaw, true), + }; + const rangeString = rangeUtil.describeTimeRange(range); + return { + isOpen: false, + rangeString, + }; }, () => { if (onChangeTime) { diff --git a/public/app/features/explore/Wrapper.tsx b/public/app/features/explore/Wrapper.tsx index 7e07aafbf6d..de1eee4c662 100644 --- a/public/app/features/explore/Wrapper.tsx +++ b/public/app/features/explore/Wrapper.tsx @@ -7,6 +7,7 @@ import { serializeStateToUrlParam, parseUrlState } from 'app/core/utils/explore' import { StoreState } from 'app/types'; import { ExploreState } from 'app/types/explore'; +import ErrorBoundary from './ErrorBoundary'; import Explore from './Explore'; interface WrapperProps { @@ -61,28 +62,33 @@ export class Wrapper extends Component { const { split, splitState } = this.state; const urlStateLeft = parseUrlState(this.urlStates[STATE_KEY_LEFT]); const urlStateRight = parseUrlState(this.urlStates[STATE_KEY_RIGHT]); + return (
- - {split && ( + + + {split && ( + + + )}
); diff --git a/public/app/features/org/new_org_ctrl.ts b/public/app/features/org/NewOrgCtrl.ts similarity index 100% rename from public/app/features/org/new_org_ctrl.ts rename to public/app/features/org/NewOrgCtrl.ts diff --git a/public/app/features/org/OrgDetailsPage.test.tsx b/public/app/features/org/OrgDetailsPage.test.tsx new file mode 100644 index 00000000000..2eb45fa368a --- /dev/null +++ b/public/app/features/org/OrgDetailsPage.test.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import { shallow } from 'enzyme'; +import { OrgDetailsPage, Props } from './OrgDetailsPage'; +import { NavModel, Organization, OrganizationPreferences } from '../../types'; + +const setup = (propOverrides?: object) => { + const props: Props = { + preferences: {} as OrganizationPreferences, + organization: {} as Organization, + navModel: {} as NavModel, + loadOrganization: jest.fn(), + loadOrganizationPreferences: jest.fn(), + loadStarredDashboards: jest.fn(), + setOrganizationName: jest.fn(), + updateOrganization: jest.fn(), + }; + + Object.assign(props, propOverrides); + + return shallow(); +}; + +describe('Render', () => { + it('should render component', () => { + const wrapper = setup(); + + expect(wrapper).toMatchSnapshot(); + }); + + it('should render organization and preferences', () => { + const wrapper = setup({ + organization: { + name: 'Cool org', + id: 1, + }, + preferences: { + homeDashboardId: 1, + theme: 'Default', + timezone: 'Default', + }, + }); + + expect(wrapper).toMatchSnapshot(); + }); +}); diff --git a/public/app/features/org/OrgDetailsPage.tsx b/public/app/features/org/OrgDetailsPage.tsx new file mode 100644 index 00000000000..86a3fab3268 --- /dev/null +++ b/public/app/features/org/OrgDetailsPage.tsx @@ -0,0 +1,85 @@ +import React, { PureComponent } from 'react'; +import { hot } from 'react-hot-loader'; +import { connect } from 'react-redux'; +import PageHeader from '../../core/components/PageHeader/PageHeader'; +import PageLoader from '../../core/components/PageLoader/PageLoader'; +import OrgProfile from './OrgProfile'; +import OrgPreferences from './OrgPreferences'; +import { + loadOrganization, + loadOrganizationPreferences, + setOrganizationName, + updateOrganization, +} from './state/actions'; +import { loadStarredDashboards } from '../../core/actions/user'; +import { NavModel, Organization, OrganizationPreferences, StoreState } from 'app/types'; +import { getNavModel } from '../../core/selectors/navModel'; + +export interface Props { + navModel: NavModel; + organization: Organization; + preferences: OrganizationPreferences; + loadOrganization: typeof loadOrganization; + loadOrganizationPreferences: typeof loadOrganizationPreferences; + loadStarredDashboards: typeof loadStarredDashboards; + setOrganizationName: typeof setOrganizationName; + updateOrganization: typeof updateOrganization; +} + +export class OrgDetailsPage extends PureComponent { + async componentDidMount() { + await this.props.loadStarredDashboards(); + await this.props.loadOrganization(); + await this.props.loadOrganizationPreferences(); + } + + onOrgNameChange = name => { + this.props.setOrganizationName(name); + }; + + onUpdateOrganization = () => { + this.props.updateOrganization(); + }; + + render() { + const { navModel, organization, preferences } = this.props; + + return ( +
+ +
+ {Object.keys(organization).length === 0 || Object.keys(preferences).length === 0 ? ( + + ) : ( +
+ this.onOrgNameChange(name)} + onSubmit={this.onUpdateOrganization} + orgName={organization.name} + /> + +
+ )} +
+
+ ); + } +} + +function mapStateToProps(state: StoreState) { + return { + navModel: getNavModel(state.navIndex, 'org-settings'), + organization: state.organization.organization, + preferences: state.organization.preferences, + }; +} + +const mapDispatchToProps = { + loadOrganization, + loadOrganizationPreferences, + loadStarredDashboards, + setOrganizationName, + updateOrganization, +}; + +export default hot(module)(connect(mapStateToProps, mapDispatchToProps)(OrgDetailsPage)); diff --git a/public/app/features/org/OrgPreferences.test.tsx b/public/app/features/org/OrgPreferences.test.tsx new file mode 100644 index 00000000000..e79e43d04f2 --- /dev/null +++ b/public/app/features/org/OrgPreferences.test.tsx @@ -0,0 +1,28 @@ +import React from 'react'; +import { shallow } from 'enzyme'; +import { OrgPreferences, Props } from './OrgPreferences'; + +const setup = () => { + const props: Props = { + preferences: { + homeDashboardId: 1, + timezone: 'UTC', + theme: 'Default', + }, + starredDashboards: [{ id: 1, title: 'Standard dashboard', url: '', uri: '', uid: '', type: '', tags: [] }], + setOrganizationTimezone: jest.fn(), + setOrganizationTheme: jest.fn(), + setOrganizationHomeDashboard: jest.fn(), + updateOrganizationPreferences: jest.fn(), + }; + + return shallow(); +}; + +describe('Render', () => { + it('should render component', () => { + const wrapper = setup(); + + expect(wrapper).toMatchSnapshot(); + }); +}); diff --git a/public/app/features/org/OrgPreferences.tsx b/public/app/features/org/OrgPreferences.tsx new file mode 100644 index 00000000000..a8133ba4a1c --- /dev/null +++ b/public/app/features/org/OrgPreferences.tsx @@ -0,0 +1,113 @@ +import React, { PureComponent } from 'react'; +import { connect } from 'react-redux'; +import { Label } from '../../core/components/Label/Label'; +import SimplePicker from '../../core/components/Picker/SimplePicker'; +import { DashboardSearchHit, OrganizationPreferences } from 'app/types'; +import { + setOrganizationHomeDashboard, + setOrganizationTheme, + setOrganizationTimezone, + updateOrganizationPreferences, +} from './state/actions'; + +export interface Props { + preferences: OrganizationPreferences; + starredDashboards: DashboardSearchHit[]; + setOrganizationHomeDashboard: typeof setOrganizationHomeDashboard; + setOrganizationTheme: typeof setOrganizationTheme; + setOrganizationTimezone: typeof setOrganizationTimezone; + updateOrganizationPreferences: typeof updateOrganizationPreferences; +} + +const themes = [{ value: '', text: 'Default' }, { value: 'dark', text: 'Dark' }, { value: 'light', text: 'Light' }]; + +const timezones = [ + { value: '', text: 'Default' }, + { value: 'browser', text: 'Local browser time' }, + { value: 'utc', text: 'UTC' }, +]; + +export class OrgPreferences extends PureComponent { + onSubmitForm = event => { + event.preventDefault(); + this.props.updateOrganizationPreferences(); + }; + + render() { + const { + preferences, + starredDashboards, + setOrganizationHomeDashboard, + setOrganizationTimezone, + setOrganizationTheme, + } = this.props; + + starredDashboards.unshift({ id: 0, title: 'Default', tags: [], type: '', uid: '', uri: '', url: '' }); + + return ( +
+

Preferences

+
+ UI Theme + theme.value === preferences.theme)} + options={themes} + getOptionValue={i => i.value} + getOptionLabel={i => i.text} + onSelected={theme => setOrganizationTheme(theme.value)} + width={20} + /> +
+
+ + dashboard.id === preferences.homeDashboardId)} + getOptionValue={i => i.id} + getOptionLabel={i => i.title} + onSelected={(dashboard: DashboardSearchHit) => setOrganizationHomeDashboard(dashboard.id)} + options={starredDashboards} + placeholder="Chose default dashboard" + width={20} + /> +
+
+ + timezone.value === preferences.timezone)} + getOptionValue={i => i.value} + getOptionLabel={i => i.text} + onSelected={timezone => setOrganizationTimezone(timezone.value)} + options={timezones} + width={20} + /> +
+
+ +
+ + ); + } +} + +function mapStateToProps(state) { + return { + preferences: state.organization.preferences, + starredDashboards: state.user.starredDashboards, + }; +} + +const mapDispatchToProps = { + setOrganizationHomeDashboard, + setOrganizationTimezone, + setOrganizationTheme, + updateOrganizationPreferences, +}; + +export default connect(mapStateToProps, mapDispatchToProps)(OrgPreferences); diff --git a/public/app/features/org/OrgProfile.test.tsx b/public/app/features/org/OrgProfile.test.tsx new file mode 100644 index 00000000000..d101eded13e --- /dev/null +++ b/public/app/features/org/OrgProfile.test.tsx @@ -0,0 +1,21 @@ +import React from 'react'; +import { shallow } from 'enzyme'; +import OrgProfile, { Props } from './OrgProfile'; + +const setup = () => { + const props: Props = { + orgName: 'Main org', + onSubmit: jest.fn(), + onOrgNameChange: jest.fn(), + }; + + return shallow(); +}; + +describe('Render', () => { + it('should render component', () => { + const wrapper = setup(); + + expect(wrapper).toMatchSnapshot(); + }); +}); diff --git a/public/app/features/org/OrgProfile.tsx b/public/app/features/org/OrgProfile.tsx new file mode 100644 index 00000000000..22dfa7bb1ce --- /dev/null +++ b/public/app/features/org/OrgProfile.tsx @@ -0,0 +1,44 @@ +import React, { SFC } from 'react'; + +export interface Props { + orgName: string; + onSubmit: () => void; + onOrgNameChange: (orgName: string) => void; +} + +const OrgProfile: SFC = ({ onSubmit, onOrgNameChange, orgName }) => { + return ( +
+

Organization profile

+
{ + event.preventDefault(); + onSubmit(); + }} + > +
+
+ Organization name + { + onOrgNameChange(event.target.value); + }} + value={orgName} + /> +
+
+
+ +
+ +
+ ); +}; + +export default OrgProfile; diff --git a/public/app/features/org/select_org_ctrl.ts b/public/app/features/org/SelectOrgCtrl.ts similarity index 100% rename from public/app/features/org/select_org_ctrl.ts rename to public/app/features/org/SelectOrgCtrl.ts diff --git a/public/app/features/org/user_invite_ctrl.ts b/public/app/features/org/UserInviteCtrl.ts similarity index 100% rename from public/app/features/org/user_invite_ctrl.ts rename to public/app/features/org/UserInviteCtrl.ts diff --git a/public/app/features/org/__snapshots__/OrgDetailsPage.test.tsx.snap b/public/app/features/org/__snapshots__/OrgDetailsPage.test.tsx.snap new file mode 100644 index 00000000000..28806d2bf1d --- /dev/null +++ b/public/app/features/org/__snapshots__/OrgDetailsPage.test.tsx.snap @@ -0,0 +1,36 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Render should render component 1`] = ` +
+ +
+ +
+
+`; + +exports[`Render should render organization and preferences 1`] = ` +
+ +
+
+ + +
+
+
+`; diff --git a/public/app/features/org/__snapshots__/OrgPreferences.test.tsx.snap b/public/app/features/org/__snapshots__/OrgPreferences.test.tsx.snap new file mode 100644 index 00000000000..06bf464a4a0 --- /dev/null +++ b/public/app/features/org/__snapshots__/OrgPreferences.test.tsx.snap @@ -0,0 +1,136 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Render should render component 1`] = ` +
+

+ Preferences +

+
+ + UI Theme + + +
+
+ + Home Dashboard + + +
+
+ + +
+
+ +
+ +`; diff --git a/public/app/features/org/__snapshots__/OrgProfile.test.tsx.snap b/public/app/features/org/__snapshots__/OrgProfile.test.tsx.snap new file mode 100644 index 00000000000..b49b63e4532 --- /dev/null +++ b/public/app/features/org/__snapshots__/OrgProfile.test.tsx.snap @@ -0,0 +1,46 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Render should render component 1`] = ` +
+

+ Organization profile +

+
+
+
+ + Organization name + + +
+
+
+ +
+ +
+`; diff --git a/public/app/features/org/all.ts b/public/app/features/org/all.ts index 9cbcec8de0d..c905853cf49 100644 --- a/public/app/features/org/all.ts +++ b/public/app/features/org/all.ts @@ -1,8 +1,3 @@ -import './profile_ctrl'; -import './select_org_ctrl'; -import './change_password_ctrl'; -import './new_org_ctrl'; -import './user_invite_ctrl'; -import './create_team_ctrl'; -import './org_details_ctrl'; -import './prefs_control'; +import './SelectOrgCtrl'; +import './NewOrgCtrl'; +import './UserInviteCtrl'; diff --git a/public/app/features/org/org_details_ctrl.ts b/public/app/features/org/org_details_ctrl.ts deleted file mode 100644 index 1d4a92c6e8b..00000000000 --- a/public/app/features/org/org_details_ctrl.ts +++ /dev/null @@ -1,38 +0,0 @@ -import angular from 'angular'; - -export class OrgDetailsCtrl { - /** @ngInject */ - constructor($scope, $http, backendSrv, contextSrv, navModelSrv) { - $scope.init = () => { - $scope.getOrgInfo(); - $scope.navModel = navModelSrv.getNav('cfg', 'org-settings', 0); - }; - - $scope.getOrgInfo = () => { - backendSrv.get('/api/org').then(org => { - $scope.org = org; - $scope.address = org.address; - contextSrv.user.orgName = org.name; - }); - }; - - $scope.update = () => { - if (!$scope.orgForm.$valid) { - return; - } - const data = { name: $scope.org.name }; - backendSrv.put('/api/org', data).then($scope.getOrgInfo); - }; - - $scope.updateAddress = () => { - if (!$scope.addressForm.$valid) { - return; - } - backendSrv.put('/api/org/address', $scope.address).then($scope.getOrgInfo); - }; - - $scope.init(); - } -} - -angular.module('grafana.controllers').controller('OrgDetailsCtrl', OrgDetailsCtrl); diff --git a/public/app/features/org/partials/orgDetails.html b/public/app/features/org/partials/orgDetails.html deleted file mode 100644 index f5a49e3d3ee..00000000000 --- a/public/app/features/org/partials/orgDetails.html +++ /dev/null @@ -1,21 +0,0 @@ - - -
-

Organization profile

- -
-
-
- Organization name - -
-
- -
- -
- - -
- - diff --git a/public/app/features/org/prefs_control.ts b/public/app/features/org/prefs_control.ts deleted file mode 100644 index 74dde250eec..00000000000 --- a/public/app/features/org/prefs_control.ts +++ /dev/null @@ -1,92 +0,0 @@ -import config from 'app/core/config'; -import coreModule from 'app/core/core_module'; - -export class PrefsControlCtrl { - prefs: any; - oldTheme: any; - prefsForm: any; - mode: string; - - timezones: any = [ - { value: '', text: 'Default' }, - { value: 'browser', text: 'Local browser time' }, - { value: 'utc', text: 'UTC' }, - ]; - themes: any = [{ value: '', text: 'Default' }, { value: 'dark', text: 'Dark' }, { value: 'light', text: 'Light' }]; - - /** @ngInject */ - constructor(private backendSrv, private $location) {} - - $onInit() { - return this.backendSrv.get(`/api/${this.mode}/preferences`).then(prefs => { - this.prefs = prefs; - this.oldTheme = prefs.theme; - }); - } - - updatePrefs() { - if (!this.prefsForm.$valid) { - return; - } - - const cmd = { - theme: this.prefs.theme, - timezone: this.prefs.timezone, - homeDashboardId: this.prefs.homeDashboardId, - }; - - this.backendSrv.put(`/api/${this.mode}/preferences`, cmd).then(() => { - window.location.href = config.appSubUrl + this.$location.path(); - }); - } -} - -const template = ` -
-

Preferences

- -
- UI Theme -
- -
-
- -
- - Home Dashboard - - Not finding dashboard you want? Star it first, then it should appear in this select box. - - - - -
- -
- -
- -
-
- -
- -
- -`; - -export function prefsControlDirective() { - return { - restrict: 'E', - controller: PrefsControlCtrl, - bindToController: true, - controllerAs: 'ctrl', - template: template, - scope: { - mode: '@', - }, - }; -} - -coreModule.directive('prefsControl', prefsControlDirective); diff --git a/public/app/features/org/state/actions.ts b/public/app/features/org/state/actions.ts new file mode 100644 index 00000000000..4df9083c323 --- /dev/null +++ b/public/app/features/org/state/actions.ts @@ -0,0 +1,118 @@ +import { ThunkAction } from 'redux-thunk'; +import { Organization, OrganizationPreferences, StoreState } from 'app/types'; +import { getBackendSrv } from '../../../core/services/backend_srv'; + +type ThunkResult = ThunkAction; + +export enum ActionTypes { + LoadOrganization = 'LOAD_ORGANISATION', + LoadPreferences = 'LOAD_PREFERENCES', + SetOrganizationName = 'SET_ORGANIZATION_NAME', + SetOrganizationTheme = 'SET_ORGANIZATION_THEME', + SetOrganizationHomeDashboard = 'SET_ORGANIZATION_HOME_DASHBOARD', + SetOrganizationTimezone = 'SET_ORGANIZATION_TIMEZONE', +} + +interface LoadOrganizationAction { + type: ActionTypes.LoadOrganization; + payload: Organization; +} + +interface LoadPreferencesAction { + type: ActionTypes.LoadPreferences; + payload: OrganizationPreferences; +} + +interface SetOrganizationNameAction { + type: ActionTypes.SetOrganizationName; + payload: string; +} + +interface SetOrganizationThemeAction { + type: ActionTypes.SetOrganizationTheme; + payload: string; +} + +interface SetOrganizationHomeDashboardAction { + type: ActionTypes.SetOrganizationHomeDashboard; + payload: number; +} + +interface SetOrganizationTimezoneAction { + type: ActionTypes.SetOrganizationTimezone; + payload: string; +} + +const organisationLoaded = (organisation: Organization) => ({ + type: ActionTypes.LoadOrganization, + payload: organisation, +}); + +const preferencesLoaded = (preferences: OrganizationPreferences) => ({ + type: ActionTypes.LoadPreferences, + payload: preferences, +}); + +export const setOrganizationName = (orgName: string) => ({ + type: ActionTypes.SetOrganizationName, + payload: orgName, +}); + +export const setOrganizationTheme = (theme: string) => ({ + type: ActionTypes.SetOrganizationTheme, + payload: theme, +}); + +export const setOrganizationHomeDashboard = (id: number) => ({ + type: ActionTypes.SetOrganizationHomeDashboard, + payload: id, +}); + +export const setOrganizationTimezone = (timezone: string) => ({ + type: ActionTypes.SetOrganizationTimezone, + payload: timezone, +}); + +export type Action = + | LoadOrganizationAction + | LoadPreferencesAction + | SetOrganizationNameAction + | SetOrganizationThemeAction + | SetOrganizationHomeDashboardAction + | SetOrganizationTimezoneAction; + +export function loadOrganization(): ThunkResult { + return async dispatch => { + const organisationResponse = await getBackendSrv().get('/api/org'); + dispatch(organisationLoaded(organisationResponse)); + + return organisationResponse; + }; +} + +export function loadOrganizationPreferences(): ThunkResult { + return async dispatch => { + const preferencesResponse = await getBackendSrv().get('/api/org/preferences'); + dispatch(preferencesLoaded(preferencesResponse)); + }; +} + +export function updateOrganization() { + return async (dispatch, getStore) => { + const organization = getStore().organization.organization; + + await getBackendSrv().put('/api/org', { name: organization.name }); + + dispatch(loadOrganization()); + }; +} + +export function updateOrganizationPreferences() { + return async (dispatch, getStore) => { + const preferences = getStore().organization.preferences; + + await getBackendSrv().put('/api/org/preferences', preferences); + + window.location.reload(); + }; +} diff --git a/public/app/features/org/state/reducers.ts b/public/app/features/org/state/reducers.ts new file mode 100644 index 00000000000..b79f915a731 --- /dev/null +++ b/public/app/features/org/state/reducers.ts @@ -0,0 +1,35 @@ +import { Organization, OrganizationPreferences, OrganizationState } from 'app/types'; +import { Action, ActionTypes } from './actions'; + +const initialState: OrganizationState = { + organization: {} as Organization, + preferences: {} as OrganizationPreferences, +}; + +const organizationReducer = (state = initialState, action: Action): OrganizationState => { + switch (action.type) { + case ActionTypes.LoadOrganization: + return { ...state, organization: action.payload }; + + case ActionTypes.LoadPreferences: + return { ...state, preferences: action.payload }; + + case ActionTypes.SetOrganizationName: + return { ...state, organization: { ...state.organization, name: action.payload } }; + + case ActionTypes.SetOrganizationTheme: + return { ...state, preferences: { ...state.preferences, theme: action.payload } }; + + case ActionTypes.SetOrganizationHomeDashboard: + return { ...state, preferences: { ...state.preferences, homeDashboardId: action.payload } }; + + case ActionTypes.SetOrganizationTimezone: + return { ...state, preferences: { ...state.preferences, timezone: action.payload } }; + } + + return state; +}; + +export default { + organization: organizationReducer, +}; diff --git a/public/app/features/panel/panel_ctrl.ts b/public/app/features/panel/panel_ctrl.ts index 5e216f6b34d..08605132e82 100644 --- a/public/app/features/panel/panel_ctrl.ts +++ b/public/app/features/panel/panel_ctrl.ts @@ -48,11 +48,6 @@ export class PanelCtrl { } $scope.$on('component-did-mount', () => this.panelDidMount()); - - $scope.$on('$destroy', () => { - this.events.emit('panel-teardown'); - this.events.removeAllListeners(); - }); } panelDidMount() { diff --git a/public/app/features/plugins/datasource_srv.ts b/public/app/features/plugins/datasource_srv.ts index 71a417a882f..fed455472c9 100644 --- a/public/app/features/plugins/datasource_srv.ts +++ b/public/app/features/plugins/datasource_srv.ts @@ -8,9 +8,10 @@ import { importPluginModule } from './plugin_loader'; // Types import { DataSourceApi } from 'app/types/series'; +import { DataSource } from 'app/types'; export class DatasourceSrv { - datasources: any; + datasources: { [name: string]: DataSource }; /** @ngInject */ constructor(private $q, private $injector, private $rootScope, private templateSrv) { @@ -61,9 +62,10 @@ export class DatasourceSrv { throw new Error('Plugin module is missing Datasource constructor'); } - const instance = this.$injector.instantiate(plugin.Datasource, { instanceSettings: dsConfig }); + const instance: DataSource = this.$injector.instantiate(plugin.Datasource, { instanceSettings: dsConfig }); instance.meta = pluginDef; instance.name = name; + instance.pluginExports = plugin; this.datasources[name] = instance; deferred.resolve(instance); }) diff --git a/public/app/features/org/change_password_ctrl.ts b/public/app/features/profile/ChangePasswordCtrl.ts similarity index 100% rename from public/app/features/org/change_password_ctrl.ts rename to public/app/features/profile/ChangePasswordCtrl.ts diff --git a/public/app/features/org/profile_ctrl.ts b/public/app/features/profile/ProfileCtrl.ts similarity index 100% rename from public/app/features/org/profile_ctrl.ts rename to public/app/features/profile/ProfileCtrl.ts diff --git a/public/app/features/org/partials/change_password.html b/public/app/features/profile/partials/change_password.html similarity index 100% rename from public/app/features/org/partials/change_password.html rename to public/app/features/profile/partials/change_password.html diff --git a/public/app/features/org/partials/profile.html b/public/app/features/profile/partials/profile.html similarity index 100% rename from public/app/features/org/partials/profile.html rename to public/app/features/profile/partials/profile.html diff --git a/public/app/features/org/create_team_ctrl.ts b/public/app/features/teams/CreateTeamCtrl.ts similarity index 100% rename from public/app/features/org/create_team_ctrl.ts rename to public/app/features/teams/CreateTeamCtrl.ts diff --git a/public/app/features/teams/TeamMembers.tsx b/public/app/features/teams/TeamMembers.tsx index 2534a08ed15..da57bfbdfd3 100644 --- a/public/app/features/teams/TeamMembers.tsx +++ b/public/app/features/teams/TeamMembers.tsx @@ -74,7 +74,7 @@ export class TeamMembers extends PureComponent {
- {syncEnabled ? this.renderLabels(member.labels) : ''} + {syncEnabled ? this.renderLabels(member.labels) : null} diff --git a/public/app/features/org/partials/create_team.html b/public/app/features/teams/partials/create_team.html similarity index 100% rename from public/app/features/org/partials/create_team.html rename to public/app/features/teams/partials/create_team.html diff --git a/public/app/partials/login.html b/public/app/partials/login.html index 260de80e389..a2bc8173766 100644 --- a/public/app/partials/login.html +++ b/public/app/partials/login.html @@ -2,7 +2,7 @@
{member.login} {member.email} this.onRemoveMember(member)} />
+ + + + + + + + + {seriesList.map((series, i) => ( + +
+ {LEGEND_STATS.map( + statName => + seriesValuesProps[statName] && ( + + ) + )} +
+ ); + } +} + +interface LegendTableHeaderProps { + statName: string; + onClick?: (statName: string) => void; +} + +class LegendTableHeaderItem extends PureComponent { + onClick = () => this.props.onClick(this.props.statName); + + render() { + const { statName, sort, sortDesc } = this.props; + return ( + + {statName} + {sort === statName && } + + ); + } +} + +export class Legend extends PureComponent { + render() { + return ( + + + + ); + } +} + +export default Legend; diff --git a/public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx b/public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx new file mode 100644 index 00000000000..2105687d8e1 --- /dev/null +++ b/public/app/plugins/panel/graph/Legend/LegendSeriesItem.tsx @@ -0,0 +1,196 @@ +import React, { PureComponent } from 'react'; +import classNames from 'classnames'; +import { TimeSeries } from 'app/core/core'; +import { SeriesColorPicker } from 'app/core/components/colorpicker/SeriesColorPicker'; + +export const LEGEND_STATS = ['min', 'max', 'avg', 'current', 'total']; + +export interface LegendLabelProps { + series: TimeSeries; + asTable?: boolean; + hidden?: boolean; + onLabelClick?: (series, event) => void; + onColorChange?: (series, color: string) => void; + onToggleAxis?: (series) => void; +} + +export interface LegendValuesProps { + values?: boolean; + min?: boolean; + max?: boolean; + avg?: boolean; + current?: boolean; + total?: boolean; +} + +type LegendItemProps = LegendLabelProps & LegendValuesProps; + +interface LegendItemState { + yaxis: number; +} + +export class LegendItem extends PureComponent { + static defaultProps = { + asTable: false, + hidden: false, + onLabelClick: () => {}, + onColorChange: () => {}, + onToggleAxis: () => {}, + }; + + constructor(props) { + super(props); + this.state = { + yaxis: this.props.series.yaxis, + }; + } + + onLabelClick = e => this.props.onLabelClick(this.props.series, e); + + onToggleAxis = () => { + const yaxis = this.state.yaxis === 2 ? 1 : 2; + const info = { alias: this.props.series.alias, yaxis: yaxis }; + this.setState({ yaxis: yaxis }); + this.props.onToggleAxis(info); + }; + + onColorChange = color => { + this.props.onColorChange(this.props.series, color); + // Because of PureComponent nature it makes only shallow props comparison and changing of series.color doesn't run + // component re-render. In this case we can't rely on color, selected by user, because it may be overwritten + // by series overrides. So we need to use forceUpdate() to make sure we have proper series color. + this.forceUpdate(); + }; + + renderLegendValues() { + const { series, asTable } = this.props; + const legendValueItems = []; + for (const valueName of LEGEND_STATS) { + if (this.props[valueName]) { + const valueFormatted = series.formatValue(series.stats[valueName]); + legendValueItems.push( + + ); + } + } + return legendValueItems; + } + + render() { + const { series, values, asTable, hidden } = this.props; + const seriesOptionClasses = classNames({ + 'graph-legend-series-hidden': hidden, + 'graph-legend-series--right-y': series.yaxis === 2, + }); + const valueItems = values ? this.renderLegendValues() : []; + const seriesLabel = ( + + ); + + if (asTable) { + return ( + + {seriesLabel} + {valueItems} + + ); + } else { + return ( +
+ {seriesLabel} + {valueItems} +
+ ); + } + } +} + +interface LegendSeriesLabelProps { + label: string; + color: string; + yaxis?: number; + onLabelClick?: (event) => void; +} + +class LegendSeriesLabel extends PureComponent { + static defaultProps = { + yaxis: undefined, + onLabelClick: () => {}, + }; + + render() { + const { label, color, yaxis } = this.props; + const { onColorChange, onToggleAxis } = this.props; + return [ + , + this.props.onLabelClick(e)}> + {label} + , + ]; + } +} + +interface LegendSeriesIconProps { + color: string; + yaxis?: number; + onColorChange?: (color: string) => void; + onToggleAxis?: () => void; +} + +interface LegendSeriesIconState { + color: string; +} + +function SeriesIcon(props) { + return ; +} + +class LegendSeriesIcon extends PureComponent { + static defaultProps = { + yaxis: undefined, + onColorChange: () => {}, + onToggleAxis: () => {}, + }; + + render() { + return ( + + + + ); + } +} + +interface LegendValueProps { + value: string; + valueName: string; + asTable?: boolean; +} + +function LegendValue(props: LegendValueProps) { + const value = props.value; + const valueName = props.valueName; + if (props.asTable) { + return {value}; + } + return
{value}
; +} diff --git a/public/app/plugins/panel/graph/graph.ts b/public/app/plugins/panel/graph/graph.ts index 7a8e24539f7..01afd0716e6 100755 --- a/public/app/plugins/panel/graph/graph.ts +++ b/public/app/plugins/panel/graph/graph.ts @@ -20,6 +20,9 @@ import { EventManager } from 'app/features/annotations/all'; import { convertToHistogramData } from './histogram'; import { alignYLevel } from './align_yaxes'; import config from 'app/core/config'; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { Legend, GraphLegendProps } from './Legend/Legend'; import { GraphCtrl } from './module'; @@ -35,6 +38,7 @@ class GraphElement { panelWidth: number; eventManager: EventManager; thresholdManager: ThresholdManager; + legendElem: HTMLElement; constructor(private scope, private elem, private timeSrv) { this.ctrl = scope.ctrl; @@ -50,7 +54,7 @@ class GraphElement { }); // panel events - this.ctrl.events.on('panel-teardown', this.onPanelteardown.bind(this)); + this.ctrl.events.on('panel-teardown', this.onPanelTeardown.bind(this)); /** * Split graph rendering into two parts. @@ -63,13 +67,14 @@ class GraphElement { // global events appEvents.on('graph-hover', this.onGraphHover.bind(this), scope); - appEvents.on('graph-hover-clear', this.onGraphHoverClear.bind(this), scope); - this.elem.bind('plotselected', this.onPlotSelected.bind(this)); - this.elem.bind('plotclick', this.onPlotClick.bind(this)); - scope.$on('$destroy', this.onScopeDestroy.bind(this)); + + // get graph legend element + if (this.elem && this.elem.parent) { + this.legendElem = this.elem.parent().find('.graph-legend')[0]; + } } onRender(renderData) { @@ -82,7 +87,26 @@ class GraphElement { const graphHeight = this.elem.height(); updateLegendValues(this.data, this.panel, graphHeight); - this.ctrl.events.emit('render-legend'); + const { values, min, max, avg, current, total } = this.panel.legend; + const { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero } = this.panel.legend; + const legendOptions = { alignAsTable, rightSide, sideWidth, sort, sortDesc, hideEmpty, hideZero }; + const valueOptions = { values, min, max, avg, current, total }; + const legendProps: GraphLegendProps = { + seriesList: this.data, + hiddenSeries: this.ctrl.hiddenSeries, + ...legendOptions, + ...valueOptions, + onToggleSeries: this.ctrl.onToggleSeries, + onToggleSort: this.ctrl.onToggleSort, + onColorChange: this.ctrl.onColorChange, + onToggleAxis: this.ctrl.onToggleAxis, + }; + const legendReactElem = React.createElement(Legend, legendProps); + ReactDOM.render(legendReactElem, this.legendElem, () => this.onLegendRenderingComplete()); + } + + onLegendRenderingComplete() { + this.render_panel(); } onGraphHover(evt) { @@ -99,17 +123,19 @@ class GraphElement { this.tooltip.show(evt.pos); } - onPanelteardown() { + onPanelTeardown() { this.thresholdManager = null; if (this.plot) { this.plot.destroy(); this.plot = null; } - } - onLegendRenderingComplete() { - this.render_panel(); + this.tooltip.destroy(); + this.elem.off(); + this.elem.remove(); + + ReactDOM.unmountComponentAtNode(this.legendElem); } onGraphHoverClear(event, info) { @@ -157,12 +183,6 @@ class GraphElement { } } - onScopeDestroy() { - this.tooltip.destroy(); - this.elem.off(); - this.elem.remove(); - } - shouldAbortRender() { if (!this.data) { return true; diff --git a/public/app/plugins/panel/graph/legend.ts b/public/app/plugins/panel/graph/legend.ts deleted file mode 100644 index db4dfdefa1c..00000000000 --- a/public/app/plugins/panel/graph/legend.ts +++ /dev/null @@ -1,306 +0,0 @@ -import _ from 'lodash'; -import $ from 'jquery'; -import baron from 'baron'; -import coreModule from 'app/core/core_module'; - -/** @ngInject */ -function graphLegendDirective(popoverSrv, $timeout) { - return { - link: (scope, elem) => { - let firstRender = true; - const ctrl = scope.ctrl; - const panel = ctrl.panel; - let data; - let seriesList; - let i; - let legendScrollbar; - const legendRightDefaultWidth = 10; - const legendElem = elem.parent(); - - scope.$on('$destroy', () => { - destroyScrollbar(); - }); - - ctrl.events.on('render-legend', () => { - data = ctrl.seriesList; - if (data) { - render(); - } - ctrl.events.emit('legend-rendering-complete'); - }); - - function getSeriesIndexForElement(el) { - return el.parents('[data-series-index]').data('series-index'); - } - - function openColorSelector(e) { - // if we clicked inside poup container ignore click - if ($(e.target).parents('.popover').length) { - return; - } - - const el = $(e.currentTarget).find('.fa-minus'); - const index = getSeriesIndexForElement(el); - const series = seriesList[index]; - - $timeout(() => { - popoverSrv.show({ - element: el[0], - position: 'bottom left', - targetAttachment: 'top left', - template: - '' + - '', - openOn: 'hover', - model: { - series: series, - toggleAxis: () => { - ctrl.toggleAxis(series); - }, - colorSelected: color => { - ctrl.changeSeriesColor(series, color); - }, - }, - }); - }); - } - - function toggleSeries(e) { - const el = $(e.currentTarget); - const index = getSeriesIndexForElement(el); - const seriesInfo = seriesList[index]; - const scrollPosition = legendScrollbar.scroller.scrollTop; - ctrl.toggleSeries(seriesInfo, e); - legendScrollbar.scroller.scrollTop = scrollPosition; - } - - function sortLegend(e) { - const el = $(e.currentTarget); - const stat = el.data('stat'); - - if (stat !== panel.legend.sort) { - panel.legend.sortDesc = null; - } - - // if already sort ascending, disable sorting - if (panel.legend.sortDesc === false) { - panel.legend.sort = null; - panel.legend.sortDesc = null; - ctrl.render(); - return; - } - - panel.legend.sortDesc = !panel.legend.sortDesc; - panel.legend.sort = stat; - ctrl.render(); - } - - function getTableHeaderHtml(statName) { - if (!panel.legend[statName]) { - return ''; - } - let html = '' + statName; - - if (panel.legend.sort === statName) { - const cssClass = panel.legend.sortDesc ? 'fa fa-caret-down' : 'fa fa-caret-up'; - html += ' '; - } - - return html + ''; - } - - function render() { - const legendWidth = legendElem.width(); - if (!ctrl.panel.legend.show) { - elem.empty(); - firstRender = true; - return; - } - - if (firstRender) { - elem.on('click', '.graph-legend-icon', openColorSelector); - elem.on('click', '.graph-legend-alias', toggleSeries); - elem.on('click', 'th', sortLegend); - firstRender = false; - } - - seriesList = data; - - elem.empty(); - - // Set min-width if side style and there is a value, otherwise remove the CSS property - // Set width so it works with IE11 - const width: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth + 'px' : ''; - const ieWidth: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth - 1 + 'px' : ''; - legendElem.css('min-width', width); - legendElem.css('width', ieWidth); - - elem.toggleClass('graph-legend-table', panel.legend.alignAsTable === true); - - let tableHeaderElem; - if (panel.legend.alignAsTable) { - let header = ''; - header += ''; - if (panel.legend.values) { - header += getTableHeaderHtml('min'); - header += getTableHeaderHtml('max'); - header += getTableHeaderHtml('avg'); - header += getTableHeaderHtml('current'); - header += getTableHeaderHtml('total'); - } - header += ''; - tableHeaderElem = $(header); - } - - if (panel.legend.sort) { - seriesList = _.sortBy(seriesList, series => { - let sort = series.stats[panel.legend.sort]; - if (sort === null) { - sort = -Infinity; - } - return sort; - }); - if (panel.legend.sortDesc) { - seriesList = seriesList.reverse(); - } - } - - // render first time for getting proper legend height - if (!panel.legend.rightSide || (panel.legend.rightSide && legendWidth !== legendRightDefaultWidth)) { - renderLegendElement(tableHeaderElem); - elem.empty(); - } - - renderLegendElement(tableHeaderElem); - } - - function renderSeriesLegendElements() { - const seriesElements = []; - for (i = 0; i < seriesList.length; i++) { - const series = seriesList[i]; - - if (series.hideFromLegend(panel.legend)) { - continue; - } - - let html = '
'; - html += '
'; - html += ''; - html += '
'; - - html += - '' + series.aliasEscaped + ''; - - if (panel.legend.values) { - const avg = series.formatValue(series.stats.avg); - const current = series.formatValue(series.stats.current); - const min = series.formatValue(series.stats.min); - const max = series.formatValue(series.stats.max); - const total = series.formatValue(series.stats.total); - - if (panel.legend.min) { - html += '
' + min + '
'; - } - if (panel.legend.max) { - html += '
' + max + '
'; - } - if (panel.legend.avg) { - html += '
' + avg + '
'; - } - if (panel.legend.current) { - html += '
' + current + '
'; - } - if (panel.legend.total) { - html += '
' + total + '
'; - } - } - - html += '
'; - seriesElements.push($(html)); - } - return seriesElements; - } - - function renderLegendElement(tableHeaderElem) { - const legendWidth = elem.width(); - - const seriesElements = renderSeriesLegendElements(); - - if (panel.legend.alignAsTable) { - const tbodyElem = $(''); - tbodyElem.append(tableHeaderElem); - tbodyElem.append(seriesElements); - elem.append(tbodyElem); - tbodyElem.wrap('
'); - } else { - elem.append('
'); - elem.find('.graph-legend-scroll').append(seriesElements); - } - - if (!panel.legend.rightSide || (panel.legend.rightSide && legendWidth !== legendRightDefaultWidth)) { - addScrollbar(); - } else { - destroyScrollbar(); - } - } - - function addScrollbar() { - const scrollRootClass = 'baron baron__root'; - const scrollerClass = 'baron__scroller'; - const scrollBarHTML = ` -
-
-
- `; - - const scrollRoot = elem; - const scroller = elem.find('.graph-legend-scroll'); - - // clear existing scroll bar track to prevent duplication - scrollRoot.find('.baron__track').remove(); - - scrollRoot.addClass(scrollRootClass); - $(scrollBarHTML).appendTo(scrollRoot); - scroller.addClass(scrollerClass); - - const scrollbarParams = { - root: scrollRoot[0], - scroller: scroller[0], - bar: '.baron__bar', - track: '.baron__track', - barOnCls: '_scrollbar', - scrollingCls: '_scrolling', - }; - - if (!legendScrollbar) { - legendScrollbar = baron(scrollbarParams); - } else { - destroyScrollbar(); - legendScrollbar = baron(scrollbarParams); - } - - // #11830 - compensates for Firefox scrollbar calculation error in the baron framework - scroller[0].style.marginRight = '-' + (scroller[0].offsetWidth - scroller[0].clientWidth) + 'px'; - - legendScrollbar.scroll(); - } - - function destroyScrollbar() { - if (legendScrollbar) { - legendScrollbar.dispose(); - legendScrollbar = undefined; - } - } - }, - }; -} - -coreModule.directive('graphLegend', graphLegendDirective); diff --git a/public/app/plugins/panel/graph/module.ts b/public/app/plugins/panel/graph/module.ts index 5878473b4e6..a6c5190d937 100644 --- a/public/app/plugins/panel/graph/module.ts +++ b/public/app/plugins/panel/graph/module.ts @@ -1,5 +1,4 @@ import './graph'; -import './legend'; import './series_overrides_ctrl'; import './thresholds_form'; @@ -244,67 +243,32 @@ class GraphCtrl extends MetricsPanelCtrl { } } - changeSeriesColor(series, color) { + onColorChange = (series, color) => { series.setColor(color); this.panel.aliasColors[series.alias] = series.color; this.render(); - } + }; - toggleSeries(serie, event) { - if (event.ctrlKey || event.metaKey || event.shiftKey) { - if (this.hiddenSeries[serie.alias]) { - delete this.hiddenSeries[serie.alias]; - } else { - this.hiddenSeries[serie.alias] = true; - } - } else { - this.toggleSeriesExclusiveMode(serie); - } + onToggleSeries = hiddenSeries => { + this.hiddenSeries = hiddenSeries; this.render(); - } + }; - toggleSeriesExclusiveMode(serie) { - const hidden = this.hiddenSeries; + onToggleSort = (sortBy, sortDesc) => { + this.panel.legend.sort = sortBy; + this.panel.legend.sortDesc = sortDesc; + this.render(); + }; - if (hidden[serie.alias]) { - delete hidden[serie.alias]; - } - - // check if every other series is hidden - const alreadyExclusive = _.every(this.seriesList, value => { - if (value.alias === serie.alias) { - return true; - } - - return hidden[value.alias]; - }); - - if (alreadyExclusive) { - // remove all hidden series - _.each(this.seriesList, value => { - delete this.hiddenSeries[value.alias]; - }); - } else { - // hide all but this serie - _.each(this.seriesList, value => { - if (value.alias === serie.alias) { - return; - } - - this.hiddenSeries[value.alias] = true; - }); - } - } - - toggleAxis(info) { + onToggleAxis = info => { let override = _.find(this.panel.seriesOverrides, { alias: info.alias }); if (!override) { override = { alias: info.alias }; this.panel.seriesOverrides.push(override); } - info.yaxis = override.yaxis = info.yaxis === 2 ? 1 : 2; + override.yaxis = info.yaxis; this.render(); - } + }; addSeriesOverride(override) { this.panel.seriesOverrides.push(override || {}); diff --git a/public/app/plugins/panel/graph/series_overrides_ctrl.ts b/public/app/plugins/panel/graph/series_overrides_ctrl.ts index 540d19fb47a..934fd835347 100644 --- a/public/app/plugins/panel/graph/series_overrides_ctrl.ts +++ b/public/app/plugins/panel/graph/series_overrides_ctrl.ts @@ -53,7 +53,7 @@ export function SeriesOverridesCtrl($scope, $element, popoverSrv) { element: $element.find('.dropdown')[0], position: 'top center', openOn: 'click', - template: '', + template: '', model: { autoClose: true, colorSelected: $scope.colorSelected, diff --git a/public/app/plugins/panel/table/column_options.ts b/public/app/plugins/panel/table/column_options.ts index ca6d271643b..4c810d9987d 100644 --- a/public/app/plugins/panel/table/column_options.ts +++ b/public/app/plugins/panel/table/column_options.ts @@ -41,6 +41,7 @@ export class ColumnOptionsCtrl { { text: 'YYYY-MM-DD HH:mm:ss.SSS', value: 'YYYY-MM-DD HH:mm:ss.SSS' }, { text: 'MM/DD/YY h:mm:ss a', value: 'MM/DD/YY h:mm:ss a' }, { text: 'MMMM D, YYYY LT', value: 'MMMM D, YYYY LT' }, + { text: 'YYYY-MM-DD', value: 'YYYY-MM-DD' }, ]; this.mappingTypes = [{ text: 'Value to text', value: 1 }, { text: 'Range to text', value: 2 }]; diff --git a/public/app/routes/routes.ts b/public/app/routes/routes.ts index 94b6b2706f2..6770011278f 100644 --- a/public/app/routes/routes.ts +++ b/public/app/routes/routes.ts @@ -14,6 +14,7 @@ import DataSourcesListPage from 'app/features/datasources/DataSourcesListPage'; import NewDataSourcePage from '../features/datasources/NewDataSourcePage'; import UsersListPage from 'app/features/users/UsersListPage'; import DataSourceDashboards from 'app/features/datasources/DataSourceDashboards'; +import OrgDetailsPage from '../features/org/OrgDetailsPage'; /** @ngInject */ export function setupAngularRoutes($routeProvider, $locationProvider) { @@ -131,8 +132,10 @@ export function setupAngularRoutes($routeProvider, $locationProvider) { }, }) .when('/org', { - templateUrl: 'public/app/features/org/partials/orgDetails.html', - controller: 'OrgDetailsCtrl', + template: '', + resolve: { + component: () => OrgDetailsPage, + }, }) .when('/org/new', { templateUrl: 'public/app/features/org/partials/newOrg.html', @@ -164,7 +167,7 @@ export function setupAngularRoutes($routeProvider, $locationProvider) { }, }) .when('/org/teams/new', { - templateUrl: 'public/app/features/org/partials/create_team.html', + templateUrl: 'public/app/features/teams/partials/create_team.html', controller: 'CreateTeamCtrl', controllerAs: 'ctrl', }) @@ -176,12 +179,12 @@ export function setupAngularRoutes($routeProvider, $locationProvider) { }, }) .when('/profile', { - templateUrl: 'public/app/features/org/partials/profile.html', + templateUrl: 'public/app/features/profile/partials/profile.html', controller: 'ProfileCtrl', controllerAs: 'ctrl', }) .when('/profile/password', { - templateUrl: 'public/app/features/org/partials/change_password.html', + templateUrl: 'public/app/features/profile/partials/change_password.html', controller: 'ChangePasswordCtrl', }) .when('/profile/select-org', { diff --git a/public/app/store/configureStore.ts b/public/app/store/configureStore.ts index ccd027a0b6d..e6d86eaa9c6 100644 --- a/public/app/store/configureStore.ts +++ b/public/app/store/configureStore.ts @@ -10,6 +10,7 @@ import dashboardReducers from 'app/features/dashboard/state/reducers'; import pluginReducers from 'app/features/plugins/state/reducers'; import dataSourcesReducers from 'app/features/datasources/state/reducers'; import usersReducers from 'app/features/users/state/reducers'; +import organizationReducers from 'app/features/org/state/reducers'; const rootReducers = { ...sharedReducers, @@ -21,6 +22,7 @@ const rootReducers = { ...pluginReducers, ...dataSourcesReducers, ...usersReducers, + ...organizationReducers, }; export let store; diff --git a/public/app/types/datasources.ts b/public/app/types/datasources.ts index 8e1991dcd9f..5522f3a11ce 100644 --- a/public/app/types/datasources.ts +++ b/public/app/types/datasources.ts @@ -1,5 +1,5 @@ import { LayoutMode } from '../core/components/LayoutSelector/LayoutSelector'; -import { Plugin } from './plugins'; +import { Plugin, PluginExports, PluginMeta } from './plugins'; export interface DataSource { id: number; @@ -16,6 +16,10 @@ export interface DataSource { isDefault: boolean; jsonData: { authType: string; defaultRegion: string }; readOnly: boolean; + meta?: PluginMeta; + pluginExports?: PluginExports; + init?: () => void; + testDatasource?: () => Promise; } export interface DataSourcesState { diff --git a/public/app/types/explore.ts b/public/app/types/explore.ts index 1db37392b0b..a96d6c084fb 100644 --- a/public/app/types/explore.ts +++ b/public/app/types/explore.ts @@ -1,5 +1,7 @@ import { Value } from 'slate'; +import { RawTimeRange } from './series'; + export interface CompletionItem { /** * The label of this completion item. By default @@ -83,7 +85,11 @@ export interface HistoryItem { export abstract class LanguageProvider { datasource: any; request: (url) => Promise; - start: () => Promise; + /** + * Returns a promise that resolves with a task list when main syntax is loaded. + * Task list consists of secondary promises that load more detailed language features. + */ + start: () => Promise; } export interface TypeaheadInput { @@ -100,11 +106,6 @@ export interface TypeaheadOutput { suggestions: CompletionItemGroup[]; } -export interface Range { - from: string; - to: string; -} - export interface Query { query: string; key?: string; @@ -131,7 +132,7 @@ export interface QueryHint { export interface QueryTransaction { id: string; done: boolean; - error?: string; + error?: string | JSX.Element; hints?: QueryHint[]; latency: number; options: any; @@ -149,13 +150,14 @@ export interface TextMatch { } export interface ExploreState { + StartPage?: any; datasource: any; datasourceError: any; datasourceLoading: boolean | null; datasourceMissing: boolean; datasourceName?: string; exploreDatasources: ExploreDatasource[]; - graphRange: Range; + graphRange: RawTimeRange; history: HistoryItem[]; /** * Initial rows of queries to push down the tree. @@ -167,7 +169,7 @@ export interface ExploreState { * Hints gathered for the query row. */ queryTransactions: QueryTransaction[]; - range: Range; + range: RawTimeRange; showingGraph: boolean; showingLogs: boolean; showingTable: boolean; @@ -179,7 +181,7 @@ export interface ExploreState { export interface ExploreUrlState { datasource: string; queries: Query[]; - range: Range; + range: RawTimeRange; } export type ResultType = 'Graph' | 'Logs' | 'Table'; diff --git a/public/app/types/index.ts b/public/app/types/index.ts index 4b03ef70714..c51622682d4 100644 --- a/public/app/types/index.ts +++ b/public/app/types/index.ts @@ -6,7 +6,7 @@ import { FolderDTO, FolderState, FolderInfo } from './folders'; import { DashboardState } from './dashboard'; import { DashboardAcl, OrgRole, PermissionLevel } from './acl'; import { ApiKey, ApiKeysState, NewApiKey } from './apiKeys'; -import { Invitee, OrgUser, User, UsersState } from './user'; +import { Invitee, OrgUser, User, UsersState, UserState } from './user'; import { DataSource, DataSourcesState } from './datasources'; import { TimeRange, @@ -22,12 +22,14 @@ import { } from './series'; import { PanelProps } from './panel'; import { PluginDashboard, PluginMeta, Plugin, PluginsState } from './plugins'; +import { Organization, OrganizationPreferences, OrganizationState } from './organization'; import { AppNotification, AppNotificationSeverity, AppNotificationsState, AppNotificationTimeout, } from './appNotifications'; +import { DashboardSearchHit } from './search'; export { Team, @@ -76,10 +78,15 @@ export { DataQueryResponse, DataQueryOptions, PluginDashboard, + Organization, + OrganizationState, + OrganizationPreferences, AppNotification, AppNotificationsState, AppNotificationSeverity, AppNotificationTimeout, + DashboardSearchHit, + UserState, }; export interface StoreState { @@ -92,5 +99,7 @@ export interface StoreState { dashboard: DashboardState; dataSources: DataSourcesState; users: UsersState; + organization: OrganizationState; appNotifications: AppNotificationsState; + user: UserState; } diff --git a/public/app/types/organization.ts b/public/app/types/organization.ts new file mode 100644 index 00000000000..52cb130e082 --- /dev/null +++ b/public/app/types/organization.ts @@ -0,0 +1,15 @@ +export interface Organization { + name: string; + id: number; +} + +export interface OrganizationPreferences { + homeDashboardId: number; + theme: string; + timezone: string; +} + +export interface OrganizationState { + organization: Organization; + preferences: OrganizationPreferences; +} diff --git a/public/app/types/plugins.ts b/public/app/types/plugins.ts index 826ce2d48ec..1b5499f88b7 100644 --- a/public/app/types/plugins.ts +++ b/public/app/types/plugins.ts @@ -6,6 +6,8 @@ export interface PluginExports { ConfigCtrl?: any; AnnotationsQueryCtrl?: any; PanelOptions?: any; + ExploreQueryField?: any; + ExploreStartPage?: any; } export interface PanelPlugin { @@ -25,6 +27,12 @@ export interface PluginMeta { name: string; info: PluginMetaInfo; includes: PluginInclude[]; + + // Datasource-specific + metrics?: boolean; + logs?: boolean; + explore?: boolean; + annotations?: boolean; } export interface PluginInclude { diff --git a/public/app/types/search.ts b/public/app/types/search.ts new file mode 100644 index 00000000000..e5e17288de1 --- /dev/null +++ b/public/app/types/search.ts @@ -0,0 +1,9 @@ +export interface DashboardSearchHit { + id: number; + tags: string[]; + title: string; + type: string; + uid: string; + uri: string; + url: string; +} diff --git a/public/app/types/user.ts b/public/app/types/user.ts index c0b7b135ff8..37c80074dca 100644 --- a/public/app/types/user.ts +++ b/public/app/types/user.ts @@ -1,4 +1,6 @@ -export interface OrgUser { +import { DashboardSearchHit } from './search'; + +export interface OrgUser { avatarUrl: string; email: string; lastSeenAt: string; @@ -43,3 +45,7 @@ export interface UsersState { externalUserMngInfo: string; hasFetched: boolean; } + +export interface UserState { + starredDashboards: DashboardSearchHit[]; +} diff --git a/public/img/grafana_enterprise_typelogo.svg b/public/img/grafana_enterprise_typelogo.svg new file mode 100644 index 00000000000..30ee925787e --- /dev/null +++ b/public/img/grafana_enterprise_typelogo.svg @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/public/img/grafana_typelogo.svg b/public/img/grafana_typelogo.svg new file mode 100644 index 00000000000..bfceac7a78d --- /dev/null +++ b/public/img/grafana_typelogo.svg @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/public/sass/_old_responsive.scss b/public/sass/_old_responsive.scss index 991b0f30aa1..cfe74d03bb1 100644 --- a/public/sass/_old_responsive.scss +++ b/public/sass/_old_responsive.scss @@ -10,6 +10,7 @@ max-width: 120px; } +.navbar-buttons--tv, .navbar-buttons--actions { display: none; } @@ -35,6 +36,7 @@ } @include media-breakpoint-up(md) { + .navbar-buttons--tv, .navbar-buttons--actions { display: flex; } diff --git a/public/sass/components/_footer.scss b/public/sass/components/_footer.scss index 3c30f5a5798..9bc99c30d1d 100644 --- a/public/sass/components/_footer.scss +++ b/public/sass/components/_footer.scss @@ -40,15 +40,15 @@ .login-page { .footer { + bottom: $spacer; + position: absolute; padding: 1rem 0 1rem 0; } } -@include media-breakpoint-up(md) { +@include media-breakpoint-up(sm) { .login-page { .footer { - bottom: $spacer; - position: absolute; padding: 5rem 0 1rem 0; } } diff --git a/public/sass/components/_panel_graph.scss b/public/sass/components/_panel_graph.scss index 63d9169a4f8..9f7a9575b61 100644 --- a/public/sass/components/_panel_graph.scss +++ b/public/sass/components/_panel_graph.scss @@ -14,7 +14,7 @@ .graph-legend-series { display: block; - padding-left: 0px; + padding-left: 4px; } .graph-legend-table .graph-legend-series { @@ -28,6 +28,7 @@ position: relative; cursor: crosshair; flex-grow: 1; + min-height: 65%; } .datapoints-warning { @@ -46,15 +47,12 @@ .graph-legend { display: flex; flex: 0 1 auto; - max-height: 30%; + max-height: 35%; margin: 0; text-align: center; padding-top: 6px; position: relative; - // fix for Firefox (white stripe on the right of scrollbar) - width: calc(100% - 1px); - .popover-content { padding: 0; } @@ -62,15 +60,6 @@ .graph-legend-content { position: relative; - - // fix for Firefox (white stripe on the right of scrollbar) - width: calc(100% - 1px); -} - -.graph-legend-scroll { - position: relative; - overflow: auto !important; - padding: 1px; } .graph-legend-icon { @@ -82,8 +71,8 @@ .graph-legend-icon, .graph-legend-alias, .graph-legend-value { + display: inline; cursor: pointer; - float: left; white-space: nowrap; font-size: 85%; text-align: left; @@ -120,6 +109,11 @@ } } +// Don't move series to the right if legend is on the right as well +.graph-panel--legend-right .graph-legend-series--right-y { + float: left; +} + .graph-legend-value { padding-left: 6px; } @@ -128,7 +122,8 @@ .body--phantomjs { .graph-panel--legend-right { .graph-legend { - display: inline-block; + display: block; + max-width: min-content; } .graph-panel__chart { @@ -138,24 +133,14 @@ .graph-legend-table { display: table; width: auto; - - .graph-legend-scroll { - display: table; - } } } } .graph-legend-table { - tbody { - display: block; - position: relative; - overflow-y: auto; - overflow-x: hidden; - padding-bottom: 1px; - padding-right: 5px; - padding-left: 5px; - } + padding-bottom: 1px; + padding-right: 5px; + padding-left: 5px; .graph-legend-series { display: table-row; diff --git a/public/sass/pages/_explore.scss b/public/sass/pages/_explore.scss index a3f60f2006b..b70b058879c 100644 --- a/public/sass/pages/_explore.scss +++ b/public/sass/pages/_explore.scss @@ -52,7 +52,7 @@ } .result-options { - margin-top: 2 * $panel-margin; + margin: 2 * $panel-margin 0; } .time-series-disclaimer { @@ -87,7 +87,7 @@ flex-wrap: wrap; } - .explore-graph__loader { + .explore-panel__loader { height: 2px; position: relative; overflow: hidden; @@ -95,7 +95,7 @@ margin: $panel-margin / 2; } - .explore-graph__loader:after { + .explore-panel__loader:after { content: ' '; display: block; width: 25%; @@ -219,7 +219,13 @@ } .logs-row-match-highlight { - background-color: lighten($blue, 20%); + // Undoing mark styling + background: inherit; + padding: inherit; + + color: $typeahead-selected-color; + border-bottom: 1px solid $typeahead-selected-color; + background-color: lighten($typeahead-selected-color, 60%); } .logs-row-level { @@ -258,6 +264,11 @@ .prom-query-field-info { margin: 0.25em 0.5em 0.5em; + display: flex; + + details { + margin-left: 1em; + } } } @@ -317,3 +328,29 @@ .ReactTable .rt-tr .rt-td:last-child { text-align: right; } + +// React-component cascade fix: show "loading" even though item can expand + +.rc-cascader-menu-item-loading:after { + position: absolute; + right: 12px; + content: 'loading'; + color: #767980; + font-style: italic; +} + +// TODO Experimental + +.cheat-sheet-item { + margin: 2*$panel-margin 0; + width: 50%; +} + +.cheat-sheet-item__title { + font-size: $font-size-h3; +} + +.cheat-sheet-item__expression { + margin: $panel-margin/2 0; + cursor: pointer; +} diff --git a/public/sass/pages/_login.scss b/public/sass/pages/_login.scss index 8e5c8f33e37..4baff47b2a8 100644 --- a/public/sass/pages/_login.scss +++ b/public/sass/pages/_login.scss @@ -1,7 +1,7 @@ $login-border: #8daac5; .login { - min-height: 85vh; + min-height: 100vh; background-position: center; background-repeat: no-repeat; min-width: 100%; @@ -97,6 +97,7 @@ select:-webkit-autofill:focus { .login-content { max-width: 700px; + width: 100%; display: flex; align-items: stretch; flex-direction: column; @@ -120,18 +121,29 @@ select:-webkit-autofill:focus { width: 70px; margin-bottom: 15px; } +} - .icon-gf-grafana_wordmark { - color: darken($white, 11%); - position: relative; - font-size: 2rem; - text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); +.app-grafana { + .logo-wordmark { + background: url('../img/grafana_typelogo.svg') top center no-repeat; + width: 100%; + height: 70px; + } +} + +.app-enterprise { + .logo-wordmark { + background: url('../img/grafana_enterprise_typelogo.svg') top center no-repeat; + width: 100%; + height: 70px; } } .login-outer-box { display: flex; overflow-y: hidden; + align-items: center; + justify-content: center; } .login-inner-box { @@ -143,6 +155,7 @@ select:-webkit-autofill:focus { justify-content: center; flex-grow: 1; max-width: 415px; + width: 100%; transform: tranlate(0px, 0px); transition: 0.25s ease; @@ -324,23 +337,19 @@ select:-webkit-autofill:focus { } @include media-breakpoint-up(sm) { - .login-content { - flex-direction: row; - } - .login-branding { - width: 35%; - padding: 4rem 2rem; - border-right: 1px solid $login-border; + padding: 1rem; .logo-icon { width: 80px; } } +} - .login-inner-box { - width: 65%; - padding: 1rem 2rem; +@include media-breakpoint-up(md) { + .login-content { + flex-direction: row; + flex: 1 0 100%; } .login-divider { @@ -348,29 +357,16 @@ select:-webkit-autofill:focus { width: 110px; } } -} - -@include media-breakpoint-up(md) { - .login { - min-height: 100vh; - } - - .login-content { - flex: 1 0 100%; - } .login-branding { width: 45%; - padding: 2rem 4rem; + padding: 2rem; flex-grow: 1; + border-right: 1px solid $login-border; .logo-icon { width: 130px; } - - .icon-gf-grafana_wordmark { - font-size: 3.2rem; - } } .login-inner-box { @@ -386,9 +382,7 @@ select:-webkit-autofill:focus { padding-top: 0; padding-left: 10px; } -} -@include media-breakpoint-up(lg) { .login-form-input { min-width: 300px; } diff --git a/public/views/error.html b/public/views/error-template.html similarity index 98% rename from public/views/error.html rename to public/views/error-template.html index 5c51e28eff4..af430fc6c3d 100644 --- a/public/views/error.html +++ b/public/views/error-template.html @@ -10,7 +10,7 @@ - + diff --git a/public/views/index.template.html b/public/views/index-template.html similarity index 94% rename from public/views/index.template.html rename to public/views/index-template.html index ced39d9af28..096684d3e37 100644 --- a/public/views/index.template.html +++ b/public/views/index-template.html @@ -14,22 +14,18 @@ + + + - +