Skip to content

Commit 1f2626e

Browse files
committed
feat: add log dir lock and unlock
1 parent 678e3c5 commit 1f2626e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lib/roby/app.rb

+35
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,8 @@ def log_setup(mod_path, level, file = nil)
785785
"engine" => {}
786786
}.freeze
787787

788+
LOCK_FILE_EXT = ".lock"
789+
788790
# @!method public_rest_interface?
789791
# @!method public_rest_interface=(flag)
790792
#
@@ -883,6 +885,8 @@ def log_setup(mod_path, level, file = nil)
883885
# Display the backtrace of all running threads on abort
884886
attr_predicate :display_all_threads_state_on_abort?, true
885887

888+
attr_reader :lock_file
889+
886890
def initialize(plan: ExecutablePlan.new)
887891
@plan = plan
888892
@argv_set = []
@@ -955,6 +959,8 @@ def initialize(plan: ExecutablePlan.new)
955959
@robots = App::RobotNames.new
956960

957961
@base_setup_done = false
962+
963+
@lock_file = nil
958964
end
959965

960966
# Loads the base configuration
@@ -1032,6 +1038,7 @@ def base_setup
10321038
load_base_config
10331039
unless @log_dir
10341040
find_and_create_log_dir
1041+
lock_log_dir
10351042
end
10361043
setup_loggers(redirections: true)
10371044

@@ -1041,6 +1048,33 @@ def base_setup
10411048
@base_setup_done = true
10421049
end
10431050

1051+
def lock_log_dir
1052+
return if log_dir_locked?
1053+
1054+
temp_lock_file = File.join(log_dir, "#{LOCK_FILE_EXT}.tmp")
1055+
final_lock_file = File.join(log_dir, LOCK_FILE_EXT)
1056+
1057+
@lock_file = File.open(temp_lock_file, File::RDWR | File::CREAT, 0o644)
1058+
if @lock_file.flock(File::LOCK_EX | File::LOCK_NB)
1059+
File.rename(temp_lock_file, final_lock_file)
1060+
@lock_file.close
1061+
@lock_file = File.open(final_lock_file, File::RDWR | File::CREAT, 0o644)
1062+
end
1063+
end
1064+
1065+
def unlock_log_dir
1066+
return unless log_dir_locked?
1067+
1068+
@lock_file.close if @lock_file
1069+
@lock_file = nil
1070+
end
1071+
1072+
def log_dir_locked?
1073+
return unless @lock_file
1074+
1075+
@lock_file.path.end_with?(LOCK_FILE_EXT)
1076+
end
1077+
10441078
# The inverse of #base_setup
10451079
def base_cleanup
10461080
unless base_setup_done?
@@ -1564,6 +1598,7 @@ def log_dir
15641598

15651599
# Reset the current log dir so that {#setup} picks a new one
15661600
def reset_log_dir
1601+
unlock_log_dir
15671602
@log_dir = nil
15681603
end
15691604

0 commit comments

Comments
 (0)