common.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 commontest
  13. import (
  14. "context"
  15. "fmt"
  16. "time"
  17. v1 "k8s.io/api/core/v1"
  18. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  19. "k8s.io/apimachinery/pkg/util/wait"
  20. "sigs.k8s.io/controller-runtime/pkg/client"
  21. )
  22. // CreateNamespace creates a new namespace in the cluster.
  23. func CreateNamespace(baseName string, c client.Client) (string, error) {
  24. return CreateNamespaceWithLabels(baseName, c, map[string]string{})
  25. }
  26. func CreateNamespaceWithLabels(baseName string, c client.Client, labels map[string]string) (string, error) {
  27. genName := fmt.Sprintf("ctrl-test-%v", baseName)
  28. ns := &v1.Namespace{
  29. ObjectMeta: metav1.ObjectMeta{
  30. GenerateName: genName,
  31. Labels: labels,
  32. },
  33. }
  34. err := wait.PollUntilContextTimeout(context.Background(), time.Second, 10*time.Second, true, func(ctx context.Context) (done bool, err error) {
  35. err = c.Create(ctx, ns)
  36. if err != nil {
  37. return false, nil
  38. }
  39. return true, nil
  40. })
  41. if err != nil {
  42. return "", err
  43. }
  44. return ns.Name, nil
  45. }
  46. func HasOwnerRef(meta metav1.ObjectMeta, kind, name string) bool {
  47. for _, ref := range meta.OwnerReferences {
  48. if ref.Kind == kind && ref.Name == name {
  49. return true
  50. }
  51. }
  52. return false
  53. }
  54. // FirstManagedFieldForManager returns the JSON representation of the first `metadata.managedFields` entry for a given manager.
  55. func FirstManagedFieldForManager(meta metav1.ObjectMeta, managerName string) string {
  56. for _, ref := range meta.ManagedFields {
  57. if ref.Manager == managerName {
  58. return ref.FieldsV1.String()
  59. }
  60. }
  61. return fmt.Sprintf("No managed fields managed by %s", managerName)
  62. }