Module: ZabbixProtocol

Defined in:
lib/zabbix_protocol.rb,
lib/zabbix_protocol/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

ZABBIX_HEADER =
"ZBXD"
ZABBIX_VERSION =
"\x01"
DATA_LEN_BYTES =
8
MIN_RESPONSE_LEN =
ZABBIX_HEADER.length + ZABBIX_VERSION.length + DATA_LEN_BYTES
VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.dump(data) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/zabbix_protocol.rb', line 15

def self.dump(data)
  if data.is_a?(Hash)
    data = MultiJson.dump(data)
  else
    data = data.to_s
  end

  [
    ZABBIX_HEADER,
    ZABBIX_VERSION,
    [data.length].pack('Q'),
    data
  ].join
end

.load(res_data) ⇒ Object



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
55
56
57
58
59
60
61
62
63
64
# File 'lib/zabbix_protocol.rb', line 30

def self.load(res_data)
  unless res_data.is_a?(String)
    raise TypeError, "wrong argument type #{res_data.class} (expected String)"
  end

  if res_data.length < MIN_RESPONSE_LEN
    raise Error, "response data is too short"
  end

  data = res_data.dup
  header = data.slice!(0, ZABBIX_HEADER.length)

  if header != ZABBIX_HEADER
    raise Error, "invalid header: #{header.inspect}"
  end

  version = data.slice!(0, ZABBIX_VERSION.length)

  if version != ZABBIX_VERSION
    raise Error, "unsupported version: #{version.inspect}"
  end

  data_len = data.slice!(0, DATA_LEN_BYTES)
  data_len = data_len.unpack("Q").first

  if data_len != data.length
    raise Error, "invalid data length: expected=#{data_len}, actual=#{data.length}"
  end

  begin
    MultiJson.load(data)
  rescue MultiJson::ParseError
    data
  end
end