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"
PAYLOAD_LEN_BYTES =
8
MIN_DATA_LEN =
ZABBIX_HEADER.bytesize + ZABBIX_VERSION.bytesize + PAYLOAD_LEN_BYTES
VERSION =
"0.1.5"

Class Method Summary collapse

Class Method Details

.dump(payload) ⇒ Object



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

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

  payload.force_encoding('ASCII-8BIT')

  [
    ZABBIX_HEADER,
    ZABBIX_VERSION,
    [payload.bytesize].pack('Q<'),
    payload
  ].join
end

.load(data) ⇒ Object



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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/zabbix_protocol.rb', line 31

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

  original_encoding = data.encoding
  data = data.dup
  data.force_encoding('ASCII-8BIT')

  if data.bytesize < MIN_DATA_LEN
    raise Error, "data length is too short (data: #{data.inspect})"
  end

  sliced = data.dup
  header = sliced.slice!(0, ZABBIX_HEADER.bytesize)

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

  version = sliced.slice!(0, ZABBIX_VERSION.bytesize)

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

  payload_len = sliced.slice!(0, PAYLOAD_LEN_BYTES)
  payload_len = payload_len.unpack('Q<').first

  if payload_len != sliced.bytesize
    raise Error, "invalid payload length: expected=#{payload_len}, actual=#{sliced.bytesize} (data: #{data.inspect})"
  end

  duplicated = sliced.dup

  begin
    duplicated.force_encoding(original_encoding)
    sliced = duplicated
  rescue
    # XXX: nothing to do
  end

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