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