/
options.go
461 lines (414 loc) · 13.6 KB
/
options.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package graph
// Options.go holds the option settings for a single graph request.
import (
"context"
"fmt"
net_http "net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/prometheus/common/model"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/kiali/kiali/business"
"github.com/kiali/kiali/business/authentication"
"github.com/kiali/kiali/config"
"github.com/kiali/kiali/log"
)
// The supported vendors
const (
VendorCytoscape string = "cytoscape"
VendorIstio string = "istio"
defaultConfigVendor string = VendorCytoscape
defaultTelemetryVendor string = VendorIstio
)
const (
BoxByApp string = "app"
BoxByCluster string = "cluster"
BoxByNamespace string = "namespace"
BoxByNone string = "none"
RateNone string = "none"
RateReceived string = "received" // tcp bytes received, grpc response messages, etc
RateRequests string = "requests" // request count
RateSent string = "sent" // tcp bytes sent, grpc request messages, etc
RateTotal string = "total" // Sent+Received
defaultBoxBy string = BoxByNone
defaultDuration string = "10m"
defaultGraphType string = GraphTypeWorkload
defaultIncludeIdleEdges bool = false
defaultInjectServiceNodes bool = false
defaultRateGrpc string = RateRequests
defaultRateHttp string = RateRequests
defaultRateTcp string = RateSent
)
const (
graphKindNamespace string = "namespace"
graphKindNode string = "node"
)
// NodeOptions are those that apply only to node-detail graphs
type NodeOptions struct {
Aggregate string
AggregateValue string
App string
Cluster string
Namespace string
Service string
Version string
Workload string
}
// CommonOptions are those supplied to Telemetry and Config Vendors
type CommonOptions struct {
Duration time.Duration
GraphType string
Params url.Values // make available the raw query params for vendor-specific handling
QueryTime int64 // unix time in seconds
}
// ConfigOptions are those supplied to Config Vendors
type ConfigOptions struct {
BoxBy string
CommonOptions
}
type RequestedAppenders struct {
All bool
AppenderNames []string
}
type RequestedRates struct {
Grpc string
Http string
Tcp string
}
// ClusterSensitiveKey is the recommended [string] type for maps keying on a cluster-sensitive name
type ClusterSensitiveKey = string
// GetClusterSensitiveKey returns a valid key for maps using a ClusterSensitiveKey
func GetClusterSensitiveKey(cluster, name string) ClusterSensitiveKey {
return fmt.Sprintf("%s:%s", cluster, name)
}
type AccessibleNamespace struct {
Cluster string
CreationTimestamp time.Time
Name string
}
// AccessibleNamepaces is a map with Key: ClusterSensitive namespace Key, Value: *AccessibleNamespace
type AccessibleNamespaces map[ClusterSensitiveKey]*AccessibleNamespace
// TelemetryOptions are those supplied to Telemetry Vendors
type TelemetryOptions struct {
AccessibleNamespaces AccessibleNamespaces
Appenders RequestedAppenders // requested appenders, nil if param not supplied
IncludeIdleEdges bool // include edges with request rates of 0
InjectServiceNodes bool // inject destination service nodes between source and destination nodes.
Namespaces NamespaceInfoMap
Rates RequestedRates
CommonOptions
NodeOptions
}
// Options comprises all available options
type Options struct {
ConfigVendor string
TelemetryVendor string
ConfigOptions
TelemetryOptions
}
func NewOptions(r *net_http.Request) Options {
// path variables (0 or more will be set)
vars := mux.Vars(r)
aggregate := vars["aggregate"]
aggregateValue := vars["aggregateValue"]
app := vars["app"]
namespace := vars["namespace"]
service := vars["service"]
version := vars["version"]
workload := vars["workload"]
// query params
params := r.URL.Query()
var duration model.Duration
var includeIdleEdges bool
var injectServiceNodes bool
var queryTime int64
appenders := RequestedAppenders{All: true}
boxBy := params.Get("boxBy")
// @TODO requires refactoring to use clusterNameFromQuery
cluster := params.Get("clusterName")
configVendor := params.Get("configVendor")
durationString := params.Get("duration")
graphType := params.Get("graphType")
includeIdleEdgesString := params.Get("includeIdleEdges")
injectServiceNodesString := params.Get("injectServiceNodes")
namespaces := params.Get("namespaces") // csl of namespaces
queryTimeString := params.Get("queryTime")
rateGrpc := params.Get("rateGrpc")
rateHttp := params.Get("rateHttp")
rateTcp := params.Get("rateTcp")
telemetryVendor := params.Get("telemetryVendor")
if _, ok := params["appenders"]; ok {
appenderNames := strings.Split(params.Get("appenders"), ",")
for i, appenderName := range appenderNames {
appenderNames[i] = strings.TrimSpace(appenderName)
}
appenders = RequestedAppenders{All: false, AppenderNames: appenderNames}
}
if cluster == "" {
cluster = Unknown
}
if configVendor == "" {
configVendor = defaultConfigVendor
} else if configVendor != VendorCytoscape {
BadRequest(fmt.Sprintf("Invalid configVendor [%s]", configVendor))
}
if durationString == "" {
duration, _ = model.ParseDuration(defaultDuration)
} else {
var durationErr error
duration, durationErr = model.ParseDuration(durationString)
if durationErr != nil {
BadRequest(fmt.Sprintf("Invalid duration [%s]", durationString))
}
}
if graphType == "" {
graphType = defaultGraphType
} else if graphType != GraphTypeApp && graphType != GraphTypeService && graphType != GraphTypeVersionedApp && graphType != GraphTypeWorkload {
BadRequest(fmt.Sprintf("Invalid graphType [%s]", graphType))
}
// service graphs do not inject service nodes
if graphType == GraphTypeService {
injectServiceNodesString = "false"
}
// app node graphs require an app graph type
if app != "" && graphType != GraphTypeApp && graphType != GraphTypeVersionedApp {
BadRequest(fmt.Sprintf("Invalid graphType [%s]. This node detail graph supports only graphType app or versionedApp.", graphType))
}
if boxBy == "" {
boxBy = defaultBoxBy
} else {
for _, box := range strings.Split(boxBy, ",") {
switch strings.TrimSpace(box) {
case BoxByApp:
continue
case BoxByCluster:
continue
case BoxByNamespace:
continue
default:
BadRequest(fmt.Sprintf("Invalid boxBy [%s]", boxBy))
}
}
}
if includeIdleEdgesString == "" {
includeIdleEdges = defaultIncludeIdleEdges
} else {
var includeIdleEdgesErr error
includeIdleEdges, includeIdleEdgesErr = strconv.ParseBool(includeIdleEdgesString)
if includeIdleEdgesErr != nil {
BadRequest(fmt.Sprintf("Invalid includeIdleEdges [%s]", includeIdleEdgesString))
}
}
if injectServiceNodesString == "" {
injectServiceNodes = defaultInjectServiceNodes
} else {
var injectServiceNodesErr error
injectServiceNodes, injectServiceNodesErr = strconv.ParseBool(injectServiceNodesString)
if injectServiceNodesErr != nil {
BadRequest(fmt.Sprintf("Invalid injectServiceNodes [%s]", injectServiceNodesString))
}
}
if queryTimeString == "" {
queryTime = time.Now().Unix()
} else {
var queryTimeErr error
queryTime, queryTimeErr = strconv.ParseInt(queryTimeString, 10, 64)
if queryTimeErr != nil {
BadRequest(fmt.Sprintf("Invalid queryTime [%s]", queryTimeString))
}
}
if telemetryVendor == "" {
telemetryVendor = defaultTelemetryVendor
} else if telemetryVendor != VendorIstio {
BadRequest(fmt.Sprintf("Invalid telemetryVendor [%s]", telemetryVendor))
}
// Process namespaces options:
namespaceMap := NewNamespaceInfoMap()
authInfoContext := authentication.GetAuthInfoContext(r.Context())
var authInfo *api.AuthInfo
if authInfoContext != nil {
if authInfoCheck, ok := authInfoContext.(*api.AuthInfo); !ok {
Error("authInfo is not of type *api.AuthInfo")
} else {
authInfo = authInfoCheck
}
} else {
Error("token missing in request context")
}
accessibleNamespaces := getAccessibleNamespaces(authInfo)
// If path variable is set then it is the only relevant namespace (it's a node graph)
// Else if namespaces query param is set it specifies the relevant namespaces
// Else error, at least one namespace is required.
if namespace != "" {
namespaces = namespace
}
if namespaces == "" {
BadRequest("At least one namespace must be specified via the namespaces query parameter.")
}
for _, namespaceName := range strings.Split(namespaces, ",") {
namespaceName = strings.TrimSpace(namespaceName)
var earliestCreationTimestamp *time.Time
for _, an := range accessibleNamespaces {
if namespaceName == an.Name {
if nil == earliestCreationTimestamp || earliestCreationTimestamp.After(an.CreationTimestamp) {
earliestCreationTimestamp = &an.CreationTimestamp
}
}
}
if nil == earliestCreationTimestamp {
Forbidden(fmt.Sprintf("Requested namespace [%s] is not accessible.", namespaceName))
} else {
namespaceMap[namespaceName] = NamespaceInfo{
Name: namespaceName,
Duration: getSafeNamespaceDuration(namespaceName, *earliestCreationTimestamp, time.Duration(duration), queryTime),
IsIstio: config.IsIstioNamespace(namespaceName),
}
}
}
// Process Rate Options
rates := RequestedRates{
Grpc: defaultRateGrpc,
Http: defaultRateHttp,
Tcp: defaultRateTcp,
}
if rateGrpc != "" {
switch rateGrpc {
case RateNone:
rates.Grpc = RateNone
case RateReceived:
rates.Grpc = RateReceived
case RateRequests:
rates.Grpc = RateRequests
case RateSent:
rates.Grpc = RateSent
case RateTotal:
rates.Grpc = RateTotal
default:
BadRequest(fmt.Sprintf("Invalid gRPC Rate [%s]", rateGrpc))
}
}
if rateHttp != "" {
switch rateHttp {
case RateNone:
rates.Http = RateNone
case RateRequests:
rates.Http = RateRequests
default:
BadRequest(fmt.Sprintf("Invalid HTTP Rate [%s]", rateHttp))
}
}
if rateTcp != "" {
switch rateTcp {
case RateNone:
rates.Tcp = RateNone
case RateReceived:
rates.Tcp = RateReceived
case RateSent:
rates.Tcp = RateSent
case RateTotal:
rates.Tcp = RateTotal
default:
BadRequest(fmt.Sprintf("Invalid TCP Rate [%s]", rateTcp))
}
}
// Service graphs require service injection
if graphType == GraphTypeService {
injectServiceNodes = true
}
options := Options{
ConfigVendor: configVendor,
TelemetryVendor: telemetryVendor,
ConfigOptions: ConfigOptions{
BoxBy: boxBy,
CommonOptions: CommonOptions{
Duration: time.Duration(duration),
GraphType: graphType,
Params: params,
QueryTime: queryTime,
},
},
TelemetryOptions: TelemetryOptions{
AccessibleNamespaces: accessibleNamespaces,
Appenders: appenders,
IncludeIdleEdges: includeIdleEdges,
InjectServiceNodes: injectServiceNodes,
Namespaces: namespaceMap,
Rates: rates,
CommonOptions: CommonOptions{
Duration: time.Duration(duration),
GraphType: graphType,
Params: params,
QueryTime: queryTime,
},
NodeOptions: NodeOptions{
Aggregate: aggregate,
AggregateValue: aggregateValue,
App: app,
Cluster: cluster,
Namespace: namespace,
Service: service,
Version: version,
Workload: workload,
},
},
}
return options
}
// GetGraphKind will return the kind of graph represented by the options.
func (o *TelemetryOptions) GetGraphKind() string {
if o.NodeOptions.App != "" ||
o.NodeOptions.Version != "" ||
o.NodeOptions.Workload != "" ||
o.NodeOptions.Service != "" {
return graphKindNode
}
return graphKindNamespace
}
// getAccessibleNamespaces returns a Set of all namespaces accessible to the user.
// The Set is implemented using the map convention. Each map entry is set to the
// creation timestamp of the namespace, to be used to ensure valid time ranges for
// queries against the namespace.
func getAccessibleNamespaces(authInfo *api.AuthInfo) AccessibleNamespaces {
// Get the namespaces
business, err := business.Get(authInfo)
CheckError(err)
namespaces, err := business.Namespace.GetNamespaces(context.TODO())
CheckError(err)
// Create a map to store the namespaces
accessibleNamespaces := make(AccessibleNamespaces)
for _, namespace := range namespaces {
accessibleNamespaces[GetClusterSensitiveKey(namespace.Cluster, namespace.Name)] = &AccessibleNamespace{
Cluster: namespace.Cluster,
CreationTimestamp: namespace.CreationTimestamp,
Name: namespace.Name,
}
}
return accessibleNamespaces
}
// getSafeNamespaceDuration returns a safe duration for the query. If queryTime-requestedDuration > namespace
// creation time just return the requestedDuration. Otherwise reduce the duration as needed to ensure the
// namespace existed for the entire time range. An error is generated if no safe duration exists (i.e. the
// queryTime precedes the namespace).
func getSafeNamespaceDuration(ns string, nsCreationTime time.Time, requestedDuration time.Duration, queryTime int64) time.Duration {
var endTime time.Time
safeDuration := requestedDuration
if !nsCreationTime.IsZero() {
if queryTime != 0 {
endTime = time.Unix(queryTime, 0)
} else {
endTime = time.Now()
}
nsLifetime := endTime.Sub(nsCreationTime)
if nsLifetime <= 0 {
BadRequest(fmt.Sprintf("Namespace [%s] did not exist at requested queryTime [%v]", ns, endTime))
}
if nsLifetime < safeDuration {
safeDuration = nsLifetime
log.Debugf("Reducing requestedDuration [%v] to safeDuration [%v]", requestedDuration, safeDuration)
}
}
return safeDuration
}