fix error messaging in DXUser::init
[spider.git] / perl / DXUser.pm
index 60d49eafe72e3d7b7f613f068f75cc132f273324..d2082d68954f0fa48923564dbf3755a8fabb6d45 100644 (file)
@@ -13,14 +13,17 @@ use DB_File;
 use Data::Dumper;
 use Fcntl;
 use IO::File;
-use DXDebug;
 use DXUtil;
 use LRU;
 use File::Copy;
+use JSON;
+use DXDebug;
+use Data::Structure::Util qw(unbless);
+       
 
 use strict;
 
-use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $v3);
+use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $v3 $v4);
 
 %u = ();
 $dbm = undef;
@@ -30,6 +33,10 @@ $lasttime = 0;
 $lrusize = 2000;
 $tooold = 86400 * 365;         # this marks an old user who hasn't given enough info to be useful
 $v3 = 0;
+$v4 = 0;
+my $json;
+
+our $maxconnlist = 3;                  # remember this many connection time (duration) [start, end] pairs
 
 # hash of valid elements and a simple prompt
 %valid = (
@@ -91,6 +98,8 @@ $v3 = 0;
                  believe => '1,Believable nodes,parray',
                  lastping => '1,Last Ping at,ptimelist',
                  maxconnect => '1,Max Connections',
+                 startt => '0,Start Time,cldatetime',
+                 connlist => '1,Connections,parraydifft',
                 );
 
 #no strict;
@@ -121,30 +130,36 @@ sub init
        my $ufn;
        my $convert;
        
-       eval {
-               require Storable;
-       };
-
        my $fn = "users";
