-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathinstrumentation_webhook.go
More file actions
189 lines (160 loc) · 7.37 KB
/
instrumentation_webhook.go
File metadata and controls
189 lines (160 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
Copyright 2025.
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 (
"context"
"fmt"
"slices"
"strings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
// SetupWebhookWithManager will setup the manager to manage the webhooks
func SetupWebhookWithManager(mgr ctrl.Manager, operatorNamespace string) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&Instrumentation{}).
WithValidator(&InstrumentationValidator{OperatorNamespace: operatorNamespace}).
WithDefaulter(&InstrumentationDefaulter{}).
Complete()
}
// +kubebuilder:webhook:path=/mutate-newrelic-com-v1beta1-instrumentation,mutating=true,failurePolicy=fail,sideEffects=None,groups=newrelic.com,resources=instrumentations,verbs=create;update,versions=v1beta1,name=minstrumentation-v1beta1.kb.io,admissionReviewVersions=v1
var _ webhook.CustomDefaulter = (*InstrumentationDefaulter)(nil)
// InstrumentationDefaulter is used to set defaults for instrumentation
type InstrumentationDefaulter struct {
}
// Default to set the default values for Instrumentation
func (r *InstrumentationDefaulter) Default(ctx context.Context, obj runtime.Object) error {
inst := obj.(*Instrumentation)
log.FromContext(ctx).V(1).Info("Setting defaults for v1beta1.Instrumentation", "name", inst.GetName())
if inst.Labels == nil {
inst.Labels = map[string]string{}
}
if inst.Labels["app.kubernetes.io/managed-by"] == "" {
inst.Labels["app.kubernetes.io/managed-by"] = "k8s-agents-operator"
}
if inst.Spec.LicenseKeySecret == "" {
inst.Spec.LicenseKeySecret = "newrelic-key-secret"
}
return nil
}
// NOTE: The 'path' attribute must follow a specific pattern and should not be modified directly here.
// Modifying the path for an invalid path can cause API server errors; failing to locate the webhook.
// +kubebuilder:webhook:verbs=create;update,path=/validate-newrelic-com-v1beta1-instrumentation,mutating=false,failurePolicy=fail,groups=newrelic.com,resources=instrumentations,versions=v1beta1,name=vinstrumentationcreateupdate-v1beta1.kb.io,sideEffects=none,admissionReviewVersions=v1
// +kubebuilder:webhook:verbs=delete,path=/validate-newrelic-com-v1beta1-instrumentation,mutating=false,failurePolicy=ignore,groups=newrelic.com,resources=instrumentations,versions=v1beta1,name=vinstrumentationdelete-v1beta1.kb.io,sideEffects=none,admissionReviewVersions=v1
var validEnvPrefixes = []string{"NEW_RELIC_", "NEWRELIC_"}
var validEnvPrefixesStr = strings.Join(validEnvPrefixes, ", ")
var _ webhook.CustomValidator = &InstrumentationValidator{}
// InstrumentationValidator is used to validate instrumentations
type InstrumentationValidator struct {
OperatorNamespace string
}
// ValidateCreate to validate the creation operation
func (r *InstrumentationValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
inst := obj.(*Instrumentation)
log.FromContext(ctx).V(1).Info("Validating creation of v1beta1.Instrumentation", "name", inst.GetName())
return r.validate(inst)
}
// ValidateUpdate to validate the update operation
func (r *InstrumentationValidator) ValidateUpdate(ctx context.Context, oldObj runtime.Object, newObj runtime.Object) (admission.Warnings, error) {
inst := newObj.(*Instrumentation)
log.FromContext(ctx).V(1).Info("Validating update of v1beta1.Instrumentation", "name", inst.GetName())
return r.validate(inst)
}
// ValidateDelete to validate the deletion operation
func (r *InstrumentationValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
inst := obj.(*Instrumentation)
log.FromContext(ctx).V(1).Info("Validating deletion of v1beta1.Instrumentation", "name", inst.GetName())
return r.validate(inst)
}
var acceptableLangs = []string{
"dotnet",
"dotnet-windows2022",
"dotnet-windows2025",
"go",
"java",
"nodejs",
"php-7.2", "php-7.3", "php-7.4", "php-8.0", "php-8.1", "php-8.2", "php-8.3", "php-8.4", "php-8.5",
"python",
"ruby",
}
var acceptLangsForAgentConfigMap = []string{"java"}
// validate to validate all the fields
func (r *InstrumentationValidator) validate(inst *Instrumentation) (admission.Warnings, error) {
if r.OperatorNamespace != inst.Namespace {
return nil, fmt.Errorf("instrumentation must be in operator namespace")
}
// Check if agent is empty first, before validating individual fields
if inst.Spec.Agent.IsEmpty() {
return nil, fmt.Errorf("instrumentation %q agent is empty", inst.Name)
}
agentLang := inst.Spec.Agent.Language
if !slices.Contains(acceptableLangs, agentLang) {
return nil, fmt.Errorf("instrumentation agent language %q must be one of the accepted languages (%s)", agentLang, strings.Join(acceptableLangs, ", "))
}
if inst.Spec.AgentConfigMap != "" {
if !slices.Contains(acceptLangsForAgentConfigMap, agentLang) {
return nil, fmt.Errorf("instrumentation agent language %q does not support an agentConfigMap, agentConfigMap can only be configured with one of these languages (%q)", agentLang, strings.Join(acceptLangsForAgentConfigMap, ", "))
}
// Check that NEWRELIC_FILE is not set when using agentConfigMap (Java only)
for _, env := range inst.Spec.Agent.Env {
if env.Name == "NEWRELIC_FILE" {
return nil, fmt.Errorf("%q is already set by the agentConfigMap", env.Name)
}
}
}
if err := r.validateEnv(inst.Spec.Agent.Env); err != nil {
return nil, err
}
if len(inst.Spec.HealthAgent.Env) > 0 && inst.Spec.HealthAgent.Image == "" {
return nil, fmt.Errorf("instrumentation %q healthAgent.image is empty, meanwhile the environment is not", inst.Name)
}
if _, err := metav1.LabelSelectorAsSelector(&inst.Spec.PodLabelSelector); err != nil {
return nil, err
}
if _, err := metav1.LabelSelectorAsSelector(&inst.Spec.NamespaceLabelSelector); err != nil {
return nil, err
}
return nil, nil
}
// validateEnv to validate the environment variables used all start with the required prefixes
func (r *InstrumentationValidator) validateEnv(envs []corev1.EnvVar) error {
// First, check that NEW_RELIC_LICENSE_KEY is not set (it should only be in the secret)
for _, env := range envs {
if env.Name == "NEW_RELIC_LICENSE_KEY" {
return fmt.Errorf("NEW_RELIC_LICENSE_KEY should not be set in agent.env; the license key should be set via the licenseKeySecret field")
}
}
// Then validate that all env vars start with valid prefixes
var invalidNames []string
for _, env := range envs {
var valid bool
for _, validEnvPrefix := range validEnvPrefixes {
if strings.HasPrefix(env.Name, validEnvPrefix) {
valid = true
break
}
}
if !valid {
invalidNames = append(invalidNames, env.Name)
}
}
if len(invalidNames) > 0 {
return fmt.Errorf("env name should start with %s; found these invalid names %s", validEnvPrefixesStr, strings.Join(invalidNames, ", "))
}
return nil
}