#!/usr/bin/perl use Socket; use URI::Escape; use POSIX ":sys_wait_h"; use POSIX qw(strftime); use File::Basename; use File::Path; use LWP::UserAgent; use HTTP::Request::Common; use Getopt::Long; use Cwd; my $port = 10000; my $addr = '127.0.0.1'; my $DEBUG = 0; my $workDir = dirname($0); my $logClient = '-'; my $sleepDuration = 10; my $logFileDir; my $logFileName; umask(0); foreach $argnum (0 .. $#ARGV) { my $argument = $ARGV[$argnum]; if ($argument eq '--help') { print "Background Job Server:\n"; print "Version: 0.1\n\n"; print "Command line arguments:\n"; print " --port= Set a custom port. Default value is $port\n"; print " --debug Write debug information to sdtout\n"; print " --help This page\n"; exit; } if ($argument eq '--debug') { $DEBUG = 1; next; } ($name, $value) = split(/=/, $argument, 2); if ($value == '') { print "Invalid argument: $argument\n"; exit; } if ($name eq '--port') { $port = $value; } } writeLog('Started Server. Listen ' . $addr . ':' . $port); socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp')) or die "socket:$!"; setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) or die "setsockopt: $!"; bind(SERVER, sockaddr_in($port, inet_aton($addr))) or die "bind: $!"; listen(SERVER, SOMAXCONN) or die "listen: $!"; sub initLogPath { my $date = strftime '%Y-%m-%d', localtime; $logFileName = "$workDir/tmp/background-job-server/$date/log.txt"; $logFileDir = dirname($logFileName); mkpath($logFileDir, 0, 0717); } sub writeLog { initLogPath(); my $str = shift; my $time = strftime '%Y-%m-%d %H:%M:%S', localtime; my $message = "$time\t$logClient\t$str"; open(my $hLog, '>>', $logFileName); print $hLog $message, "\n"; close($hLog); if ($DEBUG == 1) { print $message, "\n"; } } sub varDump { print "=" x 80, "\n"; print shift, "\n"; print "=" x 80, "\n"; } sub REAPER { while ((my $waitedpid = waitpid(-1, WNOHANG)) > 0) { } $SIG{CHLD} = \&REAPER; } $SIG{CHLD} = \&REAPER; while(1) { my $paddr; for(; $paddr = accept(CLIENT, SERVER); close CLIENT) { my $pid = fork(); if (not defined $pid) { print "resources not avilable.\n"; } elsif ($pid == 0) { # child process my($port, $iaddr) = sockaddr_in($paddr); my $ip = inet_ntoa($iaddr); $logClient = "$ip:$port"; writeLog('connected'); processClientRequest(); writeLog('disconnected'); $logClient = '-'; exit(-1); } else { # parent process } } } sub processClientRequest { local $SIG{ALRM} = sub { }; my $line = ; my $url = ''; chomp($line); ($name, $value) = split(/\s/, $line, 2); if ($name eq "START") { $url = $value; writeLog($line); do { my $res = `lwp-request "$url"`; @array = split(" ", $res); writeLog("$res sleep $sleepDuration seconds"); sleep $sleepDuration; writeLog('wakeup'); } while ($array[0] eq 'CONTINUE'); } }