Skip to content

Commit

Permalink
Add a validation webhook for ptp
Browse files Browse the repository at this point in the history
This commit adds a validation webhook when creating or updating ptp
config.
Validate that if interface is set in ptpconfig, then no other interfaces
are specified in ptp4lconf.
Also validate that summary_interval matches logSyncInterval
  • Loading branch information
josephdrichard committed Oct 26, 2021
1 parent 3edfdd3 commit 6fb2007
Show file tree
Hide file tree
Showing 47 changed files with 5,221 additions and 5 deletions.
6 changes: 5 additions & 1 deletion PROJECT
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
domain: openshift.io
layout: go.kubebuilder.io/v3
layout:
- go.kubebuilder.io/v3
plugins:
manifests.sdk.operatorframework.io/v2: {}
scorecard.sdk.operatorframework.io/v2: {}
Expand All @@ -15,6 +16,9 @@ resources:
kind: PtpConfig
path: github.com/openshift/ptp-operator/api/v1
version: v1
webhooks:
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: true
Expand Down
143 changes: 143 additions & 0 deletions api/v1/ptpconfig_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
Copyright 2021.
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 v1

import (
"errors"
"fmt"
"strings"

"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"
)

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

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

type ptp4lConfSection struct {
options map[string]string
}

type ptp4lConf struct {
sections map[string]ptp4lConfSection
}

func (output *ptp4lConf) populatePtp4lConf(config *string, ptp4lopts *string) error {
lines := strings.Split(*config, "\n")
var currentSection string
output.sections = make(map[string]ptp4lConfSection)

for _, line := range lines {
if strings.HasPrefix(line, "[") {
currentSection = line
currentLine := strings.Split(line, "]")

if len(currentLine) < 2 {
return errors.New("Section missing closing ']'")
}

currentSection = fmt.Sprintf("%s]", currentLine[0])
section := ptp4lConfSection{options: map[string]string{}}
output.sections[currentSection] = section
} else if currentSection != "" {
split := strings.IndexByte(line, ' ')
if split > 0 {
section := output.sections[currentSection]
section.options[line[:split]] = line[split+1:]
output.sections[currentSection] = section
}
} else {
return errors.New("Config option not in section")
}
}
_, exist := output.sections["[global]"]
if !exist {
output.sections["[global]"] = ptp4lConfSection{options: map[string]string{}}
}

// When validating, add ptp4lopts to conf for fields we check
opts := strings.Split(*ptp4lopts, " ")
for index, opt := range opts {
if opt == "--summary_interval" && index < len(opts)-1 {
output.sections["[global]"].options["summary_interval"] = opts[index+1]
}
}
return nil
}

func (r *PtpConfig) validate() error {
profiles := r.Spec.Profile
for _, profile := range profiles {
conf := &ptp4lConf{}
conf.populatePtp4lConf(profile.Ptp4lConf, profile.Ptp4lOpts)

// Validate that interface field only set in ordinary clock
if *profile.Interface != "" {
for section := range conf.sections {
if section != "[global]" {
if section != ("[" + *profile.Interface + "]") {
return errors.New("interface section " + section + " not allowed when specifying interface section")
}
}
}
}

// Validate that summary_interval matches logSyncInterval
summary_interval := "0"
logSyncInterval := "0"
for option, value := range conf.sections["[global]"].options {
if option == "summary_interval" {
summary_interval = value
}
if option == "logSyncInterval" {
logSyncInterval = value
}
}
if summary_interval != logSyncInterval {
return errors.New("summary_interval " + summary_interval + " must match logSyncInterval " + logSyncInterval)
}
}
return nil
}

var _ webhook.Validator = &PtpConfig{}

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

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

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *PtpConfig) ValidateDelete() error {
ptpconfiglog.Info("validate delete", "name", r.Name)
return nil
}
2 changes: 1 addition & 1 deletion bindata/linuxptp/ptp-daemon.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ kind: Service
metadata:
annotations:
prometheus.io/scrape: "true"
service.alpha.openshift.io/serving-cert-secret-name: linuxptp-daemon-secret
service.beta.openshift.io/serving-cert-secret-name: linuxptp-daemon-secret
labels:
name: ptp-monitor-service
name: ptp-monitor-service
Expand Down
6 changes: 3 additions & 3 deletions config/default/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ bases:
- ../manager
# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- ../webhook
- ../webhook
# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'. 'WEBHOOK' components are required.
#- ../certmanager
# [PROMETHEUS] To enable prometheus monitor, uncomment all sections with 'PROMETHEUS'.
Expand All @@ -29,12 +29,12 @@ patchesStrategicMerge:

# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- manager_webhook_patch.yaml
- manager_webhook_patch.yaml

# [CERTMANAGER] To enable cert-manager, uncomment all sections with 'CERTMANAGER'.
# Uncomment 'CERTMANAGER' sections in crd/kustomization.yaml to enable the CA injection in the admission webhooks.
# 'CERTMANAGER' needs to be enabled to use ca injection
#- webhookcainjection_patch.yaml
- webhookcainjection_patch.yaml

# the following config is for teaching kustomize how to do var substitution
vars:
Expand Down
25 changes: 25 additions & 0 deletions config/default/manager_webhook_patch.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: ptp-operator
namespace: openshift-ptp
annotations:
service.beta.openshift.io/serving-cert-secret-name: webhook-server-cert
spec:
template:
spec:
containers:
- name: ptp-operator
ports:
- containerPort: 9443
name: webhook-server
protocol: TCP
volumeMounts:
- mountPath: /tmp/k8s-webhook-server/serving-certs
name: cert
readOnly: true
volumes:
- name: cert
secret:
defaultMode: 420
secretName: webhook-server-cert
6 changes: 6 additions & 0 deletions config/default/webhookcainjection_patch.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: ptpconfig-validating-webhook-configuration
annotations:
service.beta.openshift.io/inject-cabundle: "true"
1 change: 1 addition & 0 deletions config/manager/manager.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ spec:
metadata:
annotations:
target.workload.openshift.io/management: '{"effect": "PreferredDuringScheduling"}'
service.beta.openshift.io/serving-cert-secret-name: webhook-server-cert
labels:
name: ptp-operator
spec:
Expand Down
6 changes: 6 additions & 0 deletions config/webhook/kustomization.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
resources:
- manifests.yaml
- service.yaml

configurations:
- kustomizeconfig.yaml
25 changes: 25 additions & 0 deletions config/webhook/kustomizeconfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# the following config is for teaching kustomize where to look at when substituting vars.
# It requires kustomize v2.1.0 or newer to work properly.
nameReference:
- kind: Service
version: v1
fieldSpecs:
- kind: MutatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/name
- kind: ValidatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/name

namespace:
- kind: MutatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/namespace
create: true
- kind: ValidatingWebhookConfiguration
group: admissionregistration.k8s.io
path: webhooks/clientConfig/service/namespace
create: true

varReference:
- path: metadata/annotations
29 changes: 29 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
creationTimestamp: null
name: ptpconfig-validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
- v1beta1
clientConfig:
service:
name: ptpconfig-validator-webhook-service
namespace: system
path: /validate-ptp-openshift-io-v1-ptpconfig
failurePolicy: Ignore
name: vptpconfig.kb.io
rules:
- apiGroups:
- ptp.openshift.io
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- ptpconfigs
sideEffects: None
15 changes: 15 additions & 0 deletions config/webhook/service.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

apiVersion: v1
kind: Service
metadata:
name: ptpconfig-validator-webhook-service
namespace: openshift-ptp
annotations:
service.beta.openshift.io/serving-cert-secret-name: webhook-server-cert
spec:
ports:
- port: 443
protocol: TCP
targetPort: 9443
selector:
name: ptp-operator
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ func main() {
setupLog.Error(err, "unable to create controller", "controller", "PtpConfig")
os.Exit(1)
}
if err = (&ptpv1.PtpConfig{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "PtpConfig")
os.Exit(1)
}
// +kubebuilder:scaffold:builder

err = createDefaultOperatorConfig(ctrl.GetConfigOrDie())
Expand Down
Loading

0 comments on commit 6fb2007

Please sign in to comment.