help.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /*
  2. Copyright 2015 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 meta
  14. import (
  15. "fmt"
  16. "reflect"
  17. "k8s.io/apimachinery/pkg/conversion"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. )
  20. // IsListType returns true if the provided Object has a slice called Items
  21. func IsListType(obj runtime.Object) bool {
  22. // if we're a runtime.Unstructured, check whether this is a list.
  23. // TODO: refactor GetItemsPtr to use an interface that returns []runtime.Object
  24. if unstructured, ok := obj.(runtime.Unstructured); ok {
  25. return unstructured.IsList()
  26. }
  27. _, err := GetItemsPtr(obj)
  28. return err == nil
  29. }
  30. // GetItemsPtr returns a pointer to the list object's Items member.
  31. // If 'list' doesn't have an Items member, it's not really a list type
  32. // and an error will be returned.
  33. // This function will either return a pointer to a slice, or an error, but not both.
  34. func GetItemsPtr(list runtime.Object) (interface{}, error) {
  35. v, err := conversion.EnforcePtr(list)
  36. if err != nil {
  37. return nil, err
  38. }
  39. items := v.FieldByName("Items")
  40. if !items.IsValid() {
  41. return nil, fmt.Errorf("no Items field in %#v", list)
  42. }
  43. switch items.Kind() {
  44. case reflect.Interface, reflect.Ptr:
  45. target := reflect.TypeOf(items.Interface()).Elem()
  46. if target.Kind() != reflect.Slice {
  47. return nil, fmt.Errorf("items: Expected slice, got %s", target.Kind())
  48. }
  49. return items.Interface(), nil
  50. case reflect.Slice:
  51. return items.Addr().Interface(), nil
  52. default:
  53. return nil, fmt.Errorf("items: Expected slice, got %s", items.Kind())
  54. }
  55. }
  56. // EachListItem invokes fn on each runtime.Object in the list. Any error immediately terminates
  57. // the loop.
  58. func EachListItem(obj runtime.Object, fn func(runtime.Object) error) error {
  59. if unstructured, ok := obj.(runtime.Unstructured); ok {
  60. return unstructured.EachListItem(fn)
  61. }
  62. // TODO: Change to an interface call?
  63. itemsPtr, err := GetItemsPtr(obj)
  64. if err != nil {
  65. return err
  66. }
  67. items, err := conversion.EnforcePtr(itemsPtr)
  68. if err != nil {
  69. return err
  70. }
  71. len := items.Len()
  72. if len == 0 {
  73. return nil
  74. }
  75. takeAddr := false
  76. if elemType := items.Type().Elem(); elemType.Kind() != reflect.Ptr && elemType.Kind() != reflect.Interface {
  77. if !items.Index(0).CanAddr() {
  78. return fmt.Errorf("unable to take address of items in %T for EachListItem", obj)
  79. }
  80. takeAddr = true
  81. }
  82. for i := 0; i < len; i++ {
  83. raw := items.Index(i)
  84. if takeAddr {
  85. raw = raw.Addr()
  86. }
  87. switch item := raw.Interface().(type) {
  88. case *runtime.RawExtension:
  89. if err := fn(item.Object); err != nil {
  90. return err
  91. }
  92. case runtime.Object:
  93. if err := fn(item); err != nil {
  94. return err
  95. }
  96. default:
  97. obj, ok := item.(runtime.Object)
  98. if !ok {
  99. return fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  100. }
  101. if err := fn(obj); err != nil {
  102. return err
  103. }
  104. }
  105. }
  106. return nil
  107. }
  108. // ExtractList returns obj's Items element as an array of runtime.Objects.
  109. // Returns an error if obj is not a List type (does not have an Items member).
  110. func ExtractList(obj runtime.Object) ([]runtime.Object, error) {
  111. itemsPtr, err := GetItemsPtr(obj)
  112. if err != nil {
  113. return nil, err
  114. }
  115. items, err := conversion.EnforcePtr(itemsPtr)
  116. if err != nil {
  117. return nil, err
  118. }
  119. list := make([]runtime.Object, items.Len())
  120. for i := range list {
  121. raw := items.Index(i)
  122. switch item := raw.Interface().(type) {
  123. case runtime.RawExtension:
  124. switch {
  125. case item.Object != nil:
  126. list[i] = item.Object
  127. case item.Raw != nil:
  128. // TODO: Set ContentEncoding and ContentType correctly.
  129. list[i] = &runtime.Unknown{Raw: item.Raw}
  130. default:
  131. list[i] = nil
  132. }
  133. case runtime.Object:
  134. list[i] = item
  135. default:
  136. var found bool
  137. if list[i], found = raw.Addr().Interface().(runtime.Object); !found {
  138. return nil, fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  139. }
  140. }
  141. }
  142. return list, nil
  143. }
  144. // objectSliceType is the type of a slice of Objects
  145. var objectSliceType = reflect.TypeOf([]runtime.Object{})
  146. // SetList sets the given list object's Items member have the elements given in
  147. // objects.
  148. // Returns an error if list is not a List type (does not have an Items member),
  149. // or if any of the objects are not of the right type.
  150. func SetList(list runtime.Object, objects []runtime.Object) error {
  151. itemsPtr, err := GetItemsPtr(list)
  152. if err != nil {
  153. return err
  154. }
  155. items, err := conversion.EnforcePtr(itemsPtr)
  156. if err != nil {
  157. return err
  158. }
  159. if items.Type() == objectSliceType {
  160. items.Set(reflect.ValueOf(objects))
  161. return nil
  162. }
  163. slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
  164. for i := range objects {
  165. dest := slice.Index(i)
  166. if dest.Type() == reflect.TypeOf(runtime.RawExtension{}) {
  167. dest = dest.FieldByName("Object")
  168. }
  169. // check to see if you're directly assignable
  170. if reflect.TypeOf(objects[i]).AssignableTo(dest.Type()) {
  171. dest.Set(reflect.ValueOf(objects[i]))
  172. continue
  173. }
  174. src, err := conversion.EnforcePtr(objects[i])
  175. if err != nil {
  176. return err
  177. }
  178. if src.Type().AssignableTo(dest.Type()) {
  179. dest.Set(src)
  180. } else if src.Type().ConvertibleTo(dest.Type()) {
  181. dest.Set(src.Convert(dest.Type()))
  182. } else {
  183. return fmt.Errorf("item[%d]: can't assign or convert %v into %v", i, src.Type(), dest.Type())
  184. }
  185. }
  186. items.Set(slice)
  187. return nil
  188. }