Skip to content

Commit

Permalink
Change string formatting to replace f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
IreneLime committed Jan 5, 2025
1 parent 49c74e1 commit a4e548a
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 54 deletions.
23 changes: 13 additions & 10 deletions application/features/Audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def launch_audio(self):
self.transport = self.client.get_transport()
self.remote_port = self.transport.request_port_forward('127.0.0.1', 0)
except Exception as e:
logger.warning("Audio: exception raised during launch audio: {}".format(e))
logger.warning("Audio: exception raised during launch audio: %s", e)
return False, str(e)

self.id = uuid.uuid4().hex
Expand All @@ -94,7 +94,7 @@ def handleConnected(self):

audio_id = self.request.path[1:]
if audio_id not in AUDIO_CONNECTIONS:
logger.warning(f'AudioWebSocket: Requested audio_id={audio_id} does not exist.')
logger.warning("AudioWebSocket: Requested audio_id=%s does not exist.", audio_id)
self.close()
return

Expand All @@ -110,10 +110,14 @@ def handleConnected(self):
f'module-null-sink sink_name={sink_name} '
exit_status, _, stdout, _ = self.audio.exec_command_blocking(load_module_command)
if exit_status != 0:
logger.warning(f'AudioWebSocket: audio_id={audio_id}: unable to load pactl module-null-sink sink_name={sink_name}')
logger.warning(
"AudioWebSocket: audio_id=%s: unable to load pactl module-null-sink sink_name=%s",
audio_id,
sink_name
)
return
load_module_stdout_lines = stdout.readlines()
logger.debug("AudioWebSocket: Load Module: {}".format(load_module_stdout_lines))
logger.debug("AudioWebSocket: Load Module: %s", load_module_stdout_lines)
self.module_id = int(load_module_stdout_lines[0])

keep_launching_ffmpeg = True
Expand All @@ -125,7 +129,7 @@ def ffmpeg_launcher():
f'-ac 2 -acodec pcm_s16le -ar 44100 -f s16le "tcp://127.0.0.1:{self.audio.remote_port}"'
# keep launching if the connection is not accepted in the writer() below
while keep_launching_ffmpeg:
logger.debug(f"AudioWebSocket: Launch ffmpeg: {launch_ffmpeg_command}")
logger.debug("AudioWebSocket: Launch ffmpeg: %s", launch_ffmpeg_command)
_, ffmpeg_stdout, _ = self.audio.client.exec_command(launch_ffmpeg_command)
ffmpeg_stdout.channel.recv_exit_status()
# if `ffmpeg` launches successfully, `ffmpeg_stdout.channel.recv_exit_status` should not return
Expand Down Expand Up @@ -156,7 +160,7 @@ def writer():
buffer += data
if len(buffer) >= AUDIO_BUFFER_SIZE:
compressed = zlib.compress(buffer, level=4)
logger.debug(f"AudioWebSocket: Send compressed message of size {len(compressed)}")
logger.debug("AudioWebSocket: Send compressed message of size %s", len(compressed))
self.sendMessage(compressed)
# print(len(compressed) / len(buffer) * 100)
buffer = b''
Expand All @@ -170,10 +174,10 @@ def writer():
def handleClose(self):
if self.module_id is not None:
# unload the module before leaving
logger.debug(f"AudioWebSocket: Unload module {self.module_id}")
logger.debug("AudioWebSocket: Unload module %s", self.module_id)
self.audio.client.exec_command(f'pactl unload-module {self.module_id}')

logger.debug(f"AudioWebSocket: End audio socket {self.audio.id} connection")
logger.debug("AudioWebSocket: End audio socket %s connection", self.audio.id)
del AUDIO_CONNECTIONS[self.audio.id]
del self.audio

Expand All @@ -183,8 +187,7 @@ def handleClose(self):
# if we are in debug mode, run the server in the second round
if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
AUDIO_PORT = find_free_port()
# print("AUDIO_PORT =", AUDIO_PORT)
logger.debug("Audio: Audio port {}".format(AUDIO_PORT))
logger.debug("Audio: Audio port %s", AUDIO_PORT)

