github.com/google/cadvisor@v0.49.1/container/containerd/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  // This code has been taken from containerd repo to avoid large library import
    16  package containerd
    17  
    18  import (
    19  	"github.com/google/cadvisor/container/containerd/namespaces"
    20  	"golang.org/x/net/context"
    21  	"google.golang.org/grpc"
    22  )
    23  
    24  type namespaceInterceptor struct {
    25  	namespace string
    26  }
    27  
    28  func (ni namespaceInterceptor) unary(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
    29  	_, ok := namespaces.Namespace(ctx)
    30  	if !ok {
    31  		ctx = namespaces.WithNamespace(ctx, ni.namespace)
    32  	}
    33  	return invoker(ctx, method, req, reply, cc, opts...)
    34  }
    35  
    36  func (ni namespaceInterceptor) stream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
    37  	_, ok := namespaces.Namespace(ctx)
    38  	if !ok {
    39  		ctx = namespaces.WithNamespace(ctx, ni.namespace)
    40  	}
    41  	return streamer(ctx, desc, cc, method, opts...)
    42  }
    43  
    44  func newNSInterceptors(ns string) (grpc.UnaryClientInterceptor, grpc.StreamClientInterceptor) {
    45  	ni := namespaceInterceptor{
    46  		namespace: ns,
    47  	}
    48  	return grpc.UnaryClientInterceptor(ni.unary), grpc.StreamClientInterceptor(ni.stream)
    49  }