Prevent from running guardian twice.
[people/stevee/guardian.git] / guardian
CommitLineData
88d9af2c
SS
1#!/usr/bin/perl
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
5# Copyright (C) 2015 IPFire Development Team #
6# #
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. #
11# #
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. #
16# #
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/>. #
19# #
20###############################################################################
21
22use strict;
23use threads;
24use threads::shared;
45bf2a03 25use Getopt::Long;
88d9af2c
SS
26use Thread::Queue;
27use Linux::Inotify2;
01147a7e 28use Time::HiRes qw[ time sleep ];
88d9af2c 29
3111df62 30require Guardian::Base;
45bf2a03 31require Guardian::Config;
ccf4f8e1 32require Guardian::Daemon;
c95dfa5b 33require Guardian::Logger;
88d9af2c 34require Guardian::Parser;
6abac3d4 35require Guardian::Socket;
88d9af2c 36
5c694317
SS
37use warnings;
38
e02ed027
SS
39# Disable warnings of unjoinded threads when stopping guardian.
40no warnings 'threads';
41
45bf2a03
SS
42# Define version.
43my $version ="2.0";
44
45bf2a03
SS
45# Get and store the given command line arguments in a hash.
46my %cmdargs = ();
47
48&GetOptions (\%cmdargs,
49 'foreground|f',
50 'config|c=s',
51 'help|h',
52 'version|v',
53);
54
55# Show help / version information.
56if (defined($cmdargs{"help"})) {
57 print "Guardian $version \n";
58 print "Usage: guardian <optional arguments>\n";
59 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
60 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
61 print " -h, --help\t\tshows this help\n";
62 print " -v, --version\t\tdisplay programm version and exit.\n";
63 exit;
64} elsif (defined($cmdargs{"version"})) {
65 print "Guardian $version \n";
66 exit;
67}
68
624876cf
SS
69# Check if another instance of guardian is allready running.
70if (&Guardian::Daemon::IsRunning()) {
71 die "Another instance of Guardian is allready running...\n";
72}
73
45bf2a03
SS
74# Read-in the configuration file and store the settings.
75# Push the may be given config file argument.
76my %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
77
c95dfa5b 78# Initialize Logger.
aab61123 79my $logger = Guardian::Logger->Init(%mainsettings);
c95dfa5b
SS
80$logger->Log("debug", "Logger successfully initialized...");
81
fc555263
SS
82# Add the logger object to the mainsettings for passing
83# it to the modules.
84$mainsettings{Logger} = $logger;
85
0815025a
SS
86# Redirect perls "die" messages to the logger before exiting.
87$SIG{__DIE__} = sub { $logger->Log("err", "@_"); };
88
3111df62
SS
89# Shared hash between the main process and all threads. It will store all
90# monitored files and their current file position.
91my %monitored_files :shared = ();
92
88d9af2c
SS
93# Create the main queue. It is used to store and process all events which are
94# reported and enqueued by the worker threads.
c0a59a63 95my $queue :shared = new Thread::Queue or die "Could not create new, empty queue. $!";;
88d9af2c 96
9c74e9bb
SS
97# Array to store all currently running worker objects.
98# (Does not include the socket thread)
99my @running_workers;
100
ccf4f8e1
SS
101# Check if guardian should be daemonized or keep in the foreground.
102unless (defined($cmdargs{"foreground"})) {
103 # Fork into background.
104 &Guardian::Daemon::Daemonize();
105} else {
106 # Write PID (process-id).
107 &Guardian::Daemon::WritePID();
108}
109
88d9af2c
SS
110# Call Init function to initzialize guardian.
111&Init();
112
113# Infinite main loop, which processes all queued events.
114while(1) {
115 # Get the amount of elements in our queue.
116 # "undef" will be returned if it is empty.
117 my $current_events = $queue->pending();
118
119 # If there is at least one element enqued
120 if($current_events > 0) {
121 # Grab the data of the top enqueued event.
122 my $event = $queue->peek();
123
c95dfa5b
SS
124 # Log processed event.
125 $logger->Log("debug", "QUEUE - Processed event: $event");
88d9af2c
SS
126
127 # Drop processed event from queue.
128 $queue->dequeue();
129 }
130
01147a7e
SS
131 # Sleep 10ms to reduce the load of the main process.
132 sleep(0.01);
88d9af2c
SS
133}
134
135#
136## Init function.
137#
138## This function contains code which has to be executed while guardian
139## is starting.
140#
141sub Init () {
915d9f45
SS
142 # Setup signal handler.
143 &SignalHandler();
144
6abac3d4
SS
145 # Setup IPC mechanism via Socket in an own thread.
146 threads->create(\&Socket);
147
3111df62
SS
148 # Generate hash of monitored files.
149 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
150
9c74e9bb
SS
151 # Start worker threads.
152 &StartWorkers();
88d9af2c
SS
153}
154
155#
156## Worker function.
157#
158## This function is responsible for monitoring modifications of the given logfile,
159## read them and pass them to the message parser.
160#
161## To get file modifications the inotify subsystem of the linux kernel is used.
162#
163## In order to prevent from permanently read and keep files opened, or dealing
164## with huge logfiles, at initialization time of the worker process, the file will
165## be opened once and the cursor position of the end of file (EOF) get stored. When
166## reading any newly added lines from the file, we directly can jump to the last
167## known position and get these lines. Afterwards, we store the current curser position
168## again, so we can do it in this way over and over again.
169#
170## All read lines get stored in an array, which will be passed to the Parser.
171#
172## If any response (action) from the parser get recieved, it will be put into the
173## shared event queue.
174#
175sub Worker ($) {
9c74e9bb
SS
176 my $file = $_[0];
177
178 # Signal handler to kill worker.
179 $SIG{'KILL'} = sub { threads->exit(); };
88d9af2c 180
88d9af2c 181 # Create inotify watcher.
c0a59a63 182 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!";
88d9af2c
SS
183
184 # Monitor the specified file.
c0a59a63 185 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!";
88d9af2c 186
9c74e9bb
SS
187 # Switch watcher into non-blocking mode.
188 $watcher->blocking(0);
88d9af2c 189
c95dfa5b
SS
190 # Log successfully spawned worker.
191 $logger->Log("debug", "Spawned worker thread for: $file");
192
9c74e9bb
SS
193 # Infinite loop.
194 while(1) {
195 # Check for any events and perform them, if there
196 # is a least one.
197 if ($watcher->read) {
198 my @message = ();
88d9af2c 199
3111df62
SS
200 # Obtain fileposition from hash.
201 my $fileposition = $monitored_files{$file};
202
9c74e9bb 203 # Open the file.
c0a59a63 204 open (FILE, $file) or die "Could not open $file. $!";
88d9af2c 205
9c74e9bb
SS
206 # Seek to the last known position.
207 seek (FILE, $fileposition, 0);
88d9af2c 208
9c74e9bb
SS
209 # Get the log message.
210 while (my $line = <FILE>) {
211 # Remove any newlines.
212 chomp $line;
88d9af2c 213
9c74e9bb
SS
214 # Add all lines to the message array.
215 push (@message, $line);
216 }
88d9af2c 217
3111df62
SS
218 {
219 # Lock shared hash.
220 lock(%monitored_files);
221
222 # Update fileposition.
223 $monitored_files{$file} = tell(FILE);
224 }
88d9af2c 225
9c74e9bb
SS
226 # Close file.
227 close(FILE);
88d9af2c 228
9c74e9bb
SS
229 # Send filename and message to the parser,
230 # which will return if an action has to be performed.
231 my @action = &Guardian::Parser::Parser("$file", @message);
88d9af2c 232
9c74e9bb
SS
233 # Send the action to the main process and put it into
234 # the queue.
235 if (@action) {
236 # Lock the queue.
237 lock($queue);
238
239 # Put the required action into the queue.
240 $queue->enqueue(@action);
241 }
242 } else {
243 # Sleep for 10ms until the next round of the loop will start.
244 sleep(0.01);
88d9af2c
SS
245 }
246 }
247}
248
6abac3d4
SS
249#
250## Socket function.
251#
252## This function uses the Socket module to create and listen to an UNIX socket.
253## It automatically accepts all incomming connections and pass the recieved
254## data messages to the the Message_Parser function which is also part of the
255## socket module.
256#
257## If a valid command has been sent through the socket, the corresponding event
258## will be enqueued into the shared event queue.
259#
260sub Socket () {
261 # Create the Server socket by calling the responsible function.
262 my $server = &Guardian::Socket::Server();
263
c95dfa5b
SS
264 # Log successfull creation of socket.
265 $logger->Log("debug", "Listening to Socket...");
266
6abac3d4
SS
267 # Accept incomming connections from the socket.
268 while (my $connection = $server->accept()) {
269 # Autoflush the socket after the data
270 # has been recieved.
271 $connection->autoflush(1);
272
273 # Gather all data from the connection.
274 while (my $message = <$connection>) {
275 # Remove any newlines.
276 chomp($message);
277
c95dfa5b
SS
278 # Log recieved socket command.
279 $logger->Log("debug", "Socket - Recieved message: $message");
280
6abac3d4
SS
281 # Send the recieved data message to the
282 # socket parser.
283 my $action = &Guardian::Socket::Message_Parser($message);
284
285 # If the parser returns to perform an action,
286 # add it to the main event queue.
287 if ($action) {
288 # Lock the queue.
289 lock($queue);
290
291 # Enqueue the returned action.
292 $queue->enqueue($action);
293 }
294 }
295 }
296}
297
915d9f45
SS
298#
299## Function for capturing process signals.
300#
301## This function captures any sent process signals and will call various
302## actions, basend on the captured signal.
303#
304sub SignalHandler {
305 $SIG{INT} = \&Shutdown;
306 $SIG{TERM} = \&Shutdown;
307 $SIG{QUIT} = \&Shutdown;
ba734c53 308 $SIG{HUP} = \&Reload;
915d9f45
SS
309}
310
9c74e9bb
SS
311#
312## Function to start the workers (threads) for all monitored files.
313#
3111df62 314## This function will loop through the hash of monitored files and will
9c74e9bb
SS
315## spawn an own thread based worker for each file. Every created worker will
316## be added to the array of running workers.
317#
318sub StartWorkers () {
3111df62
SS
319 # Loop through the hash which contains the monitored files and start
320 # a worker thread for each single one.
321 foreach my $file (keys %monitored_files) {
c95dfa5b 322 $logger->Log("debug", "Starting worker thread for $file");
3111df62
SS
323 # Create worker thread for the file.
324 push @running_workers, threads->create(\&Worker,$file);
9c74e9bb
SS
325 }
326}
327
328#
329## Function to stop all running workers.
330#
331## This function is used to stop all currently running workers and will be
332## called when reloading or shutting down guardian.
333#
334sub StopWorkers () {
335 # Loop through all running workers.
336 foreach my $worker (@running_workers) {
337 # Send the worker the "KILL" signal and detach the
338 # thread so perl can do an automatically clean-up.
4d19939e 339 $worker->kill('KILL');
9c74e9bb 340 }
c95dfa5b 341 $logger->Log("debug", "All workers are stopped now...");
9c74e9bb
SS
342}
343
ba734c53
SS
344#
345## Reload function.
346#
347## This function will get called if the signal handler recieves a "SIGHUP" signal,
348## or the reload command will be sent via socket connection. It is responsible for
349## reloading all configure options and stopping/starting the worker threads.
350#
351sub Reload () {
c95dfa5b
SS
352 # Log reload.
353 $logger->Log("info", "Reload configuration...");
354
ba734c53
SS
355 # Stop all running workers.
356 &StopWorkers();
357
358 # Re-read configuration file.
359 %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
360
fc555263 361 # Update Logger settings.
aab61123 362 $logger = Guardian::Logger->Init(%mainsettings);
fc555263
SS
363
364 # Update logger object in mainsettings hash.
365 $mainsettings{Logger} = $logger;
366
ba734c53
SS
367 # Re-generate hash of monitored files.
368 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
369
370 # Restart the worker threads.
371 &StartWorkers();
372}
373
915d9f45
SS
374#
375## Shutdown function.
376#
377## This function is used to do a clean shutdown of guardian. It will be called
378## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
379#
380sub Shutdown () {
c95dfa5b
SS
381 # Log shutdown.
382 $logger->Log("info", "Shutting down...");
383
9c74e9bb
SS
384 # Stop all workers.
385 &StopWorkers();
386
915d9f45
SS
387 # Remove socket file on exit.
388 &Guardian::Socket::RemoveSocketFile();
389
0eb86493
SS
390 # Remove pid file on exit.
391 &Guardian::Daemon::RemovePIDFile();
392
a9ef502c
SS
393 # Sleep for one second to give perl some
394 # time to proper clean up everything before
395 # exiting.
396 sleep(1);
397
c95dfa5b
SS
398 # Log good bye message.
399 $logger->Log("debug", "Good Bye!");
400
915d9f45
SS
401 # Exit guardian.
402 exit;
403}