if os.environ.get('SSL_CERT_PATH') is None:
logger.debug("Audio: SSL Certification Path not set. Generating self-signing certificate")
Expand Down
30 changes: 14 additions & 16 deletions application/features/Connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,10 @@ def handle(self):
)
)
logger.debug(
"Connected! Tunnel open %r -> %r -> %r"
% (
self.request.getpeername(),
chan.getpeername(),
("127.0.0.1", self.server.chain_port),
)
"Connected! Tunnel open %r -> %r -> %r",
self.request.getpeername(),
chan.getpeername(),
("127.0.0.1", self.server.chain_port),
)

try:
Expand Down Expand Up @@ -115,9 +113,9 @@ def __del__(self):
def _client_connect(self, client: paramiko.SSHClient,
host, username,
password=None, key_filename=None, private_key_str=None):
if self._jump_channel != None:
if self._jump_channel is not None:
logger.debug("Connection: Connection initialized through Jump Channel")
logger.debug(f"Connection: Connecting to {username}@{host}")
logger.debug("Connection: Connecting to %s@%s", username, host)
if password is not None:
client.connect(host, username=username, password=password, timeout=15, sock=self._jump_channel)
elif key_filename is not None:
Expand All @@ -144,16 +142,16 @@ def _init_jump_channel(self, host, username, **auth_methods):

self._jump_client = paramiko.SSHClient()
self._jump_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
logger.debug(f"Connection: Initialize Jump Client for connection to {username}@remote.ecf.utoronto.ca")
logger.debug("Connection: Initialize Jump Client for connection to %s@remote.ecf.utoronto.ca", username)
self._client_connect(self._jump_client, 'remote.ecf.utoronto.ca', username, **auth_methods)
logger.debug(f"Connection: Open Jump channel connection to {host} at port 22")
logger.debug("Connection: Open Jump channel connection to %s at port 22", host)
self._jump_channel = self._jump_client.get_transport().open_channel('direct-tcpip',
(host, 22),
('127.0.0.1', 22))

def connect(self, host: str, username: str, **auth_methods):
try:
logger.debug(f"Connection: Connection attempt to {username}@{host}")
logger.debug("Connection: Connection attempt to %s@%s", username, host)
self._init_jump_channel(host, username, **auth_methods)
self._client_connect(self.client, host, username, **auth_methods)
except Exception as e:
Expand All @@ -164,7 +162,7 @@ def connect(self, host: str, username: str, **auth_methods):
self.host = host
self.username = username

logger.debug(f"Connection: Successfully connected to {username}@{host}")
logger.debug("Connection: Successfully connected to %s@%s", username, host)
return True, ''

@staticmethod
Expand All @@ -180,11 +178,11 @@ def ssh_keygen(key_filename=None, key_file_obj=None, public_key_comment=''):

# save the private key
if key_filename is not None:
logger.debug(f"Connection: RSA SSH private key written to {key_filename}")
logger.debug("Connection: RSA SSH private key written to %s", key_filename)
rsa_key.write_private_key_file(key_filename)
elif key_file_obj is not None:
rsa_key.write_private_key(key_file_obj)
logger.debug(f"Connection: RSA SSH private key written to {key_file_obj}")
logger.debug("Connection: RSA SSH private key written to %s", key_file_obj)
else:
raise ValueError('Neither key_filename nor key_file_obj is provided.')

Expand Down Expand Up @@ -285,8 +283,8 @@ def is_load_high(self):

my_pts_count = len(output) - 1 # -1: excluding the `uptime` output

logger.debug(f"Connection: pts count: {pts_count}; my pts count: {my_pts_count}")
logger.debug(f"Connection: load sum: {load_sum}")
logger.debug("Connection: pts count: %s; my pts count: %s", pts_count, my_pts_count)
logger.debug("Connection: load sum: %s", load_sum)

if pts_count > my_pts_count: # there are more terminals than mine
return True
Expand Down
25 changes: 11 additions & 14 deletions application/features/SFTP.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def ls(self, path=""):
self.sftp.chdir(path)
cwd = self.sftp.getcwd()
attrs = self.sftp.listdir_attr(cwd)
logger.debug(f"SFTP: ls {cwd}: {attrs}")
logger.debug("SFTP: ls %s: %s", cwd, attrs)

