grpc.go 1.8 KB

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