github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/namespaces/grpc.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 22 "google.golang.org/grpc/metadata" 23 ) 24 25 const ( 26 // GRPCHeader defines the header name for specifying a containerd namespace. 27 GRPCHeader = "containerd-namespace" 28 ) 29 30 // NOTE(stevvooe): We can stub this file out if we don't want a grpc dependency here. 31 32 func withGRPCNamespaceHeader(ctx context.Context, namespace string) context.Context { 33 // also store on the grpc headers so it gets picked up by any clients that 34 // are using this. 35 nsheader := metadata.Pairs(GRPCHeader, namespace) 36 md, ok := metadata.FromOutgoingContext(ctx) // merge with outgoing context. 37 if !ok { 38 md = nsheader 39 } else { 40 // order ensures the latest is first in this list. 41 md = metadata.Join(nsheader, md) 42 } 43 44 return metadata.NewOutgoingContext(ctx, md) 45 } 46 47 func fromGRPCHeader(ctx context.Context) (string, bool) { 48 // try to extract for use in grpc servers. 49 md, ok := metadata.FromIncomingContext(ctx) 50 if !ok { 51 // TODO(stevvooe): Check outgoing context? 52 return "", false 53 } 54 55 values := md[GRPCHeader] 56 if len(values) == 0 { 57 return "", false 58 } 59 60 return values[0], true 61 }