Class: GRI::TextWriter

Inherits:
Writer show all
Defined in:
lib/gri/writer.rb

Constant Summary

Constants inherited from Writer

Writer::TYPES

Instance Attribute Summary

Attributes inherited from Writer

#loop

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Writer

create

Constructor Details

#initialize(options = {}) ⇒ TextWriter

Returns a new instance of TextWriter.



124
125
126
127
128
# File 'lib/gri/writer.rb', line 124

def initialize options={}
  @options = options
  @dir = @options[:tra_dir]
  Dir.mkdir @dir unless File.exist? @dir
end

Class Method Details

.expire(dir, day) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/gri/writer.rb', line 163

def self.expire dir, day
  run_expire_path = dir + '/.run_expire'
  now = Time.now
  if File.exist? run_expire_path
    last_run = nil
    open(run_expire_path) {|f| last_run = f.read}
    last_run = Time.at(last_run.to_i)
    return if (now - last_run < 24*3600) and !$debug
  end
  if (day = day.to_i) > 0
    t = (now - day * 24 * 3600)
    expire_date = "%04d%02d%02d" % [t.year, t.mon, t.day]
    begin
      Dir.glob(dir + '/*') {|hdir|
        next if File.symlink? hdir
        Dir.glob(hdir + '/*') {|path|
          if File.directory? path
            Dir.glob(path + '/*') {|path2|
              if (basename = File.basename path2) < expire_date
                File.unlink path2
              end
            }
          end
        }
      }
      open(run_expire_path, 'w') {|f| f.print now.to_i.to_s}
    rescue SystemCallError
      Log.error "ERROR: #{$!}"
    end
  end
end

Instance Method Details

#finalizeObject



154
155
# File 'lib/gri/writer.rb', line 154

def finalize
end

#purge_logsObject



157
158
159
160
161
# File 'lib/gri/writer.rb', line 157

def purge_logs
  if (day = @options[:tra_expire_day].to_i) > 0
    self.class.expire @dir, day
  end
end

#write(records) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/gri/writer.rb', line 130

def write records
  now = Time.now
  date = "%04d%02d%02d" % [now.year, now.mon, now.day]
  time = now.to_i
  @ios = {}
  for record in records
    #record['_time'] = time
    if (host = record['_host']) and (key = record['_key'])
      hdir = "#{@dir}/#{host}"
      Dir.mkdir hdir unless File.exist? hdir
      data_name, index = key.scan(/\A([^_\d]*)(_?.*)/).first
      interval = record['_interval']
      kdir = "#{hdir}/#{data_name}_#{interval}"
      Dir.mkdir kdir unless File.exist? kdir
      path = kdir + '/' + date
      unless io = @ios[path]
        io = @ios[path] = File.open(path, 'a')
      end
      io.puts LTSV.serialize(record)
    end
  end
  @ios.each {|k, io| io.close}
end