grabwebcams.in 8.68 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3
#
# Copyright (c) 2005 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file 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 Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24
#
use English;
25
use Getopt::Std;
26
use Errno qw(ESRCH);
27 28
use POSIX ":sys_wait_h";
use BSD::Resource;
29 30

#
31
# Grab webcam images daemon. 
32
#
33 34
sub usage()
{
35
    print(STDOUT
36
	  "Usage: grabwebcams [-d] [-v] [-m] [-f fps] [-t timeout]\n" .
37 38 39 40
	  "       grabwebcams [-d] [-v] [-t timeout] [-k] pid eid\n" .
	  "switches and arguments:\n".
	  "-d      - Debug mode, use to prevent daemonization\n".
	  "-v      - Verbose mode (causes vlc to spit lots of goo)\n".
41 42
	  "-m      - Movie option; create a 24fps movie from each camera\n".
	  "-f <N>  - Set the frame rate for your movie\n".
43 44 45
	  "-t <N>  - Terminate automatically and N seconds\n".
	  "-k      - Kill a daemonized grabwebcams (only use with pid/eid)\n".
	  "pid eid - Project and Experiment (for use with swapin)\n");
46 47
    exit(-1);
}
48
my $optlist  = "dt:vkmf:";
49 50 51
my $debug    = 0;
my $verbose  = 0;
my $timeout  = 0;
52
my $fps      = 0;
53 54 55 56
my $killmode = 0;
my $movie    = 0;
my $pid;
my $eid;
57 58

#
59
# Configure variables
60
#
61 62 63 64 65
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBLOGS      = "@TBLOGSEMAIL@";
my $VLC		= "/usr/X11R6/bin/vlc";
my $WGET	= "/usr/local/bin/wget";
66
my $PIDFILE	= "/var/run/emulab/grabwebcams.pid";
67 68 69

# We don't want to run this script unless its the real version.
if ($EUID != 0) {
70
    die("*** $0:\n".
71
	"    Must be root! Maybe its a development version?\n");
72 73
}

74
#
75
# Please do not run as root. Hard to track what has happened.
76
#
77 78 79 80
if ($UID == 0) {
    die("*** $0:\n".
	"    Please do not run this as root!\n");
}
81 82 83 84 85 86 87 88 89 90 91 92 93

# un-taint path
$ENV{'PATH'} = '/bin:/usr/bin:/usr/local/bin:/usr/site/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1; 

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use libdb;
94
use libtestbed;
95

96 97 98
# Be careful not to exit on transient error
$libdb::DBQUERY_MAXTRIES = 30;

99
#
100 101
# Locals
# 
102 103 104
my $logfile;
my %webcams     = ();
my %children    = ();
105

106
#
107 108 109 110 111 112 113 114
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
115 116 117 118 119 120 121 122
    $debug = 1;
}
if (defined($options{"v"})) {
    $verbose = 1;
}
if (defined($options{"t"})) {
    $timeout = $options{"t"};
}
123 124 125
if (defined($options{"f"})) {
    $fps = $options{"f"};
}
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
if (defined($options{"m"})) {
    $movie = 1;
}
if (defined($options{"k"})) {
    $killmode = 1;
}
if (@ARGV) {
    usage()
	if (scalar(@ARGV) != 2 || $movie);
    
    ($pid,$eid) = @ARGV;

    if ($pid =~ /^([-\w]+)$/) {
	$pid = $1;
    }
    else {
	die("Bad data in argument: $pid.");
    }
    if ($eid =~ /^([-\w]+)$/) {
	$eid = $1;
    }
    else {
	die("Bad data in argument: $eid.");
    }
}

#
# Deal with stopping a running webcam script, as when an experiment is
# swapped out.
#
if ($killmode) {
    if (-e $PIDFILE) {    
	my $epid = `cat $PIDFILE`;
	# untaint
	if ($epid =~ /^(\d*)$/) {
	    $epid = $1;
	}
	else {
	    fatal("Bad data in pid: $epid!\n");
	}
	unlink($PIDFILE);

168
	if (kill(0, $epid) || ! $!{ESRCH}) {
169
	    if (! kill('TERM', $epid)) {
170
		fatal("Failed to stop webcam capture ($epid)!\n");
171 172 173 174 175 176
	    }
	}
    }
    exit(0);
}

