Debian Codegraph @

scripts/sql/radsqlrelay

raw
1 #!/usr/bin/perl -w
2 ##
3 ## radsqlrelay.pl This program tails a SQL logfile and forwards
4 ## the queries to a database server. Used to
5 ## replicate accounting records to one (central)
6 ## database, even if the database has extended
7 ## downtime.
8 ##
9 ## Version: $Id: 74531ba9bf7588eb42bb409fc69ecd0abdf919f5 $
10 ##
11 ## Author: Nicolas Baradakis <[email protected]>
12 ##
13 ## Copyright (C) 2005 Cegetel
14 ## Copyright (C) 2019 Network RADIUS
15 ##
16 ## This program is free software; you can redistribute it and/or
17 ## modify it under the terms of the GNU General Public License
18 ## as published by the Free Software Foundation; either version 2
19 ## of the License, or (at your option) any later version.
20 ##
21 ## This program is distributed in the hope that it will be useful,
22 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ## GNU General Public License for more details.
25 ##
26 ## You should have received a copy of the GNU General Public License
27 ## along with this program; if not, write to the Free Software
28 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 ##
30
31 use strict;
32
33 use DBI;
34 use Fcntl;
35 use Getopt::Std;
36 use POSIX qw(:unistd_h :errno_h);
37 use Time::HiRes qw(clock_gettime usleep CLOCK_MONOTONIC);
38
39 # We send watchdogs at half the indicated interval if the
40 # Linux::Systemd::Daemon module is available and the WATCHDOG_USEC environment
41 # variable is set by the systemd service manager.
42 my $watchdog_usec;
43 my $next_watchdog;
44 eval {
45 require Linux::Systemd::Daemon;
46 Linux::Systemd::Daemon->import();
47 $watchdog_usec = $ENV{'WATCHDOG_USEC'} || undef;
48 };
49
50 # To synthetically test the watchdog functionality then uncomment these next
51 # lines:
52 #
53 # $watchdog_usec = 30 *1000*1000;
54 # sub sd_notify {}
55
56 my $maxcollect = 100; # tunable, works for MySQL!
57
58 my $lastinsert;
59 my @values;
60
61 my $need_exit = 0;
62 my $debug = 0;
63
64 sub got_signal()
65 {
66 $need_exit = 1;
67 sd_notify(stopping => 1, status => 'Signalled. Shutting down.') if $watchdog_usec;
68 }
69
70 sub debug
71 {
72 print shift if $debug;
73 }
74
75 # /!\ OS-dependent structure
76 # Linux struct flock
77 # short l_type;
78 # short l_whence;
79 # off_t l_start;
80 # off_t l_len;
81 # pid_t l_pid;
82 # c2ph says: typedef='s2 l2 i', sizeof=16
83 my $FLOCK_STRUCT = 's2l2i';
84
85 sub setlock($;$$)
86 {
87 my ($fh, $start, $len) = @_;
88 $start = 0 unless defined $start;
89 $len = 0 unless defined $len;
90
91 #type whence start till pid
92 my $packed = pack($FLOCK_STRUCT, F_WRLCK, SEEK_SET, $start, $len, 0);
93 if (fcntl($fh, F_SETLKW, $packed)) { return 1 }
94 else { return 0 }
95 }
96
97 sub usage()
98 {
99 print STDERR <<HERE;
100 usage: radsqlrelay [options] file_path
101 options:
102 -? Print this help message.
103 -1 One-shot mode: push the file to database and exit.
104 -b database Name of the database to use.
105 -d sql_driver Driver to use: mysql, pg, oracle.
106 -f file Read password from file, instead of command line.
107 -h host Connect to host.
108 -P port Port number to use for connection.
109 -p password Password to use when connecting to server.
110 -u user User for login.
111 -x Turn on debugging.
112 HERE
113 }
114
115
116 # Sleep for given amount of time, but don't oversleep the watchdog interval.
117 # Send a watchdog notification if it is due.
118 # interval can be given as 0 to just check whether a watchdog is due and send
119 # it as necessary, in which case we do not yield.
120 sub sleep_for ($)
121 {
122 my $interval=shift;
123 $interval*=1000*1000;
124 if ($watchdog_usec) {
125 my $now=clock_gettime(CLOCK_MONOTONIC)*1000*1000;
126 if ($now >= $next_watchdog) {
127 $next_watchdog=$now+($watchdog_usec / 2);
128 debug "Sending watchdog\n";
129 sd_notify(watchdog => 1);
130 debug "Next watchdog due in ".(($next_watchdog-$now)/1000/1000)." secs.\n";
131 }
132 # Don't oversleep!
133 $interval=$next_watchdog-$now if $next_watchdog-$now < $interval;
134 }
135 return unless $interval; # Don't yield if we are not asked to sleep
136 debug "Sleeping for ".($interval/1000/1000)." secs.\n";
137 usleep ($interval);
138 }
139
140
141 sub connect_wait($)
142 {
143 my $dbinfo = shift;
144 my $dbh;
145 debug "Connecting to " . $dbinfo->{base};
146 while (!$dbh) {
147 debug ".";
148 $dbh = DBI->connect($dbinfo->{base}, $dbinfo->{user}, $dbinfo->{pass},
149 { RaiseError => 0, PrintError => 0,
150 AutoCommit => 1 });
151 sleep_for (1) if !$dbh;
152 exit if $need_exit;
153 }
154 debug "\n";
155 $dbinfo->{handle} = $dbh;
156 }
157
158
159
160 sub process_file($$)
161 {
162 my ($dbinfo, $path) = @_;
163
164 sub do_inserts($) {
165 my $dbinfo = shift;
166 debug "I";
167 if (scalar(@values) > 0) {
168 my $query = $lastinsert . " ";
169 $query .= join(" ), ( ",@values);
170 $query .= " );";
171 do_query($dbinfo,$query);
172 }
173 @values = ();
174 }
175
176 sub do_query($$) {
177 my ($dbinfo,$query) = @_;
178 debug ">";
179 until ($dbinfo->{handle}->do($query)) {
180 # If an error occured and we're disconnected then try to recomnnect
181 # and redo the query, otherwise give up so we don't become stuck.
182 print $dbinfo->{handle}->errstr."\n";
183 if ($dbinfo->{handle}->ping) {
184 sleep_for (1);
185 last;
186 } else {
187 print "error: Lost connection to database\n";
188 $dbinfo->{handle}->disconnect;
189 connect_wait($dbinfo);
190 }
191 }
192 sleep_for(0) if $watchdog_usec; # Send a watchdog if it is due
193 }
194
195 unless (-e $path.'.work') {
196 debug "Waiting for $path\n";
197 until (rename($path, $path.'.work')) {
198 if ($! == ENOENT) {
199 sleep_for(1);
200 return if $need_exit;
201 } else {
202 print STDERR "error: Couldn't move $path to $path.work: $!\n";
203 exit 1;
204 }
205 }
206 debug "Renamed $path to $path.work\n";
207 }
208
209 debug "\nOpening $path.work\n";
210 open(FILE, "+< $path.work") or die "error: Couldn't open $path.work: $!\n";
211 debug "Getting file lock\n";
212 setlock(\*FILE) or die "error: Couldn't lock $path.work: $!\n";
213
214 $lastinsert = "";
215 @values = ();
216
217 debug "Reading: ";
218 my $lines = 0;
219 while (<FILE>) {
220 chomp (my $line = $_);
221 $lines++;
222
223 if (!($line =~ /^\s*insert\s+into\s+`?\w+`?\s+(?:\(.*?\)\s+)?
224 values\s*\(.*\)\s*;\s*$/ix)) {
225 # This is no INSERT, so start new collection
226 do_inserts($dbinfo);
227 debug ".";
228 $lastinsert = "";
229 # must output this line
230 do_query($dbinfo, "$line");
231
232 } else {
233 # This is an INSERT, so collect it
234 debug "+";
235 my $insert = $line;
236 my $values = $line;
237 $insert =~ s/^\s*(insert\s+into\s+`?\w+`?\s+(?:\(.*?\)\s+)?
238 values\s*\().*\)\s*;\s*$/$1/ix;
239 $values =~ s/^\s*insert\s+into\s+`?\w+`?\s+(?:\(.*?\)\s+)?
240 values\s*\((.*)\)\s*;\s*$/$1/ix;
241
242 if (($lastinsert ne "") && ($insert ne $lastinsert)) {
243 # This is different from the last one
244 do_inserts($dbinfo);
245 }
246 push(@values, $values);
247 $lastinsert = $insert; # start new collection
248 }
249
250 # limit to $maxcollect collected lines
251 if (scalar(@values) >= $maxcollect) {
252 debug "hit maxcollect limit, doing inserts";
253 do_inserts($dbinfo);
254 }
255 }
256
257 # Cleanup
258 debug "\nNo more lines to read, doing any final inserts: ";
259 do_inserts($dbinfo);
260 debug "\n";
261
262 debug "Processed $lines lines\n";
263 debug "Removing and closing $path.work\n\n";
264 unlink($path.'.work');
265 close(FILE); # and unlock
266 }
267
268 # sub main()
269
270 my %args = (
271 b => 'radius',
272 d => 'mysql',
273 h => 'localhost',
274 p => 'radius',
275 u => 'radius',
276 );
277 my $ret = getopts("b:d:f:h:P:p:u:x1?", \%args);
278 if (!$ret or @ARGV != 1) {
279 usage();
280 exit 1;
281 }
282 if ($args{'?'}) {
283 usage();
284 exit 0;
285 }
286 $debug = 1 if $args{'x'};
287
288 my $data_source;
289 if (lc($args{d}) eq 'mysql') {
290 $data_source = "DBI:mysql:database=$args{b};host=$args{h}";
291 } elsif (lc($args{d}) eq 'pg') {
292 $data_source = "DBI:Pg:dbname=$args{b};host=$args{h}";
293 } elsif (lc($args{d}) eq 'oracle') {
294 $data_source = "DBI:Oracle:$args{b}";
295 # Oracle does not conform to the SQL standard for multirow INSERTs
296 $maxcollect = 1;
297 } else {
298 print STDERR "error: SQL driver not supported yet: $args{d}\n";
299 exit 1;
300 }
301 $data_source .= ";port=$args{P}" if $args{'P'};
302
303 my $pw;
304 if($args{f}) {
305 open(FILE, "< $args{f}") or die "error: Couldn't open $args{f}: $!\n";
306 $pw = <FILE>;
307 chomp($pw);
308 close(FILE);
309 } else {
310 # args{p} is always defined.
311 $pw = $args{p};
312 }
313
314 $SIG{INT} = \&got_signal;
315 $SIG{TERM} = \&got_signal;
316
317 if ($watchdog_usec) {
318 debug "Watchdog set to $watchdog_usec\n";
319 my $now=clock_gettime(CLOCK_MONOTONIC)*1000*1000;
320 $next_watchdog=$now+($watchdog_usec / 2);
321 sd_notify(ready => 1, status => 'Started');
322 }
323
324 my %dbinfo = (
325 base => $data_source,
326 user => $args{u},
327 pass => $pw,
328 );
329 connect_wait(\%dbinfo);
330
331 my $path = shift @ARGV;
332
333 until ($need_exit) {
334 process_file(\%dbinfo, $path);
335 last if ($args{1} || $need_exit);
336 debug "Sleeping\n";
337 sleep_for(10);
338 }
339
340 debug "Disconnecting from database\n";
341 $dbinfo{handle}->disconnect;
342