tablegenerator.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package printers
  14. import (
  15. "fmt"
  16. "reflect"
  17. "k8s.io/apimachinery/pkg/api/meta"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  21. )
  22. // GenerateOptions encapsulates attributes for table generation.
  23. type GenerateOptions struct {
  24. NoHeaders bool
  25. Wide bool
  26. }
  27. // TableGenerator - an interface for generating metav1.Table provided a runtime.Object
  28. type TableGenerator interface {
  29. GenerateTable(obj runtime.Object, options GenerateOptions) (*metav1.Table, error)
  30. }
  31. // PrintHandler - interface to handle printing provided an array of metav1.TableColumnDefinition
  32. type PrintHandler interface {
  33. TableHandler(columns []metav1.TableColumnDefinition, printFunc interface{}) error
  34. }
  35. type handlerEntry struct {
  36. columnDefinitions []metav1.TableColumnDefinition
  37. printFunc reflect.Value
  38. }
  39. // HumanReadableGenerator is an implementation of TableGenerator used to generate
  40. // a table for a specific resource. The table is printed with a TablePrinter using
  41. // PrintObj().
  42. type HumanReadableGenerator struct {
  43. handlerMap map[reflect.Type]*handlerEntry
  44. }
  45. var _ TableGenerator = &HumanReadableGenerator{}
  46. var _ PrintHandler = &HumanReadableGenerator{}
  47. // NewTableGenerator creates a HumanReadableGenerator suitable for calling GenerateTable().
  48. func NewTableGenerator() *HumanReadableGenerator {
  49. return &HumanReadableGenerator{
  50. handlerMap: make(map[reflect.Type]*handlerEntry),
  51. }
  52. }
  53. // With method - accepts a list of builder functions that modify HumanReadableGenerator
  54. func (h *HumanReadableGenerator) With(fns ...func(PrintHandler)) *HumanReadableGenerator {
  55. for _, fn := range fns {
  56. fn(h)
  57. }
  58. return h
  59. }
  60. // GenerateTable returns a table for the provided object, using the printer registered for that type. It returns
  61. // a table that includes all of the information requested by options, but will not remove rows or columns. The
  62. // caller is responsible for applying rules related to filtering rows or columns.
  63. func (h *HumanReadableGenerator) GenerateTable(obj runtime.Object, options GenerateOptions) (*metav1.Table, error) {
  64. t := reflect.TypeOf(obj)
  65. handler, ok := h.handlerMap[t]
  66. if !ok {
  67. return nil, fmt.Errorf("no table handler registered for this type %v", t)
  68. }
  69. args := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(options)}
  70. results := handler.printFunc.Call(args)
  71. if !results[1].IsNil() {
  72. return nil, results[1].Interface().(error)
  73. }
  74. var columns []metav1.TableColumnDefinition
  75. if !options.NoHeaders {
  76. columns = handler.columnDefinitions
  77. if !options.Wide {
  78. columns = make([]metav1.TableColumnDefinition, 0, len(handler.columnDefinitions))
  79. for i := range handler.columnDefinitions {
  80. if handler.columnDefinitions[i].Priority != 0 {
  81. continue
  82. }
  83. columns = append(columns, handler.columnDefinitions[i])
  84. }
  85. }
  86. }
  87. table := &metav1.Table{
  88. ListMeta: metav1.ListMeta{
  89. ResourceVersion: "",
  90. },
  91. ColumnDefinitions: columns,
  92. Rows: results[0].Interface().([]metav1.TableRow),
  93. }
  94. if m, err := meta.ListAccessor(obj); err == nil {
  95. table.ResourceVersion = m.GetResourceVersion()
  96. table.SelfLink = m.GetSelfLink()
  97. table.Continue = m.GetContinue()
  98. table.RemainingItemCount = m.GetRemainingItemCount()
  99. } else {
  100. if m, err := meta.CommonAccessor(obj); err == nil {
  101. table.ResourceVersion = m.GetResourceVersion()
  102. table.SelfLink = m.GetSelfLink()
  103. }
  104. }
  105. return table, nil
  106. }
  107. // TableHandler adds a print handler with a given set of columns to HumanReadableGenerator instance.
  108. // See ValidateRowPrintHandlerFunc for required method signature.
  109. func (h *HumanReadableGenerator) TableHandler(columnDefinitions []metav1.TableColumnDefinition, printFunc interface{}) error {
  110. printFuncValue := reflect.ValueOf(printFunc)
  111. if err := ValidateRowPrintHandlerFunc(printFuncValue); err != nil {
  112. utilruntime.HandleError(fmt.Errorf("unable to register print function: %v", err))
  113. return err
  114. }
  115. entry := &handlerEntry{
  116. columnDefinitions: columnDefinitions,
  117. printFunc: printFuncValue,
  118. }
  119. objType := printFuncValue.Type().In(0)
  120. if _, ok := h.handlerMap[objType]; ok {
  121. err := fmt.Errorf("registered duplicate printer for %v", objType)
  122. utilruntime.HandleError(err)
  123. return err
  124. }
  125. h.handlerMap[objType] = entry
  126. return nil
  127. }
  128. // ValidateRowPrintHandlerFunc validates print handler signature.
  129. // printFunc is the function that will be called to print an object.
  130. // It must be of the following type:
  131. // func printFunc(object ObjectType, options GenerateOptions) ([]metav1.TableRow, error)
  132. // where ObjectType is the type of the object that will be printed, and the first
  133. // return value is an array of rows, with each row containing a number of cells that
  134. // match the number of columns defined for that printer function.
  135. func ValidateRowPrintHandlerFunc(printFunc reflect.Value) error {
  136. if printFunc.Kind() != reflect.Func {
  137. return fmt.Errorf("invalid print handler. %#v is not a function", printFunc)
  138. }
  139. funcType := printFunc.Type()
  140. if funcType.NumIn() != 2 || funcType.NumOut() != 2 {
  141. return fmt.Errorf("invalid print handler." +
  142. "Must accept 2 parameters and return 2 value")
  143. }
  144. if funcType.In(1) != reflect.TypeOf((*GenerateOptions)(nil)).Elem() ||
  145. funcType.Out(0) != reflect.TypeOf((*[]metav1.TableRow)(nil)).Elem() ||
  146. funcType.Out(1) != reflect.TypeOf((*error)(nil)).Elem() {
  147. return fmt.Errorf("invalid print handler. The expected signature is: "+
  148. "func handler(obj %v, options GenerateOptions) ([]metav1.TableRow, error)", funcType.In(0))
  149. }
  150. return nil
  151. }