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