github.com/demonoid81/containerd@v1.3.4/namespaces/context.go (about) 1 /* 2 Copyright The containerd 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 namespaces 18 19 import ( 20 "context" 21 "os" 22 23 "github.com/containerd/containerd/errdefs" 24 "github.com/pkg/errors" 25 ) 26 27 const ( 28 // NamespaceEnvVar is the environment variable key name 29 NamespaceEnvVar = "CONTAINERD_NAMESPACE" 30 // Default is the name of the default namespace 31 Default = "default" 32 ) 33 34 type namespaceKey struct{} 35 36 // WithNamespace sets a given namespace on the context 37 func WithNamespace(ctx context.Context, namespace string) context.Context { 38 ctx = context.WithValue(ctx, namespaceKey{}, namespace) // set our key for namespace 39 // also store on the grpc and ttrpc headers so it gets picked up by any clients that 40 // are using this. 41 return withTTRPCNamespaceHeader(withGRPCNamespaceHeader(ctx, namespace), namespace) 42 } 43 44 // NamespaceFromEnv uses the namespace defined in CONTAINERD_NAMESPACE or 45 // default 46 func NamespaceFromEnv(ctx context.Context) context.Context { 47 namespace := os.Getenv(NamespaceEnvVar) 48 if namespace == "" { 49 namespace = Default 50 } 51 return WithNamespace(ctx, namespace) 52 } 53 54 // Namespace returns the namespace from the context. 55 // 56 // The namespace is not guaranteed to be valid. 57 func Namespace(ctx context.Context) (string, bool) { 58 namespace, ok := ctx.Value(namespaceKey{}).(string) 59 if !ok { 60 if namespace, ok = fromGRPCHeader(ctx); !ok { 61 return fromTTRPCHeader(ctx) 62 } 63 } 64 return namespace, ok 65 } 66 67 // NamespaceRequired returns the valid namespace from the context or an error. 68 func NamespaceRequired(ctx context.Context) (string, error) { 69 namespace, ok := Namespace(ctx) 70 if !ok || namespace == "" { 71 return "", errors.Wrapf(errdefs.ErrFailedPrecondition, "namespace is required") 72 } 73 if err := Validate(namespace); err != nil { 74 return "", errors.Wrap(err, "namespace validation") 75 } 76 return namespace, nil 77 }