dd35c5e7aeeb268bbcc1706feb5a06ff2cc0a876
[spider.git] / perl / DXUser.pm
1 #
2 # DX cluster user routines
3 #
4 # Copyright (c) 1998 - Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package DXUser;
10
11 use DXLog;
12 use DB_File;
13 use Data::Dumper;
14 use Fcntl;
15 use IO::File;
16 use DXDebug;
17 use DXUtil;
18 use LRU;
19 use File::Copy;
20 use Data::Structure::Util qw(unbless);
21 use Time::HiRes qw(gettimeofday tv_interval);
22 use IO::File;
23 use DXChannel;
24 use DXJSON;
25
26 use strict;
27
28 use vars qw(%u $dbm $filename %valid $lastoperinterval $lasttime $lru $lrusize $tooold $veryold $v3);
29
30 %u = ();
31 $dbm = undef;
32 $filename = undef;
33 $lastoperinterval = 60*24*60*60;
34 $lasttime = 0;
35 $lrusize = 5000;
36 $tooold = 86400 * 365 * 2;              # this marks an old user who hasn't given enough info to be useful
37 $veryold = $tooold * 6;         # Ancient default 12 years
38 $v3 = 0;
39 our $maxconnlist = 3;                   # remember this many connection time (duration) [start, end] pairs
40
41 my $json;
42
43 # hash of valid elements and a simple prompt
44 %valid = (
45                   'sort' => '0,Type of User', # A - ak1a, U - User, S - spider cluster, B - BBS
46                   addr => '0,Full Address',
47                   alias => '0,Real Callsign',
48                   annok => '9,Accept Announces?,yesno', # accept his announces?
49                   bbs => '0,Home BBS',
50                   believe => '1,Believable nodes,parray',
51                   buddies => '0,Buddies,parray',
52                   build => '1,Build',
53                   call => '0,Callsign',
54                   connlist => '1,Connections,parraydifft',
55                   dxok => '9,Accept DX Spots?,yesno', # accept his dx spots?
56                   email => '0,E-mail Address,parray',
57                   group => '0,Group,parray',    # used to create a group of users/nodes for some purpose or other
58                   hmsgno => '0,Highest Msgno',
59                   homenode => '0,Home Node',
60                   isolate => '9,Isolate network,yesno',
61                   K => '9,Seen on PC92 K,yesno',
62                   lang => '0,Language',
63                   lastin => '0,Last Time in,cldatetime',
64                   lastoper => '9,Last for/oper,cldatetime',
65                   lastping => '1,Last Ping at,ptimelist',
66                   lastseen => '0,Last Seen,cldatetime',
67                   lat => '0,Latitude,slat',
68                   lockout => '9,Locked out?,yesno',     # won't let them in at all
69                   long => '0,Longitude,slong',
70                   maxconnect => '1,Max Connections',
71                   name => '0,Name',
72                   node => '0,Last Node',
73                   nopings => '9,Ping Obs Count',
74                   nothere => '0,Not Here Text',
75                   pagelth => '0,Current Pagelth',
76                   passphrase => '9,Pass Phrase,yesno',
77                   passwd => '9,Password,yesno',
78                   pingint => '9,Node Ping interval',
79                   priv => '9,Privilege Level',
80                   prompt => '0,Required Prompt',
81                   qra => '0,Locator',
82                   qth => '0,Home QTH',
83                   rbnseeme => '0,RBN See Me',
84                   registered => '9,Registered?,yesno',
85                   startt => '0,Start Time,cldatetime',
86                   version => '1,Version',
87                   wantann => '0,Req Announce,yesno',
88                   wantann_talk => '0,Talklike Anns,yesno',
89                   wantbeacon => '0,Want RBN Beacon,yesno',
90                   wantbeep => '0,Req Beep,yesno',
91                   wantcw => '0,Want RBN CW,yesno',
92                   wantdx => '0,Req DX Spots,yesno',
93                   wantdxcq => '0,Show CQ Zone,yesno',
94                   wantdxitu => '0,Show ITU Zone,yesno',
95                   wantecho => '0,Req Echo,yesno',
96                   wantemail => '0,Req Msgs as Email,yesno',
97                   wantft => '0,Want RBN FT4/8,yesno',
98                   wantgtk => '0,Want GTK interface,yesno',
99                   wantlogininfo => '0,Login Info Req,yesno',
100                   wantpc16 => '9,Want Users from node,yesno',
101                   wantpc9x => '0,Want PC9X interface,yesno',
102                   wantpsk => '0,Want RBN PSK,yesno',
103                   wantrbn => '0,Want RBN spots,yesno',
104                   wantroutepc19 => '9,Route PC19,yesno',
105                   wantrtty => '0,Want RBN RTTY,yesno',
106                   wantsendpc16 => '9,Send PC16,yesno',
107                   wanttalk => '0,Req Talk,yesno',
108                   wantusstate => '0,Show US State,yesno',
109                   wantwcy => '0,Req WCY,yesno',
110                   wantwwv => '0,Req WWV,yesno',
111                   wantwx => '0,Req WX,yesno',
112                   width => '0,Preferred Width',
113                   xpert => '0,Expert Status,yesno',
114           wantgrid => '0,Show DX Grid,yesno',
115                  );
116
117 #no strict;
118 sub AUTOLOAD
119 {
120         no strict;
121         my $name = $AUTOLOAD;
122   
123         return if $name =~ /::DESTROY$/;
124         $name =~ s/^.*:://o;
125   
126         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
127         # this clever line of code creates a subroutine which takes over from autoload
128         # from OO Perl - Conway
129         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
130        goto &$AUTOLOAD;
131 }
132
133 #use strict;
134
135 #
136 # initialise the system
137 #
138 sub init
139 {
140         my $mode = shift;
141   
142         $json = DXJSON->new->canonical(1);
143         my $fn = "users";
144         $filename = localdata("$fn.v3j");
145         unless (-e $filename || $mode == 2 ) {
146                 if (-e localdata("$fn.v3") || -e localdata("$fn.v2")) {
147                         LogDbg('DXUser', "New User File version $filename does not exist, running conversion from users.v3 or v2, please wait");
148                         system('/spider/perl/convert-users-v3-to-v3j.pl');
149                         init(1);
150                         export();
151                         return;
152                 }
153         }
154         if (-e $filename || $mode) {
155                 $lru = LRU->newbase("DXUser", $lrusize);
156                 if ($mode) {
157                         $dbm = tie (%u, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_json?]";
158                 } else {
159                         $dbm = tie (%u, 'DB_File', $filename, O_RDONLY, 0666, $DB_BTREE) or confess "can't open user file: $fn ($!) [rebuild it from user_json?]";
160                 }
161         }
162         die "Cannot open $filename ($!)\n" unless $dbm || $mode == 2;
163         return;
164 }
165
166 # delete files with extreme prejudice
167 sub del_file
168 {
169         # with extreme prejudice
170         unlink "$main::data/users.v3j";
171         unlink "$main::local_data/users.v3j";
172 }
173
174 #
175 # periodic processing
176 #
177 sub process
178 {
179         if ($main::systime > $lasttime + 15) {
180                 $dbm->sync if $dbm;
181                 $lasttime = $main::systime;
182         }
183 }
184
185 #
186 # close the system
187 #
188
189 sub finish
190 {
191         $dbm->sync;
192         undef $dbm;
193         untie %u;
194 }
195
196 #
197 # new - create a new user
198 #
199
200 sub alloc
201 {
202         my $pkg = shift;
203         my $call = uc shift;
204         my $self = bless {call => $call, 'sort'=>'U'}, $pkg;
205         return $self;
206 }
207
208 sub new
209 {
210         my $pkg = shift;
211         my $call = shift;
212         #  $call =~ s/-\d+$//o;
213   
214 #       confess "can't create existing call $call in User\n!" if $u{$call};
215
216         my $self = $pkg->alloc($call);
217         $self->put;
218         return $self;
219 }
220
221 #
222 # get - get an existing user - this seems to return a different reference everytime it is
223 #       called - see below
224 #
225
226 sub get
227 {
228         my $call = uc shift;
229         my $data;
230         
231         # is it in the LRU cache?
232         my $ref = $lru->get($call);
233         if ($ref && ref $ref eq 'DXUser') {
234                 return $ref;
235         }
236         
237         # search for it
238         unless ($dbm->get($call, $data)) {
239                 eval { $ref = decode($data); };
240                 if ($ref) {
241                         if (!UNIVERSAL::isa($ref, 'DXUser')) {
242                                 dbg("DXUser::get: got strange answer from decode of $call". ref $ref. " ignoring");
243                                 return undef;
244                         }
245                         # we have a reference and it *is* a DXUser
246                 } else {
247                         if ($@) {
248                                 LogDbg('err', "DXUser::get decode error on $call '$@'");
249                         } else {
250                                 dbg("DXUser::get: no reference returned from decode of $call $!");
251                         }
252                         return undef;
253                 }
254                 $lru->put($call, $ref);
255                 return $ref;
256         }
257         return undef;
258 }
259
260 #
261 # get an existing either from the channel (if there is one) or from the database
262 #
263 # It is important to note that if you have done a get (for the channel say) and you
264 # want access or modify that you must use this call (and you must NOT use get's all
265 # over the place willy nilly!)
266 #
267
268 sub get_current
269 {
270         my $call = uc shift;
271   
272         my $dxchan = DXChannel::get($call);
273         if ($dxchan) {
274                 my $ref = $dxchan->user;
275                 return $ref if $ref && UNIVERSAL::isa($ref, 'DXUser');
276
277                 dbg("DXUser::get_current: got invalid user ref for $call from dxchan $dxchan->{call} ". ref $ref. " ignoring");
278         }
279         return get($call);
280 }
281
282 #
283 # get all callsigns in the database 
284 #
285
286 sub get_all_calls
287 {
288         return (sort keys %u);
289 }
290
291 #
292 # put - put a user
293 #
294
295 sub put
296 {
297         my $self = shift;
298         confess "Trying to put nothing!" unless $self && ref $self;
299         my $call = $self->{call};
300
301         $dbm->del($call);
302         delete $self->{annok};
303         delete $self->{dxok};
304         $self->{lastseen} = $main::systime;
305         $lru->put($call, $self);
306         my $ref = $self->encode;
307         $dbm->put($call, $ref);
308         DXChannel::refresh_user($call, $ref);
309         return $ref;
310 }
311
312
313 # thaw the user
314 sub decode
315 {
316         return $json->decode(shift, __PACKAGE__);
317 }
318
319 # freeze the user
320 sub encode
321 {
322         return $json->encode(shift);
323 }
324
325
326 #
327 # del - delete a user
328 #
329
330 sub del
331 {
332         my $self = shift;
333         my $call = $self->{call};
334         $lru->remove($call);
335         $dbm->del($call);
336 }
337
338 #
339 # close - close down a user
340 #
341
342 sub close
343 {
344         my $self = shift;
345         my $startt = shift;
346         my $ip = shift;
347         # add a record to the connect list
348         $self->{lastin} = $main::systime;
349         my $ref = [$startt || $self->{startt}, $main::systime];
350         push @$ref, $ip if $ip;
351         push @{$self->{connlist}}, $ref;
352         shift @{$self->{connlist}} if @{$self->{connlist}} > $maxconnlist;
353         $self->put();
354 }
355
356 #
357 # sync the database
358 #
359
360 sub sync
361 {
362         $dbm->sync;
363 }
364
365 #
366 # return a list of valid elements 
367
368
369 sub fields
370 {
371         return keys(%valid);
372 }
373
374
375 #
376 # group handling
377 #
378
379 # add one or more groups
380 sub add_group
381 {
382         my $self = shift;
383         my $ref = $self->{group} || [ 'local' ];
384         $self->{group} = $ref if !$self->{group};
385         push @$ref, @_ if @_;
386 }
387
388 # remove one or more groups
389 sub del_group
390 {
391         my $self = shift;
392         my $ref = $self->{group} || [ 'local' ];
393         my @in = @_;
394         
395         $self->{group} = $ref if !$self->{group};
396         
397         @$ref = map { my $a = $_; return (grep { $_ eq $a } @in) ? () : $a } @$ref;
398 }
399
400 # does this thing contain all the groups listed?
401 sub union
402 {
403         my $self = shift;
404         my $ref = $self->{group};
405         my $n;
406         
407         return 0 if !$ref || @_ == 0;
408         return 1 if @$ref == 0 && @_ == 0;
409         for ($n = 0; $n < @_; ) {
410                 for (@$ref) {
411                         my $a = $_;
412                         $n++ if grep $_ eq $a, @_; 
413                 }
414         }
415         return $n >= @_;
416 }
417
418 # simplified group test just for one group
419 sub in_group
420 {
421         my $self = shift;
422         my $s = shift;
423         my $ref = $self->{group};
424         
425         return 0 if !$ref;
426         return grep $_ eq $s, $ref;
427 }
428
429 # set up a default group (only happens for them's that connect direct)
430 sub new_group
431 {
432         my $self = shift;
433         $self->{group} = [ 'local' ];
434 }
435
436 # set up empty buddies (only happens for them's that connect direct)
437 sub new_buddies
438 {
439         my $self = shift;
440         $self->{buddies} = [  ];
441 }
442
443 #
444 # return a prompt for a field
445 #
446
447 sub field_prompt
448
449         my ($self, $ele) = @_;
450         return $valid{$ele};
451 }
452
453 # some variable accessors
454 sub sort
455 {
456         my $self = shift;
457         @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
458 }
459
460 # some accessors
461
462 # want is default = 1
463 sub _want
464 {
465         my $n = shift;
466         my $self = shift;
467         my $val = shift;
468         my $s = "want$n";
469         $self->{$s} = $val if defined $val;
470         return exists $self->{$s} ? $self->{$s} : 1;
471 }
472
473 # wantnot is default = 0
474 sub _wantnot
475 {
476         my $n = shift;
477         my $self = shift;
478         my $val = shift;
479         my $s = "want$n";
480         $self->{$s} = $val if defined $val;
481         return exists $self->{$s} ? $self->{$s} : 0;
482 }
483
484 sub wantbeep
485 {
486         return _want('beep', @_);
487 }
488
489 sub wantann
490 {
491         return _want('ann', @_);
492 }
493
494 sub wantwwv
495 {
496         return _want('wwv', @_);
497 }
498
499 sub wantwcy
500 {
501         return _want('wcy', @_);
502 }
503
504 sub wantecho
505 {
506         return _want('echo', @_);
507 }
508
509 sub wantwx
510 {
511         return _want('wx', @_);
512 }
513
514 sub wantdx
515 {
516         return _want('dx', @_);
517 }
518
519 sub wanttalk
520 {
521         return _want('talk', @_);
522 }
523
524 sub wantgrid
525 {
526         return _wantnot('grid', @_);
527 }
528
529 sub wantemail
530 {
531         return _want('email', @_);
532 }
533
534 sub wantann_talk
535 {
536         return _want('ann_talk', @_);
537 }
538
539 sub wantpc16
540 {
541         return _want('pc16', @_);
542 }
543
544 sub wantsendpc16
545 {
546         return _want('sendpc16', @_);
547 }
548
549 sub wantroutepc16
550 {
551         return _want('routepc16', @_);
552 }
553
554 sub wantusstate
555 {
556         return _want('usstate', @_);
557 }
558
559 sub wantdxcq
560 {
561         return _wantnot('dxcq', @_);
562 }
563
564 sub wantdxitu
565 {
566         return _wantnot('dxitu', @_);
567 }
568
569 sub wantgtk
570 {
571         return _want('gtk', @_);
572 }
573
574 sub wantpc9x
575 {
576         return _want('pc9x', @_);
577 }
578
579 sub wantlogininfo
580 {
581         my $self = shift;
582         my $val = shift;
583         $self->{wantlogininfo} = $val if defined $val;
584         return $self->{wantlogininfo};
585 }
586
587 sub is_node
588 {
589         my $self = shift;
590         return $self->{sort} =~ /^[ACRSX]$/;
591 }
592
593 sub is_local_node
594 {
595         my $self = shift;
596         return grep $_ eq 'local_node', @{$self->{group}};
597 }
598
599 sub is_user
600 {
601         my $self = shift;
602         return $self->{sort} =~ /^[UW]$/;
603 }
604
605 sub is_web
606 {
607         my $self = shift;
608         return $self->{sort} eq 'W';
609 }
610
611 sub is_bbs
612 {
613         my $self = shift;
614         return $self->{sort} eq 'B';
615 }
616
617 sub is_spider
618 {
619         my $self = shift;
620         return $self->{sort} eq 'S';
621 }
622
623 sub is_clx
624 {
625         my $self = shift;
626         return $self->{sort} eq 'C';
627 }
628
629 sub is_dxnet
630 {
631         my $self = shift;
632         return $self->{sort} eq 'X';
633 }
634
635 sub is_arcluster
636 {
637         my $self = shift;
638         return $self->{sort} eq 'R';
639 }
640
641 sub is_ak1a
642 {
643         my $self = shift;
644         return $self->{sort} eq 'A';
645 }
646
647 sub is_rbn
648 {
649         my $self = shift;
650         return $self->{sort} eq 'N'
651 }
652
653 sub unset_passwd
654 {
655         my $self = shift;
656         delete $self->{passwd};
657 }
658
659 sub unset_passphrase
660 {
661         my $self = shift;
662         delete $self->{passphrase};
663 }
664
665 sub set_believe
666 {
667         my $self = shift;
668         my $call = uc shift;
669         $self->{believe} ||= [];
670         push @{$self->{believe}}, $call unless grep $_ eq $call, @{$self->{believe}};
671 }
672
673 sub unset_believe
674 {
675         my $self = shift;
676         my $call = uc shift;
677         if (exists $self->{believe}) {
678                 $self->{believe} = [grep {$_ ne $call} @{$self->{believe}}];
679                 delete $self->{believe} unless @{$self->{believe}};
680         }
681 }
682
683 sub believe
684 {
685         my $self = shift;
686         return exists $self->{believe} ? @{$self->{believe}} : ();
687 }
688
689 sub lastping
690 {
691         my $self = shift;
692         my $call = shift;
693         $self->{lastping} ||= {};
694         $self->{lastping} = {} unless ref $self->{lastping};
695         my $b = $self->{lastping};
696         $b->{$call} = shift if @_;
697         return $b->{$call};     
698 }
699
700
701 #
702 # export the database to an ascii file
703 #
704
705 sub export
706 {
707         my $name = shift || 'user_json';
708
709         my $fn = $name ne 'user_json' ? $name : "$main::local_data/$name";                       # force use of local
710         
711         # save old ones
712         copy $fn, "$fn.keep" unless -e "$fn.keep";
713         copy "$fn.ooooo", "$fn.backstop" unless -e "$fn,backstop";
714
715         move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
716         move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
717         move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
718         move "$fn.o", "$fn.oo" if -e "$fn.o";
719         move "$fn", "$fn.o" if -e "$fn";
720
721         
722         my $ta = [gettimeofday];
723         my $count = 0;
724         my $err = 0;
725         my $del = 0;
726         my $spurious = 0;
727         my $unlocked = 0;
728         my $old =  0;
729         my $ancient =  0;
730         my $nodes = 0;
731         my $renamed = 0;
732
733         my %del;
734         
735         my $fh = new IO::File ">$fn" or return "cannot open $fn ($!)";
736         if ($fh) {
737                 my $key = 0;
738                 my $val = undef;
739                 my $action;
740                 my $t = scalar localtime;
741                 print $fh export_preamble();
742                 
743
744         for ($action = R_FIRST; !$dbm->seq($key, $val, $action); $action = R_NEXT) {
745                         if (!is_callsign($key) || $key =~ /^0/) {
746                                 my $eval = $val;
747                                 my $ekey = $key;
748                                 $eval =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
749                                 $ekey =~ s/([\%\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg;
750                                 LogDbg('DXCommand', "Export Error1: invalid call '$key' => '$val'");
751
752                                 $del{$key} = $val;
753                                 ++$err;
754                                 next;
755                         }
756                         my $ref;
757                         eval {$ref = decode($val); };
758                         if ($ref) {
759                                 my $t = $ref->{lastseen} if exists $ref->{lastseen};
760                                 $t ||= $ref->{lastin} if exists $ref->{lastin};
761                                 $t ||= $ref->{lastoper} if exists $ref->{lastoper};
762                                 $t //= 0;
763                                 
764                                 if ($ref->is_user) {
765                                         if (!$ref->{priv} && $main::systime > $t + $tooold) {
766                                                 unless (($ref->{lat} && $ref->{long}) || $ref->{qth} || $ref->{name} || $ref->{qra}) {
767                                                         LogDbg('DXCommand', sprintf("$ref->{call} deleted, empty and too Old at %s", difft($t, ' ')));
768                                                         ++$del;
769                                                         ++$old;
770                                                         $del{$key} = $val;
771                                                         next;
772                                                 }
773                                         }
774                                         if ($main::systime > $t + $veryold) {
775                                                 LogDbg('DXCommand', sprintf("$ref->{call} deleted, POSITIVELY ANCIENT at %s", difft($t, ' ')));
776                                                 ++$del;
777                                                 ++$ancient;
778                                                 $del{$key} = $val;
779                                                 next;
780                                         }
781                                         if (exists $ref->{lockout} && $ref->{lockout} == 1 && exists $ref->{priv} && $ref->{priv} == 1) {
782                                                 LogDbg('DXCommand', "$ref->{call} depriv'd and unlocked");
783                                                 $ref->{lockout} = $ref->{priv} = 0;
784                                                 $ref->put;
785                                                 ++$unlocked;
786                                         }
787                                         if ($ref->is_node && $main::systime > $t + $veryold) {
788                                                 LogDbg('DXCommand', sprintf("NODE $ref->{call} deleted (%s) old", difft($t, ' ')));
789                                                 ++$del;
790                                                 ++$nodes;
791                                                 $del{$key} = $val;
792                                                 next;
793                                         }
794                                         
795                                         my $normcall = normalise_call($key);
796                                         if ($normcall ne $key) {
797                                                 # if the normalised call does not exist, create it from the duff call.
798                                                 my $nref = DXUser::get_current($normcall);
799                                                 unless ($nref) {
800                                                         $ref->{call} = $normcall;
801                                                         $ref->put;
802                                                         LogDbg('DXCommand', "DXProt: spurious call $key normalises to $normcall renaming $key -> $normcall");
803                                                         ++$renamed;
804                                                 } 
805                                                 LogDbg('DXCommand', "DXProt: spurious call $key (should be $normcall), removing");
806                                                 $del{$key} = $val;
807                                                 ++$spurious;
808                                                 ++$del;
809                                                 next;
810                                         }
811                                 }
812                         } else {
813                                 LogDbg('DXCommand', "Export Error3: '$key'\t" . carp($val) ."\n$@");
814                                 $del{$key} = $val;
815                                 ++$err;
816                                 next;
817                         }
818                         
819                         # only store users that are reasonably active or have useful information
820                         print $fh "$key\t" . encode($ref) . "\n";
821                         ++$count;
822                 }
823         } 
824         $fh->close;
825         
826         while (my ($k, $v) = each %del) {
827                 eval {$dbm->del($k)};
828                 LogDbg('DXCommand', "Error deleting key: $k value: $v error: $@") if $@;
829         }
830
831         my $diff = _diffms($ta);
832         my $s = qq{Exported users to $fn - $count Users,  $del Deleted ($old empty \& too old, $ancient ancient, $nodes nodes, $spurious spurious), $renamed renamed, $unlocked Unlocked, $err Errors in $diff mS ('sh/log Export' for details)};
833         LogDbg('command', $s);
834         return ($s);
835 }
836
837 sub export_preamble
838 {
839         return q{#!/usr/bin/perl
840 #
841 # The exported userfile for a DXSpider System
842 #
843 # Input file: $filename
844 #       Time: $t
845 #
846                         
847 package main;
848                         
849 # search local then perl directories
850 BEGIN {
851         umask 002;
852                                 
853         # root of directory tree for this system
854         $root = "/spider"; 
855         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
856         
857         unshift @INC, "$root/perl";     # this IS the right way round!
858         unshift @INC, "$root/local";
859         
860         # try to detect a lockfile (this isn't atomic but 
861         # should do for now
862         $lockfn = "$root/local_data/cluster.lck";       # lock file name
863         if (-e $lockfn) {
864                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
865                 my $pid = <CLLOCK>;
866                 chomp $pid;
867                 die "Lockfile ($lockfn) and process $pid exists - cluster must be stopped first\n" if kill 0, $pid;
868                 close CLLOCK;
869         }
870 }
871
872 use SysVar;
873 use DXUtil;
874 use DXUser;
875 use DXChannel;
876 use JSON;
877 use Time::HiRes qw(gettimeofday tv_interval);
878 package DXUser;
879
880 our $json = JSON->new->canonical(1);
881
882 my $ta = [gettimeofday];
883 our $filename = "$main::local_data/users.v3j";
884 my $exists = -e $filename ? "OVERWRITING" : "CREATING"; 
885 print "perl user_json $exists $filename\n";
886
887 del_file();
888 init(2);
889 %u = ();
890 my $count = 0;
891 my $err = 0;
892
893 while (<DATA>) {
894         chomp;
895         my @f = split /\t/;
896         my $ref = decode($f[1]);
897         if ($ref) {
898                 $ref->put();
899                 $count++;
900         } else {
901                 print "# Error: $f[0]\t$f[1]\n";
902                 $err++
903         }
904 }
905 DXUser::sync(); DXUser::finish();
906 my $diff = _diffms($ta);
907 print "There are $count user records and $err errors in $diff mS\n";
908
909 exit $err ? -1 : 0;
910
911 __DATA__
912 };
913
914 }
915
916 sub recover
917 {
918         my $name = shift || 'recover_json';
919
920         my $fn = $name ne 'recover_json' ? $name : "$main::local_data/$name";                       # force use of local
921         
922         # save old ones
923         move "$fn.oooo", "$fn.ooooo" if -e "$fn.oooo";
924         move "$fn.ooo", "$fn.oooo" if -e "$fn.ooo";
925         move "$fn.oo", "$fn.ooo" if -e "$fn.oo";
926         move "$fn.o", "$fn.oo" if -e "$fn.o";
927         move "$fn", "$fn.o" if -e "$fn";
928
929         my $ta = [gettimeofday];
930         my $count = 0;
931         my $errs = 0;
932         my $total = 0;
933                 
934         my $strings = "strings $filename";
935         my $ifh = new IO::File "$strings |" or return "cannot open input $filename ($!)";
936         my $fh = new IO::File ">$fn" or return "cannot open output $fn ($!)";
937         if ($ifh && $fh) {
938                 my $key = 0;
939                 my $val = undef;
940                 my $action;
941                 my $t = scalar localtime;
942                 print $fh export_preamble();
943
944                 my $call;
945                 my $l;
946
947                 my $last = '';
948                 while (defined ($l = $ifh->getline)) {
949                         next unless  $l =~ /^{"call":"[-\d\w\/]+"/;
950                         dbg("recover: $l");
951                         $l =~ s/[^}]+$//;
952                         my $data = $l;
953                         if ($data) {
954                                 my $v;
955                                 
956                                 eval{ $v = decode($data); };
957                                 if ($@) {
958                                         ++$errs;
959                                         ++$total;
960                                 } else {
961                                         next if $data eq $last;
962                                         print $fh  "$v->{call}\t$l\n";
963                                         ++$count;
964                                         ++$total;
965                                         $last = $l;
966                                 }
967                         }
968                 }
969         }
970         $fh->close;
971         $ifh->close;
972
973         my $diff = _diffms($ta);
974         my $s = qq{Recovered users to $fn - $count Users, $errs errors $total possible records read in $diff mS ('sh/log recover' for details)};
975         LogDbg('command', $s);
976         return ($s);
977 }
978         
979 1;
980 __END__
981
982
983
984
985