help.go 7.0 KB

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