Debian Codegraph @

lemonldap-ng-common/eg/lokiSender

raw
1 #!/usr/bin/perl
2
3 use strict;
4 use Getopt::Long;
5 use POSIX;
6 use Pod::Usage;
7
8 our $VERSION = "2.22.0";
9
10 # Options
11 my $opts = {};
12 my $help;
13 my $opt_user = '__APACHEUSER__';
14 my $opt_group = '__APACHEGROUP__';
15
16 my @CMDLINE = @ARGV;
17
18 GetOptions(
19 'daemon' => \$opts->{daemon},
20 'defer-dir=s' => \$opts->{deferDir},
21 'debug' => \$opts->{debug},
22 'delay=s' => \$opts->{delay},
23 'group|g=s' => \$opts->{group},
24 'help|h' => \$help,
25 'ini-file=s' => \$opts->{iniFile},
26 'syslog-facility' => \$opts->{syslogFacility},
27 'user|u=s' => \$opts->{user},
28 ) or pod2usage( -exitcode => 1, -verbose => 0 );
29
30 foreach my $opt ( keys %$opts ) {
31 $opts->{$opt} //= $ENV{ 'LLNG_LOKI_' . uc($opt) };
32 }
33
34 pod2usage( -exitcode => 0, -verbose => 2 ) if $help;
35
36 $opts->{delay} ||= 60 if $opts->{daemon};
37 $opts->{deferDir} ||= &_getDeferDir;
38 mkdir $opts->{deferDir} unless -e $opts->{deferDir};
39 die "Missing directory $opts->{deferDir}" unless -d $opts->{deferDir};
40 die "Cannot write into $opts->{deferDir}" unless -w $opts->{deferDir};
41
42 die 'Missing --defer-dir' unless $opts->{deferDir};
43
44 # Change owner if asked
45 POSIX::nice(10);
46 if ( $opts->{group} || $opts->{user} ) {
47 eval {
48 no warnings;
49 my ( $gid, $uid );
50 if ( $opts->{group} ) {
51 $gid = getgrnam( $opts->{group} );
52 POSIX::setgid($gid);
53 }
54 if ( $opts->{user} ) {
55 $uid = getpwnam( $opts->{user} );
56 chown( $uid, ( $gid // [ stat( $opts->{deferDir} ) ]->[5] ),
57 $opts->{deferDir} )
58 and chmod( 0700, $opts->{deferDir} );
59 POSIX::setuid( scalar( getpwnam( $opts->{user} ) ) )
60 if $opts->{user};
61 my (
62 undef, undef, undef, undef, undef,
63 undef, undef, $homedir, undef
64 ) = getpwnam( $opts->{user} );
65 $ENV{HOME} = $homedir if $homedir;
66 }
67 };
68 }
69
70 &daemonize if $opts->{daemon};
71
72 require HTTP::Request;
73 require JSON;
74 require LWP::UserAgent;
75 require Sys::Syslog;
76
77 my $j = JSON->new->canonical;
78
79 my $syslogOpened;
80
81 sub _log {
82 my ( $level, $msg ) = @_;
83 if ( $opts->{daemon} ) {
84 unless ($syslogOpened) {
85 Sys::Syslog::openlog( 'LLNG-Loki', 'cons,pid,ndelay',
86 $opts->{syslogFacility} || 'daemon' );
87 $syslogOpened++;
88 }
89 Sys::Syslog::syslog( $level, $msg );
90 }
91 else {
92 print STDERR "[$level] $msg\n";
93 }
94 }
95
96 sub debug {
97 map { _log( 'debug', $_ ) } @_ if $opts->{debug};
98 }
99
100 sub warning {
101 map { _log( 'warning', $_ ) } @_;
102 }
103
104 sub error {
105 map { _log( 'err', $_ ) } @_;
106 }
107
108 sub _getDeferDir {
109
110 require Lemonldap::NG::Common::Conf;
111 my $ca = Lemonldap::NG::Common::Conf->new( { (
112 $opts->{iniFile}
113 ? ( confFile => $opts->{iniFile} )
114 : ()
115 )
116 }
117 );
118
119 no warnings;
120 die $Lemonldap::NG::Common::Conf::msg unless ($ca);
121 my $conf = $ca->getConf('all');
122 my $localConf = $ca->getLocalConf( 'all', $_[0]->{iniFile} );
123 $conf = { %$conf, %$localConf };
124
125 unless ( $conf->{lokiDeferDir} ) {
126 die 'Missing lokiDeferDir';
127 }
128 debug "Conf downloaded from Lemonldap::NG::Common::Conf: $conf->{cfgNum}";
129 return $conf->{lokiDeferDir};
130 }
131
132 sub sendLogs {
133 my $i;
134 my $ret = 1;
135 if ( opendir my $dh, $opts->{deferDir} ) {
136 debug "Checking for logs into $opts->{deferDir}";
137 my $i = 0;
138 my ( %logs, %filesToDel, @headers, $hdr_done, %streams, %urls );
139 while ( my $name = readdir($dh) ) {
140 $i++;
141 my $fn = "$opts->{deferDir}/$name";
142 next if $name =~ m#^\.# or !-f $fn;
143 my $fh;
144 unless ( open $fh, '<', $fn ) {
145 error "Unable to open $fn: $!";
146 $ret = 0;
147 goto END;
148 }
149 my $tmp = <$fh>;
150 unless ($tmp) {
151 warning "Empty file $fn";
152 goto END;
153 }
154 chomp $tmp;
155 my ( $meth, $url ) = split( /\s+/, $tmp, 2 );
156 unless ( $meth and $url and $meth eq 'POST' ) {
157 warning "Not a valid file $fn";
158 goto END;
159 }
160
161 # Get headers;
162 while ( my $line = <$fh> ) {
163 chomp $line;
164 $line =~ s/\r//g;
165 unless ($line) {
166 $hdr_done = 1;
167 last;
168 }
169 next if $hdr_done;
170 my ( $k, $v ) = split( /:\s+/, $line );
171 push @headers, $k, $v if $v and lc($k) ne 'content-length';
172 }
173
174 # Get content
175 my $content;
176 {
177 local $/ = undef;
178 while ( my $line = <$fh> ) {
179 chomp $line;
180 $line =~ s/[\r\n]//g;
181 next unless $line;
182 $content = eval { $j->decode($line)->{streams} };
183 if ( $@ or not $content ) {
184 warning "Malformed line ($fn): $line";
185 last;
186 }
187 }
188 }
189 next unless $content;
190 foreach my $stream (@$content) {
191 my $k = $j->encode( $stream->{stream} );
192 push @{ $logs{$k} }, @{ $stream->{values} };
193 push @{ $filesToDel{$k} }, $fn;
194 $streams{$k} ||= $stream->{stream};
195 $urls{$k} ||= $url;
196 }
197 END: close $fh;
198 }
199 my $ua = LWP::UserAgent->new;
200 $ua->env_proxy;
201 foreach my $key ( keys %logs ) {
202 my $req = HTTP::Request->new(
203 POST => $urls{$key},
204 \@headers,
205
206 #HTTP::Headers->new(@{$headers{$key}}),
207 $j->encode( {
208 streams => [ {
209 stream => $streams{$key},
210 values => $logs{$key},
211 },
212 ]
213 }
214 )
215 );
216 my $resp = $ua->request($req);
217 if ( $resp->is_success ) {
218 debug "Logs $key sent";
219 unlink( @{ $filesToDel{$key} } ) or warning $!;
220 }
221 else {
222 $ret = 0;
223 error "Fail to send logs: " . $resp->status_line;
224 }
225 }
226 }
227 else {
228 error "Unable to open $opts->{deferDir}: $!";
229 }
230 return $ret;
231 }
232
233 sub daemonize {
234 open STDIN, '<', '/dev/null' or die "Can't read /dev/null: $!";
235 open STDOUT, '>', '/dev/null' or die "Can't write to /dev/null: $!";
236 open STDERR, '>', '/dev/null' or die "Can't write to /dev/null: $!";
237
238 defined( my $pid = fork ) or die "Can't fork: $!";
239 exit if $pid;
240
241 setsid() or die "Can't start a new session: $!";
242
243 defined( $pid = fork ) or die "Can't fork again: $!";
244 exit if $pid;
245
246 umask 0;
247
248 if ( $opts->{pidFile} ) {
249 open my $fh, '>', $opts->{pidFile}
250 or die "Can't write $opts->{pidFile} $!";
251 print $fh "$$\n";
252 close $fh;
253 }
254 $0 = join ' ', $0, @CMDLINE;
255 }
256
257 ## MAIN
258
259 if ( $opts->{delay} ) {
260 $SIG{$_} = \&sendLogs foreach (qw(ALRM USR1 USR2));
261 $SIG{$_} = sub {
262 debug "End asked";
263 exit( &sendLogs ? 0 : 1 );
264 }
265 foreach (qw(INT TERM QUIT KILL ABRT HUP));
266 while (1) {
267 &sendLogs;
268 sleep $opts->{delay};
269 }
270 }
271 else {
272 &sendLogs || exit 1;
273 }
274
275 __END__
276
277 =encoding UTF-8
278
279 =head1 NAME
280
281 lokiSender - daemon I<(or cron job)> to send to L<Loki> API the logs stored in
282 a temporary directory by L<Lemonldap-ng|https://lemonldap-ng.org/> Loki logger.
283
284 =head1 SYNOPSIS
285
286 $ lokiSender --defer-dir /tmp/loki --daemon --delay 60
287
288 =head1 DESCRIPTION
289
290 B<lokiSender> is a web-based pub/sub server designed for L<LemonLDAP::NG|https://lemonldap-ng.org>
291 when the Loki logger is configured to store logs into a temporary directory.
292
293 =head2 Options
294
295 All options except B<--help> can have default value overriden by an
296 environment variable.
297
298 =head3 Start options
299
300 When launched without B<--delay> or B<--daemon>, lokiSender just send all logs
301 to Loki API I<(grouped)>. This can be used as cron task.
302
303 =over
304
305 =item * B<--daemon>
306
307 Daemonize the server.
308
309 Environment variable: B<LLNG_LOKI_DAEMON>
310
311 =item * B<--delay E<lt>valueE<gt>>
312
313 With or without B<--daemon>, send all pending logs to Loki API every
314 E<lt>valueE<gt> seconds.
315
316 Environment variable: B<LLNG_LOKI_DELAY>
317
318 =item * B<--defer-dir E<lt>valueE<gt>>
319
320 Define the directory where B<Lemonldap-NG> stores its Loki logs
321 I<(option B<lokiDeferDir>)>. When not given, B<lokiSender> tries to find it
322 inside Lemonldap-NG configuration.
323
324 Environment variable: B<LLNG_LOKI_DEFERDIR>
325
326 =item * B<--ini-file E<lt>valueE<gt>>
327
328 When B<--defer-dir> isn't defined, you can override here the default place of
329 B<lemonldap-ng.ini> file to find the B<lokiDeferDir> parameter.
330
331 Environment variable: B<LLNG_LOKI_INIFILE>
332
333 =back
334
335 =head3 Daemon options
336
337 =over
338
339 =item * B<--pid-file E<lt>valueE<gt>>
340
341 When B<--daemon> is set, write the processus number into the given file.
342
343 Environment variable: B<LLNG_LOKI_PID_FILE>
344
345 =item * B<--user> E<lt>valueE<gt>>
346
347 Change uid to the given value after opening socket.
348
349 Environment variable: B<LLNG_LOKI_USER>
350
351 =item * B<--group> E<lt>valueE<gt>>
352
353 Change gid to the given value after opening socket.
354
355 Environment variable: B<LLNG_LOKI_GROUP>
356
357 =back
358
359 =head3 Logging options
360
361 =over
362
363
364 =item * B<--debug>
365
366 Display additional information.
367
368 Environment variable: B<LLNG_LOKI_DEBUG>
369
370 =item * B<--syslog-facility E<lt>valueE<gt>>
371
372 When launched as daemon, logs are sent to syslog instead of stderr.
373
374 Environment variable: B<LLNG_LOKI_SYSLOGFACILITY
375
376 =back
377
378 =head3 Other
379
380 =over
381
382 =item * B<--help>
383
384 Display this.
385
386 =back
387
388 =head1 SEE ALSO
389
390 =over
391
392 =item * L<Lemonldap::NG logs|https://lemonldap-ng.org/documentation/latest/logs.html>
393
394 =item * L<http://lemonldap-ng.org/>
395
396 =back
397
398 =head1 BUG REPORT
399
400 Use OW2 system to report bug or ask for features:
401 L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>
402
403
404 =head1 AUTHORS
405
406 =over
407
408 =item Xavier Guimard, E<lt>[email protected]<gt>
409
410 =back
411
412 =head1 COPYRIGHT AND LICENSE
413
414 See COPYING file for details.
415
416 This library is free software; you can redistribute it and/or modify
417 it under the terms of the GNU General Public License as published by
418 the Free Software Foundation; either version 2, or (at your option)
419 any later version.
420
421 This program is distributed in the hope that it will be useful,
422 but WITHOUT ANY WARRANTY; without even the implied warranty of
423 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
424 GNU General Public License for more details.
425
426 You should have received a copy of the GNU General Public License
427 along with this program. If not, see L<http://www.gnu.org/licenses/>.
428
429 =cut