Class: ScoutRails::LayawayFile

Inherits:
Object
  • Object
show all
Defined in:
lib/scout_rails/layaway_file.rb

Overview

Logic for the serialized file access

Instance Method Summary collapse

Instance Method Details

#dump(object) ⇒ Object



7
8
9
# File 'lib/scout_rails/layaway_file.rb', line 7

def dump(object)
  Marshal.dump(object)
end

#get_data(f) ⇒ Object



44
45
46
47
48
49
# File 'lib/scout_rails/layaway_file.rb', line 44

def get_data(f)
  data = read_until_end(f)
  result = load(data)
  f.truncate(0)
  result
end

#load(dump) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/scout_rails/layaway_file.rb', line 11

def load(dump)
  if dump.size == 0
    ScoutRails::Agent.instance.logger.debug("No data in layaway file.")
    return nil
  end
  Marshal.load(dump)
rescue ArgumentError, TypeError => e
  ScoutRails::Agent.instance.logger.debug("Error loading data from layaway file: #{e.inspect}")
  ScoutRails::Agent.instance.logger.debug(e.backtrace.inspect)
  nil
end

#pathObject



3
4
5
# File 'lib/scout_rails/layaway_file.rb', line 3

def path
  "#{ScoutRails::Agent.instance.log_path}/scout_rails.db"
end

#read_and_writeObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/scout_rails/layaway_file.rb', line 23

def read_and_write
  File.open(path, File::RDWR | File::CREAT) do |f|
    f.flock(File::LOCK_EX)
    begin
      result = (yield get_data(f))
      f.rewind
      f.truncate(0)
      if result
        write(f, dump(result))
      end
    ensure
      f.flock(File::LOCK_UN)
    end
  end
rescue Errno::ENOENT, Exception  => e
  ScoutRails::Agent.instance.logger.error("Unable to access the layaway file [#{e.message}]. The user running the app must have read+write access.")
  ScoutRails::Agent.instance.logger.debug(e.backtrace.split("\n"))
  # ensure the in-memory metric hash is cleared so data doesn't continue to accumulate.
  ScoutRails::Agent.instance.store.metric_hash = {}
end

#read_until_end(f) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/scout_rails/layaway_file.rb', line 61

def read_until_end(f)
  contents = ""
  while true
    contents << f.read_nonblock(10_000)
  end
rescue Errno::EAGAIN, Errno::EINTR
  IO.select([f])
  retry
rescue EOFError
  contents
end

#write(f, string) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/scout_rails/layaway_file.rb', line 51

def write(f, string)
  result = 0
  while (result < string.length)
    result += f.write_nonblock(string)
  end
rescue Errno::EAGAIN, Errno::EINTR
  IO.select(nil, [f])
  retry
end