sedbgmux/sedbgmux/ch/file_logger.py

61 lines
2.1 KiB
Python

# This file is a part of sedbgmux, an open source DebugMux client.
# Copyright (c) 2023 Vadim Yanitskiy <fixeria@osmocom.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import threading
import typing
import queue
from . import DbgMuxConnHandler
# local logger for this module
log = logging.getLogger(__name__)
class DbgMuxConnFileLogger(DbgMuxConnHandler):
''' Log all received connection data to a file (binary mode) '''
def __init__(self, file: typing.BinaryIO):
super().__init__()
self._file = file
self._rx_thread = threading.Thread(target=self._rx_worker,
daemon=True)
self._shutdown = threading.Event()
def _rx_worker(self) -> None:
''' Dequeue data blocks from the Rx queue and write to file '''
while not self._shutdown.is_set():
try:
data: bytes = self._rx_data_queue.get(block=True, timeout=0.2)
self._file.write(data)
self._rx_data_queue.task_done()
except queue.Empty:
pass
log.debug('Thread \'%s-Rx\' is shutting down', self.__class__.__name__)
def _conn_established(self) -> None:
''' Called when a connection has been established '''
self._shutdown.clear()
self._rx_thread.start()
def _conn_terminated(self) -> None:
''' Called when a connection has been terminated '''
self._shutdown.set()
self._rx_thread.join()