aradial usage import: fix integer binding, update statement RT#29053
[freeside.git] / bin / aradial-sftp_and_import
1 #!/usr/bin/perl -w
2
3 #i'm kinda like freeside-cdr-sftp_and_import... some parts should be libraried
4
5 use strict;
6 use Getopt::Std;
7 use Date::Format;
8 use Text::CSV_XS;
9 use DBI qw( :sql_types );
10 use Net::SFTP::Foreign;
11 #use FS::UID qw( adminsuidsetup datasrc );
12
13 #adjusted these for what we're actually seeing in the real log files
14 our %aradial2db = (
15   #'Date' => '',
16   #'NASIP' => 'NASIPAddress',
17   'NASID' => 'NASIPAddress',
18   'AcctSessionId' => 'AcctSessionId',
19   'Port' => 'NasPortId',
20   #'Status-Type' => 'Acct-Status-Type',
21   #'UserID' => 'UserName',
22   'User ID' => 'UserName',
23   'Authentic' => 'AcctAuthentic',
24   'Service-Type' => 'ServiceType',
25   'FramedProtocol' => 'FramedProtocol',
26   #'FramedCompression' => '', #not handled, needed?  unlikely
27   'FramedAddress' => 'FramedIPAddress',
28   'Acct-Delay-Time' => 'AcctStartDelay', #?
29   'Session-Time' => 'AcctSessionTime',
30   #'Input-Gigawords' => '', #XXX handle lots of data
31   'Input-Octets' => 'AcctInputOctets',
32   #'Output-Gigawords' => '', #XXX handle lots of data
33   'Output-Octets' => 'AcctOutputOctets',
34   'NAS-Port-Type' => 'NASPortType',
35   'Acct-Terminate-Cause' => 'AcctTerminateCause',
36 );
37
38 our %bind_type = (
39   'AcctInputOctets'  => SQL_INTEGER,
40   'AcctOutputOctets' => SQL_INTEGER,
41   'AcctSessionTime'  => SQL_INTEGER,
42   'AcctStartDelay'   => SQL_INTEGER,
43   'AcctStopDelay'    => SQL_INTEGER,
44 );
45
46 #http://www.iana.org/assignments/radius-types/radius-types.xhtml#radius-types-10
47 our %status_type = (
48    1 => 'Start',
49    2 => 'Stop',
50    3 => 'Interim-Update',
51   #4-6,'Unassigned',
52    7 => 'Accounting-On',
53    8 => 'Accounting-Off',
54    9 => 'Tunnel-Start',
55   10 => 'Tunnel-Stop',
56   11 => 'Tunnel-Reject',
57   12 => 'Tunnel-Link-Start',
58   13 => 'Tunnel-Link-Stop',
59   14 => 'Tunnel-Link-Reject',
60   15 => 'Failed',
61 );
62
63 ###
64 # parse command line
65 ###
66
67 use vars qw( $opt_m $opt_a $opt_b $opt_r $opt_d $opt_v $opt_P );
68 getopts('m:abr:dP:v:');
69
70 my %options = ();
71
72 my $user = shift or die &usage;
73 #adminsuidsetup $user;
74
75 # %%%FREESIDE_CACHE%%% & hardcoded datasrc
76 #my $cachedir = '%%%FREESIDE_CACHE%%%/cache.'. datasrc. '/cdrs';
77 my $cachedir = '/usr/local/etc/freeside/cache.DBI:Pg:dbname=freeside/cdrs';
78 mkdir $cachedir unless -d $cachedir;
79
80 my $servername = shift or die &usage;
81
82 my( $datasrc, $db_user, $db_pass ) = ( shift, shift, shift );
83 my $dbh = DBI->connect( $datasrc, $db_user, $db_pass)
84   or die "can't connect: $DBI::errstr\n";
85
86 my $csv = Text::CSV_XS->new;
87
88 ###
89 # get the file list
90 ###
91
92 warn "Retrieving directory listing\n" if $opt_v;
93
94 $opt_m = 'sftp' if !defined($opt_m);
95 $opt_m = lc($opt_m);
96
97 my $ls;
98
99 if($opt_m eq 'ftp') {
100   $options{'Port'}    = $opt_P if $opt_P;
101   $options{'Debug'}   = $opt_v if $opt_v;
102   $options{'Passive'} = $opt_a if $opt_a;
103
104   my $ls_ftp = ftp();
105
106   $ls = [ grep { /^.*$/i } $ls_ftp->ls ];
107 }
108 elsif($opt_m eq 'sftp') {
109   $options{'port'}    = $opt_P if $opt_P;
110   $options{'debug'}   = $opt_v if $opt_v;
111
112   my $ls_sftp = sftp();
113
114   $ls_sftp->setcwd($opt_r) or die "can't chdir to $opt_r\n"
115     if $opt_r;
116
117   $ls = $ls_sftp->ls('.', no_wanted  => qr/^\.+$/,
118                           names_only => 1 );
119 }
120 else {
121   die "Method '$opt_m' not supported; must be ftp or sftp\n";
122 }
123
124 ###
125 # import each file
126 ###
127
128 foreach my $filename ( @$ls ) {
129
130   warn "Downloading $filename\n" if $opt_v;
131
132   #get the file
133   if($opt_m eq 'ftp') {
134     my $ftp = ftp();
135     $ftp->get($filename, "$cachedir/$filename")
136       or die "Can't get $filename: ". $ftp->message . "\n";
137   }
138   else {
139     my $sftp = sftp();
140     $sftp->get($filename, "$cachedir/$filename")
141       or die "Can't get $filename: ". $sftp->error . "\n";
142   }
143
144   warn "Processing $filename\n" if $opt_v;
145  
146   open my $fh, "$cachedir/$filename" or die "$cachedir/$filename: $!";
147   my $header = $csv->getline($fh);
148
149   while ( my $row = $csv->getline($fh) ) {
150
151     my $i = 0;
152     my %hash = map { $_ => $row->[$i++] } @$header;
153
154     my %dbhash = map { $aradial2db{$_} => $hash{$_} }
155                    grep $aradial2db{$_},
156                      keys %hash;
157
158     my @keys = keys %dbhash;
159
160     $hash{'Status-Type'} = $status_type{ $hash{'Status-Type'} }
161       if exists $status_type{ $hash{'Status-Type'} };
162
163     my $sql;
164     my @extra_values = ();
165     if ( $hash{'Status-Type'} eq 'Start' ) {
166
167       $dbhash{'AcctStartTime'} = $hash{'Date'};
168
169       $sql = 'INSERT INTO radacct ( ', join(',', @keys).
170              ' ) VALUES ( '. map( ' ? ', @keys ). ' )';
171
172     } elsif ( $hash{'Status-Type'} eq 'Stop' ) {
173
174       my $AcctSessionId = delete($dbhash{AcctSessionId});
175       $dbhash{'AcctStopTime'} = $hash{'Date'};
176
177       push @extra_values, $AcctSessionId;
178
179       $sql = 'UPDATE radacct SET '. join(',', map "$_ = ?", @keys ).
180              ' WHERE AcctSessionId = ? ';
181
182     } elsif ( $hash{'Status-Type'} eq 'Interim' ) {
183       #not handled, but stop should capture the usage.  unless session are
184       # normally super-long, extending across month boundaries, or we need
185       # real-time-ish data usage detail, it isn't a big deal
186     } else {
187       warn 'Unknown Status-Type '. $hash{'Status-Type'}. "; skipping\n";
188       next;
189     }
190
191     my $sth = $dbh->prepare($sql) or die $dbh->errstr;
192
193     my $p_num = 1;
194     foreach my $value ( map $dbhash{$_}, @keys ) {
195       my $key = shift @keys;
196       my $type = exists($bind_type{$key}) ? $bind_type{$key} : SQL_VARCHAR;
197       $sth->bind_param($p_num++, $value, $type);
198     }
199     foreach my $value ( @extra_values ) {
200       $sth->bind_param($p_num++, $value);
201     }
202
203     $sth->execute or die $sth->errstr;
204
205   }
206   
207   if ( $opt_d ) {
208     my $file_timestamp = $filename.'-'.time2str('%Y-%m-%d', time);
209     if ( $opt_m eq 'ftp') {
210       my $ftp = ftp();
211       $ftp->rename($filename, "$opt_d/$file_timestamp")
212         or do {
213           unlink "$cachedir/$filename";
214           die "Can't move $filename to $opt_d: ".$ftp->message . "\n";
215         };
216     } else {
217       my $sftp = sftp();
218       $sftp->rename($filename, "$opt_d/$file_timestamp")
219         or do {
220           unlink "$cachedir/$filename";
221           die "can't move $filename to $opt_d: ". $sftp->error . "\n";
222         };
223     }
224   }
225
226   unlink "$cachedir/$filename";
227
228 }
229
230 ###
231 # subs
232 ###
233
234 sub usage {
235   "Usage:
236   aradial-sftp_and_import [ -m method ] [ -a ] [ -b ]
237     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
238     user [sftpuser@]servername dbi_datasrc dbi_username dbi_pass
239   ";
240 }
241
242 use vars qw( $sftp $ftp );
243
244 sub ftp {
245   return $ftp if $ftp && $ftp->pwd;
246   
247   my ($hostname, $userpass) = reverse split('@', $servername);
248   my ($ftp_user, $ftp_pass) = split(':', $userpass);
249
250   my $ftp = Net::FTP->new($hostname, %options) 
251     or die "FTP connection to '$hostname' failed.";
252   $ftp->login($ftp_user, $ftp_pass) or die "FTP login failed: ".$ftp->message;
253   $ftp->cwd($opt_r) or die "can't chdir to $opt_r\n" if $opt_r;
254   $ftp->binary or die "can't set BINARY mode: ". $ftp->message if $opt_b;
255   return $ftp;
256 }
257
258 sub sftp {
259
260   #reuse connections
261   return $sftp if $sftp && $sftp->cwd;
262
263   my %sftp = ( host => $servername );
264
265   $sftp = Net::SFTP::Foreign->new(%sftp);
266   $sftp->error and die "SFTP connection failed: ". $sftp->error;
267
268   $sftp;
269 }
270
271 =head1 NAME
272
273 freeside-aradial-sftp_and_import - Download Aradial "CDR" (really RADIUS detail) files from a remote server via SFTP
274
275 =head1 SYNOPSIS
276
277   aradial-sftp_and_import [ -m method ] [ -a ] [ -b ]
278     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
279     user [sftpuser@]servername dbi_datasrc dbi_username dbi_pass
280
281 =head1 DESCRIPTION
282
283 Command line tool to download CDR files from a remote server via SFTP 
284 or FTP and then import them into the database.
285
286 -m: transfer method (sftp or ftp), defaults to sftp
287
288 -a: use ftp passive mode
289
290 -b: use ftp binary mode
291
292 -r: if specified, changes into this remote folder before starting
293
294 -d: if specified, moves files to the specified folder when done
295
296 -P: if specified, sets the port to use
297
298 -v: set verbosity level; this script only has one level, but it will 
299     be passed as the 'debug' argument to the transport method
300
301 user: freeside username
302
303 [sftpuser@]servername: remote server
304 (or ftpuser:ftppass@servername)
305
306 =head1 BUGS
307
308 =head1 SEE ALSO
309
310 L<FS::cdr>
311
312 =cut
313
314 1;
315