file_list = []
# TODO: should support uid and gid later
Expand Down Expand Up @@ -104,12 +104,10 @@ def _zip_dir_recurse(self, z, parent, file):
try:
mode = self.sftp.stat(fullpath).st_mode
if stat.S_ISREG(mode):
# print(fullpath, 'is file')
logger.debug(f"SFTP: {fullpath} is a file")
logger.debug("SFTP: %s is a file", fullpath)
z.write_iter(fullpath, self.dl_generator(fullpath))
elif stat.S_ISDIR(mode):
# print(fullpath, 'is dir')
logger.debug(f"SFTP: {fullpath} is a directory")
logger.debug("SFTP: %s is a directory", fullpath)
# TODO: support writing an empty directory if len(dir_ls)==0
# That will involve modifying the zipstream library
dir_ls = self.sftp.listdir(fullpath)
Expand All @@ -123,12 +121,12 @@ def _zip_dir_recurse(self, z, parent, file):
return

def zip_generator(self, cwd, file_list):
logger.debug(f"SFTP: zip_generator on directory: {cwd}")
logger.debug("SFTP: zip_generator on directory: %s", cwd)
self.sftp.chdir(cwd)
z = zipstream.ZipFile(compression=zipstream.ZIP_DEFLATED, allowZip64=True)

for file in file_list:
logger.debug(f"SFTP: zip_generator on file: {file}")
logger.debug("SFTP: zip_generator on file: %s", file)
self._zip_dir_recurse(z, '', file)

return z
Expand All @@ -137,7 +135,7 @@ def rename(self, cwd, old, new):
try:
self.sftp.chdir(cwd)
self.sftp.rename(old, new)
logger.debug(f"SFTP: Rename {old} in directory {cwd} to {new}")
logger.debug("SFTP: Rename %s in directory %s to %s", old, cwd, new)
except Exception as e:
return False, repr(e)

Expand All @@ -146,11 +144,10 @@ def rename(self, cwd, old, new):
def chmod(self, path, mode, recursive):
_, _, _, stderr = self.exec_command_blocking(
f'chmod {"-R" if recursive else ""} {"{0:0{1}o}".format(mode, 3)} "{path}"')
logger.debug("SFTP: Change permission on " + path + " to '{0:0{1}o}'".format(mode, 3))
logger.debug("SFTP: Change permission on %s to '%s'", path, "{0:0{1}o}".format(mode, 3))
stderr_lines = stderr.readlines()
if len(stderr_lines) != 0:
logger.warning(f"SFTP: chmod failed due to {stderr_lines}")
# print(stderr_lines)
logger.warning("SFTP: chmod failed due to %s", stderr_lines)
return False, 'Some files were not applied with the request mode due to permission issues.'

return True, ''
Expand All @@ -171,7 +168,7 @@ def rm(self, cwd, file_list):

counter += 1
if counter == 50:
logger.debug(f"SFTP: Execute Command {' '.join(cmd_list)}")
logger.debug("SFTP: Execute Command %s", ' '.join(cmd_list))
_, _, stderr = self.client.exec_command(" ".join(cmd_list))
stderr_lines = stderr.readlines()
if len(stderr_lines) != 0:
Expand All @@ -182,7 +179,7 @@ def rm(self, cwd, file_list):
counter = 0
cmd_list = [f'cd "{cwd}" && rm -rf']

logger.debug(f"SFTP: Execute Command {' '.join(cmd_list)}")
logger.debug("SFTP: Execute Command %s", ' '.join(cmd_list))
_, _, stderr = self.client.exec_command(" ".join(cmd_list))
stderr_lines = stderr.readlines()
if len(stderr_lines) != 0:
Expand All @@ -194,7 +191,7 @@ def rm(self, cwd, file_list):
return True, ''

def mkdir(self, cwd, name):
logger.debug(f"SFTP: Make directory {name} at {cwd}")
logger.debug("SFTP: Make directory %s at %s", name, cwd)
_, _, _, stderr = self.exec_command_blocking(f'cd "{cwd}"&& mkdir "{name}"')
stderr_lines = stderr.readlines()
if len(stderr_lines) != 0:
Expand Down
16 changes: 7 additions & 9 deletions application/features/Term.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def launch_shell(self):

def resize(self, width, height):
try:
logger.debug(f"Term: Resizing Term to {width}x{height}")
logger.debug("Term: Resizing Term to %sx%s", width, height)
self.channel.resize_pty(width, height)
except Exception as e:
return False, str(e)
Expand All @@ -82,7 +82,7 @@ def __init__(self, *args, **kwargs):
self.term = None

