Module: Messhy::WireguardStatusParser

Included in:
HealthChecker
Defined in:
lib/messhy/wireguard_status_parser.rb

Constant Summary collapse

TIME_UNITS_IN_SECONDS =
{
  'second' => 1,
  'minute' => 60,
  'hour' => 3_600,
  'day' => 86_400
}.freeze

Class Method Summary collapse

Class Method Details

.extract_allowed_ips(peer_block) ⇒ Object



57
58
59
# File 'lib/messhy/wireguard_status_parser.rb', line 57

def extract_allowed_ips(peer_block)
  line_value(peer_block, 'allowed ips: ')
end

.extract_endpoint(peer_block) ⇒ Object



53
54
55
# File 'lib/messhy/wireguard_status_parser.rb', line 53

def extract_endpoint(peer_block)
  line_value(peer_block, 'endpoint: ')
end

.extract_handshake_time(peer_block) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/messhy/wireguard_status_parser.rb', line 36

def extract_handshake_time(peer_block)
  return nil unless peer_block

  desc = line_value(peer_block, 'latest handshake: ')
  return nil unless desc&.include?('ago')

  parse_handshake_seconds(desc)
end

.extract_peer_block(status, target_ip) ⇒ Object



14
15
16
17
18
# File 'lib/messhy/wireguard_status_parser.rb', line 14

def extract_peer_block(status, target_ip)
  status.split('peer:').drop(1).find do |block|
    block.include?("allowed ips: #{target_ip}/32")
  end
end

.extract_transfer_stats(peer_block) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/messhy/wireguard_status_parser.rb', line 45

def extract_transfer_stats(peer_block)
  transfer = line_value(peer_block, 'transfer: ')
  rx, tx = transfer&.split(' received, ', 2)
  tx = tx&.delete_suffix(' sent')

  { received: rx || '0 B', sent: tx || '0 B' }
end

.integer_token?(value) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/messhy/wireguard_status_parser.rb', line 65

def integer_token?(value)
  !value.empty? && value.each_char.all? { |char| char.between?('0', '9') }
end

.line_value(block, prefix) ⇒ Object



61
62
63
# File 'lib/messhy/wireguard_status_parser.rb', line 61

def line_value(block, prefix)
  block.each_line(chomp: true).find { |line| line.start_with?(prefix) }&.delete_prefix(prefix)
end

.parse_handshake_seconds(desc) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/messhy/wireguard_status_parser.rb', line 20

def parse_handshake_seconds(desc)
  return nil if desc.strip.casecmp('(none)').zero?

  total = 0
  words = desc.downcase.delete(',').split

  words.each_cons(2) do |value, unit|
    unit = unit.delete_suffix('s')
    next unless integer_token?(value) && TIME_UNITS_IN_SECONDS.key?(unit)

    total += TIME_UNITS_IN_SECONDS.fetch(unit) * value.to_i
  end

  total.positive? ? total : nil
end