garbage.pl 14 KB

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