fix inserts and don't generate extra noise on trailing blanks, 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     #skip blank records
161     next unless grep defined($_), values %dbhash;
162
163     $hash{'Status-Type'} = $status_type{ $hash{'Status-Type'} }
164       if exists $status_type{ $hash{'Status-Type'} };
165
166     my $sql;
167     my @extra_values = ();
168     if ( $hash{'Status-Type'} eq 'Start' ) {
169
170       $dbhash{'AcctStartTime'} = $hash{'Date'};
171
172       $sql = 'INSERT INTO radacct ( '. join(',', @keys).
173              ' ) VALUES ( '. join(',', map ' ? ', @keys ). ' )';
174
175     } elsif ( $hash{'Status-Type'} eq 'Stop' ) {
176
177       my $AcctSessionId = delete($dbhash{AcctSessionId});
178       $dbhash{'AcctStopTime'} = $hash{'Date'};
179
180       push @extra_values, $AcctSessionId;
181
182       $sql = 'UPDATE radacct SET '. join(',', map "$_ = ?", @keys ).
183              ' WHERE AcctSessionId = ? ';
184
185     } elsif ( $hash{'Status-Type'} eq 'Interim' ) {
186       #not handled, but stop should capture the usage.  unless session are
187       # normally super-long, extending across month boundaries, or we need
188       # real-time-ish data usage detail, it isn't a big deal
189     } else {
190       warn 'Unknown Status-Type '. $hash{'Status-Type'}. "; skipping\n";
191       next;
192     }
193
194     my $sth = $dbh->prepare($sql) or die $dbh->errstr;
195
196     my $p_num = 1;
197     foreach my $value ( map $dbhash{$_}, @keys ) {
198       my $key = shift @keys;
199       my $type = exists($bind_type{$key}) ? $bind_type{$key} : SQL_VARCHAR;
200       $value ||= 0 if $type == SQL_INTEGER;
201       $sth->bind_param($p_num++, $value, $type);
202     }
203     foreach my $value ( @extra_values ) {
204       $sth->bind_param($p_num++, $value);
205     }
206
207     $sth->execute or die $sth->errstr;
208
209   }
210   
211   if ( $opt_d ) {
212     my $file_timestamp = $filename.'-'.time2str('%Y-%m-%d', time);
213     if ( $opt_m eq 'ftp') {
214       my $ftp = ftp();
215       $ftp->rename($filename, "$opt_d/$file_timestamp")
216         or do {
217           unlink "$cachedir/$filename";
218           die "Can't move $filename to $opt_d: ".$ftp->message . "\n";
219         };
220     } else {
221       my $sftp = sftp();
222       $sftp->rename($filename, "$opt_d/$file_timestamp")
223         or do {
224           unlink "$cachedir/$filename";
225           die "can't move $filename to $opt_d: ". $sftp->error . "\n";
226         };
227     }
228   }
229
230   unlink "$cachedir/$filename";
231
232 }
233
234 ###
235 # subs
236 ###
237
238 sub usage {
239   "Usage:
240   aradial-sftp_and_import [ -m method ] [ -a ] [ -b ]
241     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
242     user [sftpuser@]servername dbi_datasrc dbi_username dbi_pass
243   ";
244 }
245
246 use vars qw( $sftp $ftp );
247
248 sub ftp {
249   return $ftp if $ftp && $ftp->pwd;
250   
251   my ($hostname, $userpass) = reverse split('@', $servername);
252   my ($ftp_user, $ftp_pass) = split(':', $userpass);
253
254   my $ftp = Net::FTP->new($hostname, %options) 
255     or die "FTP connection to '$hostname' failed.";
256   $ftp->login($ftp_user, $ftp_pass) or die "FTP login failed: ".$ftp->message;
257   $ftp->cwd($opt_r) or die "can't chdir to $opt_r\n" if $opt_r;
258   $ftp->binary or die "can't set BINARY mode: ". $ftp->message if $opt_b;
259   return $ftp;
260 }
261
262 sub sftp {
263
264   #reuse connections
265   return $sftp if $sftp && $sftp->cwd;
266
267   my %sftp = ( host => $servername );
268
269   $sftp = Net::SFTP::Foreign->new(%sftp);
270   $sftp->error and die "SFTP connection failed: ". $sftp->error;
271
272   $sftp;
273 }
274
275 =head1 NAME
276
277 freeside-aradial-sftp_and_import - Download Aradial "CDR" (really RADIUS detail) files from a remote server via SFTP
278
279 =head1 SYNOPSIS
280
281   aradial-sftp_and_import [ -m method ] [ -a ] [ -b ]
282     [ -r remotefolder ] [ -d donefolder ] [ -v level ] [ -P port ]
283     user [sftpuser@]servername dbi_datasrc dbi_username dbi_pass
284
285 =head1 DESCRIPTION
286
287 Command line tool to download CDR files from a remote server via SFTP 
288 or FTP and then import them into the database.
289
290 -m: transfer method (sftp or ftp), defaults to sftp
291
292 -a: use ftp passive mode
293
294 -b: use ftp binary mode
295
296 -r: if specified, changes into this remote folder before starting
297
298 -d: if specified, moves files to the specified folder when done
299
300 -P: if specified, sets the port to use
301
302 -v: set verbosity level; this script only has one level, but it will 
303     be passed as the 'debug' argument to the transport method
304
305 user: freeside username
306
307 [sftpuser@]servername: remote server
308 (or ftpuser:ftppass@servername)
309
310 =head1 BUGS
311
312 =head1 SEE ALSO
313
314 L<FS::cdr>
315
316 =cut
317
318 1;
319