]>
git.ipfire.org Git - people/stevee/guardian.git/blob - guardian.in
767171407ab006e718a36fbf10a11bae64fd42b9
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2015-2016 IPFire Development Team #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
28 use Time
::HiRes qw
[ time sleep ];
30 require Guardian
::Base
;
31 require Guardian
::Config
;
32 require Guardian
::Daemon
;
33 require Guardian
::Events
;
34 require Guardian
::Logger
;
35 require Guardian
::Parser
;
36 require Guardian
::Socket
;
40 # Disable warnings of unjoinded threads when stopping guardian.
41 no warnings
'threads';
44 my $version ="@PACKAGE_VERSION@";
46 # Get and store the given command line arguments in a hash.
49 &GetOptions
(\
%cmdargs,
56 # Show help / version information.
57 if (defined($cmdargs{"help"})) {
58 print "Guardian $version \n";
59 print "Usage: guardian <optional arguments>\n";
60 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
61 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
62 print " -h, --help\t\tshows this help\n";
63 print " -v, --version\t\tdisplay programm version and exit.\n";
65 } elsif (defined($cmdargs{"version"})) {
66 print "Guardian $version \n";
70 # Check if another instance of guardian is allready running.
71 if (&Guardian
::Daemon
::IsRunning
()) {
72 die "Another instance of Guardian is allready running...\n";
75 # Read-in the configuration file and store the settings.
76 # Push the may be given config file argument.
77 my %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
80 my $logger = Guardian
::Logger
->Init(%mainsettings);
81 $logger->Log("debug", "Logger successfully initialized...");
83 # Add the logger object to the mainsettings for passing
85 $mainsettings{Logger
} = $logger;
87 # Redirect perls "die" messages to the logger before exiting.
88 $SIG{__DIE__
} = sub { $logger->Log("err", "@_"); };
90 # Initialize the event handler.
91 my $events = Guardian
::Events
->Init(%mainsettings);
93 # Hash to store the currently monitored files and their configured
95 my %monitored_files = ();
97 # Shared hash between the main process and all threads. It will store the
98 # monitored files and their current file position.
99 my %file_positions :shared
= ();
101 # Create the main queue. It is used to store and process all events which are
102 # reported and enqueued by the worker threads.
103 my $queue :shared
= new Thread
::Queue
or die "Could not create new, empty queue. $!";;
105 # Hash to store all currently running worker objects and their corresponding files.
106 # (Does not include the socket thread)
109 # Variable to store if the workers should pause or compute.
110 my $workers_pause :shared
= 0;
112 # Check if guardian should be daemonized or keep in the foreground.
113 unless (defined($cmdargs{"foreground"})) {
114 # Fork into background.
115 &Guardian
::Daemon
::Daemonize
();
117 # Write PID (process-id).
118 &Guardian
::Daemon
::WritePID
();
121 # Call Init function to initzialize guardian.
124 # Infinite main loop, which processes all queued events.
126 # Get the amount of elements in our queue.
127 # "undef" will be returned if it is empty.
128 my $current_events = $queue->pending();
130 # If there is at least one element enqued
131 if($current_events > 0) {
132 # Grab the data of the top enqueued event.
133 my $event = $queue->peek();
135 # Log processed event.
136 $logger->Log("debug", "QUEUE - Processed event: $event");
138 # Send event data to the events parser to determine
139 # if any action is required.
140 $events->CheckAction($event);
142 # Drop processed event from queue.
146 # Call RemoveBlocks routine from the Events module to check
147 # if items from the block list can be dropped.
148 $events->RemoveBlocks();
150 # Sleep 10ms to reduce the load of the main process.
157 ## This function contains code which has to be executed while guardian
161 # Setup signal handler.
164 # Setup IPC mechanism via Socket in an own thread.
165 threads
->create(\
&Socket
);
167 # Generate hash of monitored files.
168 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
170 # Start worker threads.
177 ## This function is responsible for monitoring modifications of the given logfile,
178 ## read them and pass them to the message parser.
180 ## To get file modifications the inotify subsystem of the linux kernel is used.
182 ## In order to prevent from permanently read and keep files opened, or dealing
183 ## with huge logfiles, at initialization time of the worker process, the file will
184 ## be opened once and the cursor position of the end of file (EOF) get stored. When
185 ## reading any newly added lines from the file, we directly can jump to the last
186 ## known position and get these lines. Afterwards, we store the current curser position
187 ## again, so we can do it in this way over and over again.
189 ## All read lines get stored in an array, which will be passed to the Parser.
191 ## If any response (action) from the parser get recieved, it will be put into the
192 ## shared event queue.
197 # Obtain the parser name which should be used to parser any
198 # messages of this file.
199 my $parser = $monitored_files{$file};
201 # Signal handler to kill worker.
202 $SIG{'KILL'} = sub { threads
->exit(); };
204 # Create inotify watcher.
205 my $watcher = new Linux
::Inotify2
or die "Could not use inotify. $!";
207 # Monitor the specified file.
208 $watcher->watch("$file", IN_MODIFY
) or die "Could not monitor $file. $!";
210 # Switch watcher into non-blocking mode.
211 $watcher->blocking(0);
213 # Log successfully spawned worker.
214 $logger->Log("debug", "Spawned worker thread for: $file");
218 # Check if the workers should pause or perform it's desired work.
219 if ($workers_pause) {
220 # Wait 1 second until the next check.
223 # Check for any events and perform them, if there
225 if ($watcher->read) {
228 # Obtain fileposition from hash.
229 my $fileposition = $file_positions{$file};
232 open (FILE
, $file) or die "Could not open $file. $!";
234 # Seek to the last known position.
235 seek (FILE
, $fileposition, 0);
237 # Get the log message.
238 while (my $line = <FILE
>) {
239 # Remove any newlines.
242 # Add all lines to the message array.
243 push (@message, $line);
248 lock(%file_positions);
250 # Update fileposition.
251 $file_positions{$file} = tell(FILE
);
257 # Send filename and message to the parser,
258 # which will return if any actions have to be performed.
259 my @actions = &Guardian
::Parser
::Parser
("$parser", @message);
261 # Send the action to the main process and put it into
267 # Loop through the actions array, and perform
268 # every single action.
269 foreach my $action (@actions) {
270 # Prevent from enqueuing empty actions.
271 if (defined($action)) {
272 # Put the required action into the queue.
273 $queue->enqueue($action);
278 # Sleep for 10ms until the next round of the loop will start.
288 ## This function uses the Socket module to create and listen to an UNIX socket.
289 ## It automatically accepts all incomming connections and pass the recieved
290 ## data messages to the the Message_Parser function which is also part of the
293 ## If a valid command has been sent through the socket, the corresponding event
294 ## will be enqueued into the shared event queue.
297 # Create the Server socket by calling the responsible function.
298 my $server = &Guardian
::Socket
::Server
($mainsettings{SocketOwner
});
300 # Log successfull creation of socket.
301 $logger->Log("debug", "Listening to Socket...");
303 # Accept incomming connections from the socket.
304 while (my $connection = $server->accept()) {
305 # Autoflush the socket after the data
307 $connection->autoflush(1);
309 # Gather all data from the connection.
310 while (my $message = <$connection>) {
311 # Remove any newlines.
314 # Log recieved socket command.
315 $logger->Log("debug", "Socket - Recieved message: $message");
317 # Send the recieved data message to the
319 my $action = &Guardian
::Socket
::Message_Parser
($message);
321 # If the parser returns to perform an action,
322 # add it to the main event queue.
327 # Enqueue the returned action.
328 $queue->enqueue($action);
335 ## Function for capturing process signals.
337 ## This function captures any sent process signals and will call various
338 ## actions, basend on the captured signal.
341 $SIG{INT
} = \
&Shutdown
;
342 $SIG{TERM
} = \
&Shutdown
;
343 $SIG{QUIT
} = \
&Shutdown
;
344 $SIG{HUP
} = \
&Reload
;
345 $SIG{USR1
} = \
&ReloadIgnoreList
;
349 ## Function to start the workers (threads) for all monitored files.
351 ## This function will loop through the hash of monitored files and will
352 ## spawn an own thread based worker for each file. Every created worker will
353 ## be added to the array of running workers.
355 sub StartWorkers
() {
356 # Init/Update hash which contains the cursor position of EOF.
357 %file_positions = &Guardian
::Base
::FilePositions
(\
%monitored_files, \
%file_positions);
359 # Loop through the hash which contains the monitored files and start
360 # a worker thread for each single one.
361 foreach my $file (keys %monitored_files) {
362 # Check if an worker allready is running for this file.
363 # If not, start the worker.
364 unless (exists($running_workers{$file})) {
365 $logger->Log("debug", "Starting worker thread for $file");
367 # Create worker thread for the file.
368 $running_workers{$file} = threads
->create(\
&Worker
,$file);
374 ## Function to stop all running workers.
376 ## This function is used to stop all currently running workers and will be
377 ## called when reloading or shutting down guardian.
380 # Loop through all running workers.
381 foreach my $worker (keys %running_workers) {
382 # Determine if the worker should be stopped.
383 # This happen if the file should not be longer monitored.
384 unless(exists($monitored_files{$worker})) {
385 $logger->Log("debug", "Stopping worker thread for $worker");
387 # Send a "KILL" signal to the worker.
388 $running_workers{$worker}->kill('KILL');
390 # Remove worker from hash of running workers.
391 delete($running_workers{$worker});
395 # Get amount of currently running worker threads.
396 if (! keys(%running_workers)) {
397 $logger->Log("debug", "All workers have been stopped...");
405 ## Function to pause all running workers.
407 ## This function is used to pause all currently running workers.
410 # Set workers_pause variable to "1".
411 # All workers will be sleep until the variable has been set to "0".
414 # Log paused workers.
415 $logger->Log("debug", "All workers have been paused...");
422 ## Function to continue all running workers.
424 ## This function is used to continue all paused workers.
426 sub ResumeWorkers
() {
427 # Set workers_suspend variable to "0" - they will continue their work
431 # Log continued workers.
432 $logger->Log("debug", "All workers are working again...");
441 ## This function will get called if the signal handler recieves a "SIGHUP" signal,
442 ## or the reload command will be sent via socket connection. It is responsible for
443 ## reloading all configure options and stopping/starting the worker threads.
447 $logger->Log("info", "Reload configuration...");
449 # Pause all running workers.
452 # Re-read configuration file.
453 %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
455 # Update Logger settings.
456 $logger = Guardian
::Logger
->Init(%mainsettings);
458 # Update logger object in mainsettings hash.
459 $mainsettings{Logger
} = $logger;
461 # Update Event handler.
462 $events->Update(\
%mainsettings);
464 # Update ignore list.
467 # Re-generate hash of monitored files.
468 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
470 # Stop workers if they are not needed anymore.
473 # Start new worker threads if required.
484 ## ReloadIgnoreList function.
486 ## This function will be called if the signal handler recieves a "SIGUSR1" signal,
487 ## or the reload-ignore-list command will be sent via the socket connection. It just
488 ## performs a simple check if an ignore file has been configured and calls the responsible
489 ## function on the events module.
491 sub ReloadIgnoreList
() {
492 # Update ignore list, if an ignorefile has been specified.
493 if (exists($mainsettings{IgnoreFile
})) {
494 # Log reload of the ignore list.
495 $logger->Log("info", "Reloading ignore list...");
497 # Call responsible function from the events module.
498 &Guardian
::Events
::GenerateIgnoreList
($mainsettings{IgnoreFile
});
503 ## Logrotate function.
505 ## This function only get called when the logrotate command will be sent via
506 ## the socket connection. It is responsible for validating and altering the current
507 ## curser positions of the monitored files and stopping/starting the worker threads.
510 # Stop all running workers.
515 lock(%file_positions);
517 # Loop through the hash which contains the current
519 foreach my $file (keys(%file_positions)) {
520 # Obtain stored value from hash.
521 my $stored_position = $file_positions{$file};
523 # Call function to get the current position.
524 my $current_position = &Guardian
::Base
::GetFileposition
($file);
526 # Compare if the current position still matches
528 if ($current_position ne $stored_position) {
529 # Update to the new position, because
530 # they has changed during file rotation.
531 $file_positions{$file} = $current_position;
533 # Log notice about rotated file.
534 $logger->Log("debug", "$file have been rotated - Using new file position.");
538 # After this bracket, the lock of the hash will be released.
541 # Restart all worker threads.
549 ## Shutdown function.
551 ## This function is used to do a clean shutdown of guardian. It will be called
552 ## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
556 $logger->Log("info", "Shutting down...");
558 # Reset hash of monitored files.
559 %monitored_files = ();
564 # Unblock all blocked hosts.
565 &Guardian
::Events
::CallFlush
();
567 # Remove socket file on exit.
568 &Guardian
::Socket
::RemoveSocketFile
();
570 # Remove pid file on exit.
571 &Guardian
::Daemon
::RemovePIDFile
();
573 # Sleep for one second to give perl some
574 # time to proper clean up everything before
578 # Log good bye message.
579 $logger->Log("debug", "Good Bye!");