def handleMessage(self):
logger.debug(f"TermWebSocket: Send message {self.data}")
logger.debug("TermWebSocket: Send message %s", self.data)
self.term.channel.send(self.data)

def handleConnected(self):
Expand All @@ -93,12 +93,11 @@ def handleConnected(self):
logger.warning("TermWebSocket: Local Authentication Failure")
return

logger.debug(f"TermWebSocket: connected to {self.address}")
logger.debug("TermWebSocket: connected to %s", self.address)
print(self.address, 'connected')
terminal_id = self.request.path[1:]
if terminal_id not in TERM_CONNECTIONS:
# print(f'TermWebSocket: Requested terminal_id={terminal_id} does not exist.')
logger.warning(f"TermWebSocket: Requested terminal_id={terminal_id} does not exist.")
logger.warning("TermWebSocket: Requested terminal_id=%s does not exist.", terminal_id)
self.close()
return

Expand All @@ -109,8 +108,7 @@ def writeall():
while True:
data = self.term.channel.recv(1024)
if not data:
# print(f"\r\n*** {terminal_id}: Shell EOF ***\r\n\r\n")
logger.debug(f"TermWebSocket: \r\n*** {terminal_id}: Shell EOF ***\r\n\r\n")
logger.debug("TermWebSocket: \r\n*** %s: Shell EOF ***\r\n\r\n", terminal_id)
self.close()
break
self.sendMessage(data)
Expand All @@ -120,7 +118,7 @@ def writeall():
writer.start()

def handleClose(self):
logger.debug(f"TermWebSocket: Closing terminal {self.term.id} connection")
logger.debug("TermWebSocket: Closing terminal %s connection", self.term.id)
del TERM_CONNECTIONS[self.term.id]
del self.term

Expand All @@ -131,7 +129,7 @@ def handleClose(self):
if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
TERMINAL_PORT = find_free_port()
print("TERMINAL_PORT =", TERMINAL_PORT)
logger.debug("Term: Terminal port {}".format(TERMINAL_PORT))
logger.debug("Term: Terminal port %s", TERMINAL_PORT)

if os.environ.get('SSL_CERT_PATH') is None:
logger.debug("Term: SSL Certification Path not set. Generating self-signing certificate")
Expand Down
8 changes: 4 additions & 4 deletions application/features/VNC.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def websocket_proxy_thread(local_websocket_port, local_vnc_port):
logger.debug("VNC: SSL Certification Path exists")
import subprocess

logger.debug(f"VNC: Run websockify on websocket port {local_websocket_port} and vncport {local_vnc_port}")
logger.debug("VNC: Run websockify on websocket port %d and vncport %d", local_websocket_port, local_vnc_port)
subprocess.run(["/var/www/ictrl/application/websockify-other/c/websockify",
f'{local_websocket_port}', f':{local_vnc_port}',
'--run-once', '--ssl-only',
Expand Down Expand Up @@ -105,7 +105,7 @@ def remove_vnc_settings(self):
_, _, _, stderr = self.exec_command_blocking(';'.join(remove_cmd_lst))
stderr_text = "\n".join(stderr)
if len(stderr_text):
logger.warning(f"VNC: Error removing VNC settings: {stderr_text}")
logger.warning("VNC: Error removing VNC settings: %s", stderr_text)
return False, stderr_text

return True, ''
Expand Down Expand Up @@ -203,8 +203,8 @@ def launch_vnc(self):
def create_tunnel(self, remote_port):
local_vnc_port = find_free_port()
local_websocket_port = find_free_port()
logger.debug(f"VNC: Local VNC Port is {local_vnc_port}")
logger.debug(f"VNC: Local Web Socket Port is {local_websocket_port}")
logger.debug("VNC: Local VNC Port is %s", local_vnc_port)
logger.debug("VNC: Local Web Socket Port is %s", local_websocket_port)
self.port_forward(local_vnc_port, remote_port)

proxy_thread = threading.Thread(target=websocket_proxy_thread,
Expand Down
2 changes: 1 addition & 1 deletion application/features/vncpasswd.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def vncpasswd(passwd_path, password=None):

with open(passwd_path, "wb") as passwd:
passwd.write(obfuscated)
logger.debug("Vnc Password: Write obfuscated password to {}".format(passwd_path))
logger.debug("Vnc Password: Write obfuscated password to %s", passwd_path)

return obfuscated

Expand Down

0 comments on commit a4e548a

Please sign in to comment.