Logfile.pm.in 12.4 KB
Newer Older
1 2
#!/usr/bin/perl -wT
#
3
# Copyright (c) 2007-2013, 2017 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
use libtestbed;
use English;
38 39 40
use Errno;
use Fcntl;
use POSIX;
41
use Data::Dumper;
42
use overload ('""' => 'Stringify');
43 44 45

# Configure variables
my $TB		  = "@prefix@";
46
my $TBOPS         = "@TBOPSEMAIL@";
47
my $TBBASE        = "@TBBASE@";
48
my $GZIP	  = "/usr/bin/gzip";
49 50 51 52 53 54 55 56

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

    #
    # Argument must be alphanumeric.
    #
62 63 64 65 66 67 68 69 70 71 72 73 74 75
    if ($logid =~ /^([\d]*)$/) {
	$query_result =
	    DBQueryWarn("select logid from logfiles where logidx='$logid'");

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

	if ($query_result->numrows > 1) {
	    print STDERR "*** More then one entry for $logid\n";
	    return undef;
	}
	($logid) = $query_result->fetchrow_array();
    }
    elsif ($logid =~ /^([\w]*)$/) {
76 77
	$logid = $1;
    }
78 79 80 81 82 83 84 85 86 87 88 89 90
    elsif ($logid =~ /^\/[\w\/\.]*$/) {
	$query_result =
	    DBQueryWarn("select logid from logfiles where filename='$logid'");

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

	if ($query_result->numrows > 1) {
	    print STDERR "*** More then one entry for $logid\n";
	    return undef;
	}
	($logid) = $query_result->fetchrow_array();
    }
91 92 93 94
    else {
	return undef;
    }

95
    $query_result =
96 97 98 99 100
	DBQueryWarn("select * from logfiles where logid='$logid'");

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

101 102
    my $self                = (ref($class) ? $class : {});
    $self->{'LOGFILE'}      = $query_result->fetchrow_hashref();
103
    $self->{'FP'}           = (ref($class) ? $class->{'FP'} : undef);
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    $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));
124 125 126 127 128 129
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'LOGFILE'}->{$_[1]}); }
sub logid($)            { return field($_[0], "logid"); }
130
sub logidx($)           { return field($_[0], "logidx"); }
131 132
sub filename($)         { return field($_[0], "filename"); }
sub isopen($)           { return field($_[0], "isopen"); }
133
sub gid_idx($)          { return field($_[0], "gid_idx"); }
134
sub date_created($)     { return field($_[0], "date_created"); }
135 136 137
sub public($)           { return field($_[0], "public"); }
sub compressed($)       { return field($_[0], "compressed"); }
sub stored($)           { return field($_[0], "stored"); }
138
sub filedescriptor($)	{ return $_[0]->{'FP'}; }
139 140 141 142 143 144 145 146 147 148
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;
149 150 151 152 153 154 155 156 157 158 159 160 161
    $self->{"FP"}            = undef;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $logid = $self->logid();

    return "[Logfile: $logid]";
162
}
163 164 165 166 167 168 169 170

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

171 172 173 174
    return 0
	if ($self->Lookup($self->logid()));

    return -1;
175 176 177 178 179 180
}

#
# Create a new logfile. We are given the optional filename, otherwise
# generate one. 
#
181
sub Create($$;$)
182
{
183 184
    my ($class, $group, $filename) = @_;
    my $gid_idx = (ref($group) ? $group->gid_idx() : $group);
185 186 187 188 189

    return undef
	if (ref($class));

    # Plain secret key, which is used to reference the file.
190 191 192 193 194 195 196 197 198 199 200 201 202 203
    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;
	}
    }
204 205

    if (!DBQueryWarn("insert into logfiles set ".
206
		     "  logid='$logid', logidx='$logidx', ".
207 208
		     "  isopen=0, ".
		     "  filename='$filename', ".
209
		     "  gid_idx='$gid_idx', ".
210 211 212 213 214 215
		     "  date_created=now()")) {
	return undef;
    }
    return Logfile->Lookup($logid);
}

