ims_daemon.in 6.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#!/usr/bin/perl -w
#
# Copyright (c) 2008-2019 University of Utah and the Flux Group.
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
#
use strict;
use English;
use Getopt::Std;
use Data::Dumper;
use Date::Parse;
use POSIX qw(strftime);

#
# Look for Image Server (Image Tracker) related things to do.
# 
sub usage()
{
    print "Usage: ims_daemon [-d] [-n] [-s]\n";
    exit(1);
}
my $optlist   = "dns";
my $debug     = 0;
my $impotent  = 0;
my $oneshot   = 0;

#
# Configure variables
#
53 54 55 56 57 58 59 60 61 62 63 64
my $TB		       = "@prefix@";
my $TBOPS              = "@TBOPSEMAIL@";
my $OURDOMAIN          = "@OURDOMAIN@";
my $MAINSITE           = @TBMAINSITE@;
my $PGENISUPPORT       = @PROTOGENI_SUPPORT@;
my $LOGFILE            = "$TB/log/ims_daemon.log";
my $EMULAB_PEMFILE     = "$TB/etc/genicm.pem";
my $TRIGGERUPDATE      = "$TB/sbin/protogeni/triggerimageupdate";
my $DELETEIMAGEDATA    = "$TB/sbin/protogeni/deleteimagedata";
my $SLEEP_INTERVAL     = 60;
my $DAILY_INTERVAL     = 24 * 3600;
my $lastdaily          = 0;
65 66 67 68 69 70 71

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

# Protos
sub fatal($);
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
#
# Turn off line buffering on output
#
$| = 1; 

if ($UID != 0) {
    fatal("Must be root to run this script\n");
}

#
# Exit if not a protogeni site.
#
if (! $PGENISUPPORT) {
    exit(0);
}

#
# Check args early so we get the right DB.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug++;
}
if (defined($options{"s"})) {
    $oneshot = 1;
}
if (defined($options{"n"})) {
    $impotent = 1;
}

# Load the Testbed support stuff.
use lib "@prefix@/lib";
use emdb;
109
use GeniImage;
110 111 112 113 114 115 116
use GeniResponse;
use libtestbed;
use emutil;
use libEmulab;
use Logfile;
use Project;
use OSImage;
117
use User;
118

119 120 121 122 123
# Ditto for the image tracker 
if (!GetSiteVar("protogeni/use_imagetracker")) {
    exit(0);
}	

124 125 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 168
#
# So we know who/what we are acting as.
#
my $certificate = GeniCertificate->LoadFromFile($EMULAB_PEMFILE);
if (!defined($certificate)) {
    fatal("Could not get uuid/urn from $EMULAB_PEMFILE\n");
}
Genixmlrpc->SetContext(Genixmlrpc->Context($certificate));
Genixmlrpc->SetTimeout(10);
$ENV{'MYUUID'} = $certificate->uuid();
$ENV{'MYURN'} = "urn:publicid:IDN+@OURDOMAIN@+authority+cm";

if (!$oneshot) {
    if (!$impotent && CheckDaemonRunning("ims_daemon")) {
	fatal("Not starting another ims daemon!");
    }
    # Go to ground.
    if (! $debug) {
	if (TBBackGround($LOGFILE)) {
	    exit(0);
	}
    }
    if (!$impotent && MarkDaemonRunning("ims_daemon")) {
	fatal("Could not mark daemon as running!");
    }
}
#
# Setup a signal handler for newsyslog.
#
sub handler()
{
    my $SAVEEUID = $EUID;
    
    $EUID = 0;
    ReOpenLog($LOGFILE);
    $EUID = $SAVEEUID;
}
$SIG{HUP} = \&handler
    if (! ($debug || $oneshot));

GeniUtil::FlipToGeniUser();

#
# Avoid duplicate email.
#
169
my %email_history = ();
170 171 172 173 174 175 176 177

sub NotifyOnce($$$)
{
    my ($token, $subject, $body) = @_;

    return
	if (exists($email_history{$token}));
    
178
    SENDMAIL($TBOPS, $subject, $body, $TBOPS);
179 180
    $email_history{$token} = $token;
}
181 182 183 184 185 186 187 188 189 190
sub NotifyClear($)
{
    my ($token) = @_;

    delete($email_history{$token});
}
sub NotifyClearAll()
{
    %email_history = ();
}
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

#
# Look for images deletions. Process in order deleted.
#
sub HandleImageDeletions()
{
    my $query_result =
	DBQueryWarn("select * from image_deletions order by deleted asc");
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $urn  = $row->{'urn'};
	my $uuid = $row->{'image_uuid'};

	if ($impotent) {
	    print "Would trigger image delete for $urn\n";
	    next;
	}

	my $output = emutil::ExecQuiet("$DELETEIMAGEDATA '$urn' $uuid");
	if ($?) {
	    print $output;
213 214 215
	    NotifyOnce($uuid,
		       "Could not delete image data at the IMS for $urn/$uuid",
		       $output);
216 217 218 219
	    next;
	}
	DBQueryWarn("delete from image_deletions ".
		    "where urn='$urn' and image_uuid='$uuid'");
220
	NotifyClear($uuid);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    }
}
  
#
# Look for image notifications; these are new local snapshots that need
# to be copied back to their origin, so we have to tell the origin of that
# image.
#
sub HandleImageNotifications()
{
    my $query_result =
	DBQueryWarn("select * from image_notifications");
    return
	if (!$query_result);
    while (my $row = $query_result->fetchrow_hashref()) {
	my $imageid = $row->{'imageid'};
	my $image   = OSImage->Lookup($imageid);
	if (!defined($image)) {
	    print STDERR "$imageid no longer exists. Skipping notification.\n";
	    next;
	}
	if ($impotent) {
	    print "Would trigger update for $image\n";
	    next;
	}
	
	#
	# Lets avoid needless errors cause the image is locked, take the
	# lock here and call it with the nolock option.
	#
	if ($image->Lock()) {
	    print STDERR "$image is locked, skipping\n";
	    next;
	}
	my $output = emutil::ExecQuiet("$TRIGGERUPDATE -l $imageid");
	my $status = $?;
	$image->Unlock();
	if ($?) {
	    print STDERR "Could not trigger an image update for $imageid:\n";
	    print STDERR $output;
261 262 263
	    NotifyOnce($image->versid(),
		       "Could not trigger an image update for $imageid",
		       $output);
264 265
	    next;
	}
266
	NotifyClear($image->versid());
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    }
}

# Do this once at startup
if (! $debug) {
    sleep(5);
}

while (1) {
    if (NoLogins()) {
	sleep(5);
	next;
    }
    print "Running at ".
	POSIX::strftime("20%y-%m-%d %H:%M:%S", localtime()) . "\n";

    HandleImageDeletions();
    HandleImageNotifications();
    exit(0)
	if ($oneshot);

    # Be certain stale info is gone.
    emutil::FlushCaches();
    GeniUtil::FlushCaches();

292 293 294 295 296
    # Clear the email once a day so we get new messages.
    if (time() - $lastdaily > $DAILY_INTERVAL) {
	NotifyClearAll();
	$lastdaily = time();
    }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  loop:
    print "Sleeping for $SLEEP_INTERVAL seconds ...\n";
    sleep($SLEEP_INTERVAL);
}
exit(0);

sub fatal($)
{
    my ($msg) = @_;

    #
    # Send a message to the testbed list. 
    #
    SENDMAIL($TBOPS,
	     "IMS daemon died",
	     $msg,
	     $TBOPS);
    MarkDaemonStopped("ims_daemon");
    die("*** $0:\n".
	"    $msg\n");
}