From f8aee99bc29187d764e572a92870ce1e215cc056 Mon Sep 17 00:00:00 2001 From: eduardacoppo Date: Fri, 28 Feb 2025 11:27:01 -0300 Subject: [PATCH] feat: add log dir lock and unlock --- lib/roby/app.rb | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/lib/roby/app.rb b/lib/roby/app.rb index 725a4222f..9902403f3 100644 --- a/lib/roby/app.rb +++ b/lib/roby/app.rb @@ -785,6 +785,8 @@ def log_setup(mod_path, level, file = nil) "engine" => {} }.freeze + LOCK_FILE_EXT = ".lock" + # @!method public_rest_interface? # @!method public_rest_interface=(flag) # @@ -955,6 +957,8 @@ def initialize(plan: ExecutablePlan.new) @robots = App::RobotNames.new @base_setup_done = false + + @lock_file = nil end # Loads the base configuration @@ -1031,7 +1035,9 @@ def base_setup load_base_config unless @log_dir + unlock_log_dir find_and_create_log_dir + lock_log_dir end setup_loggers(redirections: true) @@ -1041,6 +1047,44 @@ def base_setup @base_setup_done = true end + def lock_log_dir + return if log_dir_locked? + + return unless @lock_file + + @lock_file ||= File.open( + File.join(@log_dir, LOCK_FILE_EXT), + File::RDWR | File::CREAT, 0o644 + ) + @lock_file.flock(File::LOCK_EX | File::LOCK_NB) + rescue Errno::ENOENT, Errno::EACCES, RuntimeError => e + warn "Failed to lock directory #{@log_dir}: #{e.message}" + end + + def unlock_log_dir + return unless log_dir_locked? + + return unless @lock_file + + @lock_file.flock(File::LOCK_UN) + @lock_file.close + @lock_file = nil + rescue Errno::ENOENT, Errno::EACCES, RuntimeError => e + warn "Failed to unlock directory #{@log_dir}: " \ + "#{e.message}" + end + + def log_dir_locked? + return unless @lock_file + + File.open(@lock_file) do |file| + return !file.flock(File::LOCK_EX | File::LOCK_NB) + end + rescue Errno::ENOENT, Errno::EACCES => e + warn "Failed to check lock status for log directory " \ + "#{@log_dir}: #{e.message}" + end + # The inverse of #base_setup def base_cleanup unless base_setup_done?