generator_schema.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package v1alpha1
  13. import (
  14. "fmt"
  15. "sync"
  16. apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/util/json"
  19. )
  20. var builder map[string]Generator
  21. var buildlock sync.RWMutex
  22. func init() {
  23. builder = make(map[string]Generator)
  24. }
  25. // Register a generator type. Register panics if a
  26. // backend with the same store is already registered.
  27. func Register(kind string, g Generator) {
  28. buildlock.Lock()
  29. defer buildlock.Unlock()
  30. _, exists := builder[kind]
  31. if exists {
  32. panic(fmt.Sprintf("kind %q already registered", kind))
  33. }
  34. builder[kind] = g
  35. }
  36. // ForceRegister adds to store schema, overwriting a store if
  37. // already registered. Should only be used for testing.
  38. func ForceRegister(kind string, g Generator) {
  39. buildlock.Lock()
  40. builder[kind] = g
  41. buildlock.Unlock()
  42. }
  43. // GetGeneratorByName returns the provider implementation by name.
  44. func GetGeneratorByName(kind string) (Generator, bool) {
  45. buildlock.RLock()
  46. f, ok := builder[kind]
  47. buildlock.RUnlock()
  48. return f, ok
  49. }
  50. // GetGenerator returns the provider from the generic store.
  51. func GetGenerator(obj *apiextensions.JSON) (Generator, error) {
  52. type unknownGenerator struct {
  53. metav1.TypeMeta `json:",inline"`
  54. metav1.ObjectMeta `json:"metadata,omitempty"`
  55. }
  56. var res unknownGenerator
  57. err := json.Unmarshal(obj.Raw, &res)
  58. if err != nil {
  59. return nil, err
  60. }
  61. buildlock.RLock()
  62. defer buildlock.RUnlock()
  63. gen, ok := builder[res.Kind]
  64. if !ok {
  65. return nil, fmt.Errorf("failed to find registered generator for: %s", string(obj.Raw))
  66. }
  67. return gen, nil
  68. }