k8s.io/apiserver@v0.31.1/pkg/warning/context.go (about) 1 /* 2 Copyright 2020 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package warning 18 19 import ( 20 "context" 21 ) 22 23 // The key type is unexported to prevent collisions 24 type key int 25 26 const ( 27 // warningRecorderKey is the context key for the warning recorder. 28 warningRecorderKey key = iota 29 ) 30 31 // Recorder provides a method for recording warnings 32 type Recorder interface { 33 // AddWarning adds the specified warning to the response. 34 // agent must be valid UTF-8, and must not contain spaces, quotes, backslashes, or control characters. 35 // text must be valid UTF-8, and must not contain control characters. 36 AddWarning(agent, text string) 37 } 38 39 // WithWarningRecorder returns a new context that wraps the provided context and contains the provided Recorder implementation. 40 // The returned context can be passed to AddWarning(). 41 func WithWarningRecorder(ctx context.Context, recorder Recorder) context.Context { 42 return context.WithValue(ctx, warningRecorderKey, recorder) 43 } 44 45 func warningRecorderFrom(ctx context.Context) (Recorder, bool) { 46 recorder, ok := ctx.Value(warningRecorderKey).(Recorder) 47 return recorder, ok 48 } 49 50 // AddWarning records a warning for the specified agent and text to the Recorder added to the provided context using WithWarningRecorder(). 51 // If no Recorder exists in the provided context, this is a no-op. 52 // agent must be valid UTF-8, and must not contain spaces, quotes, backslashes, or control characters. 53 // text must be valid UTF-8, and must not contain control characters. 54 func AddWarning(ctx context.Context, agent string, text string) { 55 recorder, ok := warningRecorderFrom(ctx) 56 if !ok { 57 return 58 } 59 recorder.AddWarning(agent, text) 60 }