the-oneacct-export-project/oneacct-export

View on GitHub
bin/oneacct-export

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
ENV['RAILS_ENV'] = ENV['RAILS_ENV'] ? ENV['RAILS_ENV'] : 'production'

require 'syslogger'
require 'oneacct_exporter'
require 'oneacct_exporter/log'
require 'settings'
require 'fileutils'
require 'json'
require 'oneacct_opts'
require 'chronic_duration'

ChronicDuration.raise_exceptions = true

# parse options from command line
options = OneacctOpts.parse(ARGV)

# initialize default logger
log = Logger.new(STDOUT)

# initialize specific logger according to the configuration
if Settings['logging'] && Settings['logging']['log_type'] == 'file'
  begin
    log_file = File.open(Settings['logging']['log_file'], File::WRONLY | File::CREAT | File::APPEND)
    log = Logger.new(log_file)
  rescue => e
    OneacctExporter::Log.setup_log_level(log)
    log.warn("Unable to create log file #{Settings['logging']['log_file']}: #{e.message}.\
           Falling back to STDOUT.")
  end
elsif Settings['logging'] && Settings['logging']['log_type'] == 'syslog'
  log = Syslogger.new('oneacct-export')
end

OneacctExporter::Log.setup_log_level(log)

begin
  range = {}
  range[:from] = Time.now - ChronicDuration.parse(options.records_for) if options.records_for

  if options.records_from || options.records_to
    range[:from] = options.records_from
    range[:to] = options.records_to
  end
rescue ChronicDuration::DurationParseError => e
  puts "Cannot parse a time period: #{e.message} Quitting."
  exit
end

groups = {}
groups[:include] = options.include_groups if options.include_groups
groups[:exclude] = options.exclude_groups if options.exclude_groups

# read groups restriction from file if chosen
if options.groups_file
  log.debug('Reading groups from file...')
  if File.exist?(options.groups_file) && File.readable?(options.groups_file)
    file = File.open(options.groups_file, 'r')
    file.each_line do |line|
      groups[groups.keys.first] << line.strip
    end
    file.close
  else
    log.error("File contaning groups: #{options.groups_file} doesn't exists or cannot be read. "\
              'Skipping groups restriction...')
    groups[groups.keys.first] = []
  end
end

# create output directory
begin
  FileUtils.mkdir_p Settings.output['output_dir']
rescue SystemCallError => e
  puts "Cannot create an output directory: #{e.message}. Quitting."
  exit
end

log.debug('Creating OneacctExporter...')

opts = {}
opts[:range] = range
opts[:groups] = groups
opts[:blocking] = options.blocking
opts[:timeout] = options.timeout
opts[:compatibility] = options.compatibility

log.debug(opts)

# run the export
oneacct_exporter = OneacctExporter.new(opts, log)
oneacct_exporter.export