177 178 179 180 181 182 183 184 185
#
# XXX Since we change the frame rate, do not allow this script to be
# run more then once at a time ... I'll change this later to support
# running multiple versions as long as the frame rate is the same.
#
if (-e $PIDFILE) {
    fatal("Another grabwebcams is in progress. Must stop that one first!");
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
# Making a movie for an experiment ...
if (defined($pid)) {
    #
    # Chdir into the project directory
    #
    my $moviedir = PROJROOT() . "/$pid/movies";
    if (! -d $moviedir) {
	if (! mkdir($moviedir, 0775)) {
	    die("*** $0:\n".
		"    Could not make directory $moviedir: $!");
	}
    }
    chdir($moviedir) or
	die("*** $0:\n".
	    "    Could not chdir to $moviedir!\n");

    #
    # Make a subdir and chdir into that.
    #
    my $dirname = $eid . "-" . TBDateTimeFSSafe();
    mkdir($dirname, 0777);
    chdir($dirname) or
	die("*** $0:\n".
	    "    Could not chdir to $dirname!\n");
}

#
# Grab the webcam data from the DB to see if we even need to continue.
#
my $query_result = DBQueryFatal("select * from webcams");
if (!$query_result->numrows) {
    print "There are no webcams!\n";
    exit(0);
}
# Okay, parse the camera data.
while (my %row = $query_result->fetchhash()) {
    my $id       = $row{"id"};
    my $server   = $row{"server"};

    $webcams{$id} = $server;
}

228 229
# Go to ground.
if (! $debug) {
230 231
    $logfile = TBMakeLogname("grabwebcams");
    
232 233 234
    if (TBBackGround($logfile)) {
	exit(0);
    }
235 236 237
}

#
238
# Write out the pid file and then drop privs. 
239
#
240
if (system("echo '$PID' > $PIDFILE")) {
241 242 243 244 245 246
    fatal("Could not create $PIDFILE!");
}
if (! $movie) {
    setpriority(PRIO_PROCESS, 0, -1);
}
$EUID = $UID;
247

248 249 250 251 252 253 254 255
#
# Handler to catch signal and kill children.
#
sub handler ($) {
    print "Caught a signal. Killing children ...\n";
    
    foreach my $id (keys(%children)) {
	my $pid = $children{$id};
256

257
	if (kill(0, $pid) || ! $!{ESRCH}) {
258 259
	    if (! kill('TERM', $pid)) {
		notify("Failed to stop vlc process $pid!");
260
	    }
261
	}
262 263 264 265 266
    }
    return 0;
}
$SIG{TERM} = \&handler;

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
#
# Set the frame rate. This is why we only allow one at a time for now.
# I am hoping for a better solution at some point, cause this causes
# an update to the flash, which the Axis people say is only good for
# 100000 writes. I suppose I could ask the camera what the framerate is
# and then change it if needed, but thats too much considering how little
# the robot testbed is currently used. 
#
if (!$fps) {
    $fps = ($movie ? 24 : 2);
}
foreach my $id (keys(%webcams)) {
    my $server = $webcams{$id};

    SetFrameRate($server, $fps);
}

284 285 286 287 288 289
#
# Now fire off vlc to capture the multicast output. 
# 
foreach my $id (keys(%webcams)) {
    my $server = $webcams{$id};
    my $file   = "video-${id}.mpg";
290
    my $URL    = "rtsp://${server}/mpeg4/1/media.amp";
291
    my $syspid;
292 293 294
    my $cmdstr = "$VLC " . ($verbose ? "-v -v " : "-q ") .
	"-I dummy --no-sap-parse --sout ".
	"#duplicate{dst=std{access=file,mux=ts,url=\"$file\"}} $URL";
295 296 297 298 299 300 301 302 303 304 305 306

    if ($syspid = fork()) {
	#
	# Parent. Just record the pid and go on.
	#
	$children{$id} = $syspid;
    }
    else {
	print "Running '$cmdstr'\n";
	my @cmdargs = split(" ", $cmdstr);
	exec(@cmdargs);
	exit(69);
307
    }
308
    sleep(1);
309
}
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

if ($timeout) {
    $SIG{ALRM} = \&handler;
    alarm($timeout);
}

#
# Now wait for children.
#
my $kid;
do {
    $kid = waitpid(-1, &WNOHANG);
    sleep(1);
} until ($kid == -1);

unlink($logfile)
    if (defined($logfile) && -e $logfile);
327
unlink($PIDFILE);
328
exit(0);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

sub fatal($)
{
    my($mesg) = $_[0];

    print "*** $0:\n".
	  "    $mesg\n";

    #
    # Send a message to the testbed list. 
    #
    if (defined($logfile)) {
	SENDMAIL($TBOPS,
		 "Webcam capture failure",
		 $mesg,
		 $TBOPS,
		 undef,
		 ($logfile));
	unlink($logfile);
    }
349
    unlink($PIDFILE);
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    exit(1);
}

sub notify($)
{
    my($mesg) = $_[0];

    print "*** $0:\n".
	  "    $mesg\n";

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "Webcam capture problem",
	     $mesg,
	     $TBOPS);
}

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
#
# Set the frame rate. This affects the camera globably, but in our context
# that is not too bad, since the robot lab is currently single use. 
#
sub SetFrameRate($$)
{
    my ($server, $rate) = @_;

    my $BASEURL = "http://operator:Frazzle69\@${server}/axis-cgi";
    my $FPSURL  = "${BASEURL}/admin/setparam.cgi?".
	"root.Image.I0.Stream.FPS=${rate}";
    my $RESTART = "${BASEURL}/mpeg4/restart_stream.cgi";

    print "Setting $server frame rate to $rate fps.\n";
    print "Using URL '$FPSURL'\n"
	if ($debug);

    system("$WGET -T 30 --non-verbose -O /dev/null $FPSURL");
    if ($?) {
	fatal("Could not change framerate on camera $server");
    }

    print "Restarting mpeg stream on camera $server\n";
    print "Using URL '$RESTART'\n"
	if ($debug);
394

395 396 397 398 399 400
    system("$WGET -T 30 --non-verbose -O /dev/null $RESTART");
    if ($?) {
	fatal("Could not restart mpeg stream on camera $server");
    }
    return 0;
}