Logfile.pm.in 9.38 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2013 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 25 26 27 28 29 30 31 32 33
#
package Logfile;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
34 35
use emdb;
use emutil;
36 37 38 39 40 41
use libtestbed;
use English;
use Data::Dumper;

# Configure variables
my $TB		  = "@prefix@";
42
my $TBOPS         = "@TBOPSEMAIL@";
43
my $TBBASE        = "@TBBASE@";
44
my $GZIP	  = "/usr/bin/gzip";
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

#
# Lookup by uuid. For now, just knowing the uuid says you can read the file. 
#
sub Lookup($$)
{
    my ($class, $logid) = @_;
    my $logfile;

    #
    # Argument must be alphanumeric.
    #
    if ($logid =~ /^([\w]*)$/) {
	$logid = $1;
    }
    else {
	return undef;
    }

    my $query_result =
	DBQueryWarn("select * from logfiles where logid='$logid'");

    return undef
	if (!$query_result || !$query_result->numrows);

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    my $self                = (ref($class) ? $class : {});
    $self->{'LOGFILE'}      = $query_result->fetchrow_hashref();
    $self->{'METADATA'}     = undef;
    # Ordered list.
    $self->{'METADATALIST'} = undef;
    my $logidx = $self->{'LOGFILE'}->{'logidx'};

    my $metadata_result =
	DBQueryWarn("select metakey,metaval from logfile_metadata ".
		    "where logidx='$logidx' order by idx");
    if ($metadata_result && $metadata_result->numrows) {
	$self->{'METADATA'} = {};
	$self->{'METADATALIST'} = [];
	my $idx = 0;

	while (my ($key,$val) = $metadata_result->fetchrow_array()) {
	    $self->{'METADATA'}->{$key} = $val;
	    $self->{"METADATALIST"}->[$idx] = [$key, $val];
	    $idx++;
	}
    }
    bless($self, $class) if (!ref($class));
92 93 94 95 96 97
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'LOGFILE'}->{$_[1]}); }
sub logid($)            { return field($_[0], "logid"); }
98
sub logidx($)           { return field($_[0], "logidx"); }
99 100
sub filename($)         { return field($_[0], "filename"); }
sub isopen($)           { return field($_[0], "isopen"); }
101
sub gid_idx($)          { return field($_[0], "gid_idx"); }
102
sub date_created($)     { return field($_[0], "date_created"); }
103 104 105 106 107 108 109 110 111 112 113 114 115 116
sub public($)           { return field($_[0], "public"); }
sub compressed($)       { return field($_[0], "compressed"); }
sub stored($)           { return field($_[0], "stored"); }
sub Metadata($)		{ return $_[0]->{'METADATA'}; }
sub MetadataList($)	{ return $_[0]->{'METADATALIST'}; }

# Break circular reference someplace to avoid exit errors.
sub DESTROY {
    my $self = shift;

    $self->{"LOGFILE"}       = undef;
    $self->{"METADATA"}      = undef;
    $self->{"METADATALIST"}  = undef;
}
117 118 119 120 121 122 123 124

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

125 126 127 128
    return 0
	if ($self->Lookup($self->logid()));

    return -1;
129 130 131 132 133 134
}

#
# Create a new logfile. We are given the optional filename, otherwise
# generate one. 
#
135
sub Create($$;$)
136
{
137 138
    my ($class, $group, $filename) = @_;
    my $gid_idx = (ref($group) ? $group->gid_idx() : $group);
139 140 141 142 143

    return undef
	if (ref($class));

    # Plain secret key, which is used to reference the file.
144 145 146 147 148 149 150 151 152 153 154 155 156 157
    my $logid  = TBGenSecretKey();
    my $logidx = TBGetUniqueIndex('next_logfile', 1);

    # This creates the file, so the owner/group are current user/group.
    if (!defined($filename)) {
	$filename = TBMakeLogname("logfile");
	
	# So tbops people can read the files ...
	if (!chmod(0664, $filename)) {
	    print STDERR "Could not chmod $filename to 0644: $!\n";
	    unlink($filename);
	    return undef;
	}
    }
158 159

    if (!DBQueryWarn("insert into logfiles set ".
160
		     "  logid='$logid', logidx='$logidx', ".
161 162
		     "  isopen=0, ".
		     "  filename='$filename', ".
163
		     "  gid_idx='$gid_idx', ".
164 165 166 167 168 169
		     "  date_created=now()")) {
	return undef;
    }
    return Logfile->Lookup($logid);
}

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
#
# Create from a string.
#
sub CreateFromString($$$)
{
    my ($class, $group, $string) = @_;
    my $logfile = Logfile->Create($group);
    return undef
	if (!defined($logfile));

    my $filename = $logfile->filename();
    if (open(LOG, ">$filename")) {
	print LOG $string;
	close(LOG);
    }
    else {
	print STDERR "Logfile::CreateFromString: Cannot write to $filename\n";
	$logfile->Delete(1);
	return undef;
    }

    return $logfile;
}

