table_printer.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 get
  14. import (
  15. "fmt"
  16. "io"
  17. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  18. metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. "k8s.io/cli-runtime/pkg/printers"
  21. "k8s.io/klog"
  22. )
  23. // TablePrinter decodes table objects into typed objects before delegating to another printer.
  24. // Non-table types are simply passed through
  25. type TablePrinter struct {
  26. Delegate printers.ResourcePrinter
  27. }
  28. func (t *TablePrinter) PrintObj(obj runtime.Object, writer io.Writer) error {
  29. table, err := decodeIntoTable(obj)
  30. if err == nil {
  31. return t.Delegate.PrintObj(table, writer)
  32. }
  33. // if we are unable to decode server response into a v1beta1.Table,
  34. // fallback to client-side printing with whatever info the server returned.
  35. klog.V(2).Infof("Unable to decode server response into a Table. Falling back to hardcoded types: %v", err)
  36. return t.Delegate.PrintObj(obj, writer)
  37. }
  38. func decodeIntoTable(obj runtime.Object) (runtime.Object, error) {
  39. if obj.GetObjectKind().GroupVersionKind().Group != metav1beta1.GroupName {
  40. return nil, fmt.Errorf("attempt to decode non-Table object into a v1beta1.Table")
  41. }
  42. if obj.GetObjectKind().GroupVersionKind().Kind != "Table" {
  43. return nil, fmt.Errorf("attempt to decode non-Table object into a v1beta1.Table")
  44. }
  45. unstr, ok := obj.(*unstructured.Unstructured)
  46. if !ok {
  47. return nil, fmt.Errorf("attempt to decode non-Unstructured object")
  48. }
  49. table := &metav1beta1.Table{}
  50. if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstr.Object, table); err != nil {
  51. return nil, err
  52. }
  53. for i := range table.Rows {
  54. row := &table.Rows[i]
  55. if row.Object.Raw == nil || row.Object.Object != nil {
  56. continue
  57. }
  58. converted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, row.Object.Raw)
  59. if err != nil {
  60. return nil, err
  61. }
  62. row.Object.Object = converted
  63. }
  64. return table, nil
  65. }