Commit 9d64f6c2 authored by ibuler's avatar ibuler

[Update] 优化sock

parent 2a450db9
...@@ -16,9 +16,9 @@ class SFTPVolume(BaseVolume): ...@@ -16,9 +16,9 @@ class SFTPVolume(BaseVolume):
def __init__(self, sftp): def __init__(self, sftp):
self.sftp = sftp self.sftp = sftp
self.root_name = 'Home' self.root_name = 'Home'
super().__init__()
self._stat_cache = {} self._stat_cache = {}
self.lock = threading.Lock() self.lock = threading.Lock()
super(SFTPVolume, self).__init__()
def close(self): def close(self):
self.sftp.close() self.sftp.close()
......
...@@ -407,7 +407,8 @@ class InteractiveServer: ...@@ -407,7 +407,8 @@ class InteractiveServer:
self.display_prompt_of_page() self.display_prompt_of_page()
def display_prompt_of_page(self): def display_prompt_of_page(self):
self.client.send(wr(_('Tips: Enter the asset ID and log directly into the asset.'), before=1)) msg = wr(_('Tips: Enter the asset ID and log directly into the asset.'))
self.client.send(msg, before=1)
prompt_page_up = _("Page up: P/p") prompt_page_up = _("Page up: P/p")
prompt_page_down = _("Page down: Enter|N/n") prompt_page_down = _("Page down: Enter|N/n")
prompt_back = _("BACK: b/q") prompt_back = _("BACK: b/q")
...@@ -457,7 +458,6 @@ class InteractiveServer: ...@@ -457,7 +458,6 @@ class InteractiveServer:
def close(self): def close(self):
logger.debug("Interactive server server close: {}".format(self)) logger.debug("Interactive server server close: {}".format(self))
self.closed = True self.closed = True
# current_app.remove_client(self.client)
# def __del__(self): # def __del__(self):
# print("GC: Interactive class been gc") # print("GC: Interactive class been gc")
...@@ -212,7 +212,7 @@ class SSHInterface(paramiko.ServerInterface): ...@@ -212,7 +212,7 @@ class SSHInterface(paramiko.ServerInterface):
client.request.type = 'subsystem' client.request.type = 'subsystem'
client.request.meta['subsystem'] = name client.request.meta['subsystem'] = name
self.event.set() self.event.set()
return super().check_channel_subsystem_request(channel, name) return super(SSHInterface, self).check_channel_subsystem_request(channel, name)
def check_channel_window_change_request(self, channel, width, height, def check_channel_window_change_request(self, channel, width, height,
pixelwidth, pixelheight): pixelwidth, pixelheight):
......
...@@ -41,7 +41,7 @@ class Connection(object): ...@@ -41,7 +41,7 @@ class Connection(object):
client.connection_id = self.id client.connection_id = self.id
self.clients[tid] = client self.clients[tid] = client
self.__class__.clients_num += 1 self.__class__.clients_num += 1
logger.debug("New client {} join, total {} now".format( logger.info("New client {} join, total {} now".format(
client, self.__class__.clients_num client, self.__class__.clients_num
)) ))
return client return client
...@@ -59,7 +59,7 @@ class Connection(object): ...@@ -59,7 +59,7 @@ class Connection(object):
client.close() client.close()
self.__class__.clients_num -= 1 self.__class__.clients_num -= 1
del self.clients[tid] del self.clients[tid]
logger.debug("Client {} leave, total {} now".format( logger.info("Client {} leave, total {} now".format(
client, self.__class__.clients_num client, self.__class__.clients_num
)) ))
...@@ -131,13 +131,16 @@ class Client(object): ...@@ -131,13 +131,16 @@ class Client(object):
self.close() self.close()
return return
@property
def closed(self):
return self.chan.closed
def recv(self, size): def recv(self, size):
return self.chan.recv(size) return self.chan.recv(size)
def close(self): def close(self):
logger.info("Client {} close".format(self)) logger.info("Client {} close".format(self))
self.chan.close() self.chan.close()
self.chan = None
return return
def __getattr__(self, item): def __getattr__(self, item):
...@@ -347,7 +350,6 @@ class BaseServer(object): ...@@ -347,7 +350,6 @@ class BaseServer(object):
logger.info("Closed server {}".format(self)) logger.info("Closed server {}".format(self))
self.r_input_output_data_filter(b'') self.r_input_output_data_filter(b'')
self.chan.close() self.chan.close()
self.chan = None
def __getattr__(self, item): def __getattr__(self, item):
return getattr(self.chan, item) return getattr(self.chan, item)
...@@ -384,8 +386,6 @@ class Server(BaseServer): ...@@ -384,8 +386,6 @@ class Server(BaseServer):
def close(self): def close(self):
super(Server, self).close() super(Server, self).close()
self.chan.transport.close() self.chan.transport.close()
self.chan.transport = None
self.chan = None
logger.debug("Backend server closed") logger.debug("Backend server closed")
if self.sock: if self.sock:
self.sock.transport.close() self.sock.transport.close()
......
...@@ -62,10 +62,11 @@ class SFTPServer(paramiko.SFTPServerInterface): ...@@ -62,10 +62,11 @@ class SFTPServer(paramiko.SFTPServerInterface):
} }
""" """
super().__init__(server, **kwargs) super(SFTPServer, self).__init__(server, **kwargs)
self.server = server self.server = server
self._sftp = {} self._sftp = {}
self.hosts = self.get_permed_hosts() self.hosts = self.get_permed_hosts()
self.is_finished = False
def get_permed_hosts(self): def get_permed_hosts(self):
hosts = {} hosts = {}
...@@ -88,7 +89,8 @@ class SFTPServer(paramiko.SFTPServerInterface): ...@@ -88,7 +89,8 @@ class SFTPServer(paramiko.SFTPServerInterface):
return hosts return hosts
def session_ended(self): def session_ended(self):
super().session_ended() self.is_finished = True
super(SFTPServer, self).session_ended()
for _, v in self._sftp.items(): for _, v in self._sftp.items():
sftp = v['client'] sftp = v['client']
proxy = v.get('proxy') proxy = v.get('proxy')
...@@ -388,7 +390,7 @@ class InternalSFTPClient(SFTPServer): ...@@ -388,7 +390,7 @@ class InternalSFTPClient(SFTPServer):
def __init__(self, connection): def __init__(self, connection):
fake_server = FakeServer() fake_server = FakeServer()
fake_server.connection = connection fake_server.connection = connection
super().__init__(fake_server) super(InternalSFTPClient, self).__init__(fake_server)
def listdir_attr(self, path): def listdir_attr(self, path):
return self.list_folder.__wrapped__(self, path) return self.list_folder.__wrapped__(self, path)
...@@ -408,15 +410,15 @@ class InternalSFTPClient(SFTPServer): ...@@ -408,15 +410,15 @@ class InternalSFTPClient(SFTPServer):
self.create_ftp_log(path, operate, success) self.create_ftp_log(path, operate, success)
def stat(self, path): def stat(self, path):
attr = super().stat.__wrapped__(self, path) attr = super(InternalSFTPClient, self).stat.__wrapped__(self, path)
return attr return attr
def lstat(self, path): def lstat(self, path):
attr = super().lstat.__wrapped__(self, path) attr = super(InternalSFTPClient, self).lstat.__wrapped__(self, path)
return attr return attr
def rmdir(self, path): def rmdir(self, path):
return super().rmdir.__wrapped__(self, path) return super(InternalSFTPClient, self).rmdir.__wrapped__(self, path)
def get_channel(self): def get_channel(self):
return FakeChannel.new() return FakeChannel.new()
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
import os import os
import socket import socket
import threading import threading
import time
import paramiko import paramiko
...@@ -25,7 +26,6 @@ class SSHServer: ...@@ -25,7 +26,6 @@ class SSHServer:
self.stop_evt = threading.Event() self.stop_evt = threading.Event()
self.workers = [] self.workers = []
self.pipe = None self.pipe = None
self.connections = []
@property @property
def host_key(self): def host_key(self):
...@@ -57,11 +57,6 @@ class SSHServer: ...@@ -57,11 +57,6 @@ class SSHServer:
except IndexError as e: except IndexError as e:
logger.error("Start SSH server error: {}".format(e)) logger.error("Start SSH server error: {}".format(e))
def new_connection(self, addr, sock):
connection = Connection.new_connection(addr=addr, sock=sock)
self.connections.append(connection)
return connection
def handle_connection(self, sock, addr): def handle_connection(self, sock, addr):
transport = paramiko.Transport(sock, gss_kex=False) transport = paramiko.Transport(sock, gss_kex=False)
try: try:
...@@ -73,7 +68,7 @@ class SSHServer: ...@@ -73,7 +68,7 @@ class SSHServer:
transport.set_subsystem_handler( transport.set_subsystem_handler(
'sftp', paramiko.SFTPServer, SFTPServer 'sftp', paramiko.SFTPServer, SFTPServer
) )
connection = self.new_connection(addr, sock=sock) connection = Connection.new_connection(addr=addr, sock=sock)
server = SSHInterface(connection) server = SSHInterface(connection)
try: try:
transport.start_server(server=server) transport.start_server(server=server)
...@@ -96,36 +91,37 @@ class SSHServer: ...@@ -96,36 +91,37 @@ class SSHServer:
t.daemon = True t.daemon = True
t.start() t.start()
transport.close() transport.close()
del transport
except paramiko.SSHException: except paramiko.SSHException:
logger.warning("SSH negotiation failed") logger.warning("SSH negotiation failed")
except EOFError as e: except EOFError as e:
logger.warning("Handle EOF Error: {}".format(e)) logger.warning("Handle EOF Error: {}".format(e))
finally: finally:
Connection.remove_connection(connection.id) Connection.remove_connection(connection.id)
del connection sock.close()
@staticmethod @staticmethod
def dispatch(client): def dispatch(client):
supported = {'pty', 'x11', 'forward-agent'} supported = {'pty', 'x11', 'forward-agent'}
chan_type = client.request.type chan_type = client.request.type
kind = client.request.kind kind = client.request.kind
if kind == 'session' and chan_type in supported: try:
logger.info("Dispatch client to interactive mode") if kind == 'session' and chan_type in supported:
try: logger.info("Dispatch client to interactive mode")
InteractiveServer(client).interact() try:
except IndexError as e: InteractiveServer(client).interact()
logger.error("Unexpected error occur: {}".format(e)) except IndexError as e:
finally: logger.error("Unexpected error occur: {}".format(e))
connection = Connection.get_connection(client.connection_id) elif chan_type == 'subsystem':
connection.remove_client(client.id) while not client.closed:
del client time.sleep(5)
elif chan_type == 'subsystem': logger.debug("SFTP session finished")
pass else:
else: msg = "Request type `{}:{}` not support now".format(kind, chan_type)
msg = "Request type `{}:{}` not support now".format(kind, chan_type) logger.error(msg)
logger.info(msg) client.send(msg)
client.send(msg) finally:
connection = Connection.get_connection(client.connection_id)
connection.remove_client(client.id)
def shutdown(self): def shutdown(self):
self.stop_evt.set() self.stop_evt.set()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment