Commit 86cf253e authored by ibuler's avatar ibuler

[Fixture] 使用gevent, 使用proxy server

parent 73a012f8
......@@ -7,3 +7,5 @@ BASE_DIR = os.path.abspath(os.path.dirname(__file__))
from .app import app, socket_io
from . import authentication, views
import logger
from flask import request
......@@ -5,6 +5,7 @@ import time
from flask import Flask
import socketio
from flask_socketio import SocketIO
from .conf import config
from .service import service
......@@ -16,8 +17,9 @@ __version__ = '0.4.0'
class Luna(Flask):
app_service = service
service = service
clients = {}
proxy_list = {}
active = True
def run(self, host=None, port=None, debug=None, **options):
......@@ -38,6 +40,7 @@ class Luna(Flask):
async_mode = 'threading'
app = Luna(__name__, template_folder='dist')
socket_io = SocketIO(app)
app.config.update(**config)
socket_io = socketio.Server(logger=False, async_mode=async_mode)
app.wsgi_app = socketio.Middleware(socket_io, app.wsgi_app)
#socket_io = socketio.Server(logger=False, async_mode=async_mode)
#app.wsgi_app = socketio.Middleware(socket_io, app.wsgi_app)
......@@ -9,10 +9,6 @@ from jms import UserService
from . import app
def is_authenticate(user_service):
pass
def login_required(func=None, login_url=None):
if func is None:
return partial(login_required, login_url=login_url)
......@@ -31,7 +27,9 @@ def login_required(func=None, login_url=None):
g.user_service = UserService(endpoint=app.config['JUMPSERVER_ENDPOINT'])
g.user_service.auth_from_session(session_id, csrf_token)
if g.user_service.is_authenticated():
user = g.user_service.is_authenticated()
if user:
g.user = user
return func(*args, **kwargs)
else:
return redirect(login_url)
......
# ~*~ coding: utf-8 ~*~
import socket
from .app import socket_io
class ProxyChannel(object):
def __init__(self, sid):
self.sid = sid
self.srv, self.cli = socket.socketpair()
self.win_width = 80
self.win_height = 24
def fileno(self):
return self.srv.fileno()
def send(self, s):
"""Proxy server中使用select, 通过socketio发送给用户"""
return socket_io.emit('data', s, root=self.sid)
def recv(self, size):
"""Proxy server使用select, 接受socketio客户端数据发送来的数据"""
return self.srv.recv(size)
def write(self, s):
"""socket io写数据,proxy可以通过recv收到"""
print('Client write message: %s' % s)
self.cli.send(s)
def set_win_size(self, size):
self.win_width, self.win_height = size
This diff is collapsed.
# ~*~ coding: utf-8 ~*~
import re
import select
import threading
import socket
import collections
import json
import logging
import paramiko
import time
from flask import request, g
from jms.utils import TtyIOParser
from jms.utils import to_dotmap
from .. import app, socket_io
from ..nav import nav
from ..tasks import command_queue, record_queue
from ..proxy import ProxyServer
from ..channel import ProxyChannel
clients = app.clients
logger = logging.getLogger(__file__)
......@@ -26,6 +24,58 @@ __all__ = [
]
@socket_io.on('nav')
def handle_api():
socket_io.emit('nav', json.dumps(nav))
@socket_io.on('connect', namespace='/')
def handle_term_connect():
clients[request.sid] = collections.defaultdict(dict)
@socket_io.on('machine')
def handle_machine(message):
sid = request.sid
clients[sid]['host'] = host = '120.25.240.109'
clients[sid]['port'] = port = 8022
user = to_dotmap({'username': 'root', 'name': 'redhat'})
asset = to_dotmap({'hostname': host, 'ip': host, 'port': 8022})
# win_width = request.cookies.get('col')
# win_height = request.cookies.get('row')
system_user = to_dotmap({'name': 'jms', 'username': 'jms', 'id': 102})
clients[sid]['proxy_chan'] = proxy_chan = ProxyChannel(sid)
# proxy_chan.set_win_size((win_width, win_height))
proxy_server = ProxyServer(app, user, asset, system_user, proxy_chan)
socket_io.start_background_task(proxy_server.proxy)
# t = threading.Thread(target=proxy_server.proxy, args=())
# t.daemon = True
# t.start()
@socket_io.on('data')
def handle_data( message):
sid = request.sid
logger.debug('Receive data: %s' % message)
if clients[sid]['proxy_chan']:
print('Sending to client channel')
clients[sid]['proxy_chan'].write(message)
@socket_io.on('disconnect')
def handle_term_disconnect():
sid = request.sid
del clients[sid]
print('term disconnect')
@socket_io.on('resize')
def handle_term_resize(json):
sid = request.sid
logger.debug('Resize term: %s' % json)
"""
@socket_io.on('nav')
def handle_api(sid):
socket_io.emit('nav', json.dumps(nav), room=sid)
......@@ -40,17 +90,25 @@ def handle_term_connect(sid, environ):
def handle_machine(sid, message):
clients[sid]['host'] = host = '120.25.240.109'
clients[sid]['port'] = port = 8022
t = threading.Thread(target=forward, args=(sid,))
user = to_dotmap({'username': 'root', 'name': 'redhat'})
asset = to_dotmap({'hostname': host, 'ip': host, 'port': 8022})
# win_width = request.cookies.get('col')
# win_height = request.cookies.get('row')
system_user = to_dotmap({'name': 'jms', 'username': 'jms', 'id': 102})
clients[sid]['proxy_chan'] = proxy_chan = ProxyChannel(sid)
# proxy_chan.set_win_size((win_width, win_height))
proxy_server = ProxyServer(app, user, asset, system_user, proxy_chan)
t = threading.Thread(target=proxy_server.proxy, args=())
t.daemon = True
t.start()
socket_io.emit('data', 'Connect to %s:%s \r\n' % (host, port), room=sid)
@socket_io.on('data')
def handle_data(sid, message):
logger.debug('Receive data: %s' % message)
if clients[sid]['chan']:
clients[sid]['chan'].send(message)
if clients[sid]['proxy_chan']:
print('Sending to client channel')
clients[sid]['proxy_chan'].write(message)
@socket_io.on('disconnect')
......@@ -62,11 +120,12 @@ def handle_term_disconnect(sid):
@socket_io.on('resize')
def handle_term_resize(sid, json):
logger.debug('Resize term: %s' % json)
"""
### Only for test ###
def forward(sid):
print(request)
try:
host = clients[sid]['host']
port = clients[sid]['port']
......@@ -86,3 +145,14 @@ def forward(sid):
break
socket_io.emit('data', data, room=sid)
del clients[sid]
def handle(p):
while True:
r, w, x = select.select([p], [], [])
if p in r:
data = p.recv(1024)
if len(data) == 0:
break
print("Recieve client: %s" % data)
#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~
from luna import app
import sys
import os
from luna import app, socket_io
host = app.config['BIND_HOST']
port = app.config['LISTEN_PORT']
......@@ -17,7 +18,9 @@ if __name__ == '__main__':
pass
try:
app.run(threaded=True, host=host, port=port)
socket_io.run(app)
# app.run(threaded=True, host=host, port=port)
except KeyboardInterrupt:
app.stop()
sys.exit()
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