1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2025-07-31 12:41:08 +00:00

format python code with black

This commit is contained in:
catborise 2022-11-02 08:54:35 +03:00
parent ea409ca863
commit 217e106c8b
55 changed files with 2510 additions and 1454 deletions

View file

@ -6,9 +6,9 @@ import logging
import django
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, '..', ''))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webvirtcloud.settings')
CERT = DIR_PATH + '/cert.pem'
ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, "..", ""))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webvirtcloud.settings")
CERT = DIR_PATH + "/cert.pem"
if ROOT_PATH not in sys.path:
sys.path.append(ROOT_PATH)
@ -17,7 +17,8 @@ django.setup()
import re
import socket
#from six.moves import http_cookies as Cookie
# from six.moves import http_cookies as Cookie
from http import cookies as Cookie
from webvirtcloud.settings import WS_PORT, WS_HOST, WS_CERT
from vrtManager.connection import CONN_SSH, CONN_SOCKET
@ -26,40 +27,40 @@ from optparse import OptionParser
parser = OptionParser()
parser.add_option("-v",
"--verbose",
dest="verbose",
action="store_true",
help="Verbose mode",
default=False)
parser.add_option(
"-v",
"--verbose",
dest="verbose",
action="store_true",
help="Verbose mode",
default=False,
)
parser.add_option("-d",
"--debug",
dest="debug",
action="store_true",
help="Debug mode",
default=False)
parser.add_option(
"-d", "--debug", dest="debug", action="store_true", help="Debug mode", default=False
)
parser.add_option("-H",
"--host",
dest="host",
action="store",
help="Listen host",
default=WS_HOST)
parser.add_option(
"-H", "--host", dest="host", action="store", help="Listen host", default=WS_HOST
)
parser.add_option("-p",
"--port",
dest="port",
action="store",
help="Listen port",
default=WS_PORT or 6080)
parser.add_option(
"-p",
"--port",
dest="port",
action="store",
help="Listen port",
default=WS_PORT or 6080,
)
parser.add_option("-c",
"--cert",
dest="cert",
action="store",
help="Certificate file path",
default=WS_CERT or CERT)
parser.add_option(
"-c",
"--cert",
dest="cert",
action="store",
help="Certificate file path",
default=WS_CERT or CERT,
)
(options, args) = parser.parse_args()
@ -74,6 +75,7 @@ else:
try:
from websockify import WebSocketProxy
try:
from websockify import ProxyRequestHandler
except ImportError:
@ -84,7 +86,7 @@ except ImportError:
try:
from novnc.wsproxy import WebSocketProxy
except ImportError:
print('Unable to import a websockify implementation,\n please install one')
print("Unable to import a websockify implementation,\n please install one")
sys.exit(1)
else:
USE_HANDLER = False
@ -95,18 +97,20 @@ def get_connection_infos(token):
from vrtManager.instance import wvmInstance
try:
temptoken = token.split('-', 1)
temptoken = token.split("-", 1)
host = int(temptoken[0])
uuid = temptoken[1]
instance = Instance.objects.get(compute_id=host, uuid=uuid)
conn = wvmInstance(instance.compute.hostname,
instance.compute.login,
instance.compute.password,
instance.compute.type,
instance.name)
if instance.compute.hostname.count(':'):
connhost = instance.compute.hostname.split(':')[0]
connport = instance.compute.hostname.split(':')[1]
conn = wvmInstance(
instance.compute.hostname,
instance.compute.login,
instance.compute.password,
instance.compute.type,
instance.name,
)
if instance.compute.hostname.count(":"):
connhost = instance.compute.hostname.split(":")[0]
connport = instance.compute.hostname.split(":")[1]
else:
connhost = instance.compute.hostname
connport = 22
@ -117,10 +121,18 @@ def get_connection_infos(token):
console_socket = conn.get_console_socket()
except Exception as e:
logging.error(
'Fail to retrieve console connection infos for token %s : %s' % (token, e))
"Fail to retrieve console connection infos for token %s : %s" % (token, e)
)
raise
return (connhost, connport, connuser, conntype, console_host,
console_port, console_socket)
return (
connhost,
connport,
connuser,
conntype,
console_host,
console_port,
console_socket,
)
class CompatibilityMixIn(object):
@ -128,25 +140,31 @@ class CompatibilityMixIn(object):
# NoVNC uses it's own convention that forward token
# from the request to a cookie header, we should check
# also for this behavior
hcookie = self.headers.get('cookie')
hcookie = self.headers.get("cookie")
if hcookie:
cookie = Cookie.SimpleCookie()
for hcookie_part in hcookie.split(';'):
for hcookie_part in hcookie.split(";"):
hcookie_part = hcookie_part.lstrip()
try:
cookie.load(hcookie_part)
except Cookie.CookieError:
# NOTE(stgleb): Do not print out cookie content
# for security reasons.
self.msg('Found malformed cookie')
self.msg("Found malformed cookie")
else:
if 'token' in cookie:
token = cookie['token'].value
if "token" in cookie:
token = cookie["token"].value
(connhost, connport, connuser, conntype, console_host, console_port,
console_socket) = get_connection_infos(token)
(
connhost,
connport,
connuser,
conntype,
console_host,
console_port,
console_socket,
) = get_connection_infos(token)
cnx_debug_msg = "Connection infos :\n"
cnx_debug_msg += "- connhost : '%s'\n" % connhost
@ -160,14 +178,16 @@ class CompatibilityMixIn(object):
if console_socket and conntype == CONN_SOCKET:
# Local socket on local host
self.msg('Try to open local socket %s' % console_socket)
self.msg("Try to open local socket %s" % console_socket)
tsock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
tsock.connect(console_socket)
elif console_socket or re.match('^127\.', console_host):
elif console_socket or re.match("^127\.", console_host):
# Need tunnel to physical host
if conntype != CONN_SSH:
self.msg("Need a tunnel to access console but can't mount " +
"one because it's not a SSH host")
self.msg(
"Need a tunnel to access console but can't mount "
+ "one because it's not a SSH host"
)
raise Exception(self.msg)
try:
# generate a string with all placeholders to avoid TypeErrors
@ -175,10 +195,25 @@ class CompatibilityMixIn(object):
# https://github.com/retspen/webvirtmgr/pull/497
error_msg = "Try to open tunnel on %s@%s:%s on console %s:%s "
error_msg += "(or socket %s)"
self.msg(error_msg % (connuser, connhost, connport,
console_host, console_port, console_socket))
tunnel = SSHTunnels(connhost, connuser, connport,
console_host, console_port, console_socket)
self.msg(
error_msg
% (
connuser,
connhost,
connport,
console_host,
console_port,
console_socket,
)
)
tunnel = SSHTunnels(
connhost,
connuser,
connport,
console_host,
console_port,
console_socket,
)
fd = tunnel.open_new()
tunnel.unlock()
tsock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
@ -202,15 +237,18 @@ class CompatibilityMixIn(object):
except Exception:
if tunnel:
self.vmsg(
"%s:%s (via %s@%s:%s) : Websocket client or Target closed" %
(console_host, console_port, connuser, connhost, connport))
"%s:%s (via %s@%s:%s) : Websocket client or Target closed"
% (console_host, console_port, connuser, connhost, connport)
)
if tsock:
tsock.shutdown(socket.SHUT_RDWR)
tsock.close()
tunnel.close_all()
raise
if USE_HANDLER:
class NovaProxyRequestHandler(ProxyRequestHandler, CompatibilityMixIn):
def msg(self, *args, **kwargs):
self.log_message(*args, **kwargs)
@ -228,9 +266,10 @@ if USE_HANDLER:
socket_factory = self.server.socket
self._new_client(daemon, socket_factory)
else:
class NovaWebSocketProxy(WebSocketProxy, CompatibilityMixIn):
else:
class NovaWebSocketProxy(WebSocketProxy, CompatibilityMixIn):
def new_client(self):
"""
Called after a new WebSocket connection has been established.
@ -241,39 +280,44 @@ else:
self._new_client(daemon, socket_factory)
if __name__ == '__main__':
if __name__ == "__main__":
if USE_HANDLER:
# Create the WebSocketProxy with NovaProxyRequestHandler handler
server = WebSocketProxy(RequestHandlerClass=NovaProxyRequestHandler,
listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
traffic=False,
target_host='ignore',
target_port='ignore',
wrap_mode='exit',
wrap_cmd=None)
server = WebSocketProxy(
RequestHandlerClass=NovaProxyRequestHandler,
listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
traffic=False,
target_host="ignore",
target_port="ignore",
wrap_mode="exit",
wrap_cmd=None,
)
else:
# Create the NovaWebSockets proxy
server = NovaWebSocketProxy(listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
target_host='ignore',
target_port='ignore',
wrap_mode='exit',
wrap_cmd=None)
server = NovaWebSocketProxy(
listen_host=options.host,
listen_port=options.port,
source_is_ipv6=False,
verbose=options.verbose,
cert=options.cert,
key=None,
ssl_only=False,
daemon=False,
record=False,
web=False,
target_host="ignore",
target_port="ignore",
wrap_mode="exit",
wrap_cmd=None,
)
server.start_server()

View file

@ -5,9 +5,9 @@ import logging
import django
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, '..', ''))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webvirtcloud.settings')
CERT = DIR_PATH + '/cert.pem'
ROOT_PATH = os.path.abspath(os.path.join(DIR_PATH, "..", ""))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webvirtcloud.settings")
CERT = DIR_PATH + "/cert.pem"
if ROOT_PATH not in sys.path:
sys.path.append(ROOT_PATH)
@ -32,7 +32,7 @@ import tty
import termios
import libvirt
#from six.moves import http_cookies as Cookie
# from six.moves import http_cookies as Cookie
from http import cookies as Cookie
from webvirtcloud.settings import SOCKETIO_PORT, SOCKETIO_HOST
from vrtManager.connection import CONN_SSH, CONN_SOCKET
@ -40,33 +40,36 @@ from optparse import OptionParser
parser = OptionParser()
parser.add_option("-v",
"--verbose",
dest="verbose",
action="store_true",
help="Verbose mode",
default=False)
parser.add_option(
"-v",
"--verbose",
dest="verbose",
action="store_true",
help="Verbose mode",
default=False,
)
parser.add_option("-d",
"--debug",
dest="debug",
action="store_true",
help="Debug mode",
default=False)
parser.add_option(
"-d", "--debug", dest="debug", action="store_true", help="Debug mode", default=False
)
parser.add_option("-H",
"--host",
dest="host",
action="store",
help="Listen host",
default=SOCKETIO_HOST)
parser.add_option(
"-H",
"--host",
dest="host",
action="store",
help="Listen host",
default=SOCKETIO_HOST,
)
parser.add_option("-p",
"--port",
dest="port",
action="store",
help="Listen port",
default=SOCKETIO_PORT or 6081)
parser.add_option(
"-p",
"--port",
dest="port",
action="store",
help="Listen port",
default=SOCKETIO_PORT or 6081,
)
(options, args) = parser.parse_args()
@ -85,26 +88,31 @@ sio = socketio.Server(async_mode=async_mode, cors_allowed_origins=[])
fd = None
child_pid = None
def get_connection_infos(token):
from instances.models import Instance
from vrtManager.instance import wvmInstance
try:
temptoken = token.split('-', 1)
temptoken = token.split("-", 1)
host = int(temptoken[0])
uuid = temptoken[1]
instance = Instance.objects.get(compute_id=host, uuid=uuid)
conn = wvmInstance(instance.compute.hostname,
instance.compute.login,
instance.compute.password,
instance.compute.type,
instance.name)
conn = wvmInstance(
instance.compute.hostname,
instance.compute.login,
instance.compute.password,
instance.compute.type,
instance.name,
)
except Exception as e:
logging.error(
'Fail to retrieve console connection infos for token %s : %s' % (token, e))
"Fail to retrieve console connection infos for token %s : %s" % (token, e)
)
raise
return (instance, conn)
def set_winsize(fd, row, col, xpix=0, ypix=0):
winsize = struct.pack("HHHH", row, col, xpix, ypix)
fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)
@ -123,41 +131,44 @@ def read_and_forward_pty_output():
sio.emit("pty_output", {"output": output})
else:
return
@sio.event
def resize(sid, message):
def resize(sid, message):
global fd
if fd:
set_winsize(fd, message["rows"], message["cols"])
@sio.event
def pty_input(sid, message):
global fd
if fd:
os.write(fd, message["input"].encode())
@sio.event
def disconnect_request(sid):
sio.disconnect(sid)
@sio.event
def connect(sid, environ):
global fd
global child_pid
hcookie = environ.get('HTTP_COOKIE')
hcookie = environ.get("HTTP_COOKIE")
if hcookie:
cookie = Cookie.SimpleCookie()
for hcookie_part in hcookie.split(';'):
for hcookie_part in hcookie.split(";"):
hcookie_part = hcookie_part.lstrip()
try:
cookie.load(hcookie_part)
except Cookie.CookieError:
logging.warn('Found malformed cookie')
logging.warn("Found malformed cookie")
else:
if 'token' in cookie:
token = cookie['token'].value
if "token" in cookie:
token = cookie["token"].value
if child_pid:
# already started child process, don't start another
@ -170,14 +181,15 @@ def connect(sid, environ):
if child_pid == 0:
(instance, conn) = get_connection_infos(token)
uuid = conn.get_uuid()
uuid = conn.get_uuid()
uri = conn.wvm.getURI()
subprocess.run(['conf/daemon/consolecallback', uri, uuid])
subprocess.run(["conf/daemon/consolecallback", uri, uuid])
else:
# this is the parent process fork.
sio.start_background_task(target=read_and_forward_pty_output)
@sio.event
def disconnect(sid):
@ -185,13 +197,15 @@ def disconnect(sid):
global child_pid
# kill pty process
os.kill(child_pid,signal.SIGKILL)
os.kill(child_pid, signal.SIGKILL)
os.wait()
# reset the variables
fd = None
child_pid = None
app = socketio.WSGIApp(sio)
import eventlet
eventlet.wsgi.server(eventlet.listen((options.host,int(options.port))), app)
eventlet.wsgi.server(eventlet.listen((options.host, int(options.port))), app)

View file

@ -28,15 +28,19 @@ class _TunnelScheduler(object):
def _handle_queue(self):
while True:
lock_cb, cb, args, = self._queue.get()
(
lock_cb,
cb,
args,
) = self._queue.get()
lock_cb()
cb(*args)
def schedule(self, lock_cb, cb, *args):
if not self._thread:
self._thread = threading.Thread(name="Tunnel thread",
target=self._handle_queue,
args=())
self._thread = threading.Thread(
name="Tunnel thread", target=self._handle_queue, args=()
)
self._thread.daemon = True
if not self._thread.is_alive():
self._thread.start()
@ -63,8 +67,11 @@ class _Tunnel(object):
return
self._closed = True
log.debug("Close tunnel PID=%s ERRFD=%s",
self._pid, self._errfd and self._errfd.fileno() or None)
log.debug(
"Close tunnel PID=%s ERRFD=%s",
self._pid,
self._errfd and self._errfd.fileno() or None,
)
# Since this is a socket object, the file descriptor is closed
# when it's garbage collected.
@ -110,8 +117,7 @@ class _Tunnel(object):
self._errfd = errfds[0]
self._errfd.setblocking(0)
log.debug("Opened tunnel PID=%d ERRFD=%d",
pid, self._errfd.fileno())
log.debug("Opened tunnel PID=%d ERRFD=%d", pid, self._errfd.fileno())
self._pid = pid
@ -124,7 +130,7 @@ def _make_ssh_command(connhost, connuser, connport, gaddr, gport, gsocket):
argv += ["-p", str(connport)]
if connuser:
argv += ['-l', connuser]
argv += ["-l", connuser]
argv += [connhost]
@ -151,8 +157,8 @@ def _make_ssh_command(connhost, connuser, connport, gaddr, gport, gsocket):
"""else"""
""" CMD="nc %(nc_params)s";"""
"""fi;"""
"""eval "$CMD";""" %
{'nc_params': nc_params})
"""eval "$CMD";""" % {"nc_params": nc_params}
)
argv.append("sh -c")
argv.append("'%s'" % nc_cmd)
@ -166,7 +172,8 @@ class SSHTunnels(object):
def __init__(self, connhost, connuser, connport, gaddr, gport, gsocket):
self._tunnels = []
self._sshcommand = _make_ssh_command(
connhost, connuser, connport, gaddr, gport, gsocket)
connhost, connuser, connport, gaddr, gport, gsocket
)
self._locked = False
def open_new(self):

View file

@ -17,7 +17,7 @@ from webvirtcloud.settings import (
WS_PUBLIC_PORT,
SOCKETIO_PUBLIC_HOST,
SOCKETIO_PUBLIC_PORT,
SOCKETIO_PUBLIC_PATH
SOCKETIO_PUBLIC_PATH,
)
@ -31,32 +31,39 @@ def console(request):
if request.method == "GET":
token = request.GET.get("token", "")
view_type = request.GET.get("view", "lite")
view_only = request.GET.get(
"view_only", app_settings.CONSOLE_VIEW_ONLY.lower())
view_only = request.GET.get("view_only", app_settings.CONSOLE_VIEW_ONLY.lower())
scale = request.GET.get("scale", app_settings.CONSOLE_SCALE.lower())
resize_session = request.GET.get(
"resize_session", app_settings.CONSOLE_RESIZE_SESSION.lower())
"resize_session", app_settings.CONSOLE_RESIZE_SESSION.lower()
)
clip_viewport = request.GET.get(
"clip_viewport", app_settings.CONSOLE_CLIP_VIEWPORT.lower())
"clip_viewport", app_settings.CONSOLE_CLIP_VIEWPORT.lower()
)
try:
temptoken = token.split("-", 1)
host = int(temptoken[0])
uuid = temptoken[1]
if not request.user.is_superuser and not request.user.has_perm("instances.view_instances"):
if not request.user.is_superuser and not request.user.has_perm(
"instances.view_instances"
):
try:
userInstance = UserInstance.objects.get(
instance__compute_id=host, instance__uuid=uuid, user__id=request.user.id
instance__compute_id=host,
instance__uuid=uuid,
user__id=request.user.id,
)
instance = Instance.objects.get(compute_id=host, uuid=uuid)
except UserInstance.DoesNotExist:
instance = None
console_error = _("User does not have permission to access console or host/instance not exist")
console_error = _(
"User does not have permission to access console or host/instance not exist"
)
return HttpResponseServerError(console_error)
else:
instance = Instance.objects.get(compute_id=host, uuid=uuid)
conn = wvmInstance(
instance.compute.hostname,
instance.compute.login,
@ -83,7 +90,9 @@ def console(request):
console_page = "console-" + console_type + "-" + view_type + ".html"
response = render(request, console_page, locals())
elif console_type == "pty":
socketio_host = SOCKETIO_PUBLIC_HOST if SOCKETIO_PUBLIC_HOST else request.get_host()
socketio_host = (
SOCKETIO_PUBLIC_HOST if SOCKETIO_PUBLIC_HOST else request.get_host()
)
socketio_port = SOCKETIO_PUBLIC_PORT if SOCKETIO_PUBLIC_PORT else 6081
socketio_path = SOCKETIO_PUBLIC_PATH if SOCKETIO_PUBLIC_PATH else "/"
@ -93,9 +102,13 @@ def console(request):
response = render(request, "console-xterm.html", locals())
else:
if console_type is None:
console_error = _("Fail to get console. Please check the console configuration of your VM.")
console_error = _(
"Fail to get console. Please check the console configuration of your VM."
)
else:
console_error = _("Console type '%(type)s' has not support") % {"type": console_type}
console_error = _("Console type '%(type)s' has not support") % {
"type": console_type
}
response = render(request, "console-vnc-lite.html", locals())
response.set_cookie("token", token)