build_release.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Copyright (C) 2021 The Android Open Source Project
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sdk
  15. import (
  16. "fmt"
  17. "math"
  18. "reflect"
  19. "strings"
  20. )
  21. // Supports customizing sdk snapshot output based on target build release.
  22. // buildRelease represents the version of a build system used to create a specific release.
  23. //
  24. // The name of the release, is the same as the code for the dessert release, e.g. S, Tiramisu, etc.
  25. type buildRelease struct {
  26. // The name of the release, e.g. S, Tiramisu, etc.
  27. name string
  28. // The index of this structure within the dessertBuildReleases list.
  29. //
  30. // The buildReleaseCurrent does not appear in the dessertBuildReleases list as it has an ordinal value
  31. // that is larger than the size of the dessertBuildReleases.
  32. ordinal int
  33. }
  34. func (br *buildRelease) EarlierThan(other *buildRelease) bool {
  35. return br.ordinal < other.ordinal
  36. }
  37. // String returns the name of the build release.
  38. func (br *buildRelease) String() string {
  39. return br.name
  40. }
  41. // buildReleaseSet represents a set of buildRelease objects.
  42. type buildReleaseSet struct {
  43. // Set of *buildRelease represented as a map from *buildRelease to struct{}.
  44. contents map[*buildRelease]struct{}
  45. }
  46. // addItem adds a build release to the set.
  47. func (s *buildReleaseSet) addItem(release *buildRelease) {
  48. s.contents[release] = struct{}{}
  49. }
  50. // addRange adds all the build releases from start (inclusive) to end (inclusive).
  51. func (s *buildReleaseSet) addRange(start *buildRelease, end *buildRelease) {
  52. for i := start.ordinal; i <= end.ordinal; i += 1 {
  53. s.addItem(dessertBuildReleases[i])
  54. }
  55. }
  56. // contains returns true if the set contains the specified build release.
  57. func (s *buildReleaseSet) contains(release *buildRelease) bool {
  58. _, ok := s.contents[release]
  59. return ok
  60. }
  61. // String returns a string representation of the set, sorted from earliest to latest release.
  62. func (s *buildReleaseSet) String() string {
  63. list := []string{}
  64. addRelease := func(release *buildRelease) {
  65. if _, ok := s.contents[release]; ok {
  66. list = append(list, release.name)
  67. }
  68. }
  69. // Add the names of the build releases in this set in the order in which they were created.
  70. for _, release := range dessertBuildReleases {
  71. addRelease(release)
  72. }
  73. // Always add "current" to the list of names last if it is present in the set.
  74. addRelease(buildReleaseCurrent)
  75. return fmt.Sprintf("[%s]", strings.Join(list, ","))
  76. }
  77. var (
  78. // nameToBuildRelease contains a map from name to build release.
  79. nameToBuildRelease = map[string]*buildRelease{}
  80. // dessertBuildReleases lists all the available dessert build releases, i.e. excluding current.
  81. dessertBuildReleases = []*buildRelease{}
  82. // allBuildReleaseSet is the set of all build releases.
  83. allBuildReleaseSet = &buildReleaseSet{contents: map[*buildRelease]struct{}{}}
  84. // Add the dessert build releases from oldest to newest.
  85. buildReleaseS = initBuildRelease("S")
  86. buildReleaseT = initBuildRelease("Tiramisu")
  87. // Add the current build release which is always treated as being more recent than any other
  88. // build release, including those added in tests.
  89. buildReleaseCurrent = initBuildRelease("current")
  90. )
  91. // initBuildRelease creates a new build release with the specified name.
  92. func initBuildRelease(name string) *buildRelease {
  93. ordinal := len(dessertBuildReleases)
  94. if name == "current" {
  95. // The current build release is more recent than all other build releases, including those
  96. // created in tests so use the max int value. It cannot just rely on being created after all
  97. // the other build releases as some are created in tests which run after the current build
  98. // release has been created.
  99. ordinal = math.MaxInt
  100. }
  101. release := &buildRelease{name: name, ordinal: ordinal}
  102. nameToBuildRelease[name] = release
  103. allBuildReleaseSet.addItem(release)
  104. if name != "current" {
  105. // As the current build release has an ordinal value that does not correspond to its position
  106. // in the dessertBuildReleases list do not add it to the list.
  107. dessertBuildReleases = append(dessertBuildReleases, release)
  108. }
  109. return release
  110. }
  111. // latestDessertBuildRelease returns the latest dessert release build name, i.e. the last dessert
  112. // release added to the list, which does not include current.
  113. func latestDessertBuildRelease() *buildRelease {
  114. return dessertBuildReleases[len(dessertBuildReleases)-1]
  115. }
  116. // nameToRelease maps from build release name to the corresponding build release (if it exists) or
  117. // the error if it does not.
  118. func nameToRelease(name string) (*buildRelease, error) {
  119. if r, ok := nameToBuildRelease[name]; ok {
  120. return r, nil
  121. }
  122. return nil, fmt.Errorf("unknown release %q, expected one of %s", name, allBuildReleaseSet)
  123. }
  124. // parseBuildReleaseSet parses a build release set string specification into a build release set.
  125. //
  126. // The specification consists of one of the following:
  127. // * a single build release name, e.g. S, T, etc.
  128. // * a closed range (inclusive to inclusive), e.g. S-T
  129. // * an open range, e.g. T+.
  130. //
  131. // This returns the set if the specification was valid or an error.
  132. func parseBuildReleaseSet(specification string) (*buildReleaseSet, error) {
  133. set := &buildReleaseSet{contents: map[*buildRelease]struct{}{}}
  134. if strings.HasSuffix(specification, "+") {
  135. rangeStart := strings.TrimSuffix(specification, "+")
  136. start, err := nameToRelease(rangeStart)
  137. if err != nil {
  138. return nil, err
  139. }
  140. end := latestDessertBuildRelease()
  141. set.addRange(start, end)
  142. // An open-ended range always includes the current release.
  143. set.addItem(buildReleaseCurrent)
  144. } else if strings.Contains(specification, "-") {
  145. limits := strings.SplitN(specification, "-", 2)
  146. start, err := nameToRelease(limits[0])
  147. if err != nil {
  148. return nil, err
  149. }
  150. end, err := nameToRelease(limits[1])
  151. if err != nil {
  152. return nil, err
  153. }
  154. if start.ordinal > end.ordinal {
  155. return nil, fmt.Errorf("invalid closed range, start release %q is later than end release %q", start.name, end.name)
  156. }
  157. set.addRange(start, end)
  158. } else {
  159. release, err := nameToRelease(specification)
  160. if err != nil {
  161. return nil, err
  162. }
  163. set.addItem(release)
  164. }
  165. return set, nil
  166. }
  167. // Given a set of properties (struct value), set the value of a field within that struct (or one of
  168. // its embedded structs) to its zero value.
  169. type fieldPrunerFunc func(structValue reflect.Value)
  170. // A property that can be cleared by a propertyPruner.
  171. type prunerProperty struct {
  172. // The name of the field for this property. It is a "."-separated path for fields in non-anonymous
  173. // sub-structs.
  174. name string
  175. // Sets the associated field to its zero value.
  176. prunerFunc fieldPrunerFunc
  177. }
  178. // propertyPruner provides support for pruning (i.e. setting to their zero value) properties from
  179. // a properties structure.
  180. type propertyPruner struct {
  181. // The properties that the pruner will clear.
  182. properties []prunerProperty
  183. }
  184. // gatherFields recursively processes the supplied structure and a nested structures, selecting the
  185. // fields that require pruning and populates the propertyPruner.properties with the information
  186. // needed to prune those fields.
  187. //
  188. // containingStructAccessor is a func that if given an object will return a field whose value is
  189. // of the supplied structType. It is nil on initial entry to this method but when this method is
  190. // called recursively on a field that is a nested structure containingStructAccessor is set to a
  191. // func that provides access to the field's value.
  192. //
  193. // namePrefix is the prefix to the fields that are being visited. It is "" on initial entry to this
  194. // method but when this method is called recursively on a field that is a nested structure
  195. // namePrefix is the result of appending the field name (plus a ".") to the previous name prefix.
  196. // Unless the field is anonymous in which case it is passed through unchanged.
  197. //
  198. // selector is a func that will select whether the supplied field requires pruning or not. If it
  199. // returns true then the field will be added to those to be pruned, otherwise it will not.
  200. func (p *propertyPruner) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string, selector fieldSelectorFunc) {
  201. for f := 0; f < structType.NumField(); f++ {
  202. field := structType.Field(f)
  203. if field.PkgPath != "" {
  204. // Ignore unexported fields.
  205. continue
  206. }
  207. // Save a copy of the field index for use in the function.
  208. fieldIndex := f
  209. name := namePrefix + field.Name
  210. fieldGetter := func(container reflect.Value) reflect.Value {
  211. if containingStructAccessor != nil {
  212. // This is an embedded structure so first access the field for the embedded
  213. // structure.
  214. container = containingStructAccessor(container)
  215. }
  216. // Skip through interface and pointer values to find the structure.
  217. container = getStructValue(container)
  218. defer func() {
  219. if r := recover(); r != nil {
  220. panic(fmt.Errorf("%s for fieldIndex %d of field %s of container %#v", r, fieldIndex, name, container.Interface()))
  221. }
  222. }()
  223. // Return the field.
  224. return container.Field(fieldIndex)
  225. }
  226. fieldType := field.Type
  227. if selector(name, field) {
  228. zeroValue := reflect.Zero(fieldType)
  229. fieldPruner := func(container reflect.Value) {
  230. if containingStructAccessor != nil {
  231. // This is an embedded structure so first access the field for the embedded
  232. // structure.
  233. container = containingStructAccessor(container)
  234. }
  235. // Skip through interface and pointer values to find the structure.
  236. container = getStructValue(container)
  237. defer func() {
  238. if r := recover(); r != nil {
  239. panic(fmt.Errorf("%s\n\tfor field (index %d, name %s)", r, fieldIndex, name))
  240. }
  241. }()
  242. // Set the field.
  243. container.Field(fieldIndex).Set(zeroValue)
  244. }
  245. property := prunerProperty{
  246. name,
  247. fieldPruner,
  248. }
  249. p.properties = append(p.properties, property)
  250. } else {
  251. switch fieldType.Kind() {
  252. case reflect.Struct:
  253. // Gather fields from the nested or embedded structure.
  254. var subNamePrefix string
  255. if field.Anonymous {
  256. subNamePrefix = namePrefix
  257. } else {
  258. subNamePrefix = name + "."
  259. }
  260. p.gatherFields(fieldType, fieldGetter, subNamePrefix, selector)
  261. case reflect.Map:
  262. // Get the type of the values stored in the map.
  263. valueType := fieldType.Elem()
  264. // Skip over * types.
  265. if valueType.Kind() == reflect.Ptr {
  266. valueType = valueType.Elem()
  267. }
  268. if valueType.Kind() == reflect.Struct {
  269. // If this is not referenced by a pointer then it is an error as it is impossible to
  270. // modify a struct that is stored directly as a value in a map.
  271. if fieldType.Elem().Kind() != reflect.Ptr {
  272. panic(fmt.Errorf("Cannot prune struct %s stored by value in map %s, map values must"+
  273. " be pointers to structs",
  274. fieldType.Elem(), name))
  275. }
  276. // Create a new pruner for the values of the map.
  277. valuePruner := newPropertyPrunerForStructType(valueType, selector)
  278. // Create a new fieldPruner that will iterate over all the items in the map and call the
  279. // pruner on them.
  280. fieldPruner := func(container reflect.Value) {
  281. mapValue := fieldGetter(container)
  282. for _, keyValue := range mapValue.MapKeys() {
  283. itemValue := mapValue.MapIndex(keyValue)
  284. defer func() {
  285. if r := recover(); r != nil {
  286. panic(fmt.Errorf("%s\n\tfor key %q", r, keyValue))
  287. }
  288. }()
  289. valuePruner.pruneProperties(itemValue.Interface())
  290. }
  291. }
  292. // Add the map field pruner to the list of property pruners.
  293. property := prunerProperty{
  294. name + "[*]",
  295. fieldPruner,
  296. }
  297. p.properties = append(p.properties, property)
  298. }
  299. }
  300. }
  301. }
  302. }
  303. // pruneProperties will prune (set to zero value) any properties in the struct referenced by the
  304. // supplied struct pointer.
  305. //
  306. // The struct must be of the same type as was originally passed to newPropertyPruner to create this
  307. // propertyPruner.
  308. func (p *propertyPruner) pruneProperties(propertiesStruct interface{}) {
  309. defer func() {
  310. if r := recover(); r != nil {
  311. panic(fmt.Errorf("%s\n\tof container %#v", r, propertiesStruct))
  312. }
  313. }()
  314. structValue := reflect.ValueOf(propertiesStruct)
  315. for _, property := range p.properties {
  316. property.prunerFunc(structValue)
  317. }
  318. }
  319. // fieldSelectorFunc is called to select whether a specific field should be pruned or not.
  320. // name is the name of the field, including any prefixes from containing str
  321. type fieldSelectorFunc func(name string, field reflect.StructField) bool
  322. // newPropertyPruner creates a new property pruner for the structure type for the supplied
  323. // properties struct.
  324. //
  325. // The returned pruner can be used on any properties structure of the same type as the supplied set
  326. // of properties.
  327. func newPropertyPruner(propertiesStruct interface{}, selector fieldSelectorFunc) *propertyPruner {
  328. structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
  329. return newPropertyPrunerForStructType(structType, selector)
  330. }
  331. // newPropertyPruner creates a new property pruner for the supplied properties struct type.
  332. //
  333. // The returned pruner can be used on any properties structure of the supplied type.
  334. func newPropertyPrunerForStructType(structType reflect.Type, selector fieldSelectorFunc) *propertyPruner {
  335. pruner := &propertyPruner{}
  336. pruner.gatherFields(structType, nil, "", selector)
  337. return pruner
  338. }
  339. // newPropertyPrunerByBuildRelease creates a property pruner that will clear any properties in the
  340. // structure which are not supported by the specified target build release.
  341. //
  342. // A property is pruned if its field has a tag of the form:
  343. //
  344. // `supported_build_releases:"<build-release-set>"`
  345. //
  346. // and the resulting build release set does not contain the target build release. Properties that
  347. // have no such tag are assumed to be supported by all releases.
  348. func newPropertyPrunerByBuildRelease(propertiesStruct interface{}, targetBuildRelease *buildRelease) *propertyPruner {
  349. return newPropertyPruner(propertiesStruct, func(name string, field reflect.StructField) bool {
  350. if supportedBuildReleases, ok := field.Tag.Lookup("supported_build_releases"); ok {
  351. set, err := parseBuildReleaseSet(supportedBuildReleases)
  352. if err != nil {
  353. panic(fmt.Errorf("invalid `supported_build_releases` tag on %s of %T: %s", name, propertiesStruct, err))
  354. }
  355. // If the field does not support tha target release then prune it.
  356. return !set.contains(targetBuildRelease)
  357. } else {
  358. // Any untagged fields are assumed to be supported by all build releases so should never be
  359. // pruned.
  360. return false
  361. }
  362. })
  363. }