Skip to content

Commit

Permalink
Use bool instead of threading event
Browse files Browse the repository at this point in the history
  • Loading branch information
yengliong93 committed Oct 10, 2024
1 parent 95e2bec commit 622ac8f
Show file tree
Hide file tree
Showing 8 changed files with 22 additions and 26 deletions.
14 changes: 5 additions & 9 deletions inbm/dispatcher-agent/dispatcher/dispatcher_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import signal
import sys
from queue import Queue
from threading import Thread, active_count, Lock, Event
from threading import Thread, active_count, Lock
from time import sleep
from typing import Optional, Any, Mapping, Tuple, Sequence

Expand Down Expand Up @@ -116,7 +116,7 @@ def __init__(self, args: list[str], broker: DispatcherBroker, install_check_serv

self.sqlite_mgr = SqliteManager()
self.ap_scheduler = APScheduler(sqlite_mgr=self.sqlite_mgr)
self._cancel_event = Event()
self._cancel_event = False

def stop(self) -> None:
self.RUNNING = False
Expand Down Expand Up @@ -185,7 +185,7 @@ def _sig_handler(signo, frame) -> None:
while self.RUNNING:
if not self.update_queue.empty():
if active_count() - active_start_count < self._thread_count:
worker = Thread(target=handle_updates, args=(self, self._cancel_event,))
worker = Thread(target=handle_updates, args=(self,))
worker.setDaemon(True)
self._thread_list.append(worker)
worker.start()
Expand Down Expand Up @@ -528,7 +528,7 @@ def _handle_cancel_request(self, request_type, manifest) -> bool:
sota_mode = resource.get('mode', None)
if sota_mode == 'cancel':
logger.debug(f"Receive sota cancel request.")
self._cancel_event.set()
self._cancel_event = True
# The list should only contain one OTA process.
for thread in self._thread_list:
if thread.is_alive():
Expand All @@ -537,7 +537,7 @@ def _handle_cancel_request(self, request_type, manifest) -> bool:
thread.join()
logger.debug(f"Request cancel complete.")
self._send_result(str(Result(CODE_OK, "Request complete.")))
self._cancel_event.clear() # Reset the event, allowing it to be set again later.
self._cancel_event = False # Reset the event, allowing it to be set again later.
return True
return False

Expand Down Expand Up @@ -787,7 +787,6 @@ def check_dispatcher_state_info(self) -> None:
self._telemetry('Dispatcher detects normal boot sequence')

def handle_updates(dispatcher: Any,
cancel_event: Event,
schedule_manifest_schema=SCHEDULE_SCHEMA_LOCATION,
manifest_schema=SCHEMA_LOCATION) -> None:
"""Global function to handle multiple requests from cloud using a FIFO queue.
Expand All @@ -803,9 +802,6 @@ def handle_updates(dispatcher: Any,
# Dispatcher sends back the acknowledgement response before processing the immediate scheduling.
dispatcher._send_result("", request_id)

# Set the cancel event for cancel request
dispatcher._cancel_event=cancel_event

if request_type == "schedule":
if not request_id:
dispatcher._send_result("Error: No request ID provided for schedule request.")
Expand Down
4 changes: 2 additions & 2 deletions inbm/dispatcher-agent/dispatcher/ota_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def get_factory(ota_type,
install_check_service: InstallCheckService,
update_logger: UpdateLogger,
dbs: ConfigDbs,
cancel_event: threading.Event) -> "OtaFactory":
cancel_event: bool) -> "OtaFactory":
"""Create an OTA factory of a specified OTA type
@param ota_type: The OTA type
Expand Down Expand Up @@ -130,7 +130,7 @@ def __init__(self,
sota_repos: Optional[str],
install_check_service: InstallCheckService,
update_logger: UpdateLogger,
cancel_event: threading.Event) -> None:
cancel_event: bool) -> None:

