#!/usr/bin/perl

=head1 NAME

pfmon - ARP listener and maintenance threads

=head1 SYNOPSIS

pfmon [options]

 Options:
   -d      Daemonize
   -h      Help
   -v      Verbose

=cut

use warnings;
use strict;
use Getopt::Std;
use Net::Pcap 0.16;
use File::Basename qw(basename);
use POSIX qw(:signal_h pause :sys_wait_h SIG_BLOCK SIG_UNBLOCK);
use Pod::Usage;
use Fcntl qw(:flock);

#pf::log must always be initilized first
BEGIN {
    # log4perl init
    use constant INSTALL_DIR => '/usr/local/pf';
    use lib INSTALL_DIR . "/lib";
    use pf::log(service => 'pfmon');
}

use pf::file_paths qw($var_dir);
use pf::accounting qw(acct_maintenance);
use pf::config qw(%Config);
use pf::constants qw($FALSE $TRUE);
use pf::config::cached;
use pf::inline::accounting;
use pf::iplog;
use pf::locationlog;
use pf::auth_log;
use pf::node;
use pf::db;
use pf::services;
use pf::traplog;
use pf::util;
use pf::services::util;
use pf::violation qw(violation_maintenance);
use pf::ConfigStore::Provisioning;
use pf::factory::provisioner;
use pf::SwitchFactory;
use pf::radius_audit_log;
use pf::StatsD;
use pf::person;
use pf::fingerbank;
use fingerbank::Config;
use fingerbank::Redis;
use fingerbank::DB;
use pf::cluster;
use Time::HiRes qw(time);
use pf::option82 qw(search_switch);

pf::SwitchFactory->preloadConfiguredModules();

# initialization
# --------------
# assign process name (see #1464)
our $PROGRAM_NAME = $0 = "pfmon";
our @REGISTERED_TASKS;
our $IS_CHILD = 0;
our %CHILDREN;
our @TASKS_RUN;
our $ALARM_RECV = 0;

my $logger = get_logger( $PROGRAM_NAME );
my $old_child_sigaction = POSIX::SigAction->new;

