Sha256: 6e6a36c7f0ca02f06e2429645494f254f6a4e0a22805251ba0bb3944857d1a86

Contents?: true

Size: 1.24 KB

Versions: 65

Compression:

Stored size: 1.24 KB

Contents

# Used to perform locked, atomic writes to the data file. 
module Scout
  class DataFile
    attr_accessor :path, :logger
    attr_reader :data
    
    def initialize(path,logger)
      @path = path
      @logger = logger
    end
    
    # atomic_write first writes to the tmp file.
    def tmp_path
      path+'.tmp'
    end
    
    # saves the data file by (1) locking the file at +path+ to ensure other processes 
    # don't overlap (2) using an atomic write to ensure other processes always read a complete file.
    def save(content)
      lock do
        atomic_write(content)
      end
    end
    
    private
    
    def lock
      File.open(path, File::RDWR | File::CREAT) do |f|
        begin
          f.flock(File::LOCK_EX)
          yield
        ensure
          f.flock(File::LOCK_UN)          
        end
      end
    rescue Errno::ENOENT, Exception  => e
      logger.error("Unable to access data file [#{e.message}]")
    end
    
    # Uses an Atomic Write - first writes to a tmp file then replace the history file. 
    # Ensures reads on the history file don't see a partial write.
    def atomic_write(content)
      File.open(tmp_path, 'w+') do |f|
        f.write(content)
      end
      FileUtils.mv(tmp_path, path)
    end
    
  end
end

Version data entries

65 entries across 65 versions & 1 rubygems

Version Path
scout-5.9.13 lib/scout/data_file.rb
scout-5.9.12 lib/scout/data_file.rb
scout-5.9.11 lib/scout/data_file.rb
scout-5.9.10.pre lib/scout/data_file.rb
scout-5.9.8 lib/scout/data_file.rb
scout-5.9.7.2.pre lib/scout/data_file.rb
scout-5.9.8.pre lib/scout/data_file.rb
scout-5.9.7.1 lib/scout/data_file.rb
scout-5.9.7.pre lib/scout/data_file.rb
scout-5.9.5 lib/scout/data_file.rb
scout-5.9.4 lib/scout/data_file.rb
scout-5.9.4.pre lib/scout/data_file.rb
scout-5.9.3 lib/scout/data_file.rb
scout-5.9.2 lib/scout/data_file.rb
scout-5.9.1 lib/scout/data_file.rb
scout-5.9.1.pre lib/scout/data_file.rb
scout-5.9.0 lib/scout/data_file.rb
scout-5.9.0.pre lib/scout/data_file.rb
scout-5.8.9 lib/scout/data_file.rb
scout-5.8.8 lib/scout/data_file.rb