eye-statd.pl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. #!/usr/bin/perl -w
  2. use utf8;
  3. use open ":encoding(utf8)";
  4. use English;
  5. use base;
  6. use FindBin '$Bin';
  7. use lib "/opt/Eye/scripts";
  8. use strict;
  9. use DBI;
  10. use Time::Local;
  11. use Net::Patricia;
  12. use Data::Dumper;
  13. use Date::Parse;
  14. use DateTime;
  15. use eyelib::config;
  16. use eyelib::main;
  17. use eyelib::net_utils;
  18. use eyelib::database;
  19. use Socket qw(AF_INET6 inet_ntop);
  20. use IO::Socket;
  21. use Data::Dumper;
  22. use File::Path::Tiny;
  23. use threads;
  24. my @router_ref = ();
  25. my @interfaces = ();
  26. my %router_svi;
  27. my %routers;
  28. my %wan_dev;
  29. my %lan_dev;
  30. my @traffic = ();
  31. my $saving = 0;
  32. #user statistics for cached data
  33. my %user_stats;
  34. my $MAXREAD = 9216;
  35. my $timeshift = get_option($dbh,55)*60;
  36. my $save_path = get_option($dbh,72);
  37. my $thread_count = $cpu_count;
  38. #save traffic to DB
  39. my $traf_lastflush = time();
  40. # NetFlow
  41. my $server_port = 2055;
  42. my $netflow5_header_len = 24;
  43. my $netflow5_flowrec_len = 48;
  44. my $netflow9_header_len = 20;
  45. my $netflow9_templates = {};
  46. # reap dead children
  47. $SIG{CHLD} = \&REAPER;
  48. $SIG{TERM} = \&TERM;
  49. $SIG{INT} = \&TERM;
  50. $SIG{HUP} = \&INIT;
  51. sub REAPER {
  52. wait;
  53. $saving = 0;
  54. $SIG{CHLD} = \&REAPER;
  55. }
  56. sub TERM {
  57. print "SIGTERM received\n";
  58. flush_traffic(1);
  59. while (wait() != -1) {}
  60. exit 0;
  61. }
  62. sub INIT {
  63. # Create new database handle. If we can't connect, die()
  64. my $hdb = init_db();
  65. InitSubnets();
  66. init_option($hdb);
  67. $save_path = get_option($dbh,72);
  68. $timeshift = get_option($hdb,55)*60;
  69. @router_ref = get_records_sql($hdb,"SELECT * FROM devices WHERE deleted=0 AND device_type=2 AND snmp_version>0 ORDER by ip" );
  70. @interfaces = get_records_sql($hdb,"SELECT * FROM `device_l3_interfaces` ORDER by device_id" );
  71. #router device_id by known device ip
  72. foreach my $row (@router_ref) {
  73. $routers{$row->{id}}=$row;
  74. my @auth_list = get_records_sql($hdb,"SELECT ip FROM User_auth WHERE deleted=0 AND user_id=".$row->{user_id});
  75. foreach my $auth (@auth_list) {
  76. $router_svi{$auth->{ip}}{id}=$row->{id};
  77. $router_svi{$auth->{ip}}{save}=$row->{netflow_save};
  78. }
  79. }
  80. #snmp index for WAN/LAN interface by device id
  81. foreach my $row (@interfaces) {
  82. if ($row->{interface_type}) { $wan_dev{$row->{device_id}}{$row->{snmpin}}=1; } else { $lan_dev{$row->{device_id}}{$row->{snmpin}}=1; }
  83. }
  84. #get userid list
  85. my @auth_list_ref = get_records_sql($hdb,"SELECT id,ip,save_traf FROM User_auth where deleted=0 ORDER by id");
  86. foreach my $row (@auth_list_ref) {
  87. $user_stats{$row->{ip}}{auth_id}=$row->{id};
  88. $user_stats{$row->{ip}}{save_traf}=$row->{save_traf};
  89. }
  90. $hdb->disconnect();
  91. }
  92. ############### MAIN ##########################
  93. #close default database
  94. $dbh->disconnect();
  95. INIT();
  96. my $lsn_nflow;
  97. my $sel = IO::Select->new();
  98. # prepare to listen for NetFlow UDP packets
  99. if ($server_port > 0) {
  100. $lsn_nflow = IO::Socket::INET->new(LocalPort => $server_port, Proto => "udp")
  101. or die "Couldn't be a NetFlow UDP server on port $server_port : $@\n";
  102. $sel->add($lsn_nflow);
  103. }
  104. my ($him,$datagram,$flags);
  105. # main datagram receive loop
  106. while (1) {
  107. while (my @ready = $sel->can_read) {
  108. foreach my $server (@ready) {
  109. $him = $server->recv($datagram, $MAXREAD);
  110. next if (!$him);
  111. my ($port, $ipaddr) = sockaddr_in($server->peername);
  112. if (defined($lsn_nflow) && $server == $lsn_nflow) {
  113. my ($version) = unpack("n", $datagram);
  114. if ($version == 5) {
  115. parse_netflow_v5($datagram, $ipaddr);
  116. } elsif ($version == 9) {
  117. parse_netflow_v9($datagram, $ipaddr);
  118. } else {
  119. print "unknown NetFlow version: $version\n";
  120. }
  121. }
  122. }
  123. }
  124. }
  125. sub parse_netflow_v5 {
  126. my $datagram = shift;
  127. my $ipaddr = shift;
  128. my ($version, $count, $sysuptime, $unix_secs, $unix_nsecs,
  129. $flow_sequence, $engine_type, $engine_id, $aggregation,
  130. $agg_version) = unpack("nnNNNNCCCC", $datagram);
  131. my $flowrecs = substr($datagram, $netflow5_header_len);
  132. #0 - N 0-3 srcaddr Source IP address
  133. #1 - N 4-7 dstaddr Destination IP address
  134. #2 - N 8-11 nexthop IP address of next hop router
  135. #3 - n 12-13 input SNMP index of input interface
  136. #4 - n 14-15 output SNMP index of output interface
  137. #5 - N 16-19 dPkts Packets in the flow
  138. #6 - N 20-23 dOctets Total number of Layer 3 bytes in the packets of the flow
  139. #7 - N 24-27 First SysUptime at start of flow
  140. #8 - N 28-31 Last SysUptime at the time the last packet of the flow was received
  141. #9 - n 32-33 src_port TCP/UDP source port number or equivalent
  142. #10- n 34-35 dst_port TCP/UDP destination port number or equivalent
  143. #11- C 36 pad1 Unused (zero) byte
  144. #12- C 37 tcp_flags Cumulative OR of TCP flags
  145. #13- C 38 prot IP protocol type (for example, TCP = 6; UDP = 17)
  146. #14- C 39 tos IP type of service (ToS)
  147. #15- n 40-41 src_as Autonomous system number of the source, either origin or peer
  148. #16- n 42-43 dst_as Autonomous system number of the destination, either origin or peer
  149. #17- C 44 src_mask Source address prefix mask bits
  150. #18- C 45 dst_mask Destination address prefix mask bits
  151. #19- n 46-47 pad2 Unused (zero) bytes
  152. for (my $i = 0; $i < $count; $i++) {
  153. my $flowrec = substr($datagram, $netflow5_header_len + ($i*$netflow5_flowrec_len), $netflow5_flowrec_len);
  154. my @flowdata = unpack("NNNnnNNNNnnCCCCnnCCn", $flowrec);
  155. my %flow;
  156. $flow{src_ip} = join '.', unpack 'C4', pack 'N', $flowdata[0];
  157. $flow{dst_ip} = join '.', unpack 'C4', pack 'N', $flowdata[1];
  158. $flow{snmp_in} = $flowdata[3] || 0;
  159. $flow{snmp_out} = $flowdata[4] || 0;
  160. $flow{pkts} = $flowdata[5] || 0;
  161. $flow{octets} = $flowdata[6] || 0;
  162. $flow{src_port} = $flowdata[9] || 0;
  163. $flow{dst_port} = $flowdata[10] || 0;
  164. $flow{proto} = $flowdata[13] || 0;
  165. $flow{xsrc_ip} = $flow{src_ip};
  166. $flow{xdst_ip} = $flow{dst_ip};
  167. $flow{starttime} = time();
  168. $flow{netflow_v} = '5';
  169. $flow{ipv} = '4';
  170. save_flow($ipaddr, \%flow);
  171. }
  172. }
  173. sub parse_netflow_v9 {
  174. my $datagram = shift;
  175. my $ipaddr = shift;
  176. # Parse packet
  177. my ($version, $count, $sysuptime, $unix_secs, $seqno, $source_id, @flowsets) = unpack("nnNNNN(nnX4/a)*", $datagram);
  178. # Loop through FlowSets and take appropriate action
  179. for (my $i = 0; $i < scalar @flowsets; $i += 2) {
  180. my $flowsetid = $flowsets[$i];
  181. my $flowsetdata = substr($flowsets[$i+1], 4); # chop off id/length
  182. if ($flowsetid == 0) {
  183. # 0 = Template FlowSet
  184. parse_netflow_v9_template_flowset($flowsetdata, $ipaddr, $source_id);
  185. } elsif ($flowsetid == 1) {
  186. # 1 - Options Template FlowSet
  187. } elsif ($flowsetid > 255) {
  188. # > 255: Data FlowSet
  189. parse_netflow_v9_data_flowset($flowsetid, $flowsetdata, $ipaddr, $source_id);
  190. } else {
  191. # reserved FlowSet
  192. print "Unknown FlowSet ID $flowsetid found\n";
  193. }
  194. }
  195. }
  196. sub parse_netflow_v9_template_flowset {
  197. my $templatedata = shift;
  198. my $ipaddr = shift;
  199. my $source_id = shift;
  200. # Note: there may be multiple templates in a Template FlowSet
  201. my @template_ints = unpack("n*", $templatedata);
  202. my $i = 0;
  203. while ($i < scalar @template_ints) {
  204. my $template_id = $template_ints[$i];
  205. my $fldcount = $template_ints[$i+1];
  206. last if (!defined($template_id) || !defined($fldcount));
  207. # print "Updated template ID $template_id (source ID $source_id, from " . inet_ntoa($ipaddr) . ")\n" if ($debug);
  208. my $template = [@template_ints[($i+2) .. ($i+2+$fldcount*2-1)]];
  209. $netflow9_templates->{$ipaddr}->{$source_id}->{$template_id}->{'template'} = $template;
  210. # Calculate total length of template data
  211. my $totallen = 0;
  212. for (my $j = 1; $j < scalar @$template; $j += 2) {
  213. $totallen += $template->[$j];
  214. }
  215. $netflow9_templates->{$ipaddr}->{$source_id}->{$template_id}->{'len'} = $totallen;
  216. $i += (2 + $fldcount*2);
  217. }
  218. }
  219. sub parse_netflow_v9_data_flowset {
  220. my $flowsetid = shift;
  221. my $flowsetdata = shift;
  222. my $ipaddr = shift;
  223. my $source_id = shift;
  224. my $template = $netflow9_templates->{$ipaddr}->{$source_id}->{$flowsetid}->{'template'};
  225. if (!defined($template)) {
  226. # print "Template ID $flowsetid from $source_id/" . inet_ntoa($ipaddr) . " does not (yet) exist\n" if ($debug);
  227. return;
  228. }
  229. # Flowset record types
  230. #define NF9_IN_BYTES 1
  231. #define NF9_IN_PACKETS 2
  232. #define NF9_IN_PROTOCOL 4
  233. #define NF9_L4_SRC_PORT 7
  234. #define NF9_IPV4_SRC_ADDR 8
  235. #define NF9_INPUT_SNMP 10
  236. #define NF9_L4_DST_PORT 11
  237. #define NF9_IPV4_DST_ADDR 12
  238. #define NF9_OUTPUT_SNMP 14
  239. #define NF9_OUT_BYTES 23
  240. #define NF9_OUT_PKTS 24
  241. #define NF9_DIRECTION 61
  242. #define NF_F_XLATE_SRC_ADDR_IPV4 225
  243. #define NF_F_XLATE_DST_ADDR_IPV4 226
  244. #define NF_F_XLATE_SRC_PORT 227
  245. #define NF_F_XLATE_DST_PORT 228
  246. #define NF9_IPV6_SRC_ADDR 27
  247. #define NF9_IPV6_DST_ADDR 28
  248. #define NF_F_XLATE_SRC_ADDR_IPV6 281
  249. #define NF_F_XLATE_DST_ADDR_IPV6 282
  250. my $len = $netflow9_templates->{$ipaddr}->{$source_id}->{$flowsetid}->{'len'};
  251. my $offset = 0;
  252. my $datalen = length($flowsetdata);
  253. while (($offset + $len) <= $datalen) {
  254. my %flow;
  255. $flow{netflow_v} = '9';
  256. $flow{ipv} = '4';
  257. $flow{starttime} = time();
  258. for (my $i = 0; $i < scalar @$template; $i += 2) {
  259. my $field_type = $template->[$i];
  260. my $field_length = $template->[$i+1];
  261. my $value = substr($flowsetdata, $offset, $field_length);
  262. $offset += $field_length;
  263. # IN_BYTES
  264. if ($field_type == 1) {
  265. if ($field_length == 4) {
  266. $flow{octets} = unpack("N", $value);
  267. } elsif ($field_length == 8) {
  268. $flow{octets} = unpack("Q>", $value);
  269. }
  270. }
  271. # IN_PACKETS
  272. elsif ($field_type == 2) {
  273. if ($field_length == 4) {
  274. $flow{pkts} = unpack("N", $value);
  275. } elsif ($field_length == 8) {
  276. $flow{pkts} = unpack("Q>", $value);
  277. }
  278. }
  279. # IN_PROTOCOL
  280. elsif ($field_type == 4) { $flow{proto} = unpack("C", $value); }
  281. # L4_SRC_PORT
  282. elsif ($field_type == 7) { $flow{src_port} = unpack("n", $value); }
  283. # IPV4_SRC_ADDR
  284. elsif ($field_type == 8) { $flow{src_ip} = inet_ntop(AF_INET, $value); }
  285. # INPUT_SNMP
  286. elsif ($field_type == 10) {
  287. if ($field_length == 2) {
  288. $flow{snmp_in} = unpack("n", $value);
  289. } elsif ($field_length == 4) {
  290. $flow{snmp_in} = unpack("N", $value);
  291. }
  292. }
  293. # L4_DST_PORT
  294. elsif ($field_type == 11) { $flow{dst_port} = unpack("n", $value); }
  295. # IPV4_DST_ADDR
  296. elsif ($field_type == 12) { $flow{dst_ip} = inet_ntop(AF_INET, $value); }
  297. # OUTPUT_SNMP
  298. elsif ($field_type == 14) {
  299. if ($field_length == 2) {
  300. $flow{snmp_out} = unpack("n", $value);
  301. } elsif ($field_length == 4) {
  302. $flow{snmp_out} = unpack("N", $value);
  303. }
  304. }
  305. # IP_PROTOCOL_VERSION
  306. elsif ($field_type == 60) { my $ipversion = unpack("C", $value);
  307. #skip ipv6
  308. if ($ipversion == 6) { %flow=(); last; }
  309. }
  310. # XLATE_SRC_ADDR_IPV4
  311. elsif ($field_type == 225) { $flow{xsrc_ip} = inet_ntop(AF_INET, $value); }
  312. # XLATE_DST_ADDR_IPV4
  313. elsif ($field_type == 226) { $flow{xdst_ip} = inet_ntop(AF_INET, $value); }
  314. }
  315. $flow{snmp_in} = 0 if (!$flow{snmp_in});
  316. $flow{snmp_out} = 0 if (!$flow{snmp_out});
  317. $flow{octets} = 0 if (!$flow{octets});
  318. $flow{pkts} = 0 if (!$flow{pkts});
  319. if (%flow and $flow{snmp_in} and $flow{snmp_out}) { save_flow($ipaddr, \%flow); }
  320. }
  321. }
  322. sub save_flow {
  323. my $router_ip = shift;
  324. my $flow = shift;
  325. $router_ip = inet_ntoa($router_ip);
  326. #direction for user, 0 - in, 1 - out
  327. $flow->{direction} = '0';
  328. my $router_id;
  329. #skip unknown router
  330. if (exists $router_svi{$router_ip}) {
  331. $router_id = $router_svi{$router_ip}{id};
  332. $flow->{router_ip} = $router_ip;
  333. $flow->{device_id} = $router_id;
  334. $flow->{save} = $router_svi{$router_ip}{save};
  335. } else { return; }
  336. #skip input traffic for router
  337. if (exists $wan_dev{$router_id}->{$flow->{snmp_out}} and exists $wan_dev{$router_id}->{$flow->{snmp_in}}) { return; }
  338. #skip local traffic for router
  339. if (!exists $wan_dev{$router_id}->{$flow->{snmp_out}} and ! exists $wan_dev{$router_id}->{$flow->{snmp_in}}) { return; }
  340. if (exists $wan_dev{$router_id}->{$flow->{snmp_out}}) { $flow->{direction} = 1; }
  341. # print Dumper($flow) if ($debug);
  342. push(@traffic,$flow);
  343. flush_traffic(0);
  344. }
  345. sub flush_traffic {
  346. my $force = shift || 0;
  347. if (!$force && ($saving || ((time - $traf_lastflush) < $timeshift))) { return; }
  348. $saving++;
  349. my $pid = fork();
  350. if (!defined $pid) {
  351. $saving = 0;
  352. print "cannot fork! Save traffic and exit...\n";
  353. } elsif ($pid != 0) {
  354. # in parent
  355. $traf_lastflush = time();
  356. #clean main cache
  357. @traffic = ();
  358. return;
  359. }
  360. #create oper-cache
  361. my @flush_table = ();
  362. push(@flush_table,@traffic);
  363. #clean main cache
  364. INIT();
  365. my $hdb=init_db();
  366. #saved packet by users
  367. my @detail_traffic = ();
  368. my @saved_netflow = ();
  369. my %routers_found;
  370. #last packet timestamp
  371. my $last_time = time();
  372. foreach my $traf_record (@flush_table) {
  373. my ($auth_id,$l_src_ip,$l_dst_ip,$user_ip,$router_id);
  374. $router_id = $traf_record->{device_id};
  375. if ($traf_record->{save}) {
  376. push(@saved_netflow,join(';',$traf_record->{starttime},$traf_record->{device_id},$traf_record->{proto},$traf_record->{snmp_in},$traf_record->{snmp_out},$traf_record->{src_ip},$traf_record->{dst_ip},$traf_record->{xsrc_ip},$traf_record->{xdst_ip},$traf_record->{src_port},$traf_record->{dst_port},$traf_record->{octets},$traf_record->{pkts}));
  377. }
  378. $routers_found{$router_id} = 1;
  379. #outbound traffic
  380. if ($traf_record->{direction}) {
  381. if (exists $user_stats{$traf_record->{src_ip}}) {
  382. $user_ip = $traf_record->{src_ip};
  383. $l_src_ip = $traf_record->{src_ip};
  384. $l_dst_ip = $traf_record->{dst_ip};
  385. if (exists $user_stats{$user_ip}{$router_id}{out}) {
  386. $user_stats{$user_ip}{$router_id}{out}+=$traf_record->{octets};
  387. } else {
  388. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  389. }
  390. if (exists $user_stats{$user_ip}{$router_id}{pkt_out}) {
  391. $user_stats{$user_ip}{$router_id}{pkt_out}+=$traf_record->{pkts};
  392. } else {
  393. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  394. }
  395. }
  396. if (!$user_ip and $config_ref{add_unknown_user}) {
  397. $user_ip = $traf_record->{src_ip};
  398. $auth_id = new_auth($hdb,$user_ip);
  399. $user_stats{$user_ip}{auth_id}=$auth_id;
  400. $user_stats{$user_ip}{$router_id}{in}=0;
  401. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  402. $user_stats{$user_ip}{$router_id}{pkt_in}=0;
  403. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  404. $user_stats{$user_ip}{save_traf}=$config_ref{save_detail};
  405. }
  406. #inbound traffic
  407. } else {
  408. if (exists $user_stats{$traf_record->{xdst_ip}}) {
  409. $user_ip = $traf_record->{xdst_ip};
  410. $l_src_ip = $traf_record->{src_ip};
  411. $l_dst_ip = $traf_record->{xdst_ip};
  412. if (exists $user_stats{$user_ip}{$router_id}{in}) {
  413. $user_stats{$user_ip}{$router_id}{in}+=$traf_record->{octets};
  414. } else {
  415. $user_stats{$user_ip}{$router_id}{in}=$traf_record->{octets};
  416. }
  417. if (exists $user_stats{$user_ip}{$router_id}{pkt_in}) {
  418. $user_stats{$user_ip}{$router_id}{pkt_in}+=$traf_record->{pkts};
  419. } else {
  420. $user_stats{$user_ip}{$router_id}{pkt_in}=$traf_record->{pkts};
  421. }
  422. }
  423. }
  424. next if (!$user_ip);
  425. $last_time = $traf_record->{starttime};
  426. $user_stats{$user_ip}{last_found} = $last_time;
  427. next if (!$config_ref{save_detail} and !$user_stats{$user_ip}{save_traf});
  428. my $l_src_ip_aton=StrToIp($l_src_ip);
  429. my $l_dst_ip_aton=StrToIp($l_dst_ip);
  430. my ($sec,$min,$hour,$day,$month,$year,$zone) = (localtime($last_time))[0,1,2,3,4,5];
  431. $month++;
  432. $year += 1900;
  433. my $full_time = sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  434. my @detail_array = ($user_stats{$user_ip}->{auth_id},$router_id,$full_time,$traf_record->{proto},$l_src_ip_aton,$l_dst_ip_aton,$traf_record->{src_port},$traf_record->{dst_port},$traf_record->{octets},$traf_record->{pkts});
  435. push(@detail_traffic,\@detail_array);
  436. }
  437. @flush_table=();
  438. #start hour
  439. my ($sec,$min,$hour,$day,$month,$year) = (localtime($last_time))[0,1,2,3,4,5];
  440. #save netflow
  441. $save_path=~s/\/$//;
  442. my $netflow_file_path = $save_path.'/'.sprintf "%04d/%02d/%02d/%02d/",$year+1900,$month+1,$day,$hour;
  443. my $netflow_file_name = $netflow_file_path.sprintf "%04d%02d%02d-%02d%02d%02d.csv",$year+1900,$month+1,$day,$hour,$min,$sec;
  444. if (scalar @saved_netflow) {
  445. File::Path::Tiny::::mk($netflow_file_path);
  446. open (ND,">$netflow_file_name") || die("Error open file $netflow_file_name!!! die...");
  447. binmode(ND,':utf8');
  448. print ND join(';',"time","device_id","proto","snmp_in","snmp_out","src_ip","dst_ip","xsrc_ip","xdst_ip","src_port","dst_port","octets","pkts")."\n";
  449. foreach my $row (@saved_netflow) {
  450. next if (!$row);
  451. print ND $row."\n";
  452. }
  453. close ND;
  454. @saved_netflow=();
  455. }
  456. #save statistics
  457. #start stat time
  458. my $hour_date1 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  459. #end hour
  460. ($hour,$day,$month,$year) = (localtime($last_time+3600))[2,3,4,5];
  461. my $hour_date2 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  462. my @batch_sql_traf=();
  463. #print Dumper(\%user_stats) if ($debug);
  464. # update database
  465. foreach my $user_ip (keys %user_stats) {
  466. next if (!exists $user_stats{$user_ip}{last_found});
  467. my $user_ip_aton=StrToIp($user_ip);
  468. my $auth_id = $user_stats{$user_ip}{auth_id};
  469. #last flow for user
  470. my ($sec,$min,$hour,$day,$month,$year) = (localtime($user_stats{$user_ip}{last_found}))[0,1,2,3,4,5];
  471. #flow time string
  472. my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
  473. #last found timestamp
  474. my $tSQL="UPDATE User_auth SET `last_found`=$flow_date WHERE id='$auth_id'";
  475. push (@batch_sql_traf,$tSQL);
  476. #per router stats
  477. foreach my $router_id (keys %routers_found) {
  478. next if (!exists $user_stats{$user_ip}{$router_id});
  479. if (!exists $user_stats{$user_ip}{$router_id}{in}) { $user_stats{$user_ip}{$router_id}{in} = 0; }
  480. if (!exists $user_stats{$user_ip}{$router_id}{out}) { $user_stats{$user_ip}{$router_id}{out} = 0; }
  481. #skip empty stats
  482. if ($user_stats{$user_ip}{$router_id}{in} + $user_stats{$user_ip}{$router_id}{out} ==0) { next; }
  483. #packet count per router
  484. if (!exists $user_stats{$user_ip}{$router_id}{pkt_in}) { $user_stats{$user_ip}{$router_id}{pkt_in} = 0; }
  485. if (!exists $user_stats{$user_ip}{$router_id}{pkt_out}) { $user_stats{$user_ip}{$router_id}{pkt_out} = 0; }
  486. #current stats
  487. my $tSQL="INSERT INTO User_stats_full (timestamp,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out,step) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}','$user_stats{$user_ip}{$router_id}{pkt_in}','$user_stats{$user_ip}{$router_id}{pkt_out}','$timeshift')";
  488. push (@batch_sql_traf,$tSQL);
  489. #hour stats
  490. # get current stats
  491. my $sql = "SELECT id, byte_in, byte_out FROM User_stats WHERE `timestamp`>=$hour_date1 AND `timestamp`<$hour_date2 AND router_id=$router_id AND auth_id=$auth_id";
  492. my $hour_stat = get_record_sql($hdb,$sql);
  493. if (!$hour_stat) {
  494. my $dSQL="INSERT INTO User_stats (timestamp,auth_id,router_id,byte_in,byte_out) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}')";
  495. push (@batch_sql_traf,$dSQL);
  496. next;
  497. }
  498. if (!$hour_stat->{byte_in}) { $hour_stat->{byte_in}=0; }
  499. if (!$hour_stat->{byte_out}) { $hour_stat->{byte_out}=0; }
  500. $hour_stat->{byte_in} += $user_stats{$user_ip}{$router_id}{in};
  501. $hour_stat->{byte_out} += $user_stats{$user_ip}{$router_id}{out};
  502. $tSQL="UPDATE User_stats SET byte_in='".$hour_stat->{byte_in}."', byte_out='".$hour_stat->{byte_out}."' WHERE id='".$auth_id."' AND router_id='".$router_id."'";
  503. push (@batch_sql_traf,$tSQL);
  504. }
  505. }
  506. #update statistics in DB
  507. batch_db_sql($hdb,\@batch_sql_traf);
  508. db_log_debug($hdb,"Recalc quotes started");
  509. foreach my $router_id (keys %routers_found) { recalc_quotes($hdb,$router_id); }
  510. db_log_debug($hdb,"Recalc quotes stopped");
  511. if (scalar(@detail_traffic)) {
  512. db_log_debug($hdb,"Start write traffic detail to DB. ".scalar @detail_traffic." lines count") if ($debug);
  513. if ($config_ref{DBTYPE} eq 'mysql') {
  514. batch_db_sql_csv("Traffic_detail", \@detail_traffic);
  515. } else {
  516. my $index = 0;
  517. my @tmp=();
  518. my $item_per_thread = int(scalar @detail_traffic / $thread_count);
  519. my @threads=();
  520. foreach my $row (@detail_traffic) {
  521. push(@tmp,$row);
  522. $index++;
  523. if ($index<=$item_per_thread) { next; }
  524. my @tmp1=();
  525. push(@tmp1,@tmp);
  526. @tmp=();
  527. push(@threads, threads->create(\&batch_db_sql_csv, "Traffic_detail", \@tmp1));
  528. }
  529. if (scalar(@tmp)) {
  530. push(@threads, threads->create(\&batch_db_sql_csv, "Traffic_detail", \@tmp));
  531. }
  532. foreach my $t (@threads) { $t->join(); }
  533. @tmp=();
  534. }
  535. @detail_traffic = ();
  536. db_log_debug($hdb,"Write traffic detail to DB stopped") if ($debug);
  537. }
  538. $hdb->disconnect();
  539. $saving = 0;
  540. exit;
  541. }