garbage.pl 13 KB

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