custom_column_printer.go 7.2 KB

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