Class: Spanx::Actor::Writer

Inherits:
Object
  • Object
show all
Includes:
Helper::Exit
Defined in:
lib/spanx/actor/writer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helper::Exit

#error_exit_with_msg, #help_exit

Constructor Details

#initialize(config) ⇒ Writer

Returns a new instance of Writer.



11
12
13
14
15
# File 'lib/spanx/actor/writer.rb', line 11

def initialize config
  @config = config
  @block_file = config[:block_file]
  @run_command = config[:run_command]
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



9
10
11
# File 'lib/spanx/actor/writer.rb', line 9

def config
  @config
end

Instance Method Details

#runObject



17
18
19
20
21
22
23
24
25
# File 'lib/spanx/actor/writer.rb', line 17

def run
  Thread.new do
    Thread.current[:name] = "writer"
    loop do
      self.write
      sleep config[:writer][:write_interval]
    end
  end
end

#run_commandObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/spanx/actor/writer.rb', line 56

def run_command
  result = system(@run_command)
  if result
    "executed successfully"
  elsif result == false
    "returned non-zero exit status"
  elsif result.nil?
    "failed -- #{$?}"
  end
end

#writeObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/spanx/actor/writer.rb', line 27

def write
  if Spanx::IPChecker.enabled?
    ips = Spanx::IPChecker.rate_limited_identifiers
  else
    Logger.log "writing empty block file due to disabled state"
    ips = []
  end

  begin
    contents_previous = File.read(@block_file) rescue nil
    Logger.logging "writing out [#{ips.size}] IP block rules to [#{@block_file}]" do
      File.open(@block_file, "w") do |file|
        ips.sort.each do |ip|
          # TODO: make this a customizable ERB template
          file.puts("deny #{ip};")
        end
      end
    end
    contents_now = File.read(@block_file)
    if contents_now != contents_previous && @run_command
      Logger.logging "running command [#{@run_command}]" do
        run_command
      end
    end
  rescue Exception => e
    error_exit_with_msg "ERROR writing to block file #{@block_file} or running command: #{e.inspect}"
  end
end