generator_schema.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 generator 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 the schema, overwriting a generator 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 a implementation from a generator
  51. // defined as json.
  52. func GetGenerator(obj *apiextensions.JSON) (Generator, error) {
  53. type unknownGenerator struct {
  54. metav1.TypeMeta `json:",inline"`
  55. metav1.ObjectMeta `json:"metadata,omitempty"`
  56. }
  57. var res unknownGenerator
  58. err := json.Unmarshal(obj.Raw, &res)
  59. if err != nil {
  60. return nil, err
  61. }
  62. buildlock.RLock()
  63. defer buildlock.RUnlock()
  64. gen, ok := builder[res.Kind]
  65. if !ok {
  66. return nil, fmt.Errorf("failed to find registered generator for: %s", string(obj.Raw))
  67. }
  68. return gen, nil
  69. }