@@ -46,8 +46,8 @@ class UnixSocketConnector(object):
4646 """Unix Domain Socket connector. Connects to socket lazily."""
4747
4848 def __init__ (self , socket_path ):
49- self .socket_path = socket_path
50- self .socket = None
49+ self ._socket_path = socket_path
50+ self ._socket = None
5151
5252 @staticmethod
5353 def _get_error_message (os_error_number ):
@@ -57,41 +57,41 @@ def _get_error_message(os_error_number):
5757 return "Connection to '{}' refused"
5858 return "Unknown error when connecting to '{}'"
5959
60- def is_connected (self ):
61- return self .socket is not None
62-
63- def _connect (self ):
64- if self .socket is None :
60+ def socket (self ):
61+ """Returns connected socket."""
62+ if self ._socket is None :
6563 try :
6664 s = socket .socket (socket .AF_UNIX , socket .SOCK_STREAM )
67- s .connect (self .socket_path )
65+ s .connect (self ._socket_path )
6866 s .settimeout (1 )
6967 # Assign last, to keep it None in case of exception.
70- self .socket = s
68+ self ._socket = s
7169 except OSError as ex :
7270 msg = self ._get_error_message (ex .errno )
73- err = BackendError (msg .format (self .socket_path ))
71+ err = BackendError (msg .format (self ._socket_path ))
7472 raise err from ex
73+ return self ._socket
7574
76- def _reconnect (self ):
77- self .socket .shutdown (socket .SHUT_RDWR )
78- self .socket .close ()
79- self .socket = None
80- self ._connect ()
75+ def close (self ):
76+ if self ._socket is not None :
77+ self ._socket .shutdown (socket .SHUT_RDWR )
78+ self ._socket .close ()
79+ self ._socket = None
80+
81+ def is_connected (self ):
82+ return self ._socket is not None
8183
8284 def recv (self , max_length ):
83- self ._connect ()
84- return self .socket .recv (max_length )
85+ return self .socket ().recv (max_length )
8586
8687 def sendall (self , data ):
87- self ._connect ()
8888 try :
89- return self .socket .sendall (data )
89+ return self .socket () .sendall (data )
9090 except OSError as ex :
9191 if ex .errno == errno .EPIPE :
92- # The connection was terminated by the backend.
93- self ._reconnect ()
94- return self .socket .sendall (data )
92+ # The connection was terminated by the backend. Try reconnect.
93+ self .close ()
94+ return self .socket () .sendall (data )
9595 else :
9696 raise
9797
0 commit comments