forked from kiali/kiali
/
grafana.go
157 lines (138 loc) · 4.78 KB
/
grafana.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package handlers
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/kiali/k-charted/kubernetes/v1alpha1"
kmodel "github.com/kiali/k-charted/model"
"github.com/kiali/kiali/config"
"github.com/kiali/kiali/log"
"github.com/kiali/kiali/models"
"github.com/kiali/kiali/status"
"github.com/kiali/kiali/util/httputil"
)
type dashboardSupplier func(string, string, *config.Auth) ([]byte, int, error)
// GetGrafanaInfo provides the Grafana URL and other info, first by checking if a config exists
// then (if not) by inspecting the Kubernetes Grafana service in Istio installation namespace
func GetGrafanaInfo(w http.ResponseWriter, r *http.Request) {
requestToken, err := getToken(r)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, "Token initialization error: "+err.Error())
return
}
info, code, err := getGrafanaInfo(requestToken, findDashboard)
if err != nil {
log.Error(err)
RespondWithError(w, code, err.Error())
return
}
RespondWithJSON(w, code, info)
}
// getGrafanaInfo returns the Grafana URL and other info, the HTTP status code (int) and eventually an error
func getGrafanaInfo(requestToken string, dashboardSupplier dashboardSupplier) (*models.GrafanaInfo, int, error) {
grafanaConfig := config.Get().ExternalServices.Grafana
if !grafanaConfig.Enabled {
return nil, http.StatusNoContent, nil
}
externalURL := status.DiscoverGrafana()
if externalURL == "" {
return nil, http.StatusServiceUnavailable, errors.New("grafana URL is not set in Kiali configuration")
}
// Check if URL is valid
_, err := validateURL(externalURL)
if err != nil {
return nil, http.StatusServiceUnavailable, errors.New("wrong format for Grafana URL: " + err.Error())
}
apiURL := externalURL
// Find the in-cluster URL to reach Grafana's REST API if properties demand so
if grafanaConfig.InClusterURL != "" {
apiURL = grafanaConfig.InClusterURL
}
// Be sure to copy config.Auth and not modify the existing
auth := grafanaConfig.Auth
if auth.UseKialiToken {
auth.Token = requestToken
}
// Call Grafana REST API to get dashboard urls
links := []kmodel.ExternalLink{}
urlParts := strings.Split(externalURL, "?")
for _, dashboardConfig := range grafanaConfig.Dashboards {
dashboardPath, err := getDashboardPath(apiURL, dashboardConfig.Name, &auth, dashboardSupplier)
if err != nil {
return nil, http.StatusServiceUnavailable, err
}
if dashboardPath != "" {
// E.g.: http://localhost:3000?orgId=1 transformed into http://localhost:3000/d/LJ_uJAvmk/istio-service-dashboard?orgId=1
externalURL = strings.TrimSuffix(urlParts[0], "/") + "/" + strings.TrimPrefix(dashboardPath, "/")
if len(urlParts) > 1 {
externalURL = externalURL + "?" + urlParts[1]
}
externalLink := kmodel.ExternalLink{
URL: externalURL,
Name: dashboardConfig.Name,
Variables: v1alpha1.MonitoringDashboardExternalLinkVariables{
App: dashboardConfig.Variables.App,
Namespace: dashboardConfig.Variables.Namespace,
Service: dashboardConfig.Variables.Service,
Version: dashboardConfig.Variables.Version,
Workload: dashboardConfig.Variables.Workload,
},
}
links = append(links, externalLink)
}
}
grafanaInfo := models.GrafanaInfo{
ExternalLinks: links,
}
return &grafanaInfo, http.StatusOK, nil
}
func getDashboardPath(basePath, name string, auth *config.Auth, dashboardSupplier dashboardSupplier) (string, error) {
body, code, err := dashboardSupplier(basePath, url.PathEscape(name), auth)
if err != nil {
return "", err
}
if code != http.StatusOK {
// Get error message
var f map[string]string
err = json.Unmarshal(body, &f)
if err != nil {
return "", fmt.Errorf("unknown error from Grafana (%d)", code)
}
message, ok := f["message"]
if !ok {
return "", fmt.Errorf("unknown error from Grafana (%d)", code)
}
return "", fmt.Errorf("error from Grafana (%d): %s", code, message)
}
// Status OK, read dashboards info
var dashboards []map[string]interface{}
err = json.Unmarshal(body, &dashboards)
if err != nil {
return "", err
}
if len(dashboards) == 0 {
log.Warningf("No Grafana dashboard found for pattern '%s'", name)
return "", nil
}
if len(dashboards) > 1 {
log.Infof("Several Grafana dashboards found for pattern '%s', picking the first one", name)
}
dashPath, ok := dashboards[0]["url"]
if !ok {
log.Warningf("URL field not found in Grafana dashboard for search pattern '%s'", name)
return "", nil
}
return dashPath.(string), nil
}
func findDashboard(url, searchPattern string, auth *config.Auth) ([]byte, int, error) {
urlParts := strings.Split(url, "?")
query := strings.TrimSuffix(urlParts[0], "/") + "/api/search?query=" + searchPattern
if len(urlParts) > 1 {
query = query + "&" + urlParts[1]
}
return httputil.HttpGet(query, auth, time.Second*10)
}