#!/usr/bin/perl
#
# $Id$
#
# Purpose:
#     keep master inform about alive node
# 
# Note:
#   1. Node-side process
#   2. Starts by procctl
#   3. Runs in background
#   4. never ends but restarted by procctl if dies

use strict;
use XML::Simple;
use Data::Dumper;
use NextCAM::Init;
use Data::Dumper;
use Log::Log4perl "get_logger";
require "$ENV{APL}/common/bin/logger.patrol";

# CONS ================================================================

my $log = get_logger('NEXTCAM::CONF::KEEPALIVE');
my $APL=$ENV{APL};
my $KEEPALIVE_INTERVAL=18; #master wait 60 seconds to declare dead node


# VARS ===============================================================


# PROC ===============================================================
sub api {
   my ($uni,$act)=@_;
   my $call=(-f "$ENV{APL_VAR}/conf/master/s_master")
      ? "$APL/conf/bin/master4node action=$act uni=$uni"
      : "ssh s_master '. $APL/base/etc/env.conf && $APL/conf/bin/master4node action=$act uni=$uni'";
   my $ret=`$call`;
   return "ERROR: call ($call) fails ($ret)" if $?;
   my $xref = XMLin($ret);
   $log->debug(Dumper($xref));
   #   print STDERR "$xref->{STATUS}:$xref->{MESSAGE}\n";
   return "$xref->{STATUS}:$xref->{MESSAGE}";
}

# MAIN ===============================================================

$log->info("keepalive starts");

open(NODE,"$APL/var/conf/node/conf") || $log->logdie("Cannot read $APL/var/conf/node/conf");
my %node=map {/(^\w+)=(.+)/} grep {/^\w+=.+/} <NODE>;
close NODE;
$log->logdie("Cannot locate correct UNI in $APL/var/conf/node/conf") if not $node{UNI}=~/^\w{22}$/;

for(;;sleep $KEEPALIVE_INTERVAL) {      # -------------------- keepalive cycle
     my $ret=api($node{UNI},'keepalive');
     $log->warn("api:keepalive returns $ret") if $ret=~/^ERROR/;
}
print "THIS MESSAGE WILL NEVER BE PRINTED\n";
