Class: ScoutApm::LayawayFile

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

Instance Method Summary collapse

Instance Method Details

#dump(object) ⇒ Object



9
10
11
# File 'lib/scout_apm/layaway_file.rb', line 9

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

#get_data(f) ⇒ Object



50
51
52
53
54
55
# File 'lib/scout_apm/layaway_file.rb', line 50

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

#load(dump) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/scout_apm/layaway_file.rb', line 13

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

#pathObject



4
5
6
7
# File 'lib/scout_apm/layaway_file.rb', line 4

def path
  ScoutApm::Agent.instance.config.value("data_file") ||
    "#{ScoutApm::Agent.instance.default_log_path}/scout_apm.db"
end

#read_and_writeObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/scout_apm/layaway_file.rb', line 25

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
  ScoutApm::Agent.instance.logger.error("Unable to access the layaway file [#{e.message}]. " +
                                        "The user running the app must have read & write access. " +
                                        "Change the path by setting the `data_file` key in scout_apm.yml"
                                       )
  ScoutApm::Agent.instance.logger.debug(e.backtrace.join("\n\t"))

  # ensure the in-memory metric hash is cleared so data doesn't continue to accumulate.
  # ScoutApm::Agent.instance.store.metric_hash = {}
end

#read_until_end(f) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/scout_apm/layaway_file.rb', line 67

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



57
58
59
60
61
62
63
64
65
# File 'lib/scout_apm/layaway_file.rb', line 57

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