194 195 196 197 198 199 200 201 202 203 204 205 206 207
#
# Delete a logfile record. Optionally delete the logfile too.
#
sub Delete($;$)
{
    my ($self, $delete) = @_;

    return -1
	if (!ref($self));

    $delete = 0
	if (!defined($delete));

    my $logid    = $self->logid();
208
    my $logidx   = $self->logidx();
209 210 211 212
    my $filename = $self->filename();
    if ($delete) {
	unlink($filename);
    }
213 214 215
    return -1
	if (!DBQueryWarn("delete from logfile_metadata ".
			 "where logidx='$logidx'"));
216 217 218 219 220 221
    return -1
	if (!DBQueryWarn("delete from logfiles where logid='$logid'"));

    return 0;
}

222 223 224 225 226 227 228
#
# AccessCheck. The user needs to be a member of the group that the logfile
# was created in. 
#
sub AccessCheck($$)
{
    my ($self, $user) = @_;
229
    require Group;
230 231 232 233 234

    # Must be a real reference. 
    return 0
	if (! ref($self));

235 236 237 238
    # Public? Anyone can look at it.
    return 1
	if ($self->public());

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    # Admins do whatever they want.
    return 1
	if ($user->IsAdmin());

    my $group = Group->Lookup($self->gid_idx());
    return 0
	if (!defined($group));

    # Membership in group.
    return 1
	if (defined($group->LookupUser($user)));

    return 0;
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
#
# Mark a file open so that the web interface knows to watch it.
#
sub Open($)
{
    my ($self) = @_;

    return -1
	if (!ref($self));

    my $logid = $self->logid();
    DBQueryWarn("update logfiles set isopen=1 where logid='$logid'")
	or return -1;
    
    return $self->Refresh();
}

#
# Mark file closed, which is used to stop the web interface from spewing.
#
sub Close($)
{
    my ($self) = @_;

    return -1
	if (!ref($self));

    my $logid = $self->logid();
    DBQueryWarn("update logfiles set isopen=0 where logid='$logid'")
	or return -1;
    
    return $self->Refresh();
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301
#
# Is file empty?
#
sub Empty($)
{
    my ($self) = @_;
    my $filename = $self->filename();

    return 1
	if (! -e $filename || ! -s $filename);

    return 0;
}

302 303 304 305 306 307 308 309 310 311
#
# Return a logfile URL.
#
sub URL($)
{
    my ($self) = @_;

    return "$TBBASE/spewlogfile.php3?logfile=" . $self->logid(); 
}

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
#
# Mark public or private.
#
sub SetPublic($$)
{
    my ($self, $public) = @_;
    $public = ($public ? 1 : 0);

    return -1
	if (!ref($self));

    my $logid = $self->logid();
    DBQueryWarn("update logfiles set public='$public' where logid='$logid'")
	or return -1;
    
    return $self->Refresh();
}

#
# Move a log file from its current location to long term storage,
# compressing on the way. Then reset its location in the DB and
# mark it as compressed. 
#
sub Store($)
{
    my ($self) = @_;

    return -1
	if (!ref($self));

    my $logid    = $self->logid();
    my $filename = $self->filename();
    my $newname  = "/usr/testbed/log/logfiles";

    # Might as well. 
    $self->Close();

    #
350 351 352 353 354 355 356
    # Well, what if we have metadata but the logfile is empty? The
    # metadata is still interesting in some situations, but rather
    # then compress a null file and take an inode, just set the
    # filename to null. This currently happens from the protogeni API.
    # If the size of the logfiles table gets out of control, we can
    # revisit this, but I think we just need to age out old ones
    # on a regular basis. 
357
    #
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    if (-e $filename && -s $filename) {
	#
	# Use first two letters of the id for the subdir. 
	#
	my $dir = lc(substr($logid, 0, 2));
	$newname = "$newname/$dir/${logid}.gz";

	if (-e $newname) {
	    print STDERR "Logfile::Store ($logid) - $newname exists\n";
	    return -1;
	}
	my $output = emutil::ExecQuiet("$GZIP -c $filename > $newname");
	if ($?) {
	    SENDMAIL($TBOPS, "Logfile Store Error",
		     "Failed to store $filename to $newname\n\n".
		     "-----------------\n".
		     "$output\n", $TBOPS);
	    return -1
	}
	$newname = "'" . $newname . "'";
378
    }
379 380
    else {
	$newname = "NULL";
381 382 383
    }
    unlink($filename);
    DBQueryWarn("update logfiles set ".
384
		"  stored=1,compressed=1,filename=$newname ".
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
		"where logid='$logid'")
	or return -1;

    return 0;
}

#
# Set the metadata (stuff to search on) for a log. Argument is an
# array of header,value pairs
#
sub SetMetadata($$$)
{
    my ($self, $argref, $purge) = @_;

    return -1
	if (!ref($self));

    my $logidx  = $self->logidx();

    # Purge old data
    DBQueryWarn("delete from logfile_metadata where logidx='$logidx'")
	if ($purge);

    foreach my $ref (@{$argref}) {
	my ($key,$val) = @{$ref};
	$key = DBQuoteSpecial($key);
	$val = DBQuoteSpecial($val);
	return -1
	    if (! DBQueryWarn("replace into logfile_metadata set ".
			      "  logidx='$logidx',metakey=$key,metaval=$val"));
    }
    return 0;
}

419 420
# _Always_ make sure that this 1 is at the end of the file...
1;