Class: Nagios::MkLiveStatus::Request

Inherits:
Object
  • Object
show all
Includes:
Nagios::MkLiveStatus
Defined in:
lib/nagios_mklivestatus/request.rb

Overview

Request manager of the Nagios MkLivestatus

Author

Esco-lan Team ([email protected])

Copyright

Copyright © 2012 GIP RECIA

License

General Public Licence

Instance Method Summary collapse

Methods included from Nagios::MkLiveStatus

init, #logger

Constructor Details

#initialize(path) ⇒ Request

Initialize the nagios mklivestatus socket informations.

Two type of socket are supported for now:

  • TCP : path equal to “tcp://<host>:<port>”

  • File : where path is the path to the file



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/nagios_mklivestatus/request.rb', line 25

def initialize(path)
  
  #check socket type
  # if the path start with tcp:// => tcp socket
  if path.strip.start_with?("tcp://")
    tmp = path[6,path.length]
    table = tmp.partition(":")
    @mk_livestatus_socket_type = "tcp"
    @mk_livestatus_socket_path = Hash.new
    @mk_livestatus_socket_path[:ip] = table[0]
    @mk_livestatus_socket_path[:port] = table[2]
    
    logger.info("type: "+@mk_livestatus_socket_type)
    logger.info("ip : "+@mk_livestatus_socket_path[:ip])
    logger.info("port : "+@mk_livestatus_socket_path[:port])
  # default socket type is set to file
  elsif File.exists? path
    @mk_livestatus_socket_path = path
    @mk_livestatus_socket_type = "file"
    
    logger.info("type : "+@mk_livestatus_socket_type)
    logger.info("file : "+@mk_livestatus_socket_path)
  else
    raise RequestException.new("Socket error : socket type not recognized for \"#{path}\".")
  end
end

Instance Method Details

#query(query = nil, options = {}) ⇒ Object

The method opens the socket and send the query then return the response of nagios

The query parameter must be set and be a Nagios::MkLiveStatus::Query representing the MKLiveStatus Query :

GET hosts

or

GET hosts
Columns: host_name
Filter: host_name ~ test
....

The options parameter is added to the query:

  • :user : is the user used with AuthUser of MkLiveStatus for hosts, services, hostgroups, servicegroup and log

  • :column_headers : set to true to have headers of the query as first line (ColumnHeaders: on)

  • :limit : limitation of the output (Limit: X)

  • :local_time : set localtime (LocalTime: X) in unix timestamp

  • :output : output format like json/python, if none provided set to CSV (OutputFormat: out)



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/nagios_mklivestatus/request.rb', line 68

def query(query=nil, options={})
  
  
  if logger.debug?
    logger.debug("query recieved :")
    query.to_s.split("\n").each do |line|
      logger.debug(line)
    end
    logger.debug("options recieved : ")
    options.keys.each do |key|
      logger.debug("#{key} : #{options[key]}")
    end
  end
  
  #set column headers
  column_header = false
  if options.has_key? :column_headers and options[:column_headers]
    column_headers = true
  end
  
  #set user
  user = nil
  if options.has_key? :user and options[:user] != nil and not options[:user].empty?
    user = options[:user]
  end
  
  #set limit
  limit = nil
  if options.has_key? :limit and options[:limit] != nil and options[:limit].to_i > 0
    limit = options[:limit].to_i
  end
  
  #set localtime 
  localtime = nil
  if options.has_key? :local_time and options[:local_time] != nil and not options[:local_time].to_i
    localtime = options[:local_time].to_i
  end
  
  #set output
  output = nil
  if options.has_key? :output and options[:output] != nil and not options[:output].empty?
    if ['json','python'].include?(options[:output])
      output = options[:output]
    else
      raise RequestException.new("Output must be one of #{['json','python'].join(', ')}")
    end
  end
  
  columns=[]
  if column_headers and query.has_stats
    columns = query.get_columns_name
  end
 
  #if socket is generated and query exists
  if query != nil and query.is_a? Nagios::MkLiveStatus::Query and query.to_s.upcase.start_with?("GET ")
    
    strQuery = "#{query}"
    #the endline must be empty
    if not strQuery.end_with?("\n")
      strQuery << "\n"
    end
    
    #set user if needed
    if user != nil and not user.empty? and strQuery.match /^GET\s+(hosts|hostgroups|services|servicegroup|log)\s*$/
      strQuery << "AuthUser: #{user}\n"
    end
    
    if localtime != nil
      strQuery << "LocalTime: #{localtime}\n"
    end
    
    # set columns headers
    if column_headers
      strQuery << "ColumnHeaders: on\n"
    end
    
    # set the limit
    if limit
      strQuery << "Limit: #{limit}"
    end
    
    #set the output format
    if output
      strQuery << "OutputFormat: #{output}"
    end
    
    logger.info("")
    logger.info("---")
    strQuery.split("\n").each do |line|
      logger.info(line)
    end
    logger.info("---")
    
    #get error message if some are given
    strQuery << "ResponseHeader: fixed16\n"
    
    socket = open_socket()
    
    logger.debug("querying ...")
    # query the socket
    socket.puts strQuery
    
    logger.debug("closing socket.")
    # close the socket
    socket.shutdown(Socket::SHUT_WR)
    logger.debug("socket closed.")
    
    # check data reception
    recieving = socket.recv(16)
    check_receiving_error recieving
    
    logger.debug("Reading results.")
    # get all the line of the socket
    response = socket.gets(nil)
    
    # if columns header are required but stats are defined > no column. So we put ours
    if columns.length > 0
      logger.debug("Adding columns")
      response = columns.join(";")+"\n"+response
    end
    
    if response
      logger.info("Results :")
      response.split("\n").each do |line|
        logger.info(line)
      end
    else
      logger.info("No results.")
    end
    
    
    return response
    
  end
    
end