通过linux-inotify事件刷新fikker-cdn

如果文件更新就刷新cdn这个是很多运维需要做的,现在用perl开发了这个脚本,由于这个cpan模块块扫描目录很慢,所以建用在文件不多的网站上.

use strict;
use EV;
use 5.010;
use Data::Dumper;
use Date::Format;
use Mojo::UserAgent;
use URI::Escape;
use AnyEvent::Inotify::Simple;

# Fikker cdn server's 
# WARNNING: do not add "/" on url end.
my $server={
	srv1=>{ url=>'http://192.168.1.99:6780',passwd=>'0000'},
	srv2=>{ url=>'http://192.168.1.88:6780',passwd=>'0000'},
};

# Monittor DIR
my $dir='/home/www/';

#Full path of Site url
my $site_url='http://www.yiyou.org/';

# open debug =1 ,close = 0
my $debug=1;

#   ===== END CONFIG ====
my $ua = Mojo::UserAgent->new;

our $login_info= do_login($ua,$server);
our $queue;

my $w = EV::timer 2, 2, sub {
   my $q=$queue;
   $queue={};
   #say "timer print";
   for my $key(keys %{$q}){
		#say  "=>",$key;
		my $url=uri_escape($site_url.$key);
		say "site url $url" if $debug;
		
		for my $srv(keys %{$server}){
			my $try=3;
			do{
				my $post_info={
					RequestID=>'thiscache-clean',
					SessionID=>$login_info->{$srv},
					Url=>$url,
					Icase=>1,
					Rules=>0,
					WithCluster=>0
				};
				my $delurl=$server->{$srv}->{url}.'/fikker/webcache.fik?type=thiscache&cmd=cleancache';
				my $res=$ua->post($delurl => form => $post_info)->res->json;
				#print Dumper $res;
				if($res->{Return} eq  "False" ){
					if($res->{ErrorNo} eq "21"){
						$login_info= do_login($ua,$server);
						say "try relogin..." if $debug ;
					}else{
						say "ERROR:";
						say Dumper $res if $debug;
					}
				}else{
					$try=-1;
				}
				$try --;
				say "try $try" if $debug;
			}while($try > 0);
		}
   }
};
my $inotify = AnyEvent::Inotify::Simple->new(
    directory      => $dir,
    event_receiver => sub {
        my ($event, $file, $moved_to) = @_;
		#print Dumper $event;
		given($event) {
			when('modify'){
				#my $last= (stat($dir."/".$file))[9];
				#print "modify $file ";
				#say time2str('%Y-%m-%d %X',$last)." => ".time2str('%Y-%m-%d %X',time);
				#say "modify $file "
				if($file =~/\.html$/){
					$queue->{$file}=1;
				}
				#say "modify => $file" if $debug;
			}
			when('delete'){
				if($file =~/\.html$/){
					$queue->{$file}=1;
				}
				#say "modify => $file" if $debug;
			}
        };

    },
);
 
EV::loop;

sub do_login{
	my ($ua,$srvs)=@_;
	my $rr;
	for my $srv(keys %{$srvs}){
		my $login_url=$srvs->{$srv}->{url}.'/fikker/webcache.fik?type=sign&cmd=in';
		#print $login_url;
		my $post_data={
				RequestID=>'LOGIN',
				Username=>'admin',
				Password=>$srvs->{$srv}->{passwd}
		};
			
		my $res= $ua->post($login_url => form => $post_data)->res->json;
		#print Dumper $res;exit;
		if($res->{SessionID}){
			$rr->{$srv}=$res->{SessionID};
		}else{
			die "[$srv] login error.";
		}
	}
	return $rr;
}