Repository navigation
Expand file tree
/
Copy pathtableconvertor.go
More file actions
484 lines (440 loc) · 15.7 KB
/
Copy pathtableconvertor.go
File metadata and controls
484 lines (440 loc) · 15.7 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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package extensionapi
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"slices"
"strings"
apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiexttableconvertor "k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor"
kerrors "k8s.io/apimachinery/pkg/api/errors"
kmeta "k8s.io/apimachinery/pkg/api/meta"
metatable "k8s.io/apimachinery/pkg/api/meta/table"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/client-go/util/jsonpath"
)
var swaggerMetadataDescriptions = meta.ObjectMeta{}.SwaggerDoc()
type (
// JSONPathTableColumnDefinition is a definition of a column in a table that is populated.
//
// Must provide a JSONPath to extract the value from the custom resource.
JSONPathTableColumnDefinition struct {
meta.TableColumnDefinition
// JSONPath is a simple JSON path (i.e. with array notation) which is evaluated against
// each custom resource to produce the value for this column.
JSONPath string
}
_JSONPathTableColumnInternalDefinition = apiext.CustomResourceColumnDefinition
)
// JSONPathColumn returns a string-typed JSONPathTableColumnDefinition extracting the value
// at the given JSONPath.
//
// It is the shorthand for the common case, i.e. a column without format, description or priority.
func JSONPathColumn(name, jsonPath string) JSONPathTableColumnDefinition {
return JSONPathTableColumnDefinition{
TableColumnDefinition: meta.TableColumnDefinition{Name: name, Type: "string"},
JSONPath: jsonPath,
}
}
// NewJSONPathTableConvertor creates a new table convertor that uses JSONPath to extract values from custom resources.
//
// It relies on apiexttableconvertor.New to create the table convertor.
func NewJSONPathTableConvertor(definitions ...JSONPathTableColumnDefinition) (rest.TableConvertor, error) {
defs := make([]_JSONPathTableColumnInternalDefinition, 0, len(definitions)+1)
agePriority := int32(0)
for i := range definitions {
switch {
case definitions[i].Name == "":
return nil, fmt.Errorf("column definition must have a non-empty name")
case definitions[i].JSONPath == "":
return nil, fmt.Errorf("column definition %q must have a non-empty JSONPath", definitions[i].Name)
case definitions[i].Priority < 0:
return nil, fmt.Errorf("column definition %q must have a non-negative priority", definitions[i].Name)
}
desc := definitions[i].Description
if desc == "" {
// NB(thxCode): Avoid the default description generated by apiexttableconvertor.New.
desc = "Description to " + definitions[i].Name
}
if strings.HasPrefix(definitions[i].JSONPath, "{") {
if strings.HasSuffix(definitions[i].JSONPath, "}") {
definitions[i].JSONPath = definitions[i].JSONPath[1 : len(definitions[i].JSONPath)-1]
} else {
definitions[i].JSONPath = definitions[i].JSONPath[1:]
}
} else if strings.HasSuffix(definitions[i].JSONPath, "}") {
definitions[i].JSONPath = definitions[i].JSONPath[:len(definitions[i].JSONPath)-1]
}
defs = append(defs, _JSONPathTableColumnInternalDefinition{
Name: definitions[i].Name,
Description: desc,
Type: definitions[i].Type,
Format: definitions[i].Format,
JSONPath: definitions[i].JSONPath,
Priority: definitions[i].Priority,
})
if definitions[i].Priority > agePriority {
agePriority = definitions[i].Priority
}
}
defs = append(defs, _JSONPathTableColumnInternalDefinition{
Name: "Age",
Description: swaggerMetadataDescriptions["creationTimestamp"],
Type: "date",
JSONPath: ".metadata.creationTimestamp",
Priority: agePriority + 1,
})
defs = slices.CompactFunc(defs, func(a, b _JSONPathTableColumnInternalDefinition) bool {
return a.Name == b.Name
})
return apiexttableconvertor.New(defs)
}
type (
// JSONPathTemplateTableColumnDefinition is a definition of a column in a table that is populated.
//
// Unlike JSONPathTableColumnDefinition, the Template MAY contain multiple `{...}`
// expressions interleaved with literal text, allowing combined fields like
// `"{.status.cpu.onceMaxRequest}/{.status.cpu.remaining}"`.
//
// Combined fields are only honored for string-typed columns. For non-string columns
// (integer/number/boolean/date) only the first expression's first match is used.
//
// Missing values within a string template are rendered as `-`.
//
// Exactly one of Template or Render must be set. Render is the escape hatch for
// display logic that jsonpath cannot express (e.g. conditional rendering based on
// which sub-struct of a discriminated union is populated). When Render is set, the
// returned string is used verbatim as the cell value; the column's Type is ignored
// (the cell is treated as a string).
JSONPathTemplateTableColumnDefinition struct {
meta.TableColumnDefinition
// Template is a jsonpath template (kubectl `-o jsonpath` syntax) evaluated
// against each object to produce the value for this column.
Template string
// Render is a callback that produces the cell value directly from the typed
// object. It receives the same runtime.Object that OnList / OnGet returned.
// An empty return string yields an empty cell.
Render func(obj runtime.Object) string
}
_JSONPathTemplateTableColumn struct {
// path is non-nil for Template-based columns.
path *jsonpath.JSONPath
// isAction[i] is true if the i-th top-level node of the parsed template is an
// action (`{...}`); false if it is literal text. Aligned with the slices returned
// by jsonpath.JSONPath.FindResults. Only meaningful when path is non-nil.
isAction []bool
// render is non-nil for Render-based columns. Mutually exclusive with path.
render func(obj runtime.Object) string
}
_JSONPathTemplateTableConvertor struct {
headers []meta.TableColumnDefinition
columns []_JSONPathTemplateTableColumn
// needsUnstructured is true when at least one column is Template-based and
// therefore needs the object converted to unstructured for jsonpath.
needsUnstructured bool
}
)
// JSONPathTemplateColumn returns a string-typed JSONPathTemplateTableColumnDefinition
// rendering the given jsonpath template.
//
// It is the shorthand for the common case, i.e. a column without format, description or priority.
func JSONPathTemplateColumn(name, template string) JSONPathTemplateTableColumnDefinition {
return JSONPathTemplateTableColumnDefinition{
TableColumnDefinition: meta.TableColumnDefinition{Name: name, Type: "string"},
Template: template,
}
}
// RenderColumn returns a string-typed JSONPathTemplateTableColumnDefinition producing the cell
// value with the given callback.
//
// T must be the concrete type that OnList / OnGet returned, as the object is asserted to it
// before rendering.
func RenderColumn[T runtime.Object](name string, render func(obj T) string) JSONPathTemplateTableColumnDefinition {
return JSONPathTemplateTableColumnDefinition{
TableColumnDefinition: meta.TableColumnDefinition{Name: name, Type: "string"},
Render: func(obj runtime.Object) string {
return render(obj.(T))
},
}
}
// NewJSONPathTemplateTableConvertor creates a new table convertor that renders each column
// from a jsonpath template (kubectl `-o jsonpath` syntax).
//
// It supports multi-expression templates like `"{.a}/{.b}"` for string-typed columns,
// substituting `-` for any expression that resolves to a missing key.
func NewJSONPathTemplateTableConvertor(definitions ...JSONPathTemplateTableColumnDefinition) (rest.TableConvertor, error) {
c := &_JSONPathTemplateTableConvertor{
headers: []meta.TableColumnDefinition{
{Name: "Name", Type: "string", Format: "name", Description: swaggerMetadataDescriptions["name"]},
},
}
agePriority := int32(0)
seen := make(map[string]struct{}, len(definitions))
for i := range definitions {
def := &definitions[i]
hasTemplate := def.Template != ""
hasRender := def.Render != nil
switch {
case def.Name == "":
return nil, fmt.Errorf("column definition must have a non-empty name")
case hasTemplate == hasRender:
return nil, fmt.Errorf("column definition %q must set exactly one of Template or Render", def.Name)
case def.Priority < 0:
return nil, fmt.Errorf("column definition %q must have a non-negative priority", def.Name)
}
if _, dup := seen[def.Name]; dup {
continue
}
seen[def.Name] = struct{}{}
col := _JSONPathTemplateTableColumn{}
if hasTemplate {
// Parse twice: once to inspect the AST for text-vs-action slot classification,
// once into a JSONPath instance for execution. Parser is exported but the
// JSONPath.parser field is not, so we cannot share the AST between the two.
parser := jsonpath.NewParser(def.Name)
if err := parser.Parse(def.Template); err != nil {
return nil, fmt.Errorf("invalid template %q for column %q: %w", def.Template, def.Name, err)
}
col.isAction = make([]bool, len(parser.Root.Nodes))
for j, n := range parser.Root.Nodes {
_, isText := n.(*jsonpath.TextNode)
col.isAction[j] = !isText
}
col.path = jsonpath.New(def.Name).AllowMissingKeys(true)
if err := col.path.Parse(def.Template); err != nil {
return nil, fmt.Errorf("invalid template %q for column %q: %w", def.Template, def.Name, err)
}
c.needsUnstructured = true
} else {
col.render = def.Render
}
desc := def.Description
if desc == "" {
desc = "Description to " + def.Name
}
c.headers = append(c.headers, meta.TableColumnDefinition{
Name: def.Name,
Description: desc,
Type: def.Type,
Format: def.Format,
Priority: def.Priority,
})
c.columns = append(c.columns, col)
if def.Priority > agePriority {
agePriority = def.Priority
}
}
c.headers = append(c.headers, meta.TableColumnDefinition{
Name: "Age",
Description: swaggerMetadataDescriptions["creationTimestamp"],
Type: "date",
Priority: agePriority + 1,
})
return c, nil
}
func (c *_JSONPathTemplateTableConvertor) ConvertToTable(_ context.Context, obj, tableOptions runtime.Object) (*meta.Table, error) {
table := &meta.Table{}
if opt, ok := tableOptions.(*meta.TableOptions); !ok || !opt.NoHeaders {
table.ColumnDefinitions = c.headers
}
if m, err := kmeta.ListAccessor(obj); err == nil {
table.ResourceVersion = m.GetResourceVersion()
table.Continue = m.GetContinue()
table.RemainingItemCount = m.GetRemainingItemCount()
} else if m, err := kmeta.CommonAccessor(obj); err == nil {
table.ResourceVersion = m.GetResourceVersion()
}
// headers[0] is Name, headers[len-1] is Age, in between are the user-defined columns
// in the same order as c.columns.
customHeaders := c.headers[1 : len(c.headers)-1]
buf := &bytes.Buffer{}
var err error
table.Rows, err = metatable.MetaToTableRow(obj, func(obj runtime.Object, m meta.Object, name, age string) ([]any, error) {
cells := make([]any, 0, 2+len(c.columns))
cells = append(cells, name)
// Convert to unstructured only if any column needs jsonpath.
var data any
if c.needsUnstructured {
us, ok := obj.(runtime.Unstructured)
if !ok {
mm, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, err
}
us = &unstructured.Unstructured{Object: mm}
}
data = us.UnstructuredContent()
}
for i := range c.columns {
col := &c.columns[i]
header := &customHeaders[i]
if col.render != nil {
cells = append(cells, col.render(obj))
continue
}
results, ferr := col.path.FindResults(data)
if ferr != nil {
cells = append(cells, nil)
continue
}
if header.Type == "string" {
buf.Reset()
if err := renderCustomFieldString(buf, col.path, col.isAction, results); err != nil {
cells = append(cells, nil)
continue
}
cells = append(cells, buf.String())
continue
}
// Typed cell: pick the first match of the first action slot.
if len(results) == 0 || len(results[0]) == 0 {
cells = append(cells, nil)
continue
}
cells = append(cells, cellForJSONValue(header.Type, results[0][0].Interface()))
}
cells = append(cells, age)
return cells, nil
})
return table, err
}
// renderCustomFieldString interleaves text-node and action-node results from
// jsonpath.FindResults.
func renderCustomFieldString(buf *bytes.Buffer, path *jsonpath.JSONPath, isAction []bool, results [][]reflect.Value) error {
// In normal cases len(results) == len(isAction). If a range/end pair shifts the
// counts, fall back to the default Execute-style behavior for the trailing slots.
for i, slot := range results {
switch {
case i < len(isAction) && isAction[i] && len(slot) == 0:
// Nothing to do.
default:
if err := path.PrintResults(buf, slot); err != nil {
return err
}
}
}
return nil
}
// cellForJSONValue mirrors the unexported helper in
// k8s.io/apiextensions-apiserver/pkg/registry/customresource/tableconvertor.
func cellForJSONValue(headerType string, value any) any {
if value == nil {
return nil
}
switch headerType {
case "integer":
switch typed := value.(type) {
case int64:
return typed
case float64:
return int64(typed)
case json.Number:
if i64, err := typed.Int64(); err == nil {
return i64
}
}
case "number":
switch typed := value.(type) {
case int64:
return float64(typed)
case float64:
return typed
case json.Number:
if f, err := typed.Float64(); err == nil {
return f
}
}
case "boolean":
if b, ok := value.(bool); ok {
return b
}
case "string":
if s, ok := value.(string); ok {
return s
}
case "date":
if typed, ok := value.(string); ok {
var timestamp meta.Time
if err := timestamp.UnmarshalQueryParameter(typed); err != nil {
return "<invalid>"
}
return metatable.ConvertToHumanReadableDateType(timestamp)
}
}
return nil
}
type _DefaultTableColumnDefinition struct{}
// NewDefaultTableConvertor creates a default convertor.
//
// It borrows from k8s.io/apiserver/pkg/registry/rest.NewDefaultTableConvertor,
// but modify the latest column name.
func NewDefaultTableConvertor() rest.TableConvertor {
return _DefaultTableColumnDefinition{}
}
func (c _DefaultTableColumnDefinition) ConvertToTable(ctx context.Context, object, tableOptions runtime.Object) (*meta.Table, error) {
var table meta.Table
fn := func(obj runtime.Object) error {
m, err := kmeta.Accessor(obj)
if err != nil {
return &kerrors.StatusError{
ErrStatus: meta.Status{
Status: meta.StatusFailure,
Code: http.StatusNotAcceptable,
Reason: meta.StatusReasonNotAcceptable,
Message: fmt.Sprintf("do not support being converted to a Table: %v", err),
},
}
}
table.Rows = append(table.Rows, meta.TableRow{
Cells: []any{
m.GetName(),
metatable.ConvertToHumanReadableDateType(m.GetCreationTimestamp()),
},
Object: runtime.RawExtension{
Object: obj,
},
})
return nil
}
switch {
case kmeta.IsListType(object):
if err := kmeta.EachListItem(object, fn); err != nil {
return nil, err
}
default:
if err := fn(object); err != nil {
return nil, err
}
}
if m, err := kmeta.ListAccessor(object); err == nil {
table.ResourceVersion = m.GetResourceVersion()
table.Continue = m.GetContinue()
table.RemainingItemCount = m.GetRemainingItemCount()
} else {
if m, err := kmeta.CommonAccessor(object); err == nil {
table.ResourceVersion = m.GetResourceVersion()
}
}
if opt, ok := tableOptions.(*meta.TableOptions); !ok || !opt.NoHeaders {
table.ColumnDefinitions = []meta.TableColumnDefinition{
{
Name: "Name",
Description: swaggerMetadataDescriptions["name"],
Type: "string",
Format: "name",
},
{
Name: "Age",
Description: swaggerMetadataDescriptions["creationTimestamp"],
Type: "date",
},
}
}
return &table, nil
}