@@ -17,6 +17,7 @@ limitations under the License.
1717package v1beta1
1818
1919import (
20+ "context"
2021 "fmt"
2122 "strings"
2223
@@ -26,11 +27,14 @@ import (
2627 "k8s.io/apimachinery/pkg/runtime/schema"
2728 "k8s.io/apimachinery/pkg/util/validation/field"
2829 ctrl "sigs.k8s.io/controller-runtime"
30+ "sigs.k8s.io/controller-runtime/pkg/client"
2931 logf "sigs.k8s.io/controller-runtime/pkg/log"
3032 "sigs.k8s.io/controller-runtime/pkg/webhook"
3133 "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
3234)
3335
36+ var ctlplaneWebhookClient client.Client
37+
3438// OpenStackControlPlaneDefaults -
3539type OpenStackControlPlaneDefaults struct {
3640 RabbitMqImageURL string
@@ -49,6 +53,10 @@ func SetupOpenStackControlPlaneDefaults(defaults OpenStackControlPlaneDefaults)
4953
5054// SetupWebhookWithManager sets up the Webhook with the Manager.
5155func (r * OpenStackControlPlane ) SetupWebhookWithManager (mgr ctrl.Manager ) error {
56+ if ctlplaneWebhookClient == nil {
57+ ctlplaneWebhookClient = mgr .GetClient ()
58+ }
59+
5260 return ctrl .NewWebhookManagedBy (mgr ).
5361 For (r ).
5462 Complete ()
@@ -64,6 +72,38 @@ func (r *OpenStackControlPlane) ValidateCreate() (admission.Warnings, error) {
6472
6573 var allErrs field.ErrorList
6674 basePath := field .NewPath ("spec" )
75+
76+ ctlplaneList := & OpenStackControlPlaneList {}
77+ listOpts := []client.ListOption {
78+ client .InNamespace (r .Namespace ),
79+ }
80+ if err := ctlplaneWebhookClient .List (context .TODO (), ctlplaneList , listOpts ... ); err != nil {
81+ return nil , apierrors .NewForbidden (
82+ schema.GroupResource {
83+ Group : GroupVersion .WithKind ("OpenStackControlPlane" ).Group ,
84+ Resource : GroupVersion .WithKind ("OpenStackControlPlane" ).Kind ,
85+ }, r .GetName (), & field.Error {
86+ Type : field .ErrorTypeForbidden ,
87+ Field : "" ,
88+ BadValue : r .Name ,
89+ Detail : err .Error (),
90+ },
91+ )
92+ }
93+ if len (ctlplaneList .Items ) >= 1 {
94+ return nil , apierrors .NewForbidden (
95+ schema.GroupResource {
96+ Group : GroupVersion .WithKind ("OpenStackControlPlane" ).Group ,
97+ Resource : GroupVersion .WithKind ("OpenStackControlPlane" ).Kind ,
98+ }, r .GetName (), & field.Error {
99+ Type : field .ErrorTypeForbidden ,
100+ Field : "" ,
101+ BadValue : r .Name ,
102+ Detail : "Only one OpenStackControlPlane instance per namespace is supported at this time." ,
103+ },
104+ )
105+ }
106+
67107 if err := r .ValidateCreateServices (basePath ); err != nil {
68108 allErrs = append (allErrs , err ... )
69109 }
0 commit comments