POSIX::sigaction(
    &POSIX::SIGALRM,
    POSIX::SigAction->new(
        'alarm_sighandler', POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or die("pfmon could not set SIGALRM handler: $!");

POSIX::sigaction(
    &POSIX::SIGHUP,
    POSIX::SigAction->new(
        'normal_sighandler' , POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or die("pfmon could not set SIGHUP handler: $!");

POSIX::sigaction(
    &POSIX::SIGINT,
    POSIX::SigAction->new(
        'normal_sighandler' , POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or die("pfmon could not set SIGINT handler: $!");

POSIX::sigaction(
    &POSIX::SIGTERM,
    POSIX::SigAction->new(
        'normal_sighandler' , POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or die("pfmon could not set SIGTERM handler: $!");

POSIX::sigaction(
    &POSIX::SIGCHLD,
    POSIX::SigAction->new(
        'child_sighandler' , POSIX::SigSet->new(), &POSIX::SA_NODEFER
    ),
    $old_child_sigaction
) or die("pfmon could not set SIGCHLD handler: $!");

POSIX::sigaction(
    &POSIX::SIGUSR1,
    POSIX::SigAction->new(
        'usr1_sighandler' , POSIX::SigSet->new(), &POSIX::SA_NODEFER
    )
) or die("pfmon could not set SIGUSR1 handler: $!");

my %args;
getopts( 'dhvr', \%args );

pod2usage( -verbose => 1 ) if ( $args{h} );

my $daemonize = $args{d};
my $verbose   = $args{v};
my $restart   = $args{r};

my $pidfile = "${var_dir}/run/pfmon.pid";

our $HAS_LOCK = 0;
open(my $fh,">>$pidfile");
#flock($fh, LOCK_EX | LOCK_NB) or die "cannot lock $pidfile another pfmon is running\n";
$HAS_LOCK = 1;

our $running = 1;

# standard signals and daemonize
daemonize($PROGRAM_NAME) if ($daemonize);
our $PARENT_PID = $$;


sub start {
    registertasks();
    runtasks();
    waitforit();
}

start();
cleanup();

END {
    if ( !$args{h} && $HAS_LOCK ) {
        unless($IS_CHILD) {
            deletepid();
            $logger->info("stopping pfmon");
        }
    }
}

exit(0);

=head1 SUBROUTINES

=head2 registertasks

    Register all tasks

=cut

sub registertasks  {
    register_task(
        'iplog rotation',
        'iplog_rotation_interval',
        sub {
            pf::iplog::rotate( $Config{'maintenance'}{'iplog_rotation_window'}, $Config{maintenance}{iplog_rotation_batch}, $Config{maintenance}{iplog_rotation_timeout} ) if ( $Config{'maintenance'}{'iplog_rotation_window'} );
        }
    );
    register_task(
        'iplog cleanup',
        'iplog_cleanup_interval',
        sub {
            pf::iplog::cleanup( $Config{'maintenance'}{'iplog_cleanup_window'}, $Config{maintenance}{iplog_cleanup_batch}, $Config{maintenance}{iplog_cleanup_timeout} ) if ( $Config{'maintenance'}{'iplog_cleanup_window'} );
        }
    );
    register_task(
        'locationlog cleanup',
        'locationlog_cleanup_interval',
        sub {
            locationlog_cleanup( $Config{'maintenance'}{'locationlog_cleanup_window'}, $Config{maintenance}{locationlog_cleanup_batch}, $Config{maintenance}{locationlog_cleanup_timeout} ) if ( $Config{'maintenance'}{'locationlog_cleanup_window'} );
        }
    );
    register_task(
        'auth_log cleanup',
        'auth_log_cleanup_interval',
        sub {
            pf::auth_log::cleanup( $Config{'maintenance'}{'auth_log_cleanup_window'}, $Config{maintenance}{auth_log_cleanup_batch}, $Config{maintenance}{auth_log_cleanup_timeout} ) if ( $Config{'maintenance'}{'auth_log_cleanup_window'} );
        }
    );
    register_task(
        'radius audit log cleanup',
        'radius_audit_log_cleanup_interval',
        sub {
            radius_audit_log_cleanup( $Config{'maintenance'}{'radius_audit_log_cleanup_window'}, $Config{maintenance}{radius_audit_log_cleanup_batch}, $Config{maintenance}{radius_audit_log_cleanup_timeout}) if ( $Config{'maintenance'}{'radius_audit_log_cleanup_window'} );
        }
    );
    register_task(
        'node cleanup',
        'node_cleanup_interval',
        sub {
            node_cleanup( $Config{'maintenance'}{'node_cleanup_window'} ) if ( $Config{'maintenance'}{'node_cleanup_window'} );
        }
    );
    register_task(
        'person cleanup',
        'person_cleanup_interval',
        sub {
            person_cleanup() if ( isenabled($Config{'maintenance'}{'person_cleanup'}) );
        }
    );
    register_task(
        'traplog cleanup',
        'traplog_cleanup_interval',
        sub {
            traplog_cleanup( $Config{'maintenance'}{'traplog_cleanup_window'} ) if ( $Config{'maintenance'}{'traplog_cleanup_window'} );
        }
    );
    register_task(
        'checking registered nodes for expiration',
        'nodes_maintenance_interval',
        sub {
            nodes_maintenance();
        }
    );
    register_task(
        'checking violations for expiration',
        'violation_maintenance_interval',
        sub {
            violation_maintenance( $Config{maintenance}{violation_maintenance_batch}, $Config{maintenance}{violation_maintenance_timeout} );
        }
    );
    register_task(
        'checking accounting data for potential bandwidth abuse',
        'inline_accounting_maintenance_interval',
        sub {
            inline_accounting_maintenance( $Config{'inline'}{'layer3_accounting_session_timeout'} ) if isenabled($Config{'inline'}{'accounting'});
        }
    );
    register_task(
        'provisioner polling enforcement',
        'provisioning_compliance_poll_interval',
        sub {
            provisioner_compliance_poll();
        }
    );
    register_task(
        'account maintenance',
        'acct_maintenance_interval',
        sub {
            acct_maintenance();
        }
    );
    register_task(
        'fingerbank data update',
        'fingerbank_data_update_interval',
        \&update_fingerbank_data
    );
    register_task(
        'cluster_check',
        'cluster_check_interval',
        \&cluster_check
    );
    register_task(
        'option82 task',
        'option82_query_interval',
        sub {
            search_switch() if isenabled($Config{'network'}{'dhcpoption82logger'});
        }
    );
}

=head2 cleanup

cleans after children

=cut

sub cleanup {
    kill_and_wait_for_children('INT',30);
    kill_and_wait_for_children('USR1',10);
    signal_children('KILL');
}

=head2 kill_and_wait_for_children

signal children and waits for them to exit process

=cut

sub kill_and_wait_for_children {
    my ($signal,$waittime) = @_;
    signal_children($signal);
    $ALARM_RECV = 0;
    alarm $waittime;
    while (((keys %CHILDREN) != 0 ) && !$ALARM_RECV) {
        pause;
    }
}

=head2 signal_children

sends a signal to all active children

=cut

sub signal_children {
    my ($signal) = @_;
    kill ( $signal, keys %CHILDREN);
}

=head2 purge_cache

purge expired items from a cache

=cut

sub purge_cache {
    my ($namespace) = @_;
    my $cache = pf::CHI->new( namespace => $namespace );
    for my $key ($cache->get_keys) {
        if($cache->exists_and_is_expired($key)) {
            #Add an eval in case of the value deleted before
            eval {
                $cache->remove($key);
            };
        }
    }
}

=head2 provisioner_compliance_poll

Polls each provisioner to enforce compliance

=cut

sub provisioner_compliance_poll {
    foreach my $id (@{pf::ConfigStore::Provisioning->new->readAllIds}) {
        my $provisioner = pf::factory::provisioner->new($id);
        if($provisioner->supportsPolling){
            $provisioner->pollAndEnforce($Config{maintenance}{provisioning_compliance_poll_interval});
        }
    }
}

=head2 normal_sighandler

the signal handler to shutdown the service

=cut

sub normal_sighandler {
    $running = 0;
}

=head2 runtasks

run all runtasks

=cut

sub runtasks {
    db_disconnect();
    my $mask = POSIX::SigSet->new(POSIX::SIGCHLD());
    sigprocmask(SIG_BLOCK,$mask);
    while(@REGISTERED_TASKS) {
        my $task = shift @REGISTERED_TASKS;
        runtask($task);
    }
    sigprocmask(SIG_UNBLOCK,$mask);
}

=head2 runtask

creates a new child to run a task

=cut

sub runtask {
    my ($task) = @_;
    my $pid = fork();
    if($pid) {
        $CHILDREN{$pid} = $task;
    } elsif ($pid == 0) {
        POSIX::sigaction(
            &POSIX::SIGCHLD,
            $old_child_sigaction,
        ) or die("pfmon could not set SIGCHLD handler: $!");
        $IS_CHILD = 1;
        _runtask(@$task);
    } else {
    }
}

=head2 _runtask

the task to is ran in a loop until it is finished

=cut

sub _runtask {
    my ($id,$parameter,$task) = @_;
    $0 = "pfmon - $id";
    my $time_taken = 0;
    while ($running) {
        pf::config::cached::ReloadConfigs();
        my $interval = $Config{'maintenance'}{$parameter};
        unless ($interval) {
            $logger->trace("task $id is disabled");
            $time_taken = 0;
            alarm 60;
            pause;
            next;
        }
        my $final_interval = $time_taken > 0 ? $interval - int($time_taken+1) : $interval;
        $logger->trace("$id is sleeping for $final_interval ($interval from configuration - $time_taken)");
        # Only wait if the interval is positive
        if($final_interval > 0) {
            alarm $final_interval;
            pause;
            last unless $running;
        }
        
        $logger->trace("$id is running");
        my $start = Time::HiRes::gettimeofday;
        eval {
            $task->();
        };
        if ($@) {
            $logger->error("Error running task $id: $@");
        }
        $time_taken = Time::HiRes::gettimeofday - $start;
        #Stop running if parent is no longer alive
        unless(is_parent_alive()) {
            $logger->error("Parent is no longer running shutting down");
            $running = 0;
        }
    }
    $logger->trace("$$ shutting down");
    exit;
}

=head2 is_parent_alive

Checks to see if parent is alive

=cut

sub is_parent_alive {
    kill (0,$PARENT_PID)
}

=head2 register_task

registers the task to run

=cut

sub register_task {
    my ($taskId, $parameter,$function) = @_;
    push @REGISTERED_TASKS, [ $taskId , $parameter, $function ];

}

=head2 waitforit

waits for signals

=cut

sub waitforit {
    while($running) {
        pause;
        $logger->info("Awake from pause");
        runtasks();
    }
}

=head2 alarm_sighandler

the alarm signal handler

=cut

sub alarm_sighandler {
    $ALARM_RECV = 1;
}

=head2 child_sighandler

reaps the children

=cut

sub child_sighandler {
    local ($!, $?);
    while(1) {
        my $child = waitpid(-1, WNOHANG);
        last unless $child > 0;
        my $task = delete $CHILDREN{$child};
        register_task(@$task);
    }
}

=head2 usr1_sighandler

the handler to cancel any currently running database queries

=cut

sub usr1_sighandler {
   db_cancel_current_query();
}

=head2 update_fingerbank_data

Update all the Fingerbank data from the API

=cut

sub update_fingerbank_data {

    if(fingerbank::Config::is_api_key_configured){
        my $apiclient = pf::client::getClient();
        foreach my $action (keys(%pf::fingerbank::ACTION_MAP)){
            if(defined($pf::fingerbank::ACTION_MAP_CONDITION{$action})){
                unless($pf::fingerbank::ACTION_MAP_CONDITION{$action}->()){
                    get_logger->debug("Not executing $action because its condition returned false");
                    next;
                }
            }
            get_logger->debug("Calling Fingerbank action $action");
            my ($status, $status_msg) = pf::cluster::notify_each_server('fingerbank_update_component', action => $action, email_admin => $FALSE, fork_to_queue => $TRUE);
            if(fingerbank::Util::is_success($status)){
                get_logger->info("Successfully executed action $action");
            }
            else {
                get_logger->error("Couldn't execute action $action : ".$status_msg);
            }
        }
    }
    else {
        get_logger->debug("Can't update fingerbank data since there is no API key configured");
    }

}

=head2 cluster_check

Check the health state of the cluster and manage any configuration conflict between members

=cut

sub cluster_check {
    my $cache = pf::CHI->new(namespace => 'clustering');
    my $now = time;
    my $last_conflict_at = $cache->get('last_config_healthy_timestamp');
    my $last_config_checked = $cache->get('last_config_checked_timestamp');

    my $conflict_resolution_threshold = $Config{active_active}{conflict_resolution_threshold};

    get_logger->info("Using $conflict_resolution_threshold resolution threshold");
    
    my $interval = $Config{'maintenance'}{'cluster_check_interval'};
    my ($servers_map, $version_map) = pf::cluster::get_all_config_version();

    # Making sure we have all available data for the decision and that there are multiple versions detected
    if(defined($last_conflict_at) && defined($last_config_checked) && keys(%$version_map) > 1) { 
        my $last_conflict_interval = $now - $last_conflict_at;
        my $last_config_checked_interval = $now - $last_config_checked;
        
        # If we haven't checked the state in the last 2 intervals, we'll ignore any conflicts and get the latest state
        if($last_config_checked_interval > 2*$interval) {
            get_logger->info("Cluster config state hasen't been checked for too long (last was : $last_config_checked_interval). Will consider config healthy for this iteration");
            $cache->set('last_config_healthy_timestamp', $now);
        }
        elsif($last_conflict_at > $conflict_resolution_threshold) {
            get_logger->info("Configuration is unhealthy since $conflict_resolution_threshold seconds. Will attempt to resolve the conflict");
            pf::cluster::handle_config_conflict();
        }
    }
    else {
        get_logger->info("All cluster members are running the same configuration version");
        $cache->set('last_config_healthy_timestamp', $now);
    }
    $cache->set('last_config_checked_timestamp', $now);
}

=head1 AUTHOR

Inverse inc. <info@inverse.ca>

Minor parts of this file may have been contributed. See CREDITS.

=head1 COPYRIGHT

Copyright (C) 2005-2016 Inverse inc.

Copyright (C) 2005 Kevin Amorin

Copyright (C) 2005 David LaPorte

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.

=cut

