/usr/share/perl5/pgBackRest/Protocol/IO.pm is in pgbackrest 1.12-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 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 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 288 289 290 291 292 293 294 295 296 297 298 299 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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 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 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 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 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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | ####################################################################################################################################
# PROTOCOL IO MODULE
####################################################################################################################################
package pgBackRest::Protocol::IO;
use strict;
use warnings FATAL => qw(all);
use Carp qw(confess);
use English '-no_match_vars';
use Exporter qw(import);
our @EXPORT = qw();
use File::Basename qw(dirname);
use IPC::Open3 qw(open3);
use IO::Select;
use POSIX qw(:sys_wait_h);
use Symbol 'gensym';
use Time::HiRes qw(gettimeofday);
use pgBackRest::Common::Exception;
use pgBackRest::Common::Log;
use pgBackRest::Common::String;
use pgBackRest::Common::Wait;
####################################################################################################################################
# Amount of time to attempt to retrieve errors when a process terminates unexpectedly
####################################################################################################################################
use constant IO_ERROR_TIMEOUT => 5;
push @EXPORT, qw(IO_ERROR_TIMEOUT);
####################################################################################################################################
# CONSTRUCTOR
####################################################################################################################################
sub new
{
my $class = shift;
# Create the class hash
my $self = {};
bless $self, $class;
# Assign function parameters, defaults, and log debug info
(
my $strOperation,
$self->{hIn}, # Input stream
$self->{hOut}, # Output stream
$self->{hErr}, # Error stream
$self->{pId}, # Process ID
$self->{strId}, # Id for messages
$self->{iProtocolTimeout}, # Protocol timeout
$self->{iBufferMax} # Maximum buffer size
) =
logDebugParam
(
__PACKAGE__ . '->new', \@_,
{name => 'hIn', required => false, trace => true},
{name => 'hOut', required => false, trace => true},
{name => 'hErr', required => false, trace => true},
{name => 'pId', required => false, trace => true},
{name => 'strId', required => false, trace => true},
{name => 'iProtocolTimeout', trace => true},
{name => 'iBufferMax', trace => true}
);
if (defined($self->{hIn}))
{
$self->{oInSelect} = IO::Select->new();
$self->{oInSelect}->add($self->{hIn});
}
# Return from function and log return values if any
return logDebugReturn
(
$strOperation,
{name => 'self', value => $self}
);
}
####################################################################################################################################
# new3
#
# Use open3 to run the command and get the io handles.
####################################################################################################################################
sub new3
{
my $class = shift;
# Assign function parameters, defaults, and log debug info
my
(
$strOperation,
$strId,
$strCommand,
$iProtocolTimeout, # Protocol timeout
$iBufferMax # Maximum buffer Size
) =
logDebugParam
(
__PACKAGE__ . '->new3', \@_,
{name => 'strId', trace => true},
{name => 'strCommand', trace => true},
{name => 'iProtocolTimeout', trace => true},
{name => 'iBufferMax', trace => true}
);
# Use open3 to run the command
my ($pId, $hIn, $hOut, $hErr);
$hErr = gensym;
$pId = IPC::Open3::open3($hIn, $hOut, $hErr, $strCommand);
# Return from function and log return values if any
return logDebugReturn
(
$strOperation,
{name => 'self', value => $class->new($hOut, $hIn, $hErr, $pId, $strId, $iProtocolTimeout, $iBufferMax)}
);
}
####################################################################################################################################
# Get pid/input/output handles
####################################################################################################################################
sub hInGet
{
my $self = shift;
return $self->{hIn};
}
sub hOutGet
{
my $self = shift;
return $self->{hOut};
}
sub pIdGet
{
my $self = shift;
return $self->{pId};
}
####################################################################################################################################
# kill
####################################################################################################################################
sub kill
{
my $self = shift;
if (defined($self->{pId}))
{
kill 'KILL', $self->{pId};
waitpid($self->{pId}, 0);
undef($self->{pId});
undef($self->{hIn});
undef($self->{hOut});
undef($self->{hErr});
}
}
####################################################################################################################################
# lineRead
#
# Read an lf-terminated line from the input or error stream.
####################################################################################################################################
sub lineRead
{
my $self = shift;
my $iTimeout = shift;
my $bInRead = shift;
my $bError = shift;
my $bIgnoreEOF = shift;
# If there's already data in the buffer try to find the next linefeed
my $iLineFeedPos = defined($self->{strBuffer}) ? index($self->{strBuffer}, "\n", $self->{iBufferPos}) : -1;
# Store the current time if a timeout is required
if ($iLineFeedPos == -1)
{
my $fTimeout = defined($iTimeout) ? $iTimeout : $self->{iProtocolTimeout};
my $fRemaining = $fTimeout;
my $fTimeStart = gettimeofday();
# If no linefeed was found then load more data
do
{
# If the buffer already has data
if (defined($self->{strBuffer}) && $self->{iBufferPos} < $self->{iBufferSize})
{
# And the buffer position is not 0 then trim it so there's room for more data
if ($self->{iBufferPos} != 0)
{
$self->{strBuffer} = substr($self->{strBuffer}, $self->{iBufferPos});
$self->{iBufferSize} = $self->{iBufferSize} - $self->{iBufferPos};
$self->{iBufferPos} = 0;
}
}
# Else the buffer is empty and data will need to be loaded
else
{
undef($self->{strBuffer}); # ??? Do we need this?
$self->{iBufferSize} = 0;
$self->{iBufferPos} = 0;
}
# Get stream handle and select object
my $hIn;
my $oSelect;
# If this is a normal input read
if (!defined($bInRead) || $bInRead)
{
$hIn = $self->{hIn};
$oSelect = $self->{oInSelect};
}
# Else this is an error read
else
{
# The select object will need to be created the first time an error is read
if (!defined($self->{oErrSelect}))
{
$self->{oErrSelect} = IO::Select->new();
$self->{oErrSelect}->add($self->{hErr});
}
$oSelect = $self->{oErrSelect};
$hIn = $self->{hErr};
}
# Load data into the buffer
my $iBufferRead = 0;
if ($oSelect->can_read($fRemaining))
{
$iBufferRead = sysread($hIn, $self->{strBuffer}, $self->{iBufferSize} >= $self->{iBufferMax} ?
$self->{iBufferMax} : $self->{iBufferMax} - $self->{iBufferSize}, $self->{iBufferSize});
# An error occurred if undef is returned
if (!defined($iBufferRead))
{
# Store the error message
my $strError = defined($!) && $! ne '' ? $! : undef;
# Check if the remote process exited unexpectedly
$self->waitPid();
# Raise the error
confess &log(ERROR, 'unable to read line' . (defined($strError) ? ": ${strError}" : ''));
}
# Error on EOF (unless reading from error stream)
if ($iBufferRead == 0 && (!defined($bIgnoreEOF) || !$bIgnoreEOF))
{
# Check if the remote process exited unexpectedly
$self->waitPid();
# Only error if reading from the input stream
if (!defined($bError) || $bError)
{
confess &log(ERROR, "unexpected EOF", ERROR_FILE_READ);
}
# If reading from error stream then just return undef
else
{
return;
}
}
}
# If data was read then check for a linefeed
if ($iBufferRead > 0)
{
$self->{iBufferSize} += $iBufferRead;
$iLineFeedPos = index($self->{strBuffer}, "\n");
}
else
{
# Check if the remote process exited unexpectedly
$self->waitPid(0);
}
# Calculate time remaining before timeout
if ($iLineFeedPos == -1)
{
$fRemaining = $fTimeout - (gettimeofday() - $fTimeStart);
}
}
while ($iLineFeedPos == -1 && $fRemaining > 0);
# If not linefeed was found within the time return undef
if ($iLineFeedPos == -1)
{
if (!defined($bError) || $bError)
{
confess &log(ERROR, "unable to read line after ${fTimeout} second(s)", ERROR_PROTOCOL_TIMEOUT);
}
return;
}
}
# Return the line that was found and adjust the buffer position
my $strLine = $iLineFeedPos - $self->{iBufferPos} == 0 ? '' :
substr($self->{strBuffer}, $self->{iBufferPos}, $iLineFeedPos - $self->{iBufferPos});
$self->{iBufferPos} = $iLineFeedPos + 1;
return $strLine;
}
####################################################################################################################################
# errorWrite
#
# Write error data to the stream.
####################################################################################################################################
sub errorWrite
{
my $self = shift;
my $strBuffer = shift;
if (defined($self->{pId}))
{
confess &log(ASSERT, 'errorWrite() not valid in master process');
}
$self->lineWrite($strBuffer, $self->{hError});
}
####################################################################################################################################
# lineWrite
#
# Write line to the stream.
####################################################################################################################################
sub lineWrite
{
my $self = shift;
my $strBuffer = shift;
my $hOut = shift;
# Check if the process has exited abnormally (doesn't seem like we should need this, but the next syswrite does a hard
# abort if the remote process has already closed)
$self->waitPid(0);
# Write the data
my $iLineOut = syswrite(defined($hOut) ? $hOut : $self->{hOut}, (defined($strBuffer) ? $strBuffer : '') . "\n");
if (!defined($iLineOut) || $iLineOut != (defined($strBuffer) ? length($strBuffer) : 0) + 1)
{
# Check if the process has exited abnormally
$self->waitPid();
confess &log(ERROR, "unable to write ${strBuffer}: $!", ERROR_PROTOCOL);
}
}
####################################################################################################################################
# bufferRead
#
# Read data from a stream.
####################################################################################################################################
sub bufferRead
{
my $self = shift;
my $tBufferRef = shift;
my $iRequestSize = shift;
my $iOffset = shift;
my $bBlock = shift;
# Set working variables
my $iRemainingSize = $iRequestSize;
$iOffset = defined($iOffset) ? $iOffset : 0;
# If there is data left over in the buffer from lineRead then use it
if (defined($self->{strBuffer}) && $self->{iBufferPos} < $self->{iBufferSize})
{
# There is enough data in the buffer to satisfy the entire request and have data left over
if ($iRemainingSize < $self->{iBufferSize} - $self->{iBufferPos})
{
$$tBufferRef = substr($self->{strBuffer}, $self->{iBufferPos}, $iRequestSize);
$self->{iBufferPos} += $iRequestSize;
return $iRequestSize;
}
# Else the entire buffer will be used (and more may be needed if blocking)
else
{
$$tBufferRef = substr($self->{strBuffer}, $self->{iBufferPos});
my $iReadSize = $self->{iBufferSize} - $self->{iBufferPos};
$iRemainingSize -= $iReadSize;
undef($self->{strBuffer});
return $iReadSize if $iRemainingSize == 0;
$iOffset += $iReadSize;
}
}
# If this is a blocking read then loop until all bytes have been read, else error. If not blocking read until the request size
# has been met or EOF.
#
# This link (http://docstore.mik.ua/orelly/perl/cookbook/ch07_15.htm) demonstrates a way to implement this same loop without
# using select. Not sure if it would be better but the link has been left here so it can be found in the future if the
# implementation needs to be changed.
my $fTimeStart = gettimeofday();
my $fRemaining = 1; #$self->{iProtocolTimeout};
do
{
# Check if the sysread call will block
if ($self->{oInSelect}->can_read($fRemaining))
{
# Read a data into the buffer
my $iReadSize = sysread($self->{hIn}, $$tBufferRef, $iRemainingSize, $iOffset);
# Process errors from the sysread
if (!defined($iReadSize))
{
my $strError = $!;
$self->waitPid();
confess &log(ERROR, 'unable to read' . (defined($strError) ? ": ${strError}" : ''));
}
# Check for EOF
if ($iReadSize == 0)
{
if (defined($bBlock) && $bBlock)
{
confess &log(ERROR,
'EOF after ' . ($iRequestSize - $iRemainingSize) . " bytes but expected ${iRequestSize}",
ERROR_FILE_READ);
}
else
{
return $iRequestSize - $iRemainingSize;
}
}
# Update remaining size and return when it reaches 0
$iRemainingSize -= $iReadSize;
if ($iRemainingSize == 0)
{
return $iRequestSize;
}
# Update the offset to advance the next read further into the buffer
$iOffset += $iReadSize;
}
# Calculate time remaining before timeout
$fRemaining = $self->{iProtocolTimeout} - (gettimeofday() - $fTimeStart);
}
while ($fRemaining > 0);
# Throw an error if timeout happened before required bytes were read
confess &log(ERROR, "unable to read ${iRequestSize} bytes after $self->{iProtocolTimeout} seconds", ERROR_PROTOCOL_TIMEOUT);
}
####################################################################################################################################
# bufferWrite
#
# Write data to a stream.
####################################################################################################################################
sub bufferWrite
{
my $self = shift;
my $tBufferRef = shift;
my $iWriteSize = shift;
# If block size is not defined, get it from buffer length
$iWriteSize = defined($iWriteSize) ? $iWriteSize : length($$tBufferRef);
# Write the block
my $iWriteOut = syswrite($self->{hOut}, $$tBufferRef, $iWriteSize);
# Report any errors
if (!defined($iWriteOut) || $iWriteOut != $iWriteSize)
{
my $strError = $!;
$self->waitPid();
confess &log(ERROR, "unable to write ${iWriteSize} bytes" . (defined($strError) ? ': ' . $strError : ''), ERROR_FILE_WRITE);
}
}
####################################################################################################################################
# waitPid
#
# See if the remote process has terminated unexpectedly.
####################################################################################################################################
sub waitPid
{
my $self = shift;
my $fWaitTime = shift;
my $bReportError = shift;
# Record the start time and set initial sleep interval
my $oWait = waitInit(defined($fWaitTime) ? $fWaitTime : IO_ERROR_TIMEOUT);
if (defined($self->{pId}))
{
do
{
my $iResult = waitpid($self->{pId}, WNOHANG);
# If there is no such process we'll assume it terminated previously
if ($iResult == -1)
{
return true;
}
# If the process exited then this is unexpected
if ($iResult > 0)
{
# Get the exit status so we can report it later
my $iExitStatus = ${^CHILD_ERROR_NATIVE} >> 8;
# Sometimes we'll expect an error so it won't always be reported
if (!defined($bReportError) || $bReportError)
{
# Default error
my $strError = undef;
# If the error stream is already closed then we can't fetch the real error
if (!defined($self->{hErr}))
{
$strError = 'no error captured because stderr is already closed';
}
# Get whatever text we can from the error stream
else
{
eval
{
while (my $strLine = $self->lineRead(0, false, false))
{
if (defined($strError))
{
$strError .= "\n";
}
$strError .= $strLine;
}
return true;
}
or do
{
if (!defined($strError))
{
my $strException = $EVAL_ERROR;
$strError =
'no output from terminated process' .
(defined($strException) && ${strException} ne '' ? ": ${strException}" : '');
}
};
}
$self->{pId} = undef;
$self->{hIn} = undef;
$self->{hOut} = undef;
$self->{hErr} = undef;
# Finally, confess the error
confess &log(
ERROR, 'remote process terminated on ' . $self->{strId} . ' host' .
($iExitStatus < ERROR_MINIMUM || $iExitStatus > ERROR_MAXIMUM ? " (exit status ${iExitStatus})" : '') .
': ' . (defined($strError) ? $strError : 'no error on stderr'),
$iExitStatus >= ERROR_MINIMUM && $iExitStatus <= ERROR_MAXIMUM ? $iExitStatus : ERROR_HOST_CONNECT);
}
return true;
}
}
while (waitMore($oWait));
}
return false;
}
1;
|