api_config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package api
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "github.com/torkelo/grafana-pro/pkg/bus"
  7. "github.com/torkelo/grafana-pro/pkg/middleware"
  8. m "github.com/torkelo/grafana-pro/pkg/models"
  9. )
  10. const configTemplate = `
  11. define(['settings'],
  12. function (Settings) {
  13. "use strict";
  14. return new Settings(%json%);
  15. });
  16. `
  17. type configJsTmplModel struct {
  18. DataSources []*m.DataSource
  19. }
  20. // TODO: cleanup this ugly code
  21. func renderConfig(data *configJsTmplModel) string {
  22. datasources := make(map[string]interface{})
  23. for i, ds := range data.DataSources {
  24. url := ds.Url
  25. if ds.Access == m.DS_ACCESS_PROXY {
  26. url = "/api/datasources/proxy/" + strconv.FormatInt(ds.Id, 10)
  27. }
  28. var dsMap = map[string]interface{}{
  29. "type": ds.Type,
  30. "url": url,
  31. }
  32. if ds.Type == m.DS_INFLUXDB {
  33. if ds.Access == m.DS_ACCESS_DIRECT {
  34. dsMap["username"] = ds.User
  35. dsMap["password"] = ds.Password
  36. dsMap["url"] = url + "/db/" + ds.Database
  37. }
  38. }
  39. // temp hack, first is always default
  40. // TODO: implement default ds account setting
  41. if i == 0 {
  42. dsMap["default"] = true
  43. }
  44. datasources[ds.Name] = dsMap
  45. }
  46. // add grafana backend data source
  47. datasources["grafana"] = map[string]interface{}{
  48. "type": "grafana",
  49. "url": "",
  50. "grafanaDB": true,
  51. }
  52. jsonObj := map[string]interface{}{
  53. "datasources": datasources,
  54. }
  55. buff, _ := json.Marshal(jsonObj)
  56. return strings.Replace(configTemplate, "%json%", string(buff), 1)
  57. }
  58. func GetConfigJS(c *middleware.Context) {
  59. query := m.GetDataSourcesQuery{AccountId: c.GetAccountId()}
  60. err := bus.Dispatch(&query)
  61. if err != nil {
  62. c.Handle(500, "cold not load data sources", err)
  63. return
  64. }
  65. vm := configJsTmplModel{DataSources: query.Result}
  66. configStr := renderConfig(&vm)
  67. if err != nil {
  68. c.Handle(500, "Failed to generate config.js", err)
  69. return
  70. }
  71. c.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
  72. c.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  73. c.Header().Set("Pragma", "no-cache")
  74. c.Header().Set("Expires", "0")
  75. c.WriteHeader(200)
  76. c.Write([]byte(configStr))
  77. }