class Infrataster::Plugin::Firewall::Capture

Reqresent capture

Attributes

output[R]
result[R]

Public Class Methods

bpf(options = {}) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 36
def self.bpf(options = {})
  is_first = true
  filter = ''

  options.each do |k, v|
    filter << ' and ' unless is_first
    filter << "#{k} #{v}"
    is_first = false
  end
  filter
end
new(node, bpf = nil, term_sec = 3) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 9
def initialize(node, bpf = nil, term_sec = 3)
  @node = node.respond_to?(:server) ? node.server :
    Net::SSH.start(node, config: true)
  @bpf = bpf
  @connected = false
  @term_sec = term_sec
  @thread = nil
  @ssh = nil
  @result = false
  @output = ''
end

Public Instance Methods

close() click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 30
def close
  sleep 0.5 until capture_done?
  @thread.kill
  @ssh.close unless @ssh.closed?
end
open(&block) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 21
def open(&block)
  open_node
  wait_connected
  return unless block

  block.call
  close
end

Private Instance Methods

capture_command() click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 97
def capture_command
  "sudo tcpdump -c1 -nnn -i any #{@bpf} > /dev/null && echo RECEIVED"
end
capture_done?() click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 92
def capture_done?
  now_sec = Time.now.to_i
  (@term_sec > 0 && now_sec - @start_sec > @term_sec) ? true : @result
end
exec_capture(channel) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 75
def exec_capture(channel)
  @start_sec = Time.now.to_i + 1
  channel.exec(capture_command) do |ch, _stream, _data|
    receive_data(ch)
    break if capture_done?
  end
end
open_node() click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 50
def open_node
  @thread = Thread.new do
    @node.ssh do |ssh|
      @ssh = ssh
      ssh.open_channel do |channel|
        output = run_check(channel)
        @output << output.to_s
      end
      ssh.loop
    end
  end
end
receive_data(channel) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 83
def receive_data(channel)
  data = ''
  channel.on_data do |_c, d|
    @connected = true
    data << d
    @result = data.include?('RECEIVED')
  end
end
run_check(channel) click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 68
def run_check(channel)
  channel.request_pty do |chan, success|
    fail 'Could not obtain pty' unless success
    exec_capture(chan)
  end
end
wait_connected() click to toggle source
# File lib/infrataster/plugin/firewall/capture.rb, line 63
def wait_connected
  sleep 0.5 until @connected
  sleep 1 # after connected wait for tcpdump ready
end