Skip to content

Commit

Permalink
issue-522,implementation for OpenSearch Egress Rules lifecycle workfl…
Browse files Browse the repository at this point in the history
…ow on APIv2
  • Loading branch information
OleksiienkoMykyta committed Aug 22, 2023
1 parent 1fd8cfd commit bde9855
Show file tree
Hide file tree
Showing 25 changed files with 758 additions and 108 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ run: manifests generate fmt vet ## Run a controller from your host.
go run ./main.go

.PHONY: docker-build
docker-build: manifests generate test ## Build docker image with the manager.
docker-build: manifests generate ## test ## Build docker image with the manager.
docker build -t ${IMG} .

.PHONY: docker-push
Expand Down
21 changes: 21 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -309,4 +309,25 @@ resources:
webhooks:
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: instaclustr.com
group: clusters
kind: OpenSearchEgressRules
path: github.com/instaclustr/operator/apis/clusterresources/v1beta1
version: v1beta1
- api:
crdVersion: v1
namespaced: true
controller: true
domain: instaclustr.com
group: clusterresources
kind: OpenSearchEgressRules
path: github.com/instaclustr/operator/apis/clusterresources/v1beta1
version: v1beta1
webhooks:
validation: true
webhookVersion: v1
version: "3"
72 changes: 72 additions & 0 deletions apis/clusterresources/v1beta1/opensearchegressrules_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/instaclustr/operator/pkg/models"
)

type OpenSearchEgressRulesSpec struct {
ClusterID string `json:"clusterId"`
Name string `json:"name"`
OpenSearchBindingId string `json:"openSearchBindingId"`
Source string `json:"source"`
Type string `json:"type"`
}

type OpenSearchEgressRulesStatus struct {
ID string `json:"id,omitempty"`
Status string `json:"status,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status

// OpenSearchEgressRules is the Schema for the opensearchegressrules API
type OpenSearchEgressRules struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

Spec OpenSearchEgressRulesSpec `json:"spec,omitempty"`
Status OpenSearchEgressRulesStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true

// OpenSearchEgressRulesList contains a list of OpenSearchEgressRules
type OpenSearchEgressRulesList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []OpenSearchEgressRules `json:"items"`
}

func (er *OpenSearchEgressRules) GetJobID(jobName string) string {
return client.ObjectKeyFromObject(er).String() + "/" + jobName
}

func (er *OpenSearchEgressRules) NewPatch() client.Patch {
old := er.DeepCopy()
old.Annotations[models.ResourceStateAnnotation] = ""
return client.MergeFrom(old)
}

func init() {
SchemeBuilder.Register(&OpenSearchEgressRules{}, &OpenSearchEgressRulesList{})
}
88 changes: 88 additions & 0 deletions apis/clusterresources/v1beta1/opensearchegressrules_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1

import (
"fmt"
"regexp"

"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"

"github.com/instaclustr/operator/pkg/models"
)

// log is for logging in this package.
var opensearchegressruleslog = logf.Log.WithName("opensearchegressrules-resource")

var openSearchBindingIDPattern, _ = regexp.Compile(`[\w-]+`)
var egressRulesIDPattern, _ = regexp.Compile(`[a-zA-Z\d-]+~\w+~[\w-]+`)

func (r *OpenSearchEgressRules) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
Complete()
}

//+kubebuilder:webhook:path=/validate-clusterresources-instaclustr-com-v1beta1-opensearchegressrules,mutating=false,failurePolicy=fail,sideEffects=None,groups=clusterresources.instaclustr.com,resources=opensearchegressrules,verbs=create;update,versions=v1beta1,name=vopensearchegressrules.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &OpenSearchEgressRules{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *OpenSearchEgressRules) ValidateCreate() error {
opensearchegressruleslog.Info("validate create", "name", r.Name)

if r.Spec.ClusterID == "" || r.Spec.OpenSearchBindingId == "" || r.Spec.Source == "" {
return fmt.Errorf("spec.ClusterID, spec.OpenSearchBindingId, spec.Source must be filled")
}

if !openSearchBindingIDPattern.MatchString(r.Spec.OpenSearchBindingId) {
return fmt.Errorf("mismatching openSearchBindingID to [\\w-]+ pattern")
}

return nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *OpenSearchEgressRules) ValidateUpdate(old runtime.Object) error {
opensearchegressruleslog.Info("validate update", "name", r.Name)

oldRules := old.(*OpenSearchEgressRules)

if r.Status.ID == "" {
return r.ValidateCreate()
}

if r.Spec != oldRules.Spec {
return models.ErrImmutableSpec
}

return nil
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *OpenSearchEgressRules) ValidateDelete() error {
opensearchegressruleslog.Info("validate delete", "name", r.Name)

if !openSearchBindingIDPattern.MatchString(r.Spec.OpenSearchBindingId) {
return fmt.Errorf("mismatching openSearchBindingID to [a-zA-Z\\d-]+~\\w+~[\\w-]+ pattern")
}

return nil
}
3 changes: 3 additions & 0 deletions apis/clusterresources/v1beta1/webhook_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ var _ = BeforeSuite(func() {
err = (&RedisUser{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&OpenSearchEgressRules{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

//+kubebuilder:scaffold:webhook

go func() {
Expand Down
89 changes: 89 additions & 0 deletions apis/clusterresources/v1beta1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
annotations:
controller-gen.kubebuilder.io/version: v0.9.2
creationTimestamp: null
name: opensearchegressrules.clusterresources.instaclustr.com
spec:
group: clusterresources.instaclustr.com
names:
kind: OpenSearchEgressRules
listKind: OpenSearchEgressRulesList
plural: opensearchegressrules
singular: opensearchegressrules
scope: Namespaced
versions:
- name: v1beta1
schema:
openAPIV3Schema:
description: OpenSearchEgressRules is the Schema for the opensearchegressrules
API
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
type: object
spec:
properties:
clusterId:
type: string
name:
type: string
openSearchBindingId:
type: string
source:
type: string
type:
type: string
required:
- clusterId
- name
- openSearchBindingId
- source
- type
type: object
status:
properties:
id:
type: string
status:
type: string
type: object
type: object
served: true
storage: true
subresources:
status: {}
3 changes: 3 additions & 0 deletions config/crd/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ resources:
- bases/clusterresources.instaclustr.com_awsencryptionkeys.yaml
- bases/clusterresources.instaclustr.com_cassandrausers.yaml
- bases/clusterresources.instaclustr.com_opensearchusers.yaml
- bases/clusterresources.instaclustr.com_opensearchegressrules.yaml
#+kubebuilder:scaffold:crdkustomizeresource

patchesStrategicMerge:
Expand Down Expand Up @@ -54,6 +55,7 @@ patchesStrategicMerge:
#- patches/webhook_in_awsencryptionkeys.yaml
#- patches/webhook_in_cassandrausers.yaml
#- patches/webhook_in_clusterbackups.yaml
#- patches/webhook_in_opensearchegressrules.yaml
#+kubebuilder:scaffold:crdkustomizewebhookpatch

# [CERTMANAGER] To enable cert-manager, uncomment all the sections with [CERTMANAGER] prefix.
Expand Down Expand Up @@ -85,6 +87,7 @@ patchesStrategicMerge:
#- patches/cainjection_in_postgresqls.yaml
#- patches/cainjection_in_clusterbackups.yaml
#- patches/cainjection_in_maintenanceevents.yaml
#- patches/cainjection_in_opensearchegressrules.yaml
#+kubebuilder:scaffold:crdkustomizecainjectionpatch

# the following config is for teaching kustomize how to do kustomization for CRDs.
Expand Down
Loading

0 comments on commit bde9855

Please sign in to comment.