help.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. "errors"
  16. "fmt"
  17. "reflect"
  18. "sync"
  19. "k8s.io/apimachinery/pkg/conversion"
  20. "k8s.io/apimachinery/pkg/runtime"
  21. )
  22. var (
  23. // isListCache maintains a cache of types that are checked for lists
  24. // which is used by IsListType.
  25. // TODO: remove and replace with an interface check
  26. isListCache = struct {
  27. lock sync.RWMutex
  28. byType map[reflect.Type]bool
  29. }{
  30. byType: make(map[reflect.Type]bool, 1024),
  31. }
  32. )
  33. // IsListType returns true if the provided Object has a slice called Items.
  34. // TODO: Replace the code in this check with an interface comparison by
  35. // creating and enforcing that lists implement a list accessor.
  36. func IsListType(obj runtime.Object) bool {
  37. switch t := obj.(type) {
  38. case runtime.Unstructured:
  39. return t.IsList()
  40. }
  41. t := reflect.TypeOf(obj)
  42. isListCache.lock.RLock()
  43. ok, exists := isListCache.byType[t]
  44. isListCache.lock.RUnlock()
  45. if !exists {
  46. _, err := getItemsPtr(obj)
  47. ok = err == nil
  48. // cache only the first 1024 types
  49. isListCache.lock.Lock()
  50. if len(isListCache.byType) < 1024 {
  51. isListCache.byType[t] = ok
  52. }
  53. isListCache.lock.Unlock()
  54. }
  55. return ok
  56. }
  57. var (
  58. errExpectFieldItems = errors.New("no Items field in this object")
  59. errExpectSliceItems = errors.New("Items field must be a slice of objects")
  60. )
  61. // GetItemsPtr returns a pointer to the list object's Items member.
  62. // If 'list' doesn't have an Items member, it's not really a list type
  63. // and an error will be returned.
  64. // This function will either return a pointer to a slice, or an error, but not both.
  65. // TODO: this will be replaced with an interface in the future
  66. func GetItemsPtr(list runtime.Object) (interface{}, error) {
  67. obj, err := getItemsPtr(list)
  68. if err != nil {
  69. return nil, fmt.Errorf("%T is not a list: %v", list, err)
  70. }
  71. return obj, nil
  72. }
  73. // getItemsPtr returns a pointer to the list object's Items member or an error.
  74. func getItemsPtr(list runtime.Object) (interface{}, error) {
  75. v, err := conversion.EnforcePtr(list)
  76. if err != nil {
  77. return nil, err
  78. }
  79. items := v.FieldByName("Items")
  80. if !items.IsValid() {
  81. return nil, errExpectFieldItems
  82. }
  83. switch items.Kind() {
  84. case reflect.Interface, reflect.Ptr:
  85. target := reflect.TypeOf(items.Interface()).Elem()
  86. if target.Kind() != reflect.Slice {
  87. return nil, errExpectSliceItems
  88. }
  89. return items.Interface(), nil
  90. case reflect.Slice:
  91. return items.Addr().Interface(), nil
  92. default:
  93. return nil, errExpectSliceItems
  94. }
  95. }
  96. // EachListItem invokes fn on each runtime.Object in the list. Any error immediately terminates
  97. // the loop.
  98. func EachListItem(obj runtime.Object, fn func(runtime.Object) error) error {
  99. if unstructured, ok := obj.(runtime.Unstructured); ok {
  100. return unstructured.EachListItem(fn)
  101. }
  102. // TODO: Change to an interface call?
  103. itemsPtr, err := GetItemsPtr(obj)
  104. if err != nil {
  105. return err
  106. }
  107. items, err := conversion.EnforcePtr(itemsPtr)
  108. if err != nil {
  109. return err
  110. }
  111. len := items.Len()
  112. if len == 0 {
  113. return nil
  114. }
  115. takeAddr := false
  116. if elemType := items.Type().Elem(); elemType.Kind() != reflect.Ptr && elemType.Kind() != reflect.Interface {
  117. if !items.Index(0).CanAddr() {
  118. return fmt.Errorf("unable to take address of items in %T for EachListItem", obj)
  119. }
  120. takeAddr = true
  121. }
  122. for i := 0; i < len; i++ {
  123. raw := items.Index(i)
  124. if takeAddr {
  125. raw = raw.Addr()
  126. }
  127. switch item := raw.Interface().(type) {
  128. case *runtime.RawExtension:
  129. if err := fn(item.Object); err != nil {
  130. return err
  131. }
  132. case runtime.Object:
  133. if err := fn(item); err != nil {
  134. return err
  135. }
  136. default:
  137. obj, ok := item.(runtime.Object)
  138. if !ok {
  139. return fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  140. }
  141. if err := fn(obj); err != nil {
  142. return err
  143. }
  144. }
  145. }
  146. return nil
  147. }
  148. // ExtractList returns obj's Items element as an array of runtime.Objects.
  149. // Returns an error if obj is not a List type (does not have an Items member).
  150. func ExtractList(obj runtime.Object) ([]runtime.Object, error) {
  151. itemsPtr, err := GetItemsPtr(obj)
  152. if err != nil {
  153. return nil, err
  154. }
  155. items, err := conversion.EnforcePtr(itemsPtr)
  156. if err != nil {
  157. return nil, err
  158. }
  159. list := make([]runtime.Object, items.Len())
  160. for i := range list {
  161. raw := items.Index(i)
  162. switch item := raw.Interface().(type) {
  163. case runtime.RawExtension:
  164. switch {
  165. case item.Object != nil:
  166. list[i] = item.Object
  167. case item.Raw != nil:
  168. // TODO: Set ContentEncoding and ContentType correctly.
  169. list[i] = &runtime.Unknown{Raw: item.Raw}
  170. default:
  171. list[i] = nil
  172. }
  173. case runtime.Object:
  174. list[i] = item
  175. default:
  176. var found bool
  177. if list[i], found = raw.Addr().Interface().(runtime.Object); !found {
  178. return nil, fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  179. }
  180. }
  181. }
  182. return list, nil
  183. }
  184. // objectSliceType is the type of a slice of Objects
  185. var objectSliceType = reflect.TypeOf([]runtime.Object{})
  186. // LenList returns the length of this list or 0 if it is not a list.
  187. func LenList(list runtime.Object) int {
  188. itemsPtr, err := GetItemsPtr(list)
  189. if err != nil {
  190. return 0
  191. }
  192. items, err := conversion.EnforcePtr(itemsPtr)
  193. if err != nil {
  194. return 0
  195. }
  196. return items.Len()
  197. }
  198. // SetList sets the given list object's Items member have the elements given in
  199. // objects.
  200. // Returns an error if list is not a List type (does not have an Items member),
  201. // or if any of the objects are not of the right type.
  202. func SetList(list runtime.Object, objects []runtime.Object) error {
  203. itemsPtr, err := GetItemsPtr(list)
  204. if err != nil {
  205. return err
  206. }
  207. items, err := conversion.EnforcePtr(itemsPtr)
  208. if err != nil {
  209. return err
  210. }
  211. if items.Type() == objectSliceType {
  212. items.Set(reflect.ValueOf(objects))
  213. return nil
  214. }
  215. slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
  216. for i := range objects {
  217. dest := slice.Index(i)
  218. if dest.Type() == reflect.TypeOf(runtime.RawExtension{}) {
  219. dest = dest.FieldByName("Object")
  220. }
  221. // check to see if you're directly assignable
  222. if reflect.TypeOf(objects[i]).AssignableTo(dest.Type()) {
  223. dest.Set(reflect.ValueOf(objects[i]))
  224. continue
  225. }
  226. src, err := conversion.EnforcePtr(objects[i])
  227. if err != nil {
  228. return err
  229. }
  230. if src.Type().AssignableTo(dest.Type()) {
  231. dest.Set(src)
  232. } else if src.Type().ConvertibleTo(dest.Type()) {
  233. dest.Set(src.Convert(dest.Type()))
  234. } else {
  235. return fmt.Errorf("item[%d]: can't assign or convert %v into %v", i, src.Type(), dest.Type())
  236. }
  237. }
  238. items.Set(slice)
  239. return nil
  240. }