Leigh B Stoller's avatar
Leigh B Stoller committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
#
# 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;
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253
#
# 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();
254
    my $logidx   = $self->logidx();
255 256 257 258
    my $filename = $self->filename();
    if ($delete) {
	unlink($filename);
    }
259 260 261
    return -1
	if (!DBQueryWarn("delete from logfile_metadata ".
			 "where logidx='$logidx'"));
262 263 264 265 266 267
    return -1
	if (!DBQueryWarn("delete from logfiles where logid='$logid'"));

    return 0;
}

268 269 270 271 272 273 274
#
# AccessCheck. The user needs to be a member of the group that the logfile
# was created in. 
#
sub AccessCheck($$)
{
    my ($self, $user) = @_;
275
    require Group;
276 277 278 279 280

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

281 282 283 284
    # Public? Anyone can look at it.
    return 1
	if ($self->public());

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    # 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;
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
#
# 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();
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
#
# Clean up a logfile.
#
sub Clean($)
{
    my ($self) = @_;

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

349 350 351 352 353 354 355 356 357 358 359 360 361 362
#
# Is file empty?
#
sub Empty($)
{
    my ($self) = @_;
    my $filename = $self->filename();

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

    return 0;
}

363 364 365 366 367 368 369 370 371 372
#
# Return a logfile URL.
#
sub URL($)
{
    my ($self) = @_;

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

373 374 375 376 377 378 379 380 381 382 383 384 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
#
# 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();

    #
411 412 413 414 415 416 417
    # 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. 
418
    #
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    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 . "'";
439
    }
440 441
    else {
	$newname = "NULL";
442 443 444
    }
    unlink($filename);
    DBQueryWarn("update logfiles set ".
445
		"  `stored`=1,compressed=1,filename=$newname ".
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
		"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;
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
#
# Open/Close the file for reading (if its currently being written) and
# store the descriptor in the object.
#
sub OpenFile($)
{
    my ($self) = @_;

    DBQueryWarn("lock tables logfiles write, logfile_metadata write")
	or return undef;
    if ($self->Refresh()) {
	DBQueryWarn("unlock tables");
	return -1;
    }
    if (!$self->isopen()) {
	print STDERR "$self is no long open\n";
	DBQueryWarn("unlock tables");
	return -1;
    }
    my $filename = $self->filename();
    if (! -e $filename) {
	print STDERR "$self: $filename does not exist\n";
	DBQueryWarn("unlock tables");
	return -1;
    }
    local *LOG;
    if (! sysopen(LOG, $filename, O_RDONLY | O_NONBLOCK)) {
	print STDERR "$self: could not open $filename: $!\n";
	DBQueryWarn("unlock tables");
	return -1;
    }
    $self->{"FP"} = *LOG;
    DBQueryWarn("unlock tables");
    return 0;
}
sub CloseFile($)
{
    my ($self) = @_;
    return 0
	if (!defined($self->filedescriptor()));

    close($self->filedescriptor());
    $self->{"FP"} = undef;
    return 0;
}
sub ReadFile($$)
{
    my ($self, $pbuf) = @_;
    my $buf;

    return undef
	if (!defined($self->filedescriptor()));

    my $cc = sysread($self->filedescriptor(), $buf, 2048 * 4);
    if (!defined($cc)) {
	if ($!{EAGAIN}) {
	    # Nothing to read
	    return 0;
	}
	print STDERR "Closing A\n";
	$self->CloseFile();
	return undef;
    }
    if ($cc == 0) {
	# Nothing to read. 
	return 0;
    }
    $$pbuf = $buf;
    return $cc;
}

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
#
# Lock and unlock the tables we use.
#
sub LockTables($)
{
    my ($class) = @_;

    DBQueryWarn("lock tables logfiles write, logfile_metadata write")
	or return -1;
    
    return 0;
}
sub UnlockTables($)
{
    my ($class) = @_;

    DBQueryWarn("unlock tables")
	or return -1;
    
    return 0;
}

573 574
# _Always_ make sure that this 1 is at the end of the file...
1;