File: top_talkers.lua

package info (click to toggle)
ntopng 2.4%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 15,888 kB
  • ctags: 8,091
  • sloc: cpp: 21,442; ansic: 10,999; sh: 1,627; makefile: 423; pascal: 312; ruby: 34; exp: 4
file content (469 lines) | stat: -rw-r--r-- 14,979 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
--
-- (C) 2013-16 - ntop.org
--

--[[
Top statistics are calculated by ntopng minute.lua callback
and keep track of minute-by-minute top hosts, asn, networks, and so on.

Since local hosts are dumped to redis, top statistics for such
hosts may be inaccurate when a local host:
1. goes idle and ntopng flushes its counters, say X and Y, to redis
2. becomes active again and ntopng restores its counters from redis

Without additional logic, top statistics would not know that
the local host has been pulled out from redis and would consider
X and Y as the last minute statistics while, in practice, they
are just counters of a past active period.

For this reason we have implemented a function that gives
hosts statistics without counting deserialized byte values:
interface.getLatestActivityHostsInfo()

For example, say 192.168.2.130 is a local host

latest = interface.getLatestActivityHostsInfo()
alltime = interface.getHostsInfo()
tprint(latest["en4"]["hosts"]["192.168.2.130"]["bytes.rcvd"])
tprint(alltime["en4"]["hosts"]["192.168.2.130"]["bytes.rcvd"])

Result in
 number 1581811117
 number 5664436991

and the correct number to consider when computing minute statistics
is the one obtained via getLatestActivityHostsInfo() as the other
includes deserialized data.

--]]

dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path

require "persistence"

other_stats_id = "Other"

-- #################################################

