github.com/google/cadvisor@v0.49.1/container/containerd/namespaces/grpc.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  /*
    15     Copyright The containerd Authors.
    16  
    17     Licensed under the Apache License, Version 2.0 (the "License");
    18     you may not use this file except in compliance with the License.
    19     You may obtain a copy of the License at
    20  
    21         http://www.apache.org/licenses/LICENSE-2.0
    22  
    23     Unless required by applicable law or agreed to in writing, software
    24     distributed under the License is distributed on an "AS IS" BASIS,
    25     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    26     See the License for the specific language governing permissions and
    27     limitations under the License.
    28  */
    29  
    30  package namespaces
    31  
    32  import (
    33  	"context"
    34  
    35  	"google.golang.org/grpc/metadata"
    36  )
    37  
    38  const (
    39  	// GRPCHeader defines the header name for specifying a containerd namespace.
    40  	GRPCHeader = "containerd-namespace"
    41  )
    42  
    43  // NOTE(stevvooe): We can stub this file out if we don't want a grpc dependency here.
    44  
    45  func withGRPCNamespaceHeader(ctx context.Context, namespace string) context.Context {
    46  	// also store on the grpc headers so it gets picked up by any clients that
    47  	// are using this.
    48  	nsheader := metadata.Pairs(GRPCHeader, namespace)
    49  	md, ok := metadata.FromOutgoingContext(ctx) // merge with outgoing context.
    50  	if !ok {
    51  		md = nsheader
    52  	} else {
    53  		// order ensures the latest is first in this list.
    54  		md = metadata.Join(nsheader, md)
    55  	}
    56  
    57  	return metadata.NewOutgoingContext(ctx, md)
    58  }
    59  
    60  func fromGRPCHeader(ctx context.Context) (string, bool) {
    61  	// try to extract for use in grpc servers.
    62  	md, ok := metadata.FromIncomingContext(ctx)
    63  	if !ok {
    64  		// TODO(stevvooe): Check outgoing context?
    65  		return "", false
    66  	}
    67  
    68  	values := md[GRPCHeader]
    69  	if len(values) == 0 {
    70  		return "", false
    71  	}
    72  
    73  	return values[0], true
    74  }