-       
-       if ($@) {
-               $ufn = localdata("users.v2");
-               $v3 = $convert = 0;
-               dbg("the module Storable appears to be missing!!");
-               dbg("trying to continue in compatibility mode (this may fail)");
-               dbg("please install Storable from CPAN as soon as possible");
-       } else {
-               import Storable qw(nfreeze thaw);
 
-               $ufn = localdata("users.v3");
-               $v3 = 1;
-               $convert++ if -e localdata("users.v2") && !-e $ufn;
+       if ($mode == 4 || -e localdata("users.v4")) {
+               $ufn = localdata("users.v4");
+               $v4 = 1;
+               $json = JSON->new();
+               $json->canonical(1);
+       } else {
+               eval {
+                       require Storable;
+               };
+               if ($@) {
+                       $ufn = localdata("users.v2");
+                       $v3 = $convert = 0;
+                       dbg("the module Storable appears to be missing!!");
+                       dbg("trying to continue in compatibility mode (this may fail)");
+                       dbg("please install Storable from CPAN as soon as possible");
+               }
+               else {
+                       import Storable qw(nfreeze thaw);
+                       $ufn = localdata("users.v3");
+                       $v3 = 1;
+                       $convert++ if -e localdata("users.v2") && !-e $ufn;
+               }
        }
        
        if ($mode) {
-               $dbm = tie (%u, 'DB_File', $ufn, O_CREAT|O_RDWR, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
+               $dbm = tie (%u, 'DB_File', $ufn, O_CREAT|O_RDWR, 0666, $DB_BTREE) or confess "can't open user file: $ufn ($!) [rebuild it from user_asc?]";
        } else {
-               $dbm = tie (%u, 'DB_File', $ufn, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_asc?]";
+               $dbm = tie (%u, 'DB_File', $ufn, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $ufn ($!) [rebuild it from user_asc?]";
        }
 
        die "Cannot open $ufn ($!)\n" unless $dbm;
@@ -156,16 +171,21 @@ sub init
                my ($key, $val, $action, $count, $err) = ('','',0,0,0);
                
                my %oldu;
-               dbg("Converting the User File to V3 ");
+               dbg("Converting the User File to V$convert ");
                dbg("This will take a while, I suggest you go and have cup of strong tea");
                my $odbm = tie (%oldu, 'DB_File', localdata("users.v2"), O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn.v2 ($!) [rebuild it from user_asc?]";
         for ($action = R_FIRST; !$odbm->seq($key, $val, $action); $action = R_NEXT) {
-                       my $ref = asc_decode($val);
-                       if ($ref) {
-                               $ref->put;
-                               $count++;
+                       my $ref;
+                       eval { $ref = asc_decode($val) };
+                       unless ($@) {
+                               if ($ref) {
+                                       $ref->put;
+                                       $count++;
+                               } else {
+                                       $err++
+                               }
                        } else {
-                               $err++
+                               Log('err', "DXUser: error decoding $@");
                        }
                } 
                undef $odbm;
@@ -177,9 +197,15 @@ sub init
 
 sub del_file
 {
-       my $fn = localdata("users");
-       $fn .= $v3 ? ".v3" : ".v2";
-       unlink $fn;
+       # with extreme prejudice
+       if ($v3) {
+               unlink "$main::data/users.v3";
+               unlink "$main::local_data/users.v3";
+       }
+       if ($v4) {
+               unlink "$main::data/users.v4";
+               unlink "$main::local_data/users.v4";
+       }
 }
 
 #
@@ -244,7 +270,8 @@ sub get
        
        # search for it
        unless ($dbm->get($call, $data)) {
-               $ref = decode($data);
+               eval { $ref = decode($data); };
+               
                if ($ref) {
                        if (!UNIVERSAL::isa($ref, 'DXUser')) {
                                dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
@@ -252,7 +279,11 @@ sub get
                        }
                        # we have a reference and it *is* a DXUser
                } else {
-                       dbg("DXUser::get: no reference returned from decode of $call $!");
+                       if ($@) {
+                               LogDbg('err', "DXUser::get decode error on $call '$@'");
+                       } else {
+                               dbg("DXUser::get: no reference returned from decode of $call $!");
+                       }
                        return undef;
                }
                $lru->put($call, $ref);
@@ -314,6 +345,7 @@ sub put
 # freeze the user
 sub encode
 {
+       goto &json_encode if $v4;
        goto &asc_encode unless $v3;
        my $self = shift;
        return nfreeze($self);
@@ -322,8 +354,11 @@ sub encode
 # thaw the user
 sub decode
 {
+       goto &json_decode if $v4;
        goto &asc_decode unless $v3;
-       return thaw(shift);
+       my $ref;
+       $ref = thaw(shift);
+       return $ref;
 }
 
 # 
@@ -358,12 +393,34 @@ sub asc_decode
        $s =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
        eval '$ref = ' . $s;
        if ($@) {
-               LogDbg('err', $@);
+               LogDbg('err', "DXUser::asc_decode: on '$s' $@");
                $ref = undef;
        }
        return $ref;
 }
 
+sub json_decode
+{
+       my $s = shift;
+    my $ref;
+       eval { $ref = $json->decode($s) };
+       if ($ref && !$@) {
+        return bless $ref, 'DXUser';
+       } else {
+               LogDbg('err', "DXUser::json_decode: on '$s' $@");
+       }
+       return undef;
+}
+
+sub json_encode
+{
+       my $ref = shift;
+       unbless($ref);
+    my $s = $json->encode($ref);
+       bless $ref, 'DXUser';
+       return $s;
+}
+       
 #
 # del - delete a user
 #
@@ -383,7 +440,14 @@ sub del
 sub close
 {
        my $self = shift;
-       $self->{lastin} = time;
+       my $startt = shift;
+       my $ip = shift;
+       $self->{lastin} = $main::systime;
+       # add a record to the connect list
+       my $ref = [$startt || $self->{startt}, $main::systime];
+       push @$ref, $ip if $ip;
+       push @{$self->{connlist}}, $ref;
+       shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
        $self->put();
 }
 
@@ -412,10 +476,10 @@ sub fields
 
 sub export
 {
-       my $name = shift;
+       my $name = shift || 'user_asc';
        my $basic_info_only = shift;
 
-       my $fn = "$main::local_data/$name";
+       my $fn = $name ne 'user_asc' ? $name : "$main::local_data/$name";                       # force use of local
        
        # save old ones
        move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
@@ -466,8 +530,6 @@ BEGIN {
        }
 }
 
-package DXUser;
-
 use SysVar;
 use DXUser;
 
@@ -476,8 +538,10 @@ if (@ARGV) {
        print "user filename now $userfn\n";
 }
 
-DXUser::del_file();
-DXUser::init();
+package DXUser;
+
+del_file();
+init(1);
 %u = ();
 my $count = 0;
 my $err = 0;
@@ -488,12 +552,13 @@ while (<DATA>) {
        if ($ref) {
                $ref->put();
                $count++;
+        DXUser::sync() unless $count % 10000;
        } else {
                print "# Error: $f[0]\t$f[1]\n";
                $err++
        }
 }
-DXUser::sync; DXUser::finish;
+DXUser::sync(); DXUser::finish();
 print "There are $count user records and $err errors\n";
 };
                print $fh "__DATA__\n";
@@ -510,7 +575,8 @@ print "There are $count user records and $err errors\n";
                                ++$err;
                                next;
                        }
-                       my $ref = decode($val);
+                       my $ref;
+                       eval {$ref = decode($val); };
                        if ($ref) {
                                my $t = $ref->{lastin} || 0;
                                if ($ref->is_user && !$ref->{priv} && $main::systime > $t + $tooold) {
@@ -526,15 +592,158 @@ print "There are $count user records and $err errors\n";
                                print $fh "$key\t" . $ref->asc_encode($basic_info_only) . "\n";
                                ++$count;
                        } else {
-                               LogDbg('DXCommand', "Export Error3: $key\t$val");
+                               LogDbg('DXCommand', "Export Error3: $key\t" . carp($val) ."\n$@");
+                               eval {$dbm->del($key)};
+                               dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
+                               ++$err;
+                       }
+               } 
+        $fh->close;
+    }
+       my $s = qq{Exported users to $fn - $count Users $del Deleted $err Errors ('sh/log Export' for details)};
+       LogDbg('command', $s);
+       return $s;
+}
+
+sub export_json
+{
+       my $name = shift || 'user_json';
+       my $basic_info_only = shift;
+
+       my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name";                       # force use of local
+       
+       # save old ones
+       move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
+       move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
+       move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
+       move "$fn.o", "$fn.oo" if -e "$fn.o";
+       move "$fn", "$fn.o" if -e "$fn";
+
+       my $json = JSON->new;
+       $json->canonical(1);
+       $json->allow_blessed(1);
+       
+       my $count = 0;
+       my $err = 0;
+       my $del = 0;
+       my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
+       if ($fh) {
+               my $key = 0;
+               my $val = undef;
+               my $action;
+               my $t = scalar localtime;
+               print $fh q{#!/usr/bin/perl
+#
+# The exported userfile for a DXSpider System
+#
+# Input file: $filename
+#       Time: $t
+#
+                       
+package main;
+                       
+# search local then perl directories
+BEGIN {
+       umask 002;
+                               
+       # root of directory tree for this system
+       $root = "/spider"; 
+       $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
+       
+       unshift @INC, "$root/perl";     # this IS the right way round!
+       unshift @INC, "$root/local";
+       
+       # try to detect a lockfile (this isn't atomic but 
+       # should do for now
+       $lockfn = "$root/local_data/cluster.lck";       # lock file name
+       if (-e $lockfn) {
+               open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
+               my $pid = <CLLOCK>;
+               chomp $pid;
+               die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
+               close CLLOCK;
+       }
+}
+
+use SysVar;
+use DXUser;
+
+if (@ARGV) {
+       $main::userfn = shift @ARGV;
+       print "user filename now $userfn\n";
+}
+
+package DXUser;
+
+use JSON;
+my $json = JSON->new;
+
+del_file();
+init(4);
+%u = ();
+my $count = 0;
+my $err = 0;
+while (<DATA>) {
+       chomp;
+       my @f = split /\t/;
+       my $ref;
+    eval { $ref = $json->decode($f[1]); };
+       if ($ref && !$@) {
+        $ref = bless $ref, 'DXUser';
+               $ref->put();
+               $count++;
+        DXUser::sync() unless $count % 10000;
+       } else {
+               print "# Error: $f[0]\t$f[1]\n";
+               $err++
+       }
+}
+DXUser::sync(); DXUser::finish();
+print "There are $count user records and $err errors\n";
+};
+               print $fh "__DATA__\n";
+
+        for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
+                       if (!is_callsign($key) || $key =~ /^0/) {
+                               my $eval = $val;
+                               my $ekey = $key;
+                               $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
+                               $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
+                               LogDbg('DXCommand', "Export Error1: $ekey\t$eval");
+                               eval {$dbm->del($key)};
+                               dbg(carp("Export Error1: $ekey\t$eval\n$@")) if $@;
+                               ++$err;
+                               next;
+                       }
+                       my $ref;
+                       eval {$ref = decode($val); };
+                       if ($ref) {
+                               my $t = $ref->{lastin} || 0;
+                               if ($ref->is_user && !$ref->{priv} && $main::systime > $t + $tooold) {
+                                       unless ($ref->{lat} && $ref->{long} || $ref->{qth} || $ref->{qra}) {
+                                               eval {$dbm->del($key)};
+                                               dbg(carp("Export Error2: $key\t$val\n$@")) if $@;
+                                               LogDbg('DXCommand', "$ref->{call} deleted, too old");
+                                               $del++;
+                                               next;
+                                       }
+                               }
+                               # only store users that are reasonably active or have useful information
+                               unbless($ref);
+                               print $fh "$key\t" . $json->encode($ref) . "\n";
+                               ++$count;
+                       } else {
+                               LogDbg('DXCommand', "Export Error3: $key\t" . carp($val) ."\n$@");
                                eval {$dbm->del($key)};
                                dbg(carp("Export Error3: $key\t$val\n$@")) if $@;
                                ++$err;
                        }
                } 
         $fh->close;
-    } 
-       return "$count Users $del Deleted $err Errors ('sh/log Export' for details)";
+    }
+       my $s = qq{Exported users to $fn - $count Users $del Deleted $err Errors ('sh/log Export' for details)};
+       LogDbg('command', $s);
+       return $s;
 }
 
 #