|
| 1 | +/* |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +*/ |
| 15 | +// +kubebuilder:docs-gen:collapse=Apache License |
| 16 | + |
| 17 | +package v1 |
| 18 | + |
| 19 | +import ( |
| 20 | + "github.com/robfig/cron" |
| 21 | + |
| 22 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 23 | + "k8s.io/apimachinery/pkg/runtime" |
| 24 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 25 | + validationutils "k8s.io/apimachinery/pkg/util/validation" |
| 26 | + "k8s.io/apimachinery/pkg/util/validation/field" |
| 27 | + |
| 28 | + ctrl "sigs.k8s.io/controller-runtime" |
| 29 | + logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" |
| 30 | + "sigs.k8s.io/controller-runtime/pkg/webhook" |
| 31 | +) |
| 32 | + |
| 33 | +// +kubebuilder:docs-gen:collapse=Go imports |
| 34 | + |
| 35 | +/* |
| 36 | +Next, we'll setup a logger for the webhooks. |
| 37 | +*/ |
| 38 | + |
| 39 | +var cronjoblog = logf.Log.WithName("cronjob-resource") |
| 40 | + |
| 41 | +/* |
| 42 | +Then, we set up the webhook with the manager. |
| 43 | +*/ |
| 44 | + |
| 45 | +func (r *CronJob) SetupWebhookWithManager(mgr ctrl.Manager) error { |
| 46 | + return ctrl.NewWebhookManagedBy(mgr). |
| 47 | + For(r). |
| 48 | + Complete() |
| 49 | +} |
| 50 | + |
| 51 | +/* |
| 52 | +Notice that we use kubebuilder markers to generate webhook manifests. |
| 53 | +This markers is responsible for generating a mutating webhook manifest. |
| 54 | +
|
| 55 | +The meaning of each marker can be found [here](../TODO.md). |
| 56 | +*/ |
| 57 | + |
| 58 | +// +kubebuilder:webhook:path=/mutate-batch-tutorial-kubebuilder-io-tutorial-kubebuilder-io-v1-cronjob,mutating=true,failurePolicy=fail,groups=batch.tutorial.kubebuilder.io.tutorial.kubebuilder.io,resources=cronjobs,verbs=create;update,versions=v1,name=mcronjob.kb.io |
| 59 | + |
| 60 | +/* |
| 61 | +We use the `webhook.Defaulter` interface to set defaults to our CRD. |
| 62 | +A webhook will automatically be served that calls this defaulting. |
| 63 | +
|
| 64 | +The `Default` method is expected to mutate the receiver, setting the defaults. |
| 65 | +*/ |
| 66 | + |
| 67 | +var _ webhook.Defaulter = &CronJob{} |
| 68 | + |
| 69 | +// Default implements webhook.Defaulter so a webhook will be registered for the type |
| 70 | +func (r *CronJob) Default() { |
| 71 | + cronjoblog.Info("default", "name", r.Name) |
| 72 | + |
| 73 | + if r.Spec.ConcurrencyPolicy == "" { |
| 74 | + r.Spec.ConcurrencyPolicy = AllowConcurrent |
| 75 | + } |
| 76 | + if r.Spec.Suspend == nil { |
| 77 | + r.Spec.Suspend = new(bool) |
| 78 | + } |
| 79 | + if r.Spec.SuccessfulJobsHistoryLimit == nil { |
| 80 | + r.Spec.SuccessfulJobsHistoryLimit = new(int32) |
| 81 | + *r.Spec.SuccessfulJobsHistoryLimit = 3 |
| 82 | + } |
| 83 | + if r.Spec.FailedJobsHistoryLimit == nil { |
| 84 | + r.Spec.FailedJobsHistoryLimit = new(int32) |
| 85 | + *r.Spec.FailedJobsHistoryLimit = 1 |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +/* |
| 90 | +Notice that we use kubebuilder markers to generate webhook manifests. |
| 91 | +This markers is responsible for generating a validating webhook manifest. |
| 92 | +
|
| 93 | +The meaning of each marker can be found [here](../TODO.md). |
| 94 | +*/ |
| 95 | + |
| 96 | +// +kubebuilder:webhook:path=/validate-batch-tutorial-kubebuilder-io-tutorial-kubebuilder-io-v1-cronjob,mutating=false,failurePolicy=fail,groups=batch.tutorial.kubebuilder.io.tutorial.kubebuilder.io,resources=cronjobs,verbs=create;update,versions=v1,name=vcronjob.kb.io |
| 97 | + |
| 98 | +/* |
| 99 | +To validate our CRD beyond what's possible with declarative validation. |
| 100 | +Generally, declarative validation should be sufficient, but sometimes more |
| 101 | +advanced use cases call for complex validation. |
| 102 | +
|
| 103 | +For instance, we'll see below that we use this to validate a well-formed cron |
| 104 | +schedule without making up a long regular expression. |
| 105 | +
|
| 106 | +If `webhook.Validator` interface is implemented, a webhook will automatically be |
| 107 | +served that calls the validation. |
| 108 | +
|
| 109 | +The `ValidateCreate` and `ValidateUpdate` methods are expected to validate that its |
| 110 | +receiver upon creation and update respectively. We separate out ValidateCreate |
| 111 | +from ValidateUpdate to allow behavior like making certain fields immutable, so |
| 112 | +that they can only be set on creation. |
| 113 | +Here, however, we just use the same shared validation. |
| 114 | +*/ |
| 115 | + |
| 116 | +var _ webhook.Validator = &CronJob{} |
| 117 | + |
| 118 | +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type |
| 119 | +func (r *CronJob) ValidateCreate() error { |
| 120 | + cronjoblog.Info("validate create", "name", r.Name) |
| 121 | + |
| 122 | + return r.validateCronJob() |
| 123 | +} |
| 124 | + |
| 125 | +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type |
| 126 | +func (r *CronJob) ValidateUpdate(old runtime.Object) error { |
| 127 | + cronjoblog.Info("validate update", "name", r.Name) |
| 128 | + |
| 129 | + return r.validateCronJob() |
| 130 | +} |
| 131 | + |
| 132 | +/* |
| 133 | +We validate the name and the spec of the CronJob. |
| 134 | +*/ |
| 135 | + |
| 136 | +func (c *CronJob) validateCronJob() error { |
| 137 | + allErrs := c.validateCronJobSpec() |
| 138 | + if err := c.validateCronJobName(); err != nil { |
| 139 | + allErrs = append(allErrs, err) |
| 140 | + } |
| 141 | + |
| 142 | + return apierrors.NewInvalid( |
| 143 | + schema.GroupKind{Group: "batch.tutorial.kubebuilder.io", Kind: "CronJob"}, |
| 144 | + c.Name, allErrs) |
| 145 | +} |
| 146 | + |
| 147 | +/* |
| 148 | +Some fields are declaratively validated by OpenAPI schema. |
| 149 | +You can find kubebuilder validation markers (prefixed |
| 150 | +with `// +kubebuilder:validation`) in the [API](api-design.md) |
| 151 | +You can find all of the kubebuilder supported markers for |
| 152 | +declaring validation in [here](../TODO.md). |
| 153 | +*/ |
| 154 | + |
| 155 | +func (c *CronJob) validateCronJobSpec() field.ErrorList { |
| 156 | + // The field helpers from the kubernetes API machinery help us return nicely |
| 157 | + // structured validation errors. |
| 158 | + allErrs := field.ErrorList{} |
| 159 | + allErrs = append(allErrs, validateScheduleFormat( |
| 160 | + c.Spec.Schedule, |
| 161 | + field.NewPath("spec").Child("schedule"))...) |
| 162 | + return allErrs |
| 163 | +} |
| 164 | + |
| 165 | +/* |
| 166 | +Validating the length of a string field can be done declaratively by |
| 167 | +the validation schema. |
| 168 | +
|
| 169 | +But the `ObjectMeta.Name` field is defined in a shared package under |
| 170 | +the apimachinery repo, so we can't declaratively validate it using |
| 171 | +the validation schema. |
| 172 | +*/ |
| 173 | + |
| 174 | +func (c *CronJob) validateCronJobName() *field.Error { |
| 175 | + if len(c.ObjectMeta.Name) > validationutils.DNS1035LabelMaxLength-11 { |
| 176 | + // The job name length is 63 character like all Kubernetes objects |
| 177 | + // (which must fit in a DNS subdomain). The cronjob controller appends |
| 178 | + // a 11-character suffix to the cronjob (`-$TIMESTAMP`) when creating |
| 179 | + // a job. The job name length limit is 63 characters. Therefore cronjob |
| 180 | + // names must have length <= 63-11=52. If we don't validate this here, |
| 181 | + // then job creation will fail later. |
| 182 | + return field.Invalid(field.NewPath("metadata").Child("name"), c.Name, "must be no more than 52 characters") |
| 183 | + } |
| 184 | + return nil |
| 185 | +} |
| 186 | + |
| 187 | +// +kubebuilder:docs-gen:collapse=Validate object name |
| 188 | + |
| 189 | +/* |
| 190 | +We'll need to validate the [cron](https://en.wikipedia.org/wiki/Cron) schedule |
| 191 | +is well-formatted. |
| 192 | +*/ |
| 193 | + |
| 194 | +func validateScheduleFormat(schedule string, fldPath *field.Path) field.ErrorList { |
| 195 | + allErrs := field.ErrorList{} |
| 196 | + if _, err := cron.ParseStandard(schedule); err != nil { |
| 197 | + allErrs = append(allErrs, field.Invalid(fldPath, schedule, err.Error())) |
| 198 | + } |
| 199 | + |
| 200 | + return allErrs |
| 201 | +} |
0 commit comments