garbage.pl 15 KB

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