super().__init__(repo_type, install_check_service)
self._sota_repos = sota_repos
Expand Down
2 changes: 1 addition & 1 deletion inbm/dispatcher-agent/dispatcher/ota_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def __init__(self,
install_check_service: InstallCheckService,
parsed_manifest: Mapping[str, Optional[Any]],
update_logger: UpdateLogger,
cancel_event: threading.Event) -> None:
cancel_event: bool) -> None:
super().__init__(repo_type, parsed_manifest,
install_check_service=install_check_service)
self._sota_repos = sota_repos
Expand Down
6 changes: 3 additions & 3 deletions inbm/dispatcher-agent/dispatcher/sota/sota.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __init__(self,
update_logger: UpdateLogger,
sota_repos: Optional[str],
install_check_service: InstallCheckService,
cancel_event: threading.Event,
cancel_event: bool,
snapshot: Optional[Any] = None,
action: Optional[Any] = None) -> None:
"""SOTA thread instance
Expand Down Expand Up @@ -323,14 +323,14 @@ def execute_from_manifest(self,
try:
if setup_helper.pre_processing():
self._download_sota_files(sota_cache_repo, release_date)
if self._cancel_event.is_set():
if self._cancel_event:
sota_cache_repo.delete_all() # clean cache directory
raise SotaError("Request cancel.")
download_success = True
snapshotter.take_snapshot()
cmd_list = self.calculate_and_execute_sota_upgrade(sota_cache_repo)
sota_cache_repo.delete_all() # clean cache directory
if self._cancel_event.is_set():
if self._cancel_event:
sota_cache_repo.delete_all() # clean cache directory
raise SotaError("Request cancel.")
if get_command_status(cmd_list) == SUCCESS:
Expand Down
2 changes: 1 addition & 1 deletion inbm/dispatcher-agent/tests/unit/sota/test_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def setUp(cls) -> None:
MockDispatcherBroker.build_mock_dispatcher_broker(),
UpdateLogger("SOTA", "metadata"),
None,
cancel_event=threading.Event(),
cancel_event=False,
install_check_service=MockInstallCheckService())
cls.sota_instance.factory = SotaOsFactory(
MockDispatcherBroker.build_mock_dispatcher_broker(), None, []).get_os('YoctoX86_64')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def setUpClass(cls) -> None:
cls.mock_disp_obj._update_logger,
None,
MockInstallCheckService(),
cancel_event=threading.Event(),
cancel_event=False,
snapshot=1)

parsed_manifest_packages = {'resource': cls.resource,
Expand All @@ -59,7 +59,7 @@ def setUpClass(cls) -> None:
cls.mock_disp_obj._update_logger,
None,
MockInstallCheckService(),
cancel_event=threading.Event(),
cancel_event=False,
snapshot=1)

def test_create_no_download_cmd_with_no_package_list(self) -> None:
Expand Down
8 changes: 4 additions & 4 deletions inbm/dispatcher-agent/tests/unit/sota/test_sota.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ def setUpClass(cls) -> None:
UpdateLogger("SOTA", "metadata"),
None,
install_check_service=MockInstallCheckService(),
cancel_event=threading.Event(),
cancel_event=False,
snapshot=1)
cls.sota_local_instance = SOTA(parsed_manifest, 'local',
cls.mock_disp_broker,
UpdateLogger("SOTA", "metadata"),
None,
install_check_service=MockInstallCheckService(),
cancel_event=threading.Event(),
cancel_event=False,
snapshot=1)
cls.sota_util_instance = SOTAUtil()

Expand Down Expand Up @@ -128,7 +128,7 @@ def test_run_raises(self, mock_reboot, mock_rollback_and_delete_snap, mock_print
sota_instance = SOTA(parsed_manifest, 'remote',
mock_disp_broker,
UpdateLogger("SOTA", "metadata"), None,
MockInstallCheckService(), cancel_event=threading.Event(),
MockInstallCheckService(), cancel_event=False,
snapshot=1)
sota_instance.execute(proceed_without_rollback=False, skip_sleeps=True)
mock_print.assert_called_once()
Expand All @@ -155,7 +155,7 @@ def test_run_pass(self, mock_run, mock_rollback_and_delete_snap, mock_print,
try:
sota_instance = SOTA(parsed_manifest, 'remote', mock_disp_broker,
UpdateLogger("SOTA", "metadata"), None, MockInstallCheckService(),
cancel_event=threading.Event(),snapshot=1)
cancel_event=False,snapshot=1)
sota_instance.execute(proceed_without_rollback=False, skip_sleeps=True)
mock_print.assert_called_once()
if TestSota.sota_instance.proceed_without_rollback:
Expand Down
8 changes: 4 additions & 4 deletions inbm/dispatcher-agent/tests/unit/test_ota_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_get_factory(ota_type, expected_factory, mock_disp_obj, mock_disp_broker
MockInstallCheckService(),
UpdateLogger(ota_type=ota_type, data="metadata"),
ConfigDbs.ON,
cancel_event=threading.Event()
cancel_event=False
)
assert isinstance(factory, expected_factory)

Expand All @@ -47,7 +47,7 @@ def test_raise_error_unsupported_ota(mock_disp_obj, mock_disp_broker) -> None:
MockInstallCheckService(),
UpdateLogger(ota_type="IOTA", data="metadata"),
ConfigDbs.OFF,
cancel_event=threading.Event()
cancel_event=False
)


Expand All @@ -66,7 +66,7 @@ def test_create_parser(ota_type, expected_parser, mock_disp_obj, mock_disp_broke
MockInstallCheckService(),
UpdateLogger(ota_type=ota_type, data="metadata"),
ConfigDbs.ON,
cancel_event=threading.Event()
cancel_event=False
).create_parser()
assert isinstance(parser, expected_parser)

Expand All @@ -86,6 +86,6 @@ def test_create_thread(ota_type, expected_thread, mock_disp_obj, mock_disp_broke
MockInstallCheckService(),
UpdateLogger(ota_type=ota_type, data="metadata"),
ConfigDbs.ON,
cancel_event=threading.Event()
cancel_event=False
).create_thread({'abc': 'def'})
assert isinstance(thread, expected_thread)

0 comments on commit 622ac8f

Please sign in to comment.