From 5a664d7260c0de1f80ebe0813f322f237ff2b610 Mon Sep 17 00:00:00 2001
From: Eric Gribkoff <ericgribkoff@google.com>
Date: Thu, 9 Aug 2018 09:02:32 -0700
Subject: [PATCH] check if channel is closed before starting core ops

---
 .../grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi  | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
index 893df8eac67..aa187e88a62 100644
--- a/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi
@@ -309,13 +309,18 @@ cdef SegregatedCall _segregated_call(
     _ChannelState state, int flags, method, host, object deadline,
     object metadata, CallCredentials credentials, operationses_and_user_tags):
   cdef _CallState call_state = _CallState()
-  cdef grpc_completion_queue *c_completion_queue = (
-      grpc_completion_queue_create_for_next(NULL))
   cdef SegregatedCall segregated_call
+  cdef grpc_completion_queue *c_completion_queue
 
   def on_success(started_tags):
     state.segregated_call_states.add(call_state)
 
+  with state.condition:
+    if state.open:
+      c_completion_queue = (grpc_completion_queue_create_for_next(NULL))
+    else:
+      raise ValueError('Cannot invoke RPC on closed channel!')
+
   try:
     _call(
         state, call_state, c_completion_queue, on_success, flags, method, host,
@@ -443,8 +448,11 @@ cdef class Channel:
 
   def check_connectivity_state(self, bint try_to_connect):
     with self._state.condition:
-      return grpc_channel_check_connectivity_state(
-          self._state.c_channel, try_to_connect)
+      if self._state.open:
+        return grpc_channel_check_connectivity_state(
+            self._state.c_channel, try_to_connect)
+      else:
+        raise ValueError('Cannot invoke RPC on closed channel!')
 
   def watch_connectivity_state(
       self, grpc_connectivity_state last_observed_state, object deadline):