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