OSDN Git Service

shogi_server.rb: Fixed a race condition in a case of switching log files
[shogi-server/shogi-server.git] / shogi_server.rb
index 7467f6f..d7a3659 100644 (file)
@@ -66,21 +66,16 @@ end
 module_function :reload
 
 class Logger < ::Logger
+  @@mkdir_mutex = Mutex.new
+
   def initialize(logdev, shift_age = 0, shift_size = 1048576)
     super
     class << @logdev
       def shift_log_period(now)
         age_file = age_file_name(now)
         move_age_file_in_the_way(age_file)
+        mkdir_for(age_file)
 
-        unless FileTest.directory?(File.dirname(age_file))
-          begin
-            FileUtils.mkdir_p File.dirname(age_file)
-          rescue
-            @dev.write("[ERROR] Could not create a directory: %s\n" % [File.dirname(age_file)])
-            raise RuntimeError.new("Could not create a directory: %s" % [File.dirname(age_file)])
-          end
-        end
         @dev.close
         rename_file(@filename, age_file)
         @dev = create_logfile(@filename)
@@ -114,7 +109,20 @@ class Logger < ::Logger
         @dev.write("[WARN] An existing '#{age_file}' is beeing moved to '#{new_file}'\n")
         rename_file(age_file, new_file)
       end
-    end
+
+      def mkdir_for(path)
+        @@mkdir_mutex.synchronize do
+          unless FileTest.directory?(File.dirname(path))
+            begin
+              FileUtils.mkdir_p File.dirname(path)
+            rescue
+              @dev.write("[ERROR] Could not create a directory: %s\n" % [File.dirname(path)])
+            end
+          end
+        end # mutex
+      end
+
+    end # @logdev
   end
 
 end # class Logger