doc
[icelog.git] / iceaccess_server
1 #!/usr/bin/perl -w
2 #
3 # Copyright (c) 2002 Ivan Kohler
4 # All rights reserved.
5 # This program is free software; you can redistribute it and/or modify it under
6 # the same terms as Perl itself.
7 #
8 # ivan-icelog@420.am
9
10 use strict;
11 use vars qw( $Debug $dsn $username $password );
12 use DBI;
13 use IO::Handle;
14 use Net::SSH qw(sshopen2);
15
16 $Debug = 0;
17
18 my $machine = shift or die &usage;
19 my $logfile = shift || '/var/log/icecast/access.log';
20 my $pos = shift || 0;
21
22 require "/etc/icelog.conf";
23
24 my $dbh = DBI->connect($dsn, $username, $password)
25   or die "Can't connect to $dsn: ". $DBI::errstr;
26
27 my $iceaccessd = '/usr/local/bin/iceaccessd';
28
29 my $me = "[iceaccess_server]";
30
31 #my $pos = 0;
32
33 while (1) {
34   my($reader, $writer) = (new IO::Handle, new IO::Handle);
35   $writer->autoflush(1);
36   warn "$me Connecting to $machine\n" if $Debug;
37   sshopen2($machine,$reader,$writer,$iceaccessd, $logfile, $pos);
38   warn "$me Entering main loop\n" if $Debug;
39   while (1) {
40     warn "$me Reading (waiting for) data\n" if $Debug;
41     my $line = scalar(<$reader>);
42     die "No response from remote iceaccessd process" unless defined($line);
43     chomp $line;
44     my %hash;
45     ( $pos, %hash ) = split(/\t/, $line);
46     if ( $pos eq 'EOF' ) { ; #re-open iceacceed process on new logfile
47       $pos = 0;
48       last;
49     }
50
51     #write to db
52
53     my $customer = $hash{mountpoint};
54     $hash{mountpoint} =~ /^\/([^\/]*)/
55       or die "weird mountpoint $hash{mountpoint}";
56     $customer = $1;
57
58     #$hash{mountpoint} =~ /\/|^([^\/]+)$/;
59     #my $file = $1;
60
61     my $liveflag;
62     if ( $hash{mountpoint} =~ /\/0+(\.\w+)?$/ ) {
63       $liveflag = 'Y';
64     } else {
65       $liveflag = 'N';
66     }
67
68     #switch to prepare_cached?
69     my $sth = $dbh->prepare(<<END) or die $dbh->errstr;
70       INSERT INTO icelog ( logdate, logmachine, logpos, customer, liveflag,
71                            hostname, start, mountpoint, bytes, useragent,
72                            seconds
73                          ) VALUES ( NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
74 END
75
76     $sth->execute(
77       $machine, #logmachine
78       $pos, #logpos
79       $customer, #customer
80       $liveflag, #liveflag
81       $hash{hostname}, #hostname
82       $hash{start}, #start
83       $hash{mountpoint}, #mountpoint
84       $hash{bytes}, #bytes
85       $hash{useragent}, #useragent,
86       $hash{seconds}, #seconds
87     ) or die $sth->errstr;
88     $sth->finish;
89
90   }
91   close $writer;
92   close $reader;
93   warn "connection to $machine lost!\n";
94   sleep 5;
95   warn "reconnecting...\n";
96 }
97
98
99
100
101 sub usage {
102   die "Usage:\n\n  iceaccess_server machine logfile position\n";
103 }