function getTop(stats, sort_field_key, max_num_entries, lastdump_dir, lastdump_key, use_threshold)
   local _filtered_stats, filtered_stats, counter, total, threshold, low_threshold

   if (use_threshold == nil) then use_threshold = true end

   -- stats is a hash of hashes organized as follows:
   -- { "id1" : { "key1": "value1", "key2": "value2", ...}, "id2 : { ... } }
   -- filter out the needed values
   _filtered_stats = {}

   for id,content in pairs(stats) do
      _filtered_stats[id] = content[sort_field_key]
   end
  local file_key = sort_field_key
  if (lastdump_key ~= nil) then
    file_key = file_key.."_"..lastdump_key
  end

   -- Read the lastdump; the name of the lastdump file has the following
   -- format: <lastdump_dir>/.<sort_field_key>_lastdump
   lastdump = lastdump_dir .. "/."..file_key.."_lastdump"
   last = nil
   if(ntop.exists(lastdump)) then
      last = persistence.load(lastdump)
   end
   if(last == nil) then last = {} end

   persistence.store(lastdump, _filtered_stats);

   for key, value in pairs(_filtered_stats) do
      if(last[key] ~= nil) then
         v = _filtered_stats[key]-last[key]
         if(v < 0) then v = 0 end
         _filtered_stats[key] = v
      end
   end

   -- order the filtered stats by using the value (bytes sent/received during
   -- the last time interval) as key
   filtered_stats = {}
   for key, value in pairs(_filtered_stats) do
      filtered_stats[value] = key
   end

   -- Compute traffic
   total = 0
   for _value,_ in pairsByKeys(filtered_stats, rev) do
      total = total + _value
   end

   threshold = total / 10 -- 10 %
   low_threshold = total * 0.05  -- 5%

   -- build a new hashtable sorted by the required field
   top_stats = {}
   other_stats = 0
   counter = 0
   for _value,_id in pairsByKeys(filtered_stats, rev) do
      if (counter < max_num_entries) then
         if ((_value == 0) or (use_threshold == true and ((_value < low_threshold or
             _value < threshold) and (counter > max_num_entries / 2)))) then
            other_stats = other_stats + _value
            goto loop_more_top
         end
         top_stats[_value] = _id -- still keep it in order
         counter = counter + 1
      else
         other_stats = other_stats + _value
      end
   ::loop_more_top::
   end

   if (other_stats > 0) then
     top_stats[other_stats] = other_stats_id
   end

   return top_stats
end

function filterBy(stats, col, val)
  local filtered_by = {}

  if (col == "" or col == nil or val == nil) then
    return stats
  end

  for id,content in pairs(stats) do
    if (content[col] == val) then
      filtered_by[id] = content
    end
  end

  return filtered_by
end

-- #####################################################

function getCurrentTopTalkers(ifid, ifname, filter_col, filter_val, concat, mode, use_threshold, lastdump_key)
   local max_num_entries = 10
   local rsp = ""
   local num = 0

   interface.select(ifname)
   hosts_stats,total = aggregateHostsStats(interface.getLatestActivityHostsInfo())
   hosts_stats = filterBy(hosts_stats, filter_col, filter_val)

   talkers_dir = fixPath(dirs.workingdir .. "/" .. ifid .. "/top_talkers")
   if(not(ntop.exists(talkers_dir))) then
      ntop.mkdir(talkers_dir)
   end

   if(concat == false and mode == nil) then
      rsp = rsp.."{\n"
   end
   rsp = rsp..'\t"hosts": [\n'

   if(mode == nil) then
      rsp = rsp .. "{\n"
      rsp = rsp .. '\t"senders": ['
   end

   --print("Hello\n")
   if((mode == nil) or (mode == "senders")) then
      top_talkers = getTop(hosts_stats, "bytes.sent", max_num_entries, talkers_dir, lastdump_key, use_threshold)
      num = 0
      other_stats = 0
      for value,id in pairsByKeys(top_talkers, rev) do
         if (id == other_stats_id) then
            other_stats = value
         else
	    if(num > 0) then rsp = rsp .. " }," end
	    rsp = rsp .. '\n\t\t { "address": "'..id.. '", "label": "'
	       ..(hosts_stats[id]["name"] or 'n.a.')

	    if((hosts_stats[id]["name"] ~= "") and (isIPv6String(id) == true)) then
	       rsp = rsp .. " (IPv6)"
	       end

	       rsp = rsp ..'", "url": "'
                  ..ntop.getHttpPrefix()..
	       '/lua/host_details.lua?host='..id..'", "value": '..value..
	       ', "local": "'..tostring(hosts_stats[id]["localhost"])..'"'
	    num = num + 1
         end
      end
      if (other_stats > 0) then
         rsp = rsp .. '},\n\t\t { "address": "'..other_stats_id.. '", "label": "'
            ..other_stats_id..'", "url": "", "value": '..other_stats..
            ', "local": "false"'
      end
   end

   if(mode == nil) then
      if(num > 0) then rsp = rsp .. " }" end
      rsp = rsp .. "\n\t],\n"
      rsp = rsp .. '\t"receivers": ['
   end

   if((mode == nil) or (mode == "receivers")) then
      top_listeners = getTop(hosts_stats, "bytes.rcvd", max_num_entries, talkers_dir, lastdump_key, use_threshold)
      num = 0
      other_stats = 0
      for value,id in pairsByKeys(top_listeners, rev) do
         if (id == other_stats_id) then
            other_stats = value
         else
	    if(num > 0) then rsp = rsp .. " }," end
	    rsp = rsp .. '\n\t\t { "address": "'..id.. '", "label": "'
	       ..(hosts_stats[id]["name"] or 'n.a.')..'", "url": "'
                  ..ntop.getHttpPrefix()..
                  '/lua/host_details.lua?host='..id..'", "value": '..value..
                  ', "local": "'..tostring(hosts_stats[id]["localhost"])..'"'
	    num = num + 1
         end
      end
      if (other_stats > 0) then
         rsp = rsp .. '},\n\t\t { "address": "'..other_stats_id.. '", "label": "'
            ..other_stats_id..'", "url": "", "value": '..other_stats..
            ', "local": "false"'
      end    
   end

   if(mode == nil) then
      if(num > 0) then rsp = rsp .. " }" end
      rsp = rsp .. "\n\t]\n"
      rsp = rsp .. "\n}\n"
   else
      if(num > 0) then rsp = rsp .. " }\n" end
   end

   rsp = rsp.."]"
   if(concat == false and mode == nil) then
      rsp = rsp.."\n}"
   end

   --print(rsp.."\n")
   return(rsp)
end

-- #####################################################

function groupStatsByColumn(ifid, ifname, col)
   local _group = {}
   local total = 0
   -- Group hosts info by the required column
   for _key, value in pairs(hosts_stats) do
      key = hosts_stats[_key][col]

      if ((not key) or
          (col == "country" and key == "") or
          (col == "local_network_id" and key == -1) or
          (col == "os" and key == "")) then goto continue end
      if (_group[key] == nil) then
         _group[key] = {}
         old = 0
      else
         assert(_group[key][col.."_bytes.sent"] ~= nil)
         assert(_group[key][col.."_bytes.rcvd"] ~= nil)
         assert(_group[key][col.."_bytes"] ~= nil)
         old = _group[key][col.."_bytes"]
      end

      if (col == "asn") then
         if(key == 0) then
            _group[key]["name"] = "0 [Local/Unknown]"
         else
            _group[key]["name"] = key .." ["..hosts_stats[_key]["asname"].."]"
         end
      elseif (col == "vlan") then
         if (key == 0) then
           _group[key]["name"] = "No VLAN"
         else
           _group[key]["name"] = "VLAN"..hosts_stats[_key]["vlan"]
         end
      elseif (col == "country") then
         if (key == "") then
           _group[key]["name"] = "Unknown"
         else
           _group[key]["name"] = key
         end
      elseif (col == "local_network_id") then
         if (key == -1) then
           _group[key]["name"] = "[Unknown]"
         else
           _group[key]["name"] = hosts_stats[_key]["local_network_name"]
         end
      elseif (col == "os") then
         if (key == "") then
           _group[key]["name"] = "[Unknown]"
         else
           _group[key]["name"] = hosts_stats[_key]["os"]
         end
      end
      val = hosts_stats[_key]["bytes.sent"] + hosts_stats[_key]["bytes.rcvd"]
      total = total + val
      _group[key][col.."_bytes"] = old + val
      _group[key][col.."_bytes"] = old + val
      _group[key][col.."_bytes.sent"] = ternary(_group[key][col.."_bytes.sent"] ~= nil,
                                                _group[key][col.."_bytes.sent"], 0)
                                        + hosts_stats[_key]["bytes.sent"]
      _group[key][col.."_bytes.rcvd"] = ternary(_group[key][col.."_bytes.rcvd"] ~= nil,
                                                _group[key][col.."_bytes.rcvd"], 0)
                                        + hosts_stats[_key]["bytes.rcvd"]
     ::continue::
   end
  return _group, total
end

function getCurrentTopGroupsSeparated(ifid, ifname, max_num_entries, use_threshold,
                                      use_delta, filter_col, filter_val, col, key, loc, concat, mode, lastdump_key)
   max_num_entries = 10  -- TODO: check if max_num_entries can be forcefully set to 10
   rsp = ""

   interface.select(ifname)
   hosts_stats,total = aggregateHostsStats(interface.getLatestActivityHostsInfo())
   hosts_stats = filterBy(hosts_stats, filter_col, filter_val)
   if (loc ~= nil) then
     hosts_stats = filterBy(hosts_stats, "localhost", loc)
   end

   talkers_dir = fixPath(dirs.workingdir .. "/" .. ifid .. "/top_talkers")
   if(not(ntop.exists(talkers_dir))) then
      ntop.mkdir(talkers_dir)
   end

   _group, total = groupStatsByColumn(ifid, ifname, col)

   if(concat == false and mode == nil) then
      rsp = rsp.."{\n"
   end
   rsp = rsp..'\t"'..key..'": [\n'

   if(mode == nil) then
      rsp = rsp .. "{\n"
      rsp = rsp .. '\t"senders": ['
   end

   if((mode == nil) or (mode == "senders")) then
      top_talkers = getTop(_group, col.."_bytes.sent", max_num_entries, talkers_dir, lastdump_key)
      num = 0
      other_stats = 0
      for value,id in pairsByKeys(top_talkers, rev) do
         if (id == other_stats_id) then
            other_stats = value
         else
	    if(num > 0) then rsp = rsp .. " }," end
	    rsp = rsp .. '\n\t\t { "label": "'.._group[id]["name"].. '", "url": "'
                  ..ntop.getHttpPrefix()..
                  '/lua/hosts_stats.lua?'..col..'='..id..'", "address": "'
                  ..id..'", "value": '..value
	    num = num + 1
         end
      end
      if (other_stats > 0) then
         rsp = rsp .. '},\n\t\t { "address": "'..other_stats_id.. '", "label": "'
            ..other_stats_id..'", "url": "", "value": '..other_stats..
            ', "local": "false"'
      end
   end

   if(mode == nil) then
      if(num > 0) then rsp = rsp .. " }" end
      rsp = rsp .. "\n\t],\n"
      rsp = rsp .. '\t"receivers": ['
   end

   if((mode == nil) or (mode == "receivers")) then
      top_listeners = getTop(_group, col.."_bytes.rcvd", max_num_entries, talkers_dir, lastdump_key)
      num = 0
      other_stats = 0
      for value,id in pairsByKeys(top_listeners, rev) do
         if (id == other_stats_id) then
            other_stats = value
         else
	    if(num > 0) then rsp = rsp .. " }," end
	    rsp = rsp .. '\n\t\t { "label": "'.._group[id]["name"].. '", "url": "'
                  ..ntop.getHttpPrefix()..
                  '/lua/hosts_stats.lua?'..col..'='..id..'", "address": "'
                  ..id..'", "value": '..value
	    num = num + 1
         end
      end
      if (other_stats > 0) then
         rsp = rsp .. '},\n\t\t { "address": "'..other_stats_id.. '", "label": "'
            ..other_stats_id..'", "url": "", "value": '..other_stats..
            ', "local": "false"'
      end
   end

   if(mode == nil) then
      if(num > 0) then rsp = rsp .. " }" end
      rsp = rsp .. "\n\t]\n"
      rsp = rsp .. "\n}\n"
   else
      if(num > 0) then rsp = rsp .. " }\n" end
   end

   rsp = rsp.."]"
   if(concat == false and mode == nil) then
      rsp = rsp.."\n}"
   end

   --print(rsp.."\n")
   return(rsp)
end

function getCurrentTopGroups(ifid, ifname, max_num_entries, use_threshold,
                             use_delta, filter_col, filter_val, col, key, concat, mode, lastdump_key)
   rsp = ""

   --if(ifname == nil) then ifname = "any" end

   interface.select(ifname)
   hosts_stats,total = aggregateHostsStats(interface.getLatestActivityHostsInfo())
   hosts_stats = filterBy(hosts_stats, filter_col, filter_val)

   talkers_dir = fixPath(dirs.workingdir .. "/" .. ifid .. "/top_talkers")
   if(not(ntop.exists(talkers_dir))) then
      ntop.mkdir(talkers_dir)
   end

   _group, total = groupStatsByColumn(ifid, ifname, col)

   if(concat == true) then
      rsp = rsp..'"'..key..'": '
   end

   rsp = rsp .. "[\n"

   -- Get top groups
   top_groups = getTop(_group, col.."_bytes", max_num_entries, talkers_dir, lastdump_key, use_threshold)

   num = 0
   other_stats = 0
   for _value,_key in pairsByKeys(top_groups, rev) do
      if (key == other_stats_id) then
         other_stats = value
      else
         if(num > 0) then rsp = rsp .. " }," end
         rsp = rsp .. '\n\t\t { "label": "'.._key..'", "url": "'
               ..ntop.getHttpPrefix()..
	    '/lua/hosts_stats.lua?'..col..'='.._key..'", "name": "'

	 if((_group[_key] ~= nil) and (_group[_key]["name"] ~= nil)) then rsp = rsp .. _group[_key]["name"] end
	 rsp = rsp ..'", "value": '.._value
         num = num + 1
      end
   end
   if (other_stats > 0) then
      rsp = rsp .. '},\n\t\t { "address": "'..other_stats_id.. '", "label": "'
         ..other_stats_id..'", "url": "", "value": '..other_stats..
         ', "local": "false"'
   end

   if (num > 0) then
      rsp = rsp .. " }\n"
   end
   rsp = rsp .. "\n]"

   return(rsp)
end