garbage.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use Encode;
  8. no warnings 'utf8';
  9. use English;
  10. use base;
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use strict;
  14. use DBI;
  15. use Date::Parse;
  16. use eyelib::config;
  17. use eyelib::database;
  18. use eyelib::net_utils;
  19. use DateTime;
  20. use Fcntl qw(:flock);
  21. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  22. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  23. my @db_tables =(
  24. 'connections',
  25. 'device_l3_interfaces',
  26. 'device_ports',
  27. 'User_list',
  28. 'User_auth',
  29. 'Unknown_mac',
  30. 'User_stats',
  31. 'User_stats_full',
  32. 'dhcp_log',
  33. 'worklog',
  34. 'remote_syslog',
  35. 'Traffic_detail',
  36. );
  37. my $debug_history = 3;
  38. my $optimize = 0;
  39. if ($ARGV[0] =~/optimize/i) { $optimize = 1; }
  40. db_log_info($dbh,'Garbage started.');
  41. sub is_dhcp_pool {
  42. my $pools = shift;
  43. my $ip_int = shift;
  44. foreach my $subnet (keys %{$pools}) {
  45. #print "net: $subnet ip: $ip_int pool: $pools->{$subnet}->{first_ip} .. $pools->{$subnet}->{last_ip}\n";
  46. if ($ip_int <= $pools->{$subnet}->{last_ip} and $ip_int>= $pools->{$subnet}->{first_ip}) { return $subnet; }
  47. }
  48. return 0;
  49. }
  50. #unblock users
  51. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  52. my $history_sql;
  53. my $history_rf;
  54. my %nets;
  55. my %dhcp_conf;
  56. foreach my $net (@office_network_list) {
  57. my $scope_name=$net;
  58. $scope_name =~s/\/\d+$//g;
  59. $nets{$scope_name}= new Net::Patricia;
  60. $nets{$scope_name}->add_string($net);
  61. }
  62. my $now = DateTime->now(time_zone=>'local');
  63. $now->set(day=>1);
  64. my $month_start=$dbh->quote($now->ymd("-")." 00:00:00");
  65. my $month_dur = DateTime::Duration->new( months => 1 );
  66. my $next_month = $now + $month_dur;
  67. $next_month->set(day=>1);
  68. my $month_stop = $dbh->quote($next_month->ymd("-")." 00:00:00");
  69. my $dhcp_networks = new Net::Patricia;
  70. my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE office=1 AND dhcp=1 AND vpn=0 ORDER BY ip_int_start');
  71. foreach my $subnet (@subnets) {
  72. $dhcp_networks->add_string($subnet->{subnet});
  73. my $subnet_name = $subnet->{subnet};
  74. $subnet_name=~s/\/\d+$//g;
  75. $dhcp_conf{$subnet_name}->{first_ip}=$subnet->{dhcp_start};
  76. $dhcp_conf{$subnet_name}->{last_ip}=$subnet->{dhcp_stop};
  77. }
  78. if ($day==1) {
  79. db_log_info($dbh,'Monthly amnesty started');
  80. db_log_verbose($dbh,"Amnistuyemo all blocked user by traffic for a month");
  81. do_sql($dbh,"Update User_list set blocked=0");
  82. do_sql($dbh,"Update User_auth set blocked=0, changed=1 WHERE blocked=1 and deleted=0");
  83. db_log_info($dbh,'Monthly amnesty stopped');
  84. } else {
  85. #month stat
  86. db_log_info($dbh,'Daily statistics started');
  87. my $month_sql="SELECT User_list.id, User_list.login, SUM( traf_all ) AS traf_sum, User_list.month_quota as uquota
  88. FROM ( SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  89. WHERE User_stats.`timestamp`>=$month_start AND User_stats.`timestamp`< $month_stop
  90. GROUP BY User_stats.auth_id ) AS V, User_auth, User_list
  91. WHERE V.auth_id = User_auth.id AND User_auth.user_id = User_list.id and User_list.blocked=1 GROUP BY login";
  92. my @month_stats = get_records_sql($dbh,$month_sql);
  93. foreach my $row (@month_stats) {
  94. my $m_quota=$row->{uquota}*$KB*$KB;
  95. next if ($m_quota < $row->{traf_sum});
  96. db_log_info($dbh,"Amnistuyemo blocked user $row->{login} [$row->{id}] by traffic for a day");
  97. do_sql($dbh,"UPDATE User_list set blocked=0 WHERE id=$row->{id}");
  98. do_sql($dbh,"UPDATE User_auth set blocked=0, changed=1 WHERE user_id=$row->{id}");
  99. }
  100. db_log_info($dbh,'Daily statistics stopped');
  101. }
  102. db_log_info($dbh,'Clean dhcp leases for dynamic hosts with overdue lease time');
  103. #clean temporary dhcp leases & connections only for dhcp pool ip
  104. my $users_sql = "SELECT * FROM User_auth WHERE deleted=0 AND (`ou_id`=".$default_user_ou_id." OR `ou_id`=".$default_hotspot_ou_id.")";
  105. my @users_auth = get_records_sql($dbh,$users_sql);
  106. foreach my $row (@users_auth) {
  107. next if (!is_dhcp_pool(\%dhcp_conf,$row->{ip_int}));
  108. my $last_dhcp_time = GetUnixTimeByStr($row->{dhcp_time});
  109. if ($dhcp_networks->match_string($row->{ip})) {
  110. my $clean_dhcp_time = $last_dhcp_time + 60*$dhcp_networks->match_string($row->{ip});
  111. if (time() - $clean_dhcp_time>0) {
  112. db_log_verbose($dbh,"Clean overdue dhcp leases for ip: $row->{ip} id: $row->{id} last dhcp: $row->{dhcp_time} clean time: ".GetTimeStrByUnixTime($clean_dhcp_time)." now: ".GetNowTime());
  113. # do_sql($dbh,"DELETE FROM connections WHERE auth_id='".$row->{id}."'");
  114. delete_record($dbh,"User_auth","id='".$row->{id}."'");
  115. my $u_count=get_count_records($dbh,'User_auth','deleted=0 and user_id='.$row->{user_id});
  116. if (!$u_count) {
  117. delete_record($dbh,"User_list","id=".$row->{'user_id'});
  118. db_log_info($dbh,"Remove dynamic user id: $row->{'user_id'} by dhcp lease timeout");
  119. }
  120. }
  121. }
  122. }
  123. db_log_info($dbh,'Finished');
  124. $now = DateTime->now(time_zone=>'local');
  125. #clean dhcp log
  126. if ($history_dhcp) {
  127. my $day_dur = DateTime::Duration->new( days => $history_dhcp );
  128. my $clean_date = $now - $day_dur;
  129. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  130. db_log_info($dbh,'Clearing outdated records dhcp log');
  131. do_sql($dbh,"DELETE FROM dhcp_log WHERE `timestamp` < $clean_str" );
  132. db_log_verbose($dbh,"Clean dhcp leases for all older that ".$clean_str);
  133. }
  134. ##### clean old connections ########
  135. if ($connections_history) {
  136. db_log_info($dbh,'Clearing outdated connection records');
  137. my $day_dur = DateTime::Duration->new( days => $connections_history );
  138. my $clean_date = $now - $day_dur;
  139. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  140. $users_sql = "SELECT id FROM User_auth WHERE `last_found` < $clean_str and last_found>0";
  141. db_log_debug($dbh,$users_sql) if ($debug);
  142. @users_auth=get_records_sql($dbh,$users_sql);
  143. foreach my $row (@users_auth) {
  144. db_log_debug($dbh,"Clear old connection for user_auth ".$row->{id});
  145. do_sql($dbh,"DELETE FROM connections WHERE auth_id='".$row->{id}."'");
  146. }
  147. }
  148. ##### clean dup connections ########
  149. db_log_info($dbh,'Clearing duplicated connection records');
  150. my $conn_sql = "SELECT id,port_id,auth_id FROM connections order by port_id";
  151. my @conn_ref = get_records_sql($dbh,$conn_sql);
  152. my $old_port_id=0;
  153. my $old_auth_id=0;
  154. foreach my $row (@conn_ref) {
  155. my $c_id = $row->{id};
  156. my $c_port_id = $row->{port_id};
  157. my $c_auth_id = $row->{auth_id};
  158. if (!$c_port_id) { $c_port_id=0; }
  159. if (!$c_auth_id) { $c_auth_id=0; }
  160. if ($old_port_id ==0 or $old_auth_id==0) { $old_port_id=$c_port_id; $old_auth_id=$c_auth_id; next; }
  161. if ($old_port_id >0 and $old_port_id != $c_port_id) { $old_port_id=$c_port_id; $old_auth_id=$c_auth_id; next; }
  162. if ($old_auth_id >0 and $old_auth_id != $c_auth_id) { $old_port_id=$c_port_id; $old_auth_id=$c_auth_id; next; }
  163. do_sql($dbh,"DELETE FROM connections WHERE id='".$c_id."'");
  164. db_log_info($dbh,"Remove dup connection $c_id: $c_port_id $c_auth_id");
  165. }
  166. ##### clean empty user account and corresponded devices for dynamic users and hotspot ################
  167. db_log_info($dbh,'Clearing empty user account and corresponded devices for dynamic users and hotspot');
  168. my $u_sql = "SELECT * FROM User_list as U WHERE (U.ou_id=".$default_hotspot_ou_id." OR U.ou_id=".$default_user_ou_id.") AND (SELECT COUNT(*) FROM User_auth WHERE User_auth.deleted=0 AND User_auth.user_id = U.id)=0";
  169. my @u_ref = get_records_sql($dbh,$u_sql);
  170. foreach my $row (@u_ref) {
  171. do_sql($dbh,"DELETE FROM User_list WHERE id='".$row->{id}."'");
  172. db_log_info($dbh,"Remove empty dynamic user with id: $row->{id} login: $row->{login}");
  173. #delete binded device
  174. my $user_device = get_record_sql($dbh,"SELECT * FROM devices WHERE user_id=".$row->{id});
  175. if ($user_device) {
  176. db_log_info($dbh,"Remove corresponded device id: $user_device->{id} name: $user_device->{device_name}");
  177. unbind_ports($dbh, $user_device->{id});
  178. do_sql($dbh, "DELETE FROM connections WHERE device_id=".$user_device->{id});
  179. do_sql($dbh, "DELETE FROM device_l3_interfaces WHERE device_id=".$user_device->{id});
  180. do_sql($dbh, "DELETE FROM device_ports WHERE device_id=".$user_device->{id});
  181. delete_record($dbh, "devices", "id=".$user_device->{id});
  182. }
  183. }
  184. ##### clean empty user account and corresponded devices ################
  185. if ($config_ref{clean_empty_user}) {
  186. db_log_info($dbh,'Clearing empty user account and corresponded devices');
  187. # my $u_sql = "SELECT * FROM User_list as U WHERE (SELECT COUNT(*) FROM User_auth WHERE User_auth.deleted=0 AND User_auth.user_id = U.id)=0 AND (SELECT COUNT(*) FROM auth_rules WHERE auth_rules.user_id = U.id)=0";
  188. my $u_sql = "SELECT * FROM User_list as U WHERE (SELECT COUNT(*) FROM User_auth WHERE User_auth.deleted=0 AND User_auth.user_id = U.id)=0";
  189. my @u_ref = get_records_sql($dbh,$u_sql);
  190. foreach my $row (@u_ref) {
  191. do_sql($dbh,"DELETE FROM User_list WHERE id='".$row->{id}."'");
  192. db_log_info($dbh,"Remove empty user with id: $row->{id} login: $row->{login}");
  193. #delete binded device
  194. my $user_device = get_record_sql($dbh,"SELECT * FROM devices WHERE user_id=".$row->{id});
  195. if ($user_device) {
  196. db_log_info($dbh,"Remove corresponded device id: $user_device->{id} name: $user_device->{device_name}");
  197. unbind_ports($dbh, $user_device->{id});
  198. do_sql($dbh, "DELETE FROM connections WHERE device_id=".$user_device->{id});
  199. do_sql($dbh, "DELETE FROM device_l3_interfaces WHERE device_id=".$user_device->{id});
  200. do_sql($dbh, "DELETE FROM device_ports WHERE device_id=".$user_device->{id});
  201. delete_record($dbh, "devices", "id=".$user_device->{id});
  202. }
  203. }
  204. }
  205. ##### Remove unreferensed auth rules
  206. do_sql($dbh, "DELETE FROM `auth_rules` WHERE user_id NOT IN (SELECT id FROM User_list)");
  207. ##### unknown mac clean ############
  208. db_log_info($dbh,'Clearing unknown mac if it found in current User_auth table');
  209. $users_sql = "SELECT mac FROM User_auth WHERE deleted=0";
  210. @users_auth = get_records_sql($dbh,$users_sql);
  211. foreach my $row (@users_auth) {
  212. next if (!$row->{mac});
  213. do_sql($dbh,"DELETE FROM Unknown_mac WHERE mac='".mac_simplify($row->{mac})."'");
  214. }
  215. ##### traffic detail ######
  216. if ($history) {
  217. my $day_dur = DateTime::Duration->new( days => $history );
  218. my $clean_date = $now - $day_dur;
  219. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  220. db_log_info($dbh,"Clean traffic detail older that ".$clean_str);
  221. #clean old traffic detail
  222. do_sql($dbh,"DELETE FROM Traffic_detail WHERE `timestamp` < $clean_str" );
  223. }
  224. ##### log ######
  225. if ($history_log_day) {
  226. my $day_dur = DateTime::Duration->new( days => $history_log_day );
  227. my $clean_date = $now - $day_dur;
  228. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  229. db_log_info($dbh,"Clean VERBOSE worklog older that ".$clean_str);
  230. do_sql($dbh,"DELETE FROM worklog WHERE level>$L_INFO AND `timestamp` < $clean_str" );
  231. }
  232. #clean debug logs older than $debug_history days
  233. if ($debug_history) {
  234. my $day_dur = DateTime::Duration->new( days => 3 );
  235. my $clean_date = $now - $day_dur;
  236. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  237. db_log_info($dbh,"Clean debug worklog older that ".$clean_str);
  238. do_sql($dbh,"DELETE FROM worklog WHERE level>$L_DEBUG AND `timestamp` < $clean_str" );
  239. }
  240. ##### remote syslog ######
  241. if ($history_syslog_day) {
  242. my $day_dur = DateTime::Duration->new( days => $history_syslog_day );
  243. my $clean_date = $now - $day_dur;
  244. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  245. db_log_info($dbh,"Clean syslog older that ".$clean_str);
  246. do_sql($dbh,"DELETE FROM remote_syslog WHERE `date` < $clean_str" );
  247. }
  248. ##### Traffic stats ######
  249. if ($history_trafstat_day) {
  250. my $day_dur = DateTime::Duration->new( days => $history_trafstat_day );
  251. my $clean_date = $now - $day_dur;
  252. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  253. db_log_info($dbh,"Clean traffic statistics older that ".$clean_str);
  254. do_sql($dbh,"DELETE FROM User_stats WHERE `timestamp` < $clean_str" );
  255. }
  256. ##### Traffic stats full ######
  257. my $iptraf_history = $config_ref{traffic_ipstat_history};
  258. if ($iptraf_history) {
  259. my $day_dur = DateTime::Duration->new( days => $iptraf_history );
  260. my $clean_date = $now - $day_dur;
  261. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  262. db_log_info($dbh,"Clean traffic full statistics older that ".$clean_str);
  263. do_sql($dbh,"DELETE FROM User_stats_full WHERE `timestamp` < $clean_str" );
  264. }
  265. #### clean unknown user ip
  266. do_sql($dbh,"DELETE FROM User_auth WHERE (mac is NULL or mac='') and deleted=1");
  267. #### save location changes
  268. my %connections;
  269. my @connections_list=get_records_sql($dbh,"SELECT * FROM connections ORDER BY auth_id");
  270. foreach my $connection (@connections_list) {
  271. next if (!$connection);
  272. $connections{$connection->{auth_id}}=$connection;
  273. }
  274. my $auth_sql="SELECT * FROM User_auth WHERE mac IS NOT NULL AND mac !='' AND deleted=0 ORDER BY last_found DESC";
  275. my %auth_table;
  276. my @auth_full_list=get_records_sql($dbh,$auth_sql);
  277. foreach my $auth (@auth_full_list) {
  278. next if (!$auth);
  279. my $auth_mac=mac_simplify($auth->{mac});
  280. next if (exists $auth_table{$auth_mac});
  281. next if (!exists $connections{$auth->{id}});
  282. $auth_table{$auth_mac}=1;
  283. my $h_sql = "SELECT * FROM mac_history WHERE mac='".$auth_mac."' ORDER BY `timestamp` DESC";
  284. my $history = get_record_sql($dbh,$h_sql);
  285. if (!$history) {
  286. #add record to history
  287. my $cur_conn = $connections{$auth->{id}};
  288. my $new;
  289. $new->{device_id}=$cur_conn->{device_id};
  290. $new->{port_id}=$cur_conn->{port_id};
  291. $new->{auth_id}=$auth->{id};
  292. $new->{ip}=$auth->{ip};
  293. $new->{mac}=$auth_mac;
  294. $new->{timestamp}=$auth->{last_found};
  295. db_log_info($dbh,"Auth id: $auth->{id} $auth_mac found at location device_id: $new->{device_id} port_id: $new->{port_id}");
  296. insert_record($dbh,"mac_history",$new);
  297. next;
  298. }
  299. my $cur_conn = $connections{$auth->{id}};
  300. #check record history
  301. if ($history->{device_id} != $cur_conn->{device_id} or $history->{port_id} != $cur_conn->{port_id}) {
  302. #add new record
  303. my $new;
  304. $new->{device_id}=$cur_conn->{device_id};
  305. $new->{port_id}=$cur_conn->{port_id};
  306. $new->{auth_id}=$auth->{id};
  307. $new->{ip}=$auth->{ip};
  308. $new->{mac}=$auth_mac;
  309. $new->{timestamp}=$auth->{last_found};
  310. db_log_info($dbh,"Auth id: $auth->{id} $auth_mac moved to another location device_id: $new->{device_id} port_id: $new->{port_id}");
  311. insert_record($dbh,"mac_history",$new);
  312. }
  313. }
  314. if ( $optimize ) {
  315. db_log_info($dbh,'Start optimize tables');
  316. foreach my $table (@db_tables) {
  317. my $opt_sql = "optimize table ".$table;
  318. my $opt_rf=$dbh->prepare($opt_sql) or die "Unable to prepare $opt_sql:" . $dbh->errstr;
  319. my $opt_result = $opt_rf->execute();
  320. #CREATE TABLE `".$table.".new` LIKE $table;
  321. #INSERT INTO `".$table.".new` SELECT * FROM $table;
  322. #RENAME TABLE $table TO `".$table.".backup`;
  323. #RENAME TABLE `".$table.".new` TO $table;
  324. #DROP TABLE `".$table.".backup`;";
  325. }
  326. db_log_info($dbh,'Optimize ended.');
  327. }
  328. db_log_info($dbh,'Garbage stopped.');
  329. $dbh->disconnect;
  330. exit 0;