/usr/share/otrs/bin/otrs.Daemon.pl is in otrs2 6.0.5-1.
This file is owned by root:root, with mode 0o755.
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 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | #!/usr/bin/perl -X
# --
# Copyright (C) 2001-2018 OTRS AG, http://otrs.com/
# --
# This program 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
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# or see http://www.gnu.org/licenses/agpl.txt.
# --
use strict;
use warnings;
use utf8;
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);
use lib dirname($RealBin) . '/Kernel/cpan-lib';
use lib dirname($RealBin) . '/Custom';
use File::Path qw();
use Time::HiRes qw(sleep);
use Fcntl qw(:flock);
use Kernel::System::ObjectManager;
print STDOUT "\nManage the OTRS daemon process.\n\n";
local $Kernel::OM = Kernel::System::ObjectManager->new(
'Kernel::System::Log' => {
LogPrefix => 'OTRS-otrs.Daemon.pl',
},
);
# Don't allow to run these scripts as root.
if ( $> == 0 ) { # $EFFECTIVE_USER_ID
print STDERR
"Error: You cannot run otrs.Daemon.pl as root. Please run it as the 'otrs' user or with the help of su:\n";
print STDERR " su -c \"bin/otrs.Daemon.pl ...\" -s /bin/bash otrs\n";
exit 1;
}
# get config object
my $ConfigObject = $Kernel::OM->Get('Kernel::Config');
# get the NodeID from the SysConfig settings, this is used on High Availability systems.
my $NodeID = $ConfigObject->Get('NodeID') || 1;
# check NodeID, if does not match its impossible to continue
if ( $NodeID !~ m{ \A \d+ \z }xms && $NodeID > 0 && $NodeID < 1000 ) {
print STDERR "NodeID '$NodeID' is invalid. Change the NodeID to a number between 1 and 999.";
exit 1;
}
# get pid directory
my $PIDDir = $ConfigObject->Get('Daemon::PID::Path') || $ConfigObject->Get('Home') . '/var/run/';
my $PIDFile = $PIDDir . "Daemon-NodeID-$NodeID.pid";
my $PIDFH;
# get default log directory
my $LogDir = $ConfigObject->Get('Daemon::Log::LogPath') || $ConfigObject->Get('Home') . '/var/log/Daemon';
if ( !-d $LogDir ) {
File::Path::mkpath( $LogDir, 0, 0770 ); ## no critic
if ( !-d $LogDir ) {
print STDERR "Failed to create path: $LogDir";
exit 1;
}
}
if ( !@ARGV ) {
PrintUsage();
exit 0;
}
# to wait until all daemon stops (in seconds)
my $DaemonStopWait = 30;
my $ForceStop;
# check for debug mode
my %DebugDaemons;
my $Debug;
if (
lc $ARGV[0] eq 'start'
&& $ARGV[1]
&& lc $ARGV[1] eq '--debug'
)
{
$Debug = 1;
# if no more arguments, then use debug mode for all daemons
if ( !$ARGV[2] ) {
$DebugDaemons{All} = 1;
}
# otherwise set debug mode specific for named daemons
else {
ARGINDEX:
for my $ArgIndex ( 2 .. 99 ) {
# stop checking if there are no more arguments
last ARGINDEX if !$ARGV[$ArgIndex];
# remember debug mode for each daemon
$DebugDaemons{ $ARGV[$ArgIndex] } = 1;
}
}
}
elsif (
lc $ARGV[0] eq 'stop'
&& $ARGV[1]
&& lc $ARGV[1] eq '--force'
)
{
$ForceStop = 1;
}
elsif ( $ARGV[1] ) {
print STDERR "Invalid option: $ARGV[1]\n\n";
PrintUsage();
exit 0;
}
# check for action
if ( lc $ARGV[0] eq 'start' ) {
exit 1 if !Start();
exit 0;
}
elsif ( lc $ARGV[0] eq 'stop' ) {
exit 1 if !Stop();
exit 0;
}
elsif ( lc $ARGV[0] eq 'status' ) {
exit 1 if !Status();
exit 0;
}
else {
PrintUsage();
exit 0;
}
sub PrintUsage {
my $UsageText = "Usage:\n";
$UsageText .= " otrs.Daemon.pl action [--debug] [--force]\n";
$UsageText .= "\nOptions:\n";
$UsageText .= sprintf " %-22s - %s", '[--debug]', 'Run the daemon in debug mode.' . "\n";
$UsageText .= sprintf " %-22s - %s", '[--force]',
'Reduce the time the main daemon waits other daemons to stop.' . "\n";
$UsageText .= "\nActions:\n";
$UsageText .= sprintf " %-22s - %s", 'start', 'Start the daemon process.' . "\n";
$UsageText .= sprintf " %-22s - %s", 'stop', 'Stop the daemon process.' . "\n";
$UsageText .= sprintf " %-22s - %s", 'status', 'Show daemon process current state.' . "\n";
$UsageText .= sprintf " %-22s - %s", 'help', 'Display help for this command.' . "\n";
$UsageText .= "\nHelp:\n";
$UsageText
.= "In debug mode if a daemon module is specified the debug mode will be activated only for that daemon.\n";
$UsageText .= "Debug information is stored in the daemon log files localed under: $LogDir\n";
$UsageText .= "\n otrs.Daemon.pl start --debug SchedulerTaskWorker SchedulerCronTaskManager\n\n";
$UsageText
.= "Forced stop reduces the time the main daemon waits other daemons to stop from normal 30 seconds to 5.\n";
$UsageText .= "\n otrs.Daemon.pl stop --force\n";
print STDOUT "$UsageText\n";
return 1;
}
sub Start {
# Create a fork of the current process.
# Parent gets the PID of the child.
# Child gets PID = 0.
my $DaemonPID = fork;
# Check if fork was not possible.
die "Can not create daemon process: $!" if !defined $DaemonPID || $DaemonPID < 0;
# Close parent gracefully.
exit 0 if $DaemonPID;
# Lock PID.
my $LockSuccess = _PIDLock();
if ( !$LockSuccess ) {
print "Daemon already running!\n";
exit 0;
}
# Get daemon modules from SysConfig.
my $DaemonModuleConfig = $Kernel::OM->Get('Kernel::Config')->Get('DaemonModules') || {};
# Create daemon module hash.
my %DaemonModules = _GetDaemonModules();
my $DaemonChecker = 1;
my $DaemonSuspend;
local $SIG{INT} = sub { $DaemonChecker = 0; $DaemonSuspend = 0; };
local $SIG{TERM} = sub { $DaemonChecker = 0; $DaemonStopWait = 5; $DaemonSuspend = 0; };
local $SIG{CHLD} = "IGNORE";
local $SIG{HUP} = sub {
# Stop current daemon run loop.
$DaemonSuspend = 1;
# Stop all daemon processes.
my %DaemonModulesCopy = %DaemonModules;
%DaemonModules = ();
_StopDaemonModules( DaemonModules => \%DaemonModulesCopy );
# Get all daemon modules using a refreshed configuration.
%DaemonModules = _GetDaemonModules();
# Continue the current daemon run.
$DaemonSuspend = 0;
};
print STDOUT "Daemon started\n";
if ($Debug) {
print STDOUT "\nDebug information is stored in the daemon log files localed under: $LogDir\n\n";
}
LOOP:
while ($DaemonChecker) {
if ($DaemonSuspend) {
sleep .5;
next LOOP;
}
MODULE:
for my $Module ( sort keys %DaemonModules ) {
last MODULE if $DaemonSuspend;
next MODULE if !$Module;
# Check if daemon is still alive.
if ( $DaemonModules{$Module}->{PID} && !kill 0, $DaemonModules{$Module}->{PID} ) {
$DaemonModules{$Module}->{PID} = 0;
}
next MODULE if $DaemonModules{$Module}->{PID};
# Fork daemon process.
my $ChildPID = fork;
if ( !$ChildPID ) {
my $ChildRun = 1;
local $SIG{INT} = sub { $ChildRun = 0; };
local $SIG{TERM} = sub { $ChildRun = 0; };
local $SIG{CHLD} = "IGNORE";
# Remove the ZZZAAuto.pm from %INC to force reloading it.
delete $INC{'Kernel/Config/Files/ZZZAAuto.pm'};
local $Kernel::OM = Kernel::System::ObjectManager->new(
'Kernel::System::Log' => {
LogPrefix => "OTRS-otrs.Daemon.pl - Daemon $Module",
},
);
# Disable in memory cache because many processes runs at the same time.
$Kernel::OM->Get('Kernel::System::Cache')->Configure(
CacheInMemory => 0,
CacheInBackend => 1,
);
# Set daemon log files.
_LogFilesSet(
Module => $DaemonModules{$Module}->{Name}
);
my $DaemonObject;
LOOP:
while ($ChildRun) {
# Create daemon object if not exists.
eval {
if (
!$DaemonObject
&& ( $DebugDaemons{All} || $DebugDaemons{ $DaemonModules{$Module}->{Name} } )
)
{
$Kernel::OM->ObjectParamAdd(
$Module => {
Debug => 1,
},
);
}
$DaemonObject ||= $Kernel::OM->Get($Module);
};
# Wait 10 seconds if creation of object is not possible.
if ( !$DaemonObject ) {
sleep 10;
last LOOP;
}
METHOD:
for my $Method ( 'PreRun', 'Run', 'PostRun' ) {
last LOOP if !eval { $DaemonObject->$Method() };
}
}
exit 0;
}
else {
if ($Debug) {
print STDOUT "Registered Daemon $Module with PID $ChildPID\n";
}
$DaemonModules{$Module}->{PID} = $ChildPID;
}
}
# Sleep 0.1 seconds to protect the system of a 100% CPU usage if one daemon
# module is damaged and produces hard errors.
sleep 0.1;
}
# Stop all daemon modules, first try soft otherwise hard.
_StopDaemonModules( DaemonModules => \%DaemonModules );
# Remove current log files without content.
_LogFilesCleanup();
return 0;
}
sub Stop {
my %Param = @_;
my $RunningDaemonPID = _PIDUnlock();
if ($RunningDaemonPID) {
if ($ForceStop) {
# Send TERM signal to running daemon.
kill 15, $RunningDaemonPID;
}
else {
# Send INT signal to running daemon.
kill 2, $RunningDaemonPID;
}
}
print STDOUT "Daemon stopped\n";
return 1;
}
sub Status {
my %Param = @_;
if ( -e $PIDFile ) {
# read existing PID file
open my $FH, '<', $PIDFile; ## no critic
# try to lock the file exclusively
if ( !flock( $FH, LOCK_EX | LOCK_NB ) ) {
# if no exclusive lock, daemon might be running, send signal to the PID
my $RegisteredPID = do { local $/; <$FH> };
close $FH;
if ($RegisteredPID) {
# check if process is running
my $RunningPID = kill 0, $RegisteredPID;
if ($RunningPID) {
print STDOUT "Daemon running\n";
return 1;
}
}
}
else {
# if exclusive lock is granted, then it is not running
close $FH;
}
}
_PIDUnlock();
print STDOUT "Daemon not running\n";
return;
}
sub _PIDLock {
# check pid directory
if ( !-e $PIDDir ) {
File::Path::mkpath( $PIDDir, 0, 0770 ); ## no critic
if ( !-e $PIDDir ) {
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Can't create directory '$PIDDir': $!",
);
exit 1;
}
}
if ( !-w $PIDDir ) {
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Don't have write permissions in directory '$PIDDir': $!",
);
exit 1;
}
if ( -e $PIDFile ) {
# read existing PID file
open my $FH, '<', $PIDFile; ## no critic
# try to get a exclusive of the pid file, if fails daemon is already running
if ( !flock( $FH, LOCK_EX | LOCK_NB ) ) {
close $FH;
return;
}
my $RegisteredPID = do { local $/; <$FH> };
close $FH;
if ($RegisteredPID) {
return 1 if $RegisteredPID eq $$;
# check if another process is running
my $AnotherRunningPID = kill 0, $RegisteredPID;
return if $AnotherRunningPID;
}
}
# create new PID file (set exclusive lock while writing the PIDFile)
open my $FH, '>', $PIDFile || die "Can not create PID file: $PIDFile\n"; ## no critic
flock( $FH, LOCK_EX | LOCK_NB ) || die "Can not get exclusive lock for writing PID file: $PIDFile\n";
print $FH $$;
close $FH;
# keep PIDFile shared locked forever
open $PIDFH, '<', $PIDFile || die "Can not read PID file: $PIDFile\n"; ## no critic
flock( $PIDFH, LOCK_SH | LOCK_NB ) || die "Can not get shared lock for reading PID file: $PIDFile\n";
return 1;
}
sub _PIDUnlock {
return if !-e $PIDFile;
# read existing PID file
open my $FH, '<', $PIDFile; ## no critic
# wait if PID is exclusively locked (and do a shared lock for reading)
flock $FH, LOCK_SH;
my $RegisteredPID = do { local $/; <$FH> };
close $FH;
unlink $PIDFile;
return $RegisteredPID;
}
sub _LogFilesSet {
my %Param = @_;
# get config object
my $ConfigObject = $Kernel::OM->Get('Kernel::Config');
# define log file names
my $FileStdOut = "$LogDir/$Param{Module}OUT";
my $FileStdErr = "$LogDir/$Param{Module}ERR";
my $SystemTime = $Kernel::OM->Create('Kernel::System::DateTime')->ToEpoch();
# get log rotation type and backup old logs if logs should be rotated by OTRS
my $RotationType = lc $ConfigObject->Get('Daemon::Log::RotationType') || 'otrs';
if ( $RotationType eq 'otrs' ) {
use File::Copy qw(move);
if ( -e "$FileStdOut.log" ) {
move( "$FileStdOut.log", "$FileStdOut-$SystemTime.log" );
}
if ( -e "$FileStdErr.log" ) {
move( "$FileStdErr.log", "$FileStdErr-$SystemTime.log" );
}
}
my $RedirectSTDOUT = $ConfigObject->Get('Daemon::Log::STDOUT') || 0;
my $RedirectSTDERR = $ConfigObject->Get('Daemon::Log::STDERR') || 0;
# redirect STDOUT and STDERR
if ($RedirectSTDOUT) {
open STDOUT, '>>', "$FileStdOut.log";
}
if ($RedirectSTDERR) {
open STDERR, '>>', "$FileStdErr.log";
}
return 1 if $RotationType ne 'otrs';
# remove not needed log files if OTRS rotation is enabled
my $DaysToKeep = $ConfigObject->Get('Daemon::Log::DaysToKeep') || 1;
my $DaysToKeepTime = $SystemTime - $DaysToKeep * 24 * 60 * 60;
my @LogFiles = glob "$LogDir/*.log";
LOGFILE:
for my $LogFile (@LogFiles) {
# skip if is not a backup file
next LOGFILE if ( $LogFile !~ m{(?: .* /)* $Param{Module} (?: OUT|ERR ) - (\d+) \.log}igmx );
# do not delete files during keep period if they have content
next LOGFILE if ( ( $1 > $DaysToKeepTime ) && -s $LogFile );
# delete file
if ( !unlink $LogFile ) {
# log old backup file cannot be deleted
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Daemon: $Param{Module} could not delete old log file $LogFile! $!",
);
}
}
return 1;
}
sub _LogFilesCleanup {
my %Param = @_;
# skip cleanup if OTRS log rotation is not enabled
my $RotationType = lc $Kernel::OM->Get('Kernel::Config')->Get('Daemon::Log::RotationType') || 'otrs';
return 1 if $RotationType ne 'otrs';
my @LogFiles = glob "$LogDir/*.log";
LOGFILE:
for my $LogFile (@LogFiles) {
# skip if is not a backup file
next LOGFILE if ( $LogFile !~ m{ (?: OUT|ERR ) (?: -\d+)* \.log}igmx );
# do not delete files if they have content
next LOGFILE if -s $LogFile;
# delete file
if ( !unlink $LogFile ) {
# log old backup file cannot be deleted
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Daemon: could not delete empty log file $LogFile! $!",
);
}
}
return 1;
}
sub _GetDaemonModules {
my %Param = @_;
$Kernel::OM->ObjectsDiscard(
Objects => [ 'Kernel::Config', ],
);
# Get daemon modules from SysConfig.
my $DaemonModuleConfig = $Kernel::OM->Get('Kernel::Config')->Get('DaemonModules') || {};
# Create daemon module hash.
my %DaemonModules;
MODULE:
for my $Module ( sort keys %{$DaemonModuleConfig} ) {
next MODULE if !$Module;
next MODULE if !$DaemonModuleConfig->{$Module};
next MODULE if ref $DaemonModuleConfig->{$Module} ne 'HASH';
next MODULE if !$DaemonModuleConfig->{$Module}->{Module};
$DaemonModules{ $DaemonModuleConfig->{$Module}->{Module} } = {
PID => 0,
Name => $Module,
};
}
return %DaemonModules;
}
sub _StopDaemonModules {
my %Param = @_;
my %DaemonModules = %{ $Param{DaemonModules} };
# Send all daemon processes a stop signal.
MODULE:
for my $Module ( sort keys %DaemonModules ) {
next MODULE if !$Module;
next MODULE if !$DaemonModules{$Module}->{PID};
if ($Debug) {
print STDOUT "Send stop signal to $Module with PID $DaemonModules{$Module}->{PID}\n";
}
kill 2, $DaemonModules{$Module}->{PID};
}
# Wait for active daemon processes to stop (typically 30 secs, or just 5 if forced).
WAITTIME:
for my $WaitTime ( 1 .. $DaemonStopWait ) {
my $ProcessesStillRunning;
MODULE:
for my $Module ( sort keys %DaemonModules ) {
next MODULE if !$Module;
next MODULE if !$DaemonModules{$Module}->{PID};
# Check if PID is still alive.
if ( !kill 0, $DaemonModules{$Module}->{PID} ) {
# Remove daemon pid from list.
$DaemonModules{$Module}->{PID} = 0;
}
else {
$ProcessesStillRunning = 1;
if ($Debug) {
print STDOUT "Waiting to stop $Module with PID $DaemonModules{$Module}->{PID}\n";
}
}
}
last WAITTIME if !$ProcessesStillRunning;
sleep 1;
}
# Hard kill of all children witch are not stopped after 30 seconds.
MODULE:
for my $Module ( sort keys %DaemonModules ) {
next MODULE if !$Module;
next MODULE if !$DaemonModules{$Module}->{PID};
print STDOUT "Killing $Module with PID $DaemonModules{$Module}->{PID}\n";
kill 9, $DaemonModules{$Module}->{PID};
}
return 1;
}
exit 0;
|