github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/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 containerd
    18  
    19  import (
    20  	"context"
    21  
    22  	"github.com/containerd/containerd/namespaces"
    23  	"google.golang.org/grpc"
    24  )
    25  
    26  type namespaceInterceptor struct {
    27  	namespace string
    28  }
    29  
    30  func (ni namespaceInterceptor) unary(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
    31  	_, ok := namespaces.Namespace(ctx)
    32  	if !ok {
    33  		ctx = namespaces.WithNamespace(ctx, ni.namespace)
    34  	}
    35  	return invoker(ctx, method, req, reply, cc, opts...)
    36  }
    37  
    38  func (ni namespaceInterceptor) stream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
    39  	_, ok := namespaces.Namespace(ctx)
    40  	if !ok {
    41  		ctx = namespaces.WithNamespace(ctx, ni.namespace)
    42  	}
    43  
    44  	return streamer(ctx, desc, cc, method, opts...)
    45  }
    46  
    47  func newNSInterceptors(ns string) (grpc.UnaryClientInterceptor, grpc.StreamClientInterceptor) {
    48  	ni := namespaceInterceptor{
    49  		namespace: ns,
    50  	}
    51  	return grpc.UnaryClientInterceptor(ni.unary), grpc.StreamClientInterceptor(ni.stream)
    52  }