Skip to content

Commit

Permalink
Merge pull request #5 from furkatgofurov7/populate-api-fields
Browse files Browse the repository at this point in the history
Add initial KubewardenAddon API version
  • Loading branch information
furkatgofurov7 authored Nov 19, 2024
2 parents 9b933ff + 9fa1af1 commit 91f7b62
Show file tree
Hide file tree
Showing 32 changed files with 771 additions and 168 deletions.
10 changes: 10 additions & 0 deletions .github/workflows/test-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ on:
push:
pull_request:

env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

jobs:
test-e2e:
name: Run on Ubuntu
Expand All @@ -17,6 +20,13 @@ jobs:
with:
go-version: '~1.22'

- name: Docker login
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Install the latest version of kind
run: |
curl -Lo ./kind https://kind.sigs.k8s.io/dl/latest/kind-linux-amd64
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,6 @@ go.work.sum

# env file
.env

# bin directory
bin/
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
run:
skip-dirs:
- test/*
timeout: 5m
allow-parallel-runners: true

Expand Down
4 changes: 4 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,7 @@ resources:
path: github.com/caapkw/cluster-api-provider-addon-kubewarden/api/v1alpha1
version: v1alpha1
version: "3"
webhooks:
defaulting: true
validation: true
webhookVersion: v1
41 changes: 31 additions & 10 deletions api/v1alpha1/kubewardenaddon_types.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2024.
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -20,22 +20,43 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.

// KubewardenAddonSpec defines the desired state of KubewardenAddon.
type KubewardenAddonSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
// Version specifies the version of Kubewarden to deploy.
Version string `json:"version,omitempty"`

// ImageRepository specifies the repository for pulling Kubewarden images.
ImageRepository string `json:"imageRepository,omitempty"`

// PolicyServerConfig holds configuration for the policy server.
PolicyServerConfig PolicyServerConfig `json:"policyServerConfig"`
}

// PolicyServerConfig represents the configuration options for the policy server.
type PolicyServerConfig struct {
// Resources defines the CPU and memory resources for the policy server.
Resources ResourceRequirements `json:"resources,omitempty"`

// Foo is an example field of KubewardenAddon. Edit kubewardenaddon_types.go to remove/update
Foo string `json:"foo,omitempty"`
// Replicas specifies the number of replicas for high availability.
Replicas int32 `json:"replicas,omitempty"`
}

// ResourceRequirements defines CPU and memory resource limits and requests.
type ResourceRequirements struct {
// CPU request for the policy server.
CPU string `json:"cpu,omitempty"`

// Memory request for the policy server.
Memory string `json:"memory,omitempty"`
}

// KubewardenAddonStatus defines the observed state of KubewardenAddon.
type KubewardenAddonStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
// Ready indicates whether the addon is successfully deployed.
Ready bool `json:"ready"`

// Conditions represent the latest available observations of the addon state.
Conditions []metav1.Condition `json:"conditions"`
}

// +kubebuilder:object:root=true
Expand Down
79 changes: 79 additions & 0 deletions api/v1alpha1/kubewardenaddon_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
Copyright 2024 The Kubernetes Authors.
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 v1alpha1

import (
"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"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

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

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

// +kubebuilder:webhook:path=/mutate-addons-cluster-x-k8s-io-v1alpha1-kubewardenaddon,mutating=true,failurePolicy=fail,sideEffects=None,groups=addons.cluster.x-k8s.io,resources=kubewardenaddons,verbs=create;update,versions=v1alpha1,name=mkubewardenaddon.kb.io,admissionReviewVersions=v1

var _ webhook.Defaulter = &KubewardenAddon{}

// Default implements webhook.Defaulter so a webhook will be registered for the type.
func (p *KubewardenAddon) Default() {
kubewardenaddonlog.Info("default", "name", p.Name)

if p.Spec.ImageRepository == "" {
p.Spec.ImageRepository = "ghcr.io/kubewarden/kubewarden-controller:v1.18.0"
}

if p.Spec.Version == "" {
p.Spec.Version = "latest"
}
}

// +kubebuilder:webhook:path=/validate-addons-cluster-x-k8s-io-v1alpha1-kubewardenaddon,mutating=false,failurePolicy=fail,sideEffects=None,groups=addons.cluster.x-k8s.io,resources=kubewardenaddons,verbs=create;update,versions=v1alpha1,name=vkubewardenaddon.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &KubewardenAddon{}

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

// TODO(user): fill in your validation logic upon object creation.
return nil, nil
}

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

// TODO(user): fill in your validation logic upon object update.
return nil, nil
}

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

// TODO(user): fill in your validation logic upon object deletion.
return nil, nil
}
134 changes: 134 additions & 0 deletions api/v1alpha1/webhook_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
Copyright 2024 The Kubernetes Authors.
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 v1alpha1

import (
"context"
"crypto/tls"
"fmt"
"net"
"path/filepath"
"testing"
"time"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
admissionv1beta1 "k8s.io/api/admission/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/envtest"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)

// These tests use Ginkgo (BDD-style Go testing framework). Refer to
// http://onsi.github.io/ginkgo/ to learn more about Ginkgo.

var (
k8sClient client.Client
testEnv *envtest.Environment
ctx context.Context
cancel context.CancelFunc
)

func TestAPIs(t *testing.T) {
RegisterFailHandler(Fail)

RunSpecs(t, "Webhook Suite")
}

var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

ctx, cancel = context.WithCancel(context.TODO())

By("bootstrapping test environment")
testEnv = &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")},
ErrorIfCRDPathMissing: false,
WebhookInstallOptions: envtest.WebhookInstallOptions{
Paths: []string{filepath.Join("..", "..", "config", "webhook")},
},
}

cfg, err := testEnv.Start()
Expect(err).NotTo(HaveOccurred())
Expect(cfg).NotTo(BeNil())

scheme := runtime.NewScheme()
err = AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

err = admissionv1beta1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

err = admissionv1beta1.AddToScheme(scheme)
Expect(err).NotTo(HaveOccurred())

// +kubebuilder:scaffold:scheme
k8sClient, err = client.New(cfg, client.Options{Scheme: scheme})
Expect(err).NotTo(HaveOccurred())
Expect(k8sClient).NotTo(BeNil())

// start webhook server using Manager
webhookInstallOptions := &testEnv.WebhookInstallOptions
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme,
WebhookServer: webhook.NewServer(
webhook.Options{
Host: webhookInstallOptions.LocalServingHost,
Port: webhookInstallOptions.LocalServingPort,
CertDir: webhookInstallOptions.LocalServingCertDir,
},
),
LeaderElection: false,
Metrics: metricsserver.Options{BindAddress: "0"},
})
Expect(err).NotTo(HaveOccurred())

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

// +kubebuilder:scaffold:webhook
go func() {
defer GinkgoRecover()
err = mgr.Start(ctx)
Expect(err).NotTo(HaveOccurred())
}()

// wait for the webhook server to get ready
dialer := &net.Dialer{Timeout: time.Second}
addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort)
Eventually(func() error {
conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true})
if err != nil {
return err
}

return conn.Close()
}).Should(Succeed())
})

var _ = AfterSuite(func() {
cancel()
By("tearing down the test environment")
err := testEnv.Stop()
Expect(err).NotTo(HaveOccurred())
})
44 changes: 42 additions & 2 deletions api/v1alpha1/zz_generated.deepcopy.go

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

Loading

0 comments on commit 91f7b62

Please sign in to comment.