customcolumn.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*
  2. Copyright 2014 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. "bufio"
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "reflect"
  20. "regexp"
  21. "strings"
  22. "github.com/liggitt/tabwriter"
  23. "k8s.io/apimachinery/pkg/api/meta"
  24. "k8s.io/apimachinery/pkg/runtime"
  25. "k8s.io/cli-runtime/pkg/printers"
  26. "k8s.io/client-go/util/jsonpath"
  27. utilprinters "k8s.io/kubernetes/pkg/kubectl/util/printers"
  28. )
  29. var jsonRegexp = regexp.MustCompile("^\\{\\.?([^{}]+)\\}$|^\\.?([^{}]+)$")
  30. // RelaxedJSONPathExpression attempts to be flexible with JSONPath expressions, it accepts:
  31. // * metadata.name (no leading '.' or curly braces '{...}'
  32. // * {metadata.name} (no leading '.')
  33. // * .metadata.name (no curly braces '{...}')
  34. // * {.metadata.name} (complete expression)
  35. // And transforms them all into a valid jsonpath expression:
  36. // {.metadata.name}
  37. func RelaxedJSONPathExpression(pathExpression string) (string, error) {
  38. if len(pathExpression) == 0 {
  39. return pathExpression, nil
  40. }
  41. submatches := jsonRegexp.FindStringSubmatch(pathExpression)
  42. if submatches == nil {
  43. return "", fmt.Errorf("unexpected path string, expected a 'name1.name2' or '.name1.name2' or '{name1.name2}' or '{.name1.name2}'")
  44. }
  45. if len(submatches) != 3 {
  46. return "", fmt.Errorf("unexpected submatch list: %v", submatches)
  47. }
  48. var fieldSpec string
  49. if len(submatches[1]) != 0 {
  50. fieldSpec = submatches[1]
  51. } else {
  52. fieldSpec = submatches[2]
  53. }
  54. return fmt.Sprintf("{.%s}", fieldSpec), nil
  55. }
  56. // NewCustomColumnsPrinterFromSpec creates a custom columns printer from a comma separated list of <header>:<jsonpath-field-spec> pairs.
  57. // e.g. NAME:metadata.name,API_VERSION:apiVersion creates a printer that prints:
  58. //
  59. // NAME API_VERSION
  60. // foo bar
  61. func NewCustomColumnsPrinterFromSpec(spec string, decoder runtime.Decoder, noHeaders bool) (*CustomColumnsPrinter, error) {
  62. if len(spec) == 0 {
  63. return nil, fmt.Errorf("custom-columns format specified but no custom columns given")
  64. }
  65. parts := strings.Split(spec, ",")
  66. columns := make([]Column, len(parts))
  67. for ix := range parts {
  68. colSpec := strings.SplitN(parts[ix], ":", 2)
  69. if len(colSpec) != 2 {
  70. return nil, fmt.Errorf("unexpected custom-columns spec: %s, expected <header>:<json-path-expr>", parts[ix])
  71. }
  72. spec, err := RelaxedJSONPathExpression(colSpec[1])
  73. if err != nil {
  74. return nil, err
  75. }
  76. columns[ix] = Column{Header: colSpec[0], FieldSpec: spec}
  77. }
  78. return &CustomColumnsPrinter{Columns: columns, Decoder: decoder, NoHeaders: noHeaders}, nil
  79. }
  80. func splitOnWhitespace(line string) []string {
  81. lineScanner := bufio.NewScanner(bytes.NewBufferString(line))
  82. lineScanner.Split(bufio.ScanWords)
  83. result := []string{}
  84. for lineScanner.Scan() {
  85. result = append(result, lineScanner.Text())
  86. }
  87. return result
  88. }
  89. // NewCustomColumnsPrinterFromTemplate creates a custom columns printer from a template stream. The template is expected
  90. // to consist of two lines, whitespace separated. The first line is the header line, the second line is the jsonpath field spec
  91. // For example, the template below:
  92. // NAME API_VERSION
  93. // {metadata.name} {apiVersion}
  94. func NewCustomColumnsPrinterFromTemplate(templateReader io.Reader, decoder runtime.Decoder) (*CustomColumnsPrinter, error) {
  95. scanner := bufio.NewScanner(templateReader)
  96. if !scanner.Scan() {
  97. return nil, fmt.Errorf("invalid template, missing header line. Expected format is one line of space separated headers, one line of space separated column specs.")
  98. }
  99. headers := splitOnWhitespace(scanner.Text())
  100. if !scanner.Scan() {
  101. return nil, fmt.Errorf("invalid template, missing spec line. Expected format is one line of space separated headers, one line of space separated column specs.")
  102. }
  103. specs := splitOnWhitespace(scanner.Text())
  104. if len(headers) != len(specs) {
  105. return nil, fmt.Errorf("number of headers (%d) and field specifications (%d) don't match", len(headers), len(specs))
  106. }
  107. columns := make([]Column, len(headers))
  108. for ix := range headers {
  109. spec, err := RelaxedJSONPathExpression(specs[ix])
  110. if err != nil {
  111. return nil, err
  112. }
  113. columns[ix] = Column{
  114. Header: headers[ix],
  115. FieldSpec: spec,
  116. }
  117. }
  118. return &CustomColumnsPrinter{Columns: columns, Decoder: decoder, NoHeaders: false}, nil
  119. }
  120. // Column represents a user specified column
  121. type Column struct {
  122. // The header to print above the column, general style is ALL_CAPS
  123. Header string
  124. // The pointer to the field in the object to print in JSONPath form
  125. // e.g. {.ObjectMeta.Name}, see pkg/util/jsonpath for more details.
  126. FieldSpec string
  127. }
  128. // CustomColumnPrinter is a printer that knows how to print arbitrary columns
  129. // of data from templates specified in the `Columns` array
  130. type CustomColumnsPrinter struct {
  131. Columns []Column
  132. Decoder runtime.Decoder
  133. NoHeaders bool
  134. // lastType records type of resource printed last so that we don't repeat
  135. // header while printing same type of resources.
  136. lastType reflect.Type
  137. }
  138. func (s *CustomColumnsPrinter) PrintObj(obj runtime.Object, out io.Writer) error {
  139. // we use reflect.Indirect here in order to obtain the actual value from a pointer.
  140. // we need an actual value in order to retrieve the package path for an object.
  141. // using reflect.Indirect indiscriminately is valid here, as all runtime.Objects are supposed to be pointers.
  142. if printers.InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {
  143. return fmt.Errorf(printers.InternalObjectPrinterErr)
  144. }
  145. if w, found := out.(*tabwriter.Writer); !found {
  146. w = utilprinters.GetNewTabWriter(out)
  147. out = w
  148. defer w.Flush()
  149. }
  150. t := reflect.TypeOf(obj)
  151. if !s.NoHeaders && t != s.lastType {
  152. headers := make([]string, len(s.Columns))
  153. for ix := range s.Columns {
  154. headers[ix] = s.Columns[ix].Header
  155. }
  156. fmt.Fprintln(out, strings.Join(headers, "\t"))
  157. s.lastType = t
  158. }
  159. parsers := make([]*jsonpath.JSONPath, len(s.Columns))
  160. for ix := range s.Columns {
  161. parsers[ix] = jsonpath.New(fmt.Sprintf("column%d", ix)).AllowMissingKeys(true)
  162. if err := parsers[ix].Parse(s.Columns[ix].FieldSpec); err != nil {
  163. return err
  164. }
  165. }
  166. if meta.IsListType(obj) {
  167. objs, err := meta.ExtractList(obj)
  168. if err != nil {
  169. return err
  170. }
  171. for ix := range objs {
  172. if err := s.printOneObject(objs[ix], parsers, out); err != nil {
  173. return err
  174. }
  175. }
  176. } else {
  177. if err := s.printOneObject(obj, parsers, out); err != nil {
  178. return err
  179. }
  180. }
  181. return nil
  182. }
  183. func (s *CustomColumnsPrinter) printOneObject(obj runtime.Object, parsers []*jsonpath.JSONPath, out io.Writer) error {
  184. columns := make([]string, len(parsers))
  185. switch u := obj.(type) {
  186. case *runtime.Unknown:
  187. if len(u.Raw) > 0 {
  188. var err error
  189. if obj, err = runtime.Decode(s.Decoder, u.Raw); err != nil {
  190. return fmt.Errorf("can't decode object for printing: %v (%s)", err, u.Raw)
  191. }
  192. }
  193. }
  194. for ix := range parsers {
  195. parser := parsers[ix]
  196. var values [][]reflect.Value
  197. var err error
  198. if unstructured, ok := obj.(runtime.Unstructured); ok {
  199. values, err = parser.FindResults(unstructured.UnstructuredContent())
  200. } else {
  201. values, err = parser.FindResults(reflect.ValueOf(obj).Elem().Interface())
  202. }
  203. if err != nil {
  204. return err
  205. }
  206. valueStrings := []string{}
  207. if len(values) == 0 || len(values[0]) == 0 {
  208. valueStrings = append(valueStrings, "<none>")
  209. }
  210. for arrIx := range values {
  211. for valIx := range values[arrIx] {
  212. valueStrings = append(valueStrings, fmt.Sprintf("%v", values[arrIx][valIx].Interface()))
  213. }
  214. }
  215. columns[ix] = strings.Join(valueStrings, ",")
  216. }
  217. fmt.Fprintln(out, strings.Join(columns, "\t"))
  218. return nil
  219. }