help.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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.Pointer:
  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. //
  99. // If items passed to fn are retained for different durations, and you want to avoid
  100. // retaining all items in obj as long as any item is referenced, use EachListItemWithAlloc instead.
  101. func EachListItem(obj runtime.Object, fn func(runtime.Object) error) error {
  102. return eachListItem(obj, fn, false)
  103. }
  104. // EachListItemWithAlloc works like EachListItem, but avoids retaining references to the items slice in obj.
  105. // It does this by making a shallow copy of non-pointer items in obj.
  106. //
  107. // If the items passed to fn are not retained, or are retained for the same duration, use EachListItem instead for memory efficiency.
  108. func EachListItemWithAlloc(obj runtime.Object, fn func(runtime.Object) error) error {
  109. return eachListItem(obj, fn, true)
  110. }
  111. // allocNew: Whether shallow copy is required when the elements in Object.Items are struct
  112. func eachListItem(obj runtime.Object, fn func(runtime.Object) error, allocNew bool) error {
  113. if unstructured, ok := obj.(runtime.Unstructured); ok {
  114. if allocNew {
  115. return unstructured.EachListItemWithAlloc(fn)
  116. }
  117. return unstructured.EachListItem(fn)
  118. }
  119. // TODO: Change to an interface call?
  120. itemsPtr, err := GetItemsPtr(obj)
  121. if err != nil {
  122. return err
  123. }
  124. items, err := conversion.EnforcePtr(itemsPtr)
  125. if err != nil {
  126. return err
  127. }
  128. len := items.Len()
  129. if len == 0 {
  130. return nil
  131. }
  132. takeAddr := false
  133. if elemType := items.Type().Elem(); elemType.Kind() != reflect.Pointer && elemType.Kind() != reflect.Interface {
  134. if !items.Index(0).CanAddr() {
  135. return fmt.Errorf("unable to take address of items in %T for EachListItem", obj)
  136. }
  137. takeAddr = true
  138. }
  139. for i := 0; i < len; i++ {
  140. raw := items.Index(i)
  141. if takeAddr {
  142. if allocNew {
  143. // shallow copy to avoid retaining a reference to the original list item
  144. itemCopy := reflect.New(raw.Type())
  145. // assign to itemCopy and type-assert
  146. itemCopy.Elem().Set(raw)
  147. // reflect.New will guarantee that itemCopy must be a pointer.
  148. raw = itemCopy
  149. } else {
  150. raw = raw.Addr()
  151. }
  152. }
  153. // raw must be a pointer or an interface
  154. // allocate a pointer is cheap
  155. switch item := raw.Interface().(type) {
  156. case *runtime.RawExtension:
  157. if err := fn(item.Object); err != nil {
  158. return err
  159. }
  160. case runtime.Object:
  161. if err := fn(item); err != nil {
  162. return err
  163. }
  164. default:
  165. obj, ok := item.(runtime.Object)
  166. if !ok {
  167. return fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  168. }
  169. if err := fn(obj); err != nil {
  170. return err
  171. }
  172. }
  173. }
  174. return nil
  175. }
  176. // ExtractList returns obj's Items element as an array of runtime.Objects.
  177. // Returns an error if obj is not a List type (does not have an Items member).
  178. //
  179. // If items in the returned list are retained for different durations, and you want to avoid
  180. // retaining all items in obj as long as any item is referenced, use ExtractListWithAlloc instead.
  181. func ExtractList(obj runtime.Object) ([]runtime.Object, error) {
  182. return extractList(obj, false)
  183. }
  184. // ExtractListWithAlloc works like ExtractList, but avoids retaining references to the items slice in obj.
  185. // It does this by making a shallow copy of non-pointer items in obj.
  186. //
  187. // If the items in the returned list are not retained, or are retained for the same duration, use ExtractList instead for memory efficiency.
  188. func ExtractListWithAlloc(obj runtime.Object) ([]runtime.Object, error) {
  189. return extractList(obj, true)
  190. }
  191. // allocNew: Whether shallow copy is required when the elements in Object.Items are struct
  192. func extractList(obj runtime.Object, allocNew bool) ([]runtime.Object, error) {
  193. itemsPtr, err := GetItemsPtr(obj)
  194. if err != nil {
  195. return nil, err
  196. }
  197. items, err := conversion.EnforcePtr(itemsPtr)
  198. if err != nil {
  199. return nil, err
  200. }
  201. list := make([]runtime.Object, items.Len())
  202. if len(list) == 0 {
  203. return list, nil
  204. }
  205. elemType := items.Type().Elem()
  206. isRawExtension := elemType == rawExtensionObjectType
  207. implementsObject := elemType.Implements(objectType)
  208. for i := range list {
  209. raw := items.Index(i)
  210. switch {
  211. case isRawExtension:
  212. item := raw.Interface().(runtime.RawExtension)
  213. switch {
  214. case item.Object != nil:
  215. list[i] = item.Object
  216. case item.Raw != nil:
  217. // TODO: Set ContentEncoding and ContentType correctly.
  218. list[i] = &runtime.Unknown{Raw: item.Raw}
  219. default:
  220. list[i] = nil
  221. }
  222. case implementsObject:
  223. list[i] = raw.Interface().(runtime.Object)
  224. case allocNew:
  225. // shallow copy to avoid retaining a reference to the original list item
  226. itemCopy := reflect.New(raw.Type())
  227. // assign to itemCopy and type-assert
  228. itemCopy.Elem().Set(raw)
  229. var ok bool
  230. // reflect.New will guarantee that itemCopy must be a pointer.
  231. if list[i], ok = itemCopy.Interface().(runtime.Object); !ok {
  232. return nil, fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  233. }
  234. default:
  235. var found bool
  236. if list[i], found = raw.Addr().Interface().(runtime.Object); !found {
  237. return nil, fmt.Errorf("%v: item[%v]: Expected object, got %#v(%s)", obj, i, raw.Interface(), raw.Kind())
  238. }
  239. }
  240. }
  241. return list, nil
  242. }
  243. var (
  244. // objectSliceType is the type of a slice of Objects
  245. objectSliceType = reflect.TypeOf([]runtime.Object{})
  246. objectType = reflect.TypeOf((*runtime.Object)(nil)).Elem()
  247. rawExtensionObjectType = reflect.TypeOf(runtime.RawExtension{})
  248. )
  249. // LenList returns the length of this list or 0 if it is not a list.
  250. func LenList(list runtime.Object) int {
  251. itemsPtr, err := GetItemsPtr(list)
  252. if err != nil {
  253. return 0
  254. }
  255. items, err := conversion.EnforcePtr(itemsPtr)
  256. if err != nil {
  257. return 0
  258. }
  259. return items.Len()
  260. }
  261. // SetList sets the given list object's Items member have the elements given in
  262. // objects.
  263. // Returns an error if list is not a List type (does not have an Items member),
  264. // or if any of the objects are not of the right type.
  265. func SetList(list runtime.Object, objects []runtime.Object) error {
  266. itemsPtr, err := GetItemsPtr(list)
  267. if err != nil {
  268. return err
  269. }
  270. items, err := conversion.EnforcePtr(itemsPtr)
  271. if err != nil {
  272. return err
  273. }
  274. if items.Type() == objectSliceType {
  275. items.Set(reflect.ValueOf(objects))
  276. return nil
  277. }
  278. slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
  279. for i := range objects {
  280. dest := slice.Index(i)
  281. if dest.Type() == rawExtensionObjectType {
  282. dest = dest.FieldByName("Object")
  283. }
  284. // check to see if you're directly assignable
  285. if reflect.TypeOf(objects[i]).AssignableTo(dest.Type()) {
  286. dest.Set(reflect.ValueOf(objects[i]))
  287. continue
  288. }
  289. src, err := conversion.EnforcePtr(objects[i])
  290. if err != nil {
  291. return err
  292. }
  293. if src.Type().AssignableTo(dest.Type()) {
  294. dest.Set(src)
  295. } else if src.Type().ConvertibleTo(dest.Type()) {
  296. dest.Set(src.Convert(dest.Type()))
  297. } else {
  298. return fmt.Errorf("item[%d]: can't assign or convert %v into %v", i, src.Type(), dest.Type())
  299. }
  300. }
  301. items.Set(slice)
  302. return nil
  303. }