-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtopology_inspect.go
More file actions
414 lines (350 loc) · 12.3 KB
/
topology_inspect.go
File metadata and controls
414 lines (350 loc) · 12.3 KB
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
package topology
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/spf13/cobra"
"github.com/stackvista/stackstate-cli/generated/stackstate_api"
"github.com/stackvista/stackstate-cli/internal/common"
"github.com/stackvista/stackstate-cli/internal/di"
"github.com/stackvista/stackstate-cli/internal/printer"
)
const UNKNOWN = "unknown"
type InspectArgs struct {
ComponentType string
Tags []string
Identifiers []string
Limit int
}
func InspectCommand(cli *di.Deps) *cobra.Command {
args := &InspectArgs{}
cmd := &cobra.Command{
Use: "inspect",
Short: "Inspect topology components",
Long: "Inspect topology components by type, tags, and identifiers. Displays component details and provides links to the UI.",
Example: `# inspect components of a specific type
sts topology inspect --type "otel service instance"
# inspect with tag filtering
sts topology inspect --type "otel service instance" --tag "service.namespace:opentelemetry-demo-demo-dev"
# inspect with multiple tags (ANDed)
sts topology inspect --type "otel service instance" \
--tag "service.namespace:opentelemetry-demo-demo-dev" \
--tag "service.name:accountingservice"
# inspect with identifier filtering
sts topology inspect --type "otel service instance" --identifier "urn:opentelemetry:..."
# inspect with limit on number of results
sts topology inspect --type "otel service instance" --limit 10
# inspect and display as JSON (includes component links)
sts topology inspect --type "otel service instance" -o json`,
RunE: cli.CmdRunEWithApi(func(cmd *cobra.Command, cli *di.Deps, api *stackstate_api.APIClient, serverInfo *stackstate_api.ServerInfo) common.CLIError {
return RunInspectCommand(cmd, cli, api, serverInfo, args)
}),
}
cmd.Flags().StringVar(&args.ComponentType, "type", "", "Component type (required)")
cmd.MarkFlagRequired("type") //nolint:errcheck
cmd.Flags().StringSliceVar(&args.Tags, "tag", []string{}, "Filter by tags in format 'tag-name:tag-value' (multiple allowed, ANDed together)")
cmd.Flags().StringSliceVar(&args.Identifiers, "identifier", []string{}, "Filter by component identifiers (multiple allowed, ANDed together)")
cmd.Flags().IntVar(&args.Limit, "limit", 0, "Maximum number of components to output (must be positive)")
return cmd
}
func RunInspectCommand(
_ *cobra.Command,
cli *di.Deps,
api *stackstate_api.APIClient,
_ *stackstate_api.ServerInfo,
args *InspectArgs,
) common.CLIError {
if args.Limit < 0 {
return common.NewExecutionError(fmt.Errorf("limit must be a positive number, got: %d", args.Limit))
}
query := buildSTQLQuery(args.ComponentType, args.Tags, args.Identifiers)
metadata := stackstate_api.NewQueryMetadata(
false,
false,
0,
false,
false,
false,
false,
false,
false,
true,
)
request := stackstate_api.NewViewSnapshotRequest(
query,
"0.0.1",
*metadata,
)
result, resp, err := api.SnapshotApi.QuerySnapshot(cli.Context).
ViewSnapshotRequest(*request).
Execute()
if err != nil {
return common.NewResponseError(err, resp)
}
// The `CmdRunEWithApi` ensures the current context is loaded, so it should be safe to access context properties
components, parseErr := parseSnapshotResponse(result, cli.CurrentContext.URL)
if parseErr != nil {
// Check if the error is a typed error from the response by examining the _type discriminator
if typedErr := handleSnapshotError(result.ViewSnapshotResponse, resp); typedErr != nil {
return typedErr
}
return common.NewExecutionError(parseErr)
}
// Apply limit if specified
if args.Limit > 0 && len(components) > args.Limit {
components = components[:args.Limit]
}
if cli.IsJson() {
cli.Printer.PrintJson(map[string]interface{}{
"components": components,
})
return nil
} else {
printTableOutput(cli, components)
}
return nil
}
func buildSTQLQuery(componentType string, tags []string, identifiers []string) string {
query := fmt.Sprintf(`type = "%s"`, componentType)
for _, tag := range tags {
query += fmt.Sprintf(` AND label = "%s"`, tag)
}
// Add identifier filters (ANDed with IN clause)
if len(identifiers) > 0 {
quotedIds := make([]string, len(identifiers))
for i, id := range identifiers {
quotedIds[i] = fmt.Sprintf(`"%s"`, id)
}
query += fmt.Sprintf(` AND identifier IN (%s)`, strings.Join(quotedIds, ", "))
}
return query
}
type Component struct {
ID int64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Identifiers []string `json:"identifiers"`
Tags []string `json:"tags"`
Properties map[string]interface{} `json:"properties"`
Layer map[string]interface{} `json:"layer"`
Domain map[string]interface{} `json:"domain"`
Link string `json:"link"`
}
type ComponentMetadata struct {
ComponentTypes map[string]string
Layers map[string]string
Domains map[string]string
}
// handleSnapshotError checks if the response is a typed error by examining the _type discriminator
func handleSnapshotError(respMap map[string]interface{}, resp *http.Response) common.CLIError {
if respMap == nil {
return nil
}
responseType, ok := respMap["_type"].(string)
if !ok {
return nil
}
// Note: the `View` prefix on the error types comes from the existing (Scala) DTO types
switch responseType {
case "ViewSnapshotFetchTimeout":
if usedTimeoutSeconds, ok := respMap["usedTimeoutSeconds"].(float64); ok {
message := fmt.Sprintf(
"Query timed out after %d seconds. Please refine your query to be more specific.",
int64(usedTimeoutSeconds),
)
return common.NewResponseError(fmt.Errorf("%s", message), resp)
}
case "ViewSnapshotTooManyActiveQueries":
message := "Too many active queries are running. Please try again later."
return common.NewResponseError(fmt.Errorf("%s", message), resp)
case "ViewSnapshotTopologySizeOverflow":
if maxSize, ok := respMap["maxSize"].(float64); ok {
message := fmt.Sprintf(
"Query result exceeded maximum size of %d components. Please refine your query to be more specific.",
int64(maxSize),
)
return common.NewResponseError(fmt.Errorf("%s", message), resp)
}
case "ViewSnapshotDataUnavailable":
if availableSinceEpochMs, ok := respMap["availableSinceEpochMs"].(float64); ok {
message := fmt.Sprintf(
"Requested data is not available. Data is available from %d (epoch ms) onwards.",
int64(availableSinceEpochMs),
)
return common.NewResponseError(fmt.Errorf("%s", message), resp)
}
}
return nil
}
func parseSnapshotResponse(
result *stackstate_api.QuerySnapshotResult,
baseURL string,
) ([]Component, error) {
// SnapshotResponse is already typed as map[string]interface{} from the generated API
respMap := result.ViewSnapshotResponse
if respMap == nil {
return nil, fmt.Errorf("response data is nil")
}
// Check if this is a Snapshot (success) or an error type
respType, ok := respMap["_type"].(string)
if !ok {
return nil, fmt.Errorf("response has no _type discriminator")
}
// Note: the `View` prefix on response type comes from the existing (Scala) DTO types
// If it's not a ViewSnapshot, it's an error type - return empty components and let error handler deal with it
if respType != "ViewSnapshot" {
return nil, fmt.Errorf("response is an error type: %s", respType)
}
metadata := parseMetadata(respMap)
// Parse components from the already-unmarshalled components field
var components []Component
if componentsSlice, ok := respMap["components"].([]interface{}); ok {
for _, comp := range componentsSlice {
if compMap, ok := comp.(map[string]interface{}); ok {
components = append(components, parseComponentFromMap(compMap, metadata, baseURL))
}
}
}
return components, nil
}
// metadataFieldMapping maps response JSON field names to the corresponding
// ComponentMetadata struct field setter. Used by parseMetadata to extract
// all metadata categories in a single loop.
var metadataFieldMapping = []struct {
field string
setter func(*ComponentMetadata, interface{})
}{
{"componentTypes", func(m *ComponentMetadata, val interface{}) { m.ComponentTypes = parseMetadataByIdentifier(val) }},
{"layers", func(m *ComponentMetadata, val interface{}) { m.Layers = parseMetadataByIdentifier(val) }},
{"domains", func(m *ComponentMetadata, val interface{}) { m.Domains = parseMetadataByIdentifier(val) }},
}
// parseMetadata extracts component type, layer, and domain metadata
// from the opaque Snapshot response using a table-driven approach.
func parseMetadata(respMap map[string]interface{}) ComponentMetadata {
metadata := ComponentMetadata{
ComponentTypes: make(map[string]string),
Layers: make(map[string]string),
Domains: make(map[string]string),
}
metadataMap, ok := respMap["metadata"].(map[string]interface{})
if !ok {
return metadata
}
for _, mapping := range metadataFieldMapping {
if fieldValue, ok := metadataMap[mapping.field]; ok {
mapping.setter(&metadata, fieldValue)
}
}
return metadata
}
// parseMetadataByIdentifier extracts metadata items by identifier.
func parseMetadataByIdentifier(metadataValue interface{}) map[string]string {
result := make(map[string]string)
if metadataValue == nil {
return result
}
items, ok := metadataValue.([]interface{})
if !ok {
return result
}
for _, item := range items {
if itemMap, ok := item.(map[string]interface{}); ok {
identifier, idOk := itemMap["identifier"].(string)
name, nameOk := itemMap["name"].(string)
if idOk && nameOk {
result[identifier] = name
}
}
}
return result
}
func parseComponentFromMap(compMap map[string]interface{}, metadata ComponentMetadata, baseURL string) Component {
comp := Component{
Identifiers: []string{},
Tags: []string{},
Properties: make(map[string]interface{}),
}
// Parse basic fields
if id, ok := compMap["id"].(float64); ok {
comp.ID = int64(id)
}
if name, ok := compMap["name"].(string); ok {
comp.Name = name
}
// Parse type from typeIdentifier and lookup from component type metadata
if typeIdentifier, ok := compMap["typeIdentifier"].(string); ok {
if typeName, found := metadata.ComponentTypes[typeIdentifier]; found {
comp.Type = typeName
} else {
comp.Type = UNKNOWN
}
}
// Parse identifiers
if identifiersRaw, ok := compMap["identifiers"].([]interface{}); ok {
for _, idRaw := range identifiersRaw {
if id, ok := idRaw.(string); ok {
comp.Identifiers = append(comp.Identifiers, id)
}
}
}
// Parse tags
if tagsRaw, ok := compMap["tags"].([]interface{}); ok {
for _, tagRaw := range tagsRaw {
if tag, ok := tagRaw.(string); ok {
comp.Tags = append(comp.Tags, tag)
}
}
}
// Parse properties
if propertiesRaw, ok := compMap["properties"].(map[string]interface{}); ok {
comp.Properties = propertiesRaw
}
// Parse layer and domain references
comp.Layer = parseComponentReference(compMap, "layerIdentifier", metadata.Layers)
comp.Domain = parseComponentReference(compMap, "domainIdentifier", metadata.Domains)
// Build link
if len(comp.Identifiers) > 0 {
comp.Link = buildComponentLink(baseURL, comp.Identifiers[0])
}
return comp
}
// parseComponentReference extracts a reference field (layer or domain)
// from a component and looks up its name in the provided metadata map.
// Returns a map with "identifier" and "name" keys, or nil if the field is not present.
func parseComponentReference(compMap map[string]interface{}, identifierFieldName string, metadataMap map[string]string) map[string]interface{} {
if refIdentifier, ok := compMap[identifierFieldName].(string); ok {
refName := UNKNOWN
if name, found := metadataMap[refIdentifier]; found {
refName = name
}
return map[string]interface{}{
"identifier": refIdentifier,
"name": refName,
}
}
return nil
}
func buildComponentLink(baseURL, identifier string) string {
encodedIdentifier := url.PathEscape(identifier)
return fmt.Sprintf("%s/#/components/%s", baseURL, encodedIdentifier)
}
func printTableOutput(
cli *di.Deps,
components []Component,
) {
var tableData [][]interface{}
for _, comp := range components {
identifiersStr := strings.Join(comp.Identifiers, ", ")
tableData = append(tableData, []interface{}{
comp.Name,
comp.Type,
identifiersStr,
})
}
cli.Printer.Table(printer.TableData{
Header: []string{"Name", "Type", "Identifiers"},
Data: tableData,
MissingTableDataMsg: printer.NotFoundMsg{Types: "components"},
})
}