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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
|
/*
Copyright 2017 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 value
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"regexp"
"strings"
"testing"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/component-base/metrics/legacyregistry"
"k8s.io/component-base/metrics/testutil"
"k8s.io/klog/v2"
)
type testTransformer struct {
from, to []byte
err error
stale bool
receivedFrom, receivedTo []byte
}
func (t *testTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx Context) (out []byte, stale bool, err error) {
t.receivedFrom = data
return t.from, t.stale, t.err
}
func (t *testTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx Context) (out []byte, err error) {
t.receivedTo = data
return t.to, t.err
}
func TestPrefixFrom(t *testing.T) {
testErr := fmt.Errorf("test error")
transformErr := fmt.Errorf("transform error")
transformers := []PrefixTransformer{
{Prefix: []byte("first:"), Transformer: &testTransformer{from: []byte("value1")}},
{Prefix: []byte("second:"), Transformer: &testTransformer{from: []byte("value2")}},
{Prefix: []byte("fails:"), Transformer: &testTransformer{err: transformErr}},
{Prefix: []byte("stale:"), Transformer: &testTransformer{from: []byte("value3"), stale: true}},
}
p := NewPrefixTransformers(testErr, transformers...)
testCases := []struct {
input []byte
expect []byte
stale bool
err error
match int
}{
{[]byte("first:value"), []byte("value1"), false, nil, 0},
{[]byte("second:value"), []byte("value2"), true, nil, 1},
{[]byte("third:value"), nil, false, testErr, -1},
{[]byte("fails:value"), nil, false, transformErr, 2},
{[]byte("stale:value"), []byte("value3"), true, nil, 3},
}
reqCtx := genericapirequest.WithRequestInfo(context.Background(), &genericapirequest.RequestInfo{Resource: "test"})
for i, test := range testCases {
got, stale, err := p.TransformFromStorage(reqCtx, test.input, nil)
if err != test.err || stale != test.stale || !bytes.Equal(got, test.expect) {
t.Errorf("%d: unexpected out: %q %t %#v", i, string(got), stale, err)
continue
}
if test.match != -1 && !bytes.Equal([]byte("value"), transformers[test.match].Transformer.(*testTransformer).receivedFrom) {
t.Errorf("%d: unexpected value received by transformer: %s", i, transformers[test.match].Transformer.(*testTransformer).receivedFrom)
}
}
}
func TestPrefixTo(t *testing.T) {
testErr := fmt.Errorf("test error")
transformErr := fmt.Errorf("test error")
testCases := []struct {
transformers []PrefixTransformer
expect []byte
err error
}{
{[]PrefixTransformer{{Prefix: []byte("first:"), Transformer: &testTransformer{to: []byte("value1")}}}, []byte("first:value1"), nil},
{[]PrefixTransformer{{Prefix: []byte("second:"), Transformer: &testTransformer{to: []byte("value2")}}}, []byte("second:value2"), nil},
{[]PrefixTransformer{{Prefix: []byte("fails:"), Transformer: &testTransformer{err: transformErr}}}, nil, transformErr},
}
reqCtx := genericapirequest.WithRequestInfo(context.Background(), &genericapirequest.RequestInfo{Resource: "test"})
for i, test := range testCases {
p := NewPrefixTransformers(testErr, test.transformers...)
got, err := p.TransformToStorage(reqCtx, []byte("value"), nil)
if err != test.err || !bytes.Equal(got, test.expect) {
t.Errorf("%d: unexpected out: %q %#v", i, string(got), err)
continue
}
if !bytes.Equal([]byte("value"), test.transformers[0].Transformer.(*testTransformer).receivedTo) {
t.Errorf("%d: unexpected value received by transformer: %s", i, test.transformers[0].Transformer.(*testTransformer).receivedTo)
}
}
}
func TestPrefixFromMetrics(t *testing.T) {
testErr := fmt.Errorf("test error")
transformerErr := fmt.Errorf("test error")
identityTransformer := PrefixTransformer{Prefix: []byte{}, Transformer: &testTransformer{from: []byte("value1")}}
identityTransformerErr := PrefixTransformer{Prefix: []byte{}, Transformer: &testTransformer{err: transformerErr}}
otherTransformer := PrefixTransformer{Prefix: []byte("other:"), Transformer: &testTransformer{from: []byte("value1")}}
otherTransformerErr := PrefixTransformer{Prefix: []byte("other:"), Transformer: &testTransformer{err: transformerErr}}
testCases := []struct {
desc string
input []byte
prefix Transformer
metrics []string
want string
expectErr bool
}{
{
desc: "identity prefix",
input: []byte("value"),
prefix: NewPrefixTransformers(testErr, identityTransformer, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="OK",transformation_type="from_storage",transformer_prefix="identity"} 1
`,
expectErr: false,
},
{
desc: "other prefix (ok)",
input: []byte("other:value"),
prefix: NewPrefixTransformers(testErr, identityTransformerErr, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="OK",transformation_type="from_storage",transformer_prefix="other:"} 1
`,
expectErr: false,
},
{
desc: "other prefix (error)",
input: []byte("other:value"),
prefix: NewPrefixTransformers(testErr, identityTransformerErr, otherTransformerErr),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="unknown-non-grpc",transformation_type="from_storage",transformer_prefix="other:"} 1
`,
expectErr: true,
},
{
desc: "unknown prefix",
input: []byte("foo:value"),
prefix: NewPrefixTransformers(testErr, identityTransformerErr, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="unknown-non-grpc",transformation_type="from_storage",transformer_prefix="unknown"} 1
`,
expectErr: true,
},
}
RegisterMetrics()
transformerOperationsTotal.Reset()
reqCtx := genericapirequest.WithRequestInfo(context.Background(), &genericapirequest.RequestInfo{Resource: "test"})
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
_, _, err := tc.prefix.TransformFromStorage(reqCtx, tc.input, nil)
if (err != nil) != tc.expectErr {
t.Fatal(err)
}
defer transformerOperationsTotal.Reset()
if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tc.want), tc.metrics...); err != nil {
t.Fatal(err)
}
})
}
}
func TestPrefixToMetrics(t *testing.T) {
testErr := fmt.Errorf("test error")
transformerErr := fmt.Errorf("test error")
otherTransformer := PrefixTransformer{Prefix: []byte("other:"), Transformer: &testTransformer{from: []byte("value1")}}
otherTransformerErr := PrefixTransformer{Prefix: []byte("other:"), Transformer: &testTransformer{err: transformerErr}}
reqCtx := genericapirequest.WithRequestInfo(context.Background(), &genericapirequest.RequestInfo{Resource: "test"})
testCases := []struct {
desc string
input []byte
prefix Transformer
metrics []string
want string
expectErr bool
ctx context.Context
}{
{
desc: "ok",
input: []byte("value"),
prefix: NewPrefixTransformers(testErr, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="OK",transformation_type="to_storage",transformer_prefix="other:"} 1
`,
expectErr: false,
ctx: reqCtx,
},
{
desc: "missing request context",
input: []byte("value"),
prefix: NewPrefixTransformers(testErr, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="",status="OK",transformation_type="to_storage",transformer_prefix="other:"} 1
`,
expectErr: false,
ctx: context.Background(),
},
{
desc: "request context with api group",
input: []byte("value"),
prefix: NewPrefixTransformers(testErr, otherTransformer),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test.testGroup",status="OK",transformation_type="to_storage",transformer_prefix="other:"} 1
`,
expectErr: false,
ctx: genericapirequest.WithRequestInfo(context.Background(), &genericapirequest.RequestInfo{APIGroup: "testGroup", Resource: "test"}),
},
{
desc: "error",
input: []byte("value"),
prefix: NewPrefixTransformers(testErr, otherTransformerErr),
metrics: []string{
"apiserver_storage_transformation_operations_total",
},
want: `
# HELP apiserver_storage_transformation_operations_total [ALPHA] Total number of transformations. Successful transformation will have a status 'OK' and a varied status string when the transformation fails. The status, resource, and transformation_type fields can be used for alerting purposes. For example, you can monitor for encryption/decryption failures using the transformation_type (e.g., from_storage for decryption and to_storage for encryption). Additionally, these fields can be used to ensure that the correct transformers are applied to each resource.
# TYPE apiserver_storage_transformation_operations_total counter
apiserver_storage_transformation_operations_total{resource="test",status="unknown-non-grpc",transformation_type="to_storage",transformer_prefix="other:"} 1
`,
expectErr: true,
ctx: reqCtx,
},
}
RegisterMetrics()
transformerOperationsTotal.Reset()
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
_, err := tc.prefix.TransformToStorage(tc.ctx, tc.input, nil)
if (err != nil) != tc.expectErr {
t.Fatal(err)
}
defer transformerOperationsTotal.Reset()
if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tc.want), tc.metrics...); err != nil {
t.Fatal(err)
}
})
}
}
func TestLogTransformErr(t *testing.T) {
klog.InitFlags(nil)
tests := []struct {
name string
ctx context.Context
err error
message string
expectedLog string
}{
{
name: "log error with request info",
ctx: genericapirequest.WithRequestInfo(testContext(t), &genericapirequest.RequestInfo{
APIGroup: "awesome.bears.com",
APIVersion: "v1",
Resource: "pandas",
Subresource: "status",
Namespace: "kube-system",
Name: "panda",
Verb: "update",
}),
err: errors.New("encryption failed"),
message: "failed to encrypt data",
expectedLog: "\"failed to encrypt data\" err=\"encryption failed\" group=\"awesome.bears.com\" version=\"v1\" resource=\"pandas\" subresource=\"status\" verb=\"update\" namespace=\"kube-system\" name=\"panda\"\n",
},
{
name: "log error without request info",
ctx: context.Background(),
err: errors.New("decryption failed"),
message: "failed to decrypt data",
expectedLog: "\"no request info on context\"\n\"failed to decrypt data\" err=\"decryption failed\" group=\"\" version=\"\" resource=\"\" subresource=\"\" verb=\"\" namespace=\"\" name=\"\"\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
flag.Set("v", "6")
flag.Parse()
klog.SetOutput(&buf)
klog.LogToStderr(false)
defer klog.LogToStderr(true)
logTransformErr(tt.ctx, tt.err, tt.message)
// remove timestamp and goroutine id from log message to make it easier to compare
gotLog := regexp.MustCompile(`\w+ \d+:\d+:\d+\.\d+.*\d+.*(transformer_test\.go|transformer\.go):\d+].`).ReplaceAllString(buf.String(), "")
if gotLog != tt.expectedLog {
t.Errorf("expected log message %q, got %q", tt.expectedLog, gotLog)
}
})
}
}
func testContext(t *testing.T) context.Context {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
return ctx
}
|