-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbitflu.pl
executable file
·3140 lines (2654 loc) · 98.5 KB
/
bitflu.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
#
# This file is part of 'Bitflu' - (C) 2006-2011 Adrian Ulrich
#
# Released under the terms of The "Artistic License 2.0".
# http://www.opensource.org/licenses/artistic-license-2.0.php
#
use strict;
use Data::Dumper;
use Getopt::Long;
use Danga::Socket;
my $bitflu_run = undef; # Start as not_running and not_killed
my $getopts = { help => undef, config => '.bitflu.config', version => undef, quiet=>undef };
$SIG{PIPE} = $SIG{CHLD} = 'IGNORE';
$SIG{INT} = $SIG{HUP} = $SIG{TERM} = \&HandleShutdown;
GetOptions($getopts, "help|h", "version", "plugins", "config=s", "daemon", "quiet|q") or exit 1;
if($getopts->{help}) {
die << "EOF";
Usage: $0 [--help --version --plugins --config=s --daemon --quiet]
-h, --help print this help.
--version display the version of bitflu and exit
--plugins list all loaded plugins and exit
--config=file use specified configuration file (default: .bitflu.config)
--daemon run bitflu as a daemon
-q, --quiet disable logging to standard output
Example: $0 --config=/etc/bitflu.config --daemon
Mail bug reports and suggestions to <adrian\@blinkenlights.ch>.
EOF
}
# -> Create bitflu object
my $bitflu = Bitflu->new(configuration_file=>$getopts->{config}) or Carp::confess("Unable to create Bitflu Object");
if($getopts->{version}) { die $bitflu->_Command_Version->{MSG}->[0]->[1]."\n" }
my @loaded_plugins = $bitflu->LoadPlugins('Bitflu');
if($getopts->{plugins}) {
print "# Loaded Plugins: (from ".$bitflu->Configuration->GetValue('plugindir').")\n";
foreach (@loaded_plugins) { printf("File %-35s provides: %s\n", $_->{file}, $_->{package}); }
exit(0);
}
elsif($getopts->{daemon}) {
$bitflu->Daemonize();
}
elsif($getopts->{quiet}) {
$bitflu->DisableConsoleOutput;
}
$bitflu->SysinitProcess();
$bitflu->SetupDirectories();
$bitflu->InitPlugins();
$bitflu->PreloopInit();
$bitflu_run = 1 if !defined($bitflu_run); # Enable mainloop and sighandler if we are still not_killed
RunPlugins();
Danga::Socket->SetPostLoopCallback( sub { return $bitflu_run } );
Danga::Socket->EventLoop();
$bitflu->Storage->terminate;
$bitflu->info("-> Shutdown completed after running for ".(int(time())-$^T)." seconds");
exit(0);
sub RunPlugins {
my $NOW = $bitflu->Network->GetTime;
foreach my $rk (keys(%{$bitflu->{_Runners}})) {
my $rx = $bitflu->{_Runners}->{$rk} or $bitflu->panic("Runner $rk vanished");
next if $rx->{runat} > $NOW;
$rx->{runat} = $NOW + $rx->{target}->run($NOW);
}
if($bitflu_run) {
Danga::Socket->AddTimer(0.1, sub { RunPlugins() })
}
}
sub HandleShutdown {
my($sig) = @_;
if(defined($bitflu_run) && $bitflu_run == 1) {
# $bitflu is running, so we can use ->info
$bitflu->info("-> Starting shutdown... (signal $sig received)");
}
else {
print "-> Starting shutdown... (signal $sig received), please wait...\n";
}
$bitflu_run = 0; # set it to not_running and killed
}
package Bitflu;
use strict;
use Carp;
use constant V_MAJOR => '1';
use constant V_MINOR => '52';
use constant V_STABLE => 1;
use constant V_TYPE => ( V_STABLE ? 'stable' : 'devel' );
use constant VERSION => V_MAJOR.'.'.V_MINOR.'-'.V_TYPE;
use constant APIVER => 20120529;
use constant LOGBUFF => 0xFF;
##########################################################################
# Create a new Bitflu-'Dispatcher' object
sub new {
my($class, %args) = @_;
my $self = {};
bless($self, $class);
$self->{_LogFH} = *STDOUT; # Must be set ASAP
$self->{_LogBuff} = []; # Empty at startup
$self->{Core}->{"00_Tools"} = Bitflu::Tools->new(super => $self); # Tools is also loaded ASAP because ::Configuration needs it
$self->{Core}->{"01_Syscall"} = Bitflu::Syscall->new(super => $self); # -> this should be one of the first core plugin started
$self->{Core}->{"10_Admin"} = Bitflu::Admin->new(super => $self);
$self->{Core}->{"20_Config"} = Bitflu::Configuration->new(super=>$self, configuration_file => $args{configuration_file});
$self->{Core}->{"30_Network"} = Bitflu::Network->new(super => $self);
$self->{Core}->{"99_QueueMgr"} = Bitflu::QueueMgr->new(super => $self);
$self->{_Runners} = {};
$self->{_Plugins} = ();
return $self;
}
##########################################################################
# Return internal version
sub GetVersion {
my($self) = @_;
return(V_MAJOR, V_MINOR, V_STABLE);
}
##########################################################################
# Return internal version as string
sub GetVersionString {
my($self) = @_;
return VERSION;
}
##########################################################################
# Call hardcoded configuration plugin
sub Configuration {
my($self) = @_;
return $self->{Core}->{"20_Config"};
}
##########################################################################
# Call hardcoded tools plugin
sub Tools {
my($self) = @_;
return $self->{Core}->{"00_Tools"};
}
##########################################################################
# Call hardcoded Network IO plugin
sub Network {
my($self) = @_;
return $self->{Core}->{"30_Network"};
}
##########################################################################
# Call hardcoded Admin plugin
sub Admin {
my($self) = @_;
return $self->{Core}->{"10_Admin"};
}
##########################################################################
# Call hardcoded Syscall plugin
sub Syscall {
my($self) = @_;
return $self->{Core}->{"01_Syscall"};
}
##########################################################################
# Call hardcoded Queue plugin
sub Queue {
my($self) = @_;
return $self->{Core}->{"99_QueueMgr"};
}
##########################################################################
# Call currently loaded storage plugin
sub Storage {
my($self) = @_;
return $self->{Plugin}->{Storage};
}
##########################################################################
# Let bitflu run the given target
sub AddRunner {
my($self,$target) = @_;
$self->{_Runners}->{$target} and $self->panic("$target is registered: wont overwrite it");
$self->{_Runners}->{$target} = { target=>$target, runat=>0 };
}
##########################################################################
# Returns a list of bitflus _Runner array as reference hash
sub GetRunnerTarget {
my($self,$target) = @_;
foreach my $rx (values(%{$self->{_Runners}})) {
return $rx->{target} if ref($rx->{target}) eq $target;
}
return undef;
}
##########################################################################
# Creates a new Simple-eXecution task
sub CreateSxTask {
my($self,%args) = @_;
$args{__SUPER_} = $self;
my $sx = Bitflu::SxTask->new(%args);
$self->AddRunner($sx);
#$self->debug("CreateSxTask returns <$sx>");
#$self->info("SxTask : ".ref($sx->{super})."->$sx->{cback} created (id: $sx)");
return $sx;
}
##########################################################################
# Kills an SxTask
sub DestroySxTask {
my($self,$taskref) = @_;
delete($self->{_Runners}->{$taskref}) or $self->panic("Could not kill non-existing task $taskref");
#$self->info("SxTask : $taskref terminated");
return 1;
}
##########################################################################
# Register the exclusive storage plugin
sub AddStorage {
my($self,$target) = @_;
if(defined($self->{Plugin}->{Storage})) { $self->panic("Unable to register additional storage driver '$target' !"); }
$self->{Plugin}->{Storage} = $target;
$self->debug("AddStorage($target)");
return 1;
}
##########################################################################
# Loads all plugins from 'plugins' directory but does NOT init them
sub LoadPlugins {
my($self,$xclass) = @_;
#
unshift(@INC, $self->Configuration->GetValue('plugindir'));
my $pdirpath = $self->Configuration->GetValue('plugindir')."/$xclass";
my @plugins = ();
my %exclude = (map { $_ => 1} split(/;/,$self->Configuration->GetValue('pluginexclude')));
opendir(PLUGINS, $pdirpath) or $self->stop("Unable to read directory '$pdirpath' : $!");
foreach my $dirent (sort readdir(PLUGINS)) {
next unless my($pfile, $porder, $pmodname) = $dirent =~ /^((\d\d)_(.+)\.pm)$/i;
if($exclude{$pfile}) {
$self->info("Skipping disabled plugin '$pfile -> $pmodname'");
}
elsif($porder eq '00' && $pmodname ne $self->Configuration->GetValue('storage')) {
$self->debug("Skipping unconfigured storage plugin '$dirent'");
}
else {
push(@plugins, {file=>$pfile, order=>$porder, class=>$xclass, modname=>$pmodname, package=>$xclass."::".$3});
$self->debug("Found plugin $plugins[-1]->{package} in folder $pdirpath");
}
}
closedir(PLUGINS);
$self->{_Plugins} = \@plugins;
foreach my $plugin (@{$self->{_Plugins}}) {
my $fname = $plugin->{class}."/".$plugin->{file};
$self->debug("Loading $fname");
eval { require $fname; };
if($@) {
my $perr = $@; chomp($perr);
$self->yell("Unable to load plugin '$fname', error was: '$perr'");
$self->stop(" -> Please fix or remove this broken plugin file from $pdirpath");
}
my $this_apiversion = $plugin->{package}->_BITFLU_APIVERSION;
if($this_apiversion != APIVER) {
$self->yell("Plugin '$fname' has an invalid API-Version ( (\$apivers = $this_apiversion) != (\$expected = ".APIVER.") )");
$self->yell("HINT: Maybe you forgot to replace the plugins at $pdirpath while upgrading bitflu?!...");
$self->stop("-> Exiting due to APIVER mismatch");
}
}
return @plugins;
}
##########################################################################
# Startup all plugins
sub InitPlugins {
my($self) = @_;
my @TO_INIT = ();
foreach my $plugin (@{$self->{_Plugins}}) {
$self->debug("Registering '$plugin->{package}'");
my $this_plugin = $plugin->{package}->register($self) or $self->panic("Regsitering '$plugin' failed, aborting");
push(@TO_INIT, {name=>$plugin->{package}, ref=>$this_plugin});
}
foreach my $toinit (@TO_INIT) {
$self->debug("++ Starting Normal-Plugin '$toinit->{name}'");
$toinit->{ref}->init() or $self->panic("Unable to init plugin : $!");
}
foreach my $coreplug (sort keys(%{$self->{Core}})) {
$self->debug("++ Starting Core-Plugin '$coreplug'");
$self->{Core}->{$coreplug}->init() or $self->panic("Unable to init Core-Plugin : $!");
}
}
##########################################################################
# Build some basic directory structure
sub SetupDirectories {
my($self) =@_;
my $workdir = $self->Configuration->GetValue('workdir') or $self->panic("No workdir configured");
my $tmpdir = $self->Tools->GetTempdir or $self->panic("No tempdir configured");
foreach my $this_dir ($workdir, $tmpdir) {
unless(-d $this_dir) {
$self->debug("mkdir($this_dir)");
mkdir($this_dir) or $self->stop("Unable to create directory '$this_dir' : $!");
}
}
}
##########################################################################
# Change nice level, chroot and drop privileges
sub SysinitProcess {
my($self) = @_;
my $chroot = $self->Configuration->GetValue('chroot');
my $chdir = $self->Configuration->GetValue('chdir');
my $uid = int($self->Configuration->GetValue('runas_uid') || 0);
my $gid = int($self->Configuration->GetValue('runas_gid') || 0);
my $renice = int($self->Configuration->GetValue('renice') || 0);
my $outlog = ($self->Configuration->GetValue('logfile') || '');
my $pidfile= ($self->Configuration->GetValue('pidfile') || '');
if(length($outlog)) {
open(LFH, ">>", $outlog) or $self->stop("Cannot write to logfile '$outlog' : $!");
$self->{_LogFH} = *LFH;
$self->{_LogFH}->autoflush(1);
$self->yell("Logging to '$outlog'");
}
if(length($pidfile)) {
$self->info("Writing pidfile at '$pidfile'");
open(PIDFILE, ">", $pidfile) or $self->stop("Cannot write to pidfile '$pidfile' : $!");
print PIDFILE "$$\n";
close(PIDFILE);
}
# Lock values because we cannot change them after we finished
foreach my $lockme (qw(runas_uid runas_gid chroot)) {
$self->Configuration->RuntimeLockValue($lockme);
}
# -> Adjust resolver settings (is this portable? does it work on *BSD?)
$ENV{RES_OPTIONS} = "timeout:1 attempts:1";
# -> Set niceness (This is done before dropping root to get negative values working)
if($renice) {
$renice = ($renice > 19 ? 19 : ($renice < -20 ? -20 : $renice) ); # Stop funny stuff...
$self->info("Setting my own niceness to $renice");
POSIX::nice($renice) or $self->warn("nice($renice) failed: $!");
}
# -> Chroot
if(defined($chroot)) {
$self->info("Chrooting into '$chroot'");
Carp::longmess("FULLY_LOADING_CARP"); # init CARP module
require 'Config_heavy.pl'; # Needed on newer perl?
my $x = gethostbyname('localhost.localdomain.invalid.tld'); # init DNS resolver
chdir($chroot) or $self->panic("Cannot change into directory '$chroot' : $!");
chroot($chroot) or $self->panic("Cannot chroot into directory '$chroot' (are you root?) : $!");
chdir('/') or $self->panic("Unable to change into new chroot topdir: $!");
}
# -> Drop group privileges
if($gid) {
$self->info("Changing gid to $gid");
$) = "$gid $gid"; # can fail with 'no such file or directory'
$! = undef;
$( = "$gid";
$self->panic("Unable to set GID: $!") if $!;
}
# -> Drop user privileges
if($uid) {
$self->info("Changing uid to $uid");
POSIX::setuid($uid) or $self->panic("Unable to change UID: $!");
}
# -> Check if we are still root. We shouldn't.
if($> == 0 or $) == 0 or $( == 0) {
$self->warn("Refusing to run with root privileges. Do not start $0 as root unless you are using");
$self->warn("the chroot option. In this case you must also specify the options runas_uid & runas_gid");
$self->stop("Bitflu refuses to run as root");
}
if($chdir) {
$self->info("Changing into directory '$chdir'");
chdir($chdir) or $self->stop("chdir($chdir) failed: $!");
}
$self->info("$0 is running with pid $$ ; uid = ($>|$<) / gid = ($)|$()");
}
##########################################################################
# This should get called after starting the mainloop
# The subroutine does the same as a 'init' in a plugin
sub PreloopInit {
my($self) = @_;
$self->Admin->RegisterCommand('die' , $self, '_Command_Shutdown' , 'Terminates bitflu');
$self->Admin->RegisterCommand('version' , $self, '_Command_Version' , 'Displays bitflu version string');
$self->Admin->RegisterCommand('date' , $self, '_Command_Date' , 'Displays current time and date');
}
##########################################################################
# Set _LogFh to undef if we are logging to stdout
# this disables logging to the console
sub DisableConsoleOutput {
my($self) = @_;
$self->debug("DisableConsoleOutput called");
if($self->{_LogFH} eq *STDOUT) {
$self->debug("=> Setting _LogFH to undef");
$self->{_LogFH} = '';
}
# Do not printout any warnings to STDOUT
$SIG{__WARN__} = sub {};
}
##########################################################################
# Fork into background
sub Daemonize {
my($self) = @_;
my $child = fork();
if(!defined($child)) {
die "Unable to fork: $!\n";
}
elsif($child != 0) {
$self->debug("Bitflu is running with pid $child");
exit(0);
}
$self->DisableConsoleOutput;
}
##########################################################################
# bye!
sub _Command_Shutdown {
my($self) = @_;
kill(2,$$);
return {MSG=>[ [1, "Shutting down $0 (with pid $$)"] ], SCRAP=>[]};
}
##########################################################################
# Return version string
sub _Command_Version {
my($self) = @_;
my $uptime = ($self->Network->GetTime - $^T)/60;
return {MSG=>[ [1, sprintf("This is Bitflu %s (API:%s) running on %s with perl %vd. Uptime: %.3f minutes (%s)",$self->GetVersionString,
APIVER, $^O, $^V, $uptime, "".localtime($^T) )] ], SCRAP=>[]};
}
##########################################################################
# Return version string
sub _Command_Date {
my($self) = @_;
return {MSG=>[ [1, "".localtime()] ], SCRAP=>[]};
}
##########################################################################
# Printout logmessage
sub _xlog {
my($self, $msg, $force_stdout) = @_;
my $rmsg = localtime()." # $msg\n";
my $xfh = $self->{_LogFH};
my $lbuff = $self->{_LogBuff};
print $xfh $rmsg if $xfh;
if($force_stdout && $xfh ne *STDOUT) {
print STDOUT $rmsg;
}
push(@$lbuff, $rmsg);
shift(@$lbuff) if int(@$lbuff) >= LOGBUFF;
}
sub info { my($self,$msg) = @_; return if $self->Configuration->GetValue('loglevel') < 4; $self->_xlog($msg); }
sub debug { my($self,$msg) = @_; return if $self->Configuration->GetValue('loglevel') < 10; $self->_xlog(" ** DEBUG ** $msg"); }
sub warn { my($self,$msg) = @_; return if $self->Configuration->GetValue('loglevel') < 2; $self->_xlog("** WARNING ** $msg"); }
sub yell { my($self,$msg) = @_; $self->_xlog($msg,1); }
sub stop { my($self,$msg) = @_; $self->yell("EXITING # $msg"); exit(1); }
sub panic {
my($self,$msg) = @_;
$self->yell("--------- BITFLU SOMEHOW MANAGED TO CRASH ITSELF; PANIC MESSAGE: ---------");
$self->yell($msg);
$self->yell("--------- BACKTRACE START ---------");
$self->yell(Carp::longmess());
$self->yell("---------- BACKTRACE END ----------");
$self->yell("SHA1-Module used : ".$self->Tools->{mname});
$self->yell("Perl Version : ".sprintf("%vd", $^V));
$self->yell("Perl Execname : ".$^X);
$self->yell("Bitflu Version : ".$self->GetVersionString);
$self->yell("OS-Name : ".$^O);
$self->yell("IPv6 ? : ".$self->Network->HaveIPv6);
$self->yell("Danga::Socket : ".$Danga::Socket::VERSION);
$self->yell("Running since : ".gmtime($^T));
$self->yell("---------- LOADED PLUGINS ---------");
foreach my $plug (@{$self->{_Plugins}}) {
$self->yell(sprintf("%-32s -> %s",$plug->{file}, $plug->{package}));
}
$self->yell("##################################");
exit(1);
}
1;
####################################################################################################################################################
####################################################################################################################################################
# Bitflu Queue manager
#
package Bitflu::QueueMgr;
use constant SHALEN => 40;
use constant HPFX => 'history_';
use constant HIST_MAX => 100;
use constant STATE_PAUSED => 1;
use constant STATE_AUTOPAUSED => 2;
sub new {
my($class, %args) = @_;
my $self = {super=> $args{super}};
bless($self,$class);
return $self;
}
##########################################################################
# Inits plugin: This resumes all found storage items
sub init {
my($self) = @_;
my $queueIds = $self->{super}->Storage->GetStorageItems();
my $toload = int(@$queueIds);
$self->info("Resuming $toload downloads, this may take a few seconds...");
foreach my $sid (@$queueIds) {
my $this_storage = $self->{super}->Storage->OpenStorage($sid) or $self->panic("Unable to open storage for sid $sid");
my $owner = $this_storage->GetSetting('owner');
$self->info(sprintf("[%3d] Loading %s", $toload--, $sid));
if(defined($owner) && (my $r_target = $self->{super}->GetRunnerTarget($owner)) ) {
$r_target->resume_this($sid);
}
else {
$self->stop("StorageObject $sid is owned by '$owner', but plugin is not loaded/registered correctly");
}
}
$self->{super}->Admin->RegisterCommand('rename' , $self, 'admincmd_rename', 'Renames a download',
[ [undef, "Renames a download"], [undef, "Usage: rename queue_id \"New Name\""] ]);
$self->{super}->Admin->RegisterCommand('cancel' , $self, 'admincmd_cancel', 'Removes a file from the download queue',
[ [undef, "Removes a file from the download queue. Use --wipe to *remove* data of completed downloads"], [undef, "Usage: cancel [--wipe] queue_id [queue_id2 ...]"] ]);
$self->{super}->Admin->RegisterCommand('history' , $self, 'admincmd_history', 'Manages download history',
[ [undef, "Manages internal download history"], [undef, ''],
[undef, "Usage: history [ queue_id [show forget] ] [list|drop|cleanup]"], [undef, ''],
[undef, "history list : List all remembered downloads"],
[undef, "history drop : List and forget all remembered downloads"],
[undef, "history cleanup : Trim history size"],
[undef, "history queue_id show : Shows details about queue_id"],
[undef, "history queue_id forget : Removes history of queue_id"],
]);
$self->{super}->Admin->RegisterCommand('pause' , $self, 'admincmd_pause', 'Stops a download',
[ [undef, "Stop given download"], [undef, ''],
[undef, "Usage: pause queue_id [queue_id2 ... | --all]"], [undef, ''],
]);
$self->{super}->Admin->RegisterCommand('resume' , $self, 'admincmd_resume', 'Resumes a paused download',
[ [undef, "Resumes a paused download"], [undef, ''],
[undef, "Usage: resume queue_id [queue_id2 ... | --all]"], [undef, ''],
]);
$self->info("--- startup completed: bitflu ".$self->{super}->GetVersionString." is ready ---");
return 1;
}
##########################################################################
# Pauses a download
sub admincmd_pause {
my($self, @args) = @_;
my @MSG = ();
my $NOEXEC = '';
$self->{super}->Tools->GetOpts(\@args);
if(int(@args)) {
foreach my $cid (@args) {
my $so = $self->{super}->Storage->OpenStorage($cid);
if($so) {
$self->SetPaused($cid);
push(@MSG, [1, "$cid: download paused"]);
}
else {
push(@MSG, [2, "$cid: does not exist in queue, cannot pause"]);
}
}
}
else {
$NOEXEC .= 'Usage: pause queue_id';
}
return({MSG=>\@MSG, SCRAP=>[], NOEXEC=>$NOEXEC});
}
##########################################################################
# Resumes a download
sub admincmd_resume {
my($self, @args) = @_;
my @MSG = ();
my $NOEXEC = '';
$self->{super}->Tools->GetOpts(\@args);
if(int(@args)) {
foreach my $cid (@args) {
my $so = $self->{super}->Storage->OpenStorage($cid);
if($so) {
$self->SetUnPaused($cid);
push(@MSG, [1, "$cid: download resumed"]);
}
else {
push(@MSG, [2, "$cid: does not exist in queue, cannot resume"]);
}
}
}
else {
$NOEXEC .= 'Usage: resume queue_id';
}
return({MSG=>\@MSG, SCRAP=>[], NOEXEC=>$NOEXEC});
}
##########################################################################
# Cancel a queue item
sub admincmd_cancel {
my($self, @args) = @_;
my @MSG = ();
my $NOEXEC = '';
my $do_wipe = 0;
if(int(@args)) {
if($args[0] eq '--wipe') {
$do_wipe = 1;
shift(@args); # remove first parameter
}
foreach my $cid (@args) {
my $storage = $self->{super}->Storage->OpenStorage($cid);
if($storage) {
my $owner = $storage->GetSetting('owner');
if(defined($owner) && (my $r_target = $self->{super}->GetRunnerTarget($owner)) ) {
$self->ModifyHistory($cid, Canceled=>'');
$storage->SetSetting('wipedata', 1) if $do_wipe;
$r_target->cancel_this($cid);
push(@MSG, [1, "'$cid' canceled"]);
}
else {
$self->panic("'$cid' has no owner, cannot cancel!");
}
}
else {
push(@MSG, [2, "'$cid' not removed from queue: No such item"]);
}
}
}
else {
$NOEXEC .= 'Usage: cancel [--wipe] queue_id [queue_id2 ...]';
}
return({MSG=>\@MSG, SCRAP=>[], NOEXEC=>$NOEXEC});
}
##########################################################################
# Rename a queue item
sub admincmd_rename {
my($self, @args) = @_;
my $sha = $args[0];
my $name = $args[1];
my @MSG = ();
my $NOEXEC = '';
if(!defined($name)) {
$NOEXEC .= "Usage: rename queue_id \"New Name\"";
}
elsif(my $storage = $self->{super}->Storage->OpenStorage($sha)) {
$storage->SetSetting('name', $name);
push(@MSG, [1, "Renamed $sha into '$name'"]);
}
else {
push(@MSG, [2, "Unable to rename $sha: queue_id does not exist"]);
}
return({MSG=>\@MSG, SCRAP=>[], NOEXEC=>$NOEXEC});
}
##########################################################################
# Manages download history
sub admincmd_history {
my($self,@args) = @_;
my $sha = ($args[0] || '');
my $cmd = ($args[1] || '');
my @MSG = ();
my $NOEXEC = '';
my $hpfx = HPFX;
my $hkey = $hpfx.$sha;
my $strg = $self->{super}->Storage;
if($sha eq 'list' or $sha eq 'drop' or $sha eq 'cleanup') {
my @cbl = $strg->ClipboardList;
my $cbi = 0;
my $drop = {};
my $drop_c = 0;
foreach my $item (@cbl) {
if(my($this_sid) = $item =~ /^$hpfx(.+)$/) {
my $hr = $self->GetHistory($this_sid); # History Reference
my $ll = "$1 : ".substr(($hr->{Name}||''),0,64); # Telnet-Safe-Name
push(@MSG, [ ($strg->OpenStorage($this_sid) ? 1 : 5 ), $ll]);
$strg->ClipboardRemove($item) if $sha eq 'drop';
push(@{$drop->{($hr->{FirstSeen}||0)}},$this_sid) if $sha eq 'cleanup'; # Create list with possible items to delete
$cbi++;
}
}
# Walk droplist (if any). From oldest to newest
foreach my $d_sid ( map(@{$drop->{$_}}, sort({$a<=>$b} keys(%$drop))) ) {
next if $strg->OpenStorage($d_sid); # do not even try to drop existing items (wouldn't do much harm but...)
last if ( $cbi-$drop_c++ ) <= HIST_MAX; # Abort if we reached our limit
$strg->ClipboardRemove(HPFX.$d_sid); # Still here ? -> ditch it. (fixme: HPFX concating is ugly)
}
push(@MSG, [1, ($sha eq 'drop' ? "History cleared" : "$cbi item".($cbi == 1 ? '' : 's')." stored in history")]);
}
elsif(length($sha)) {
if(my $ref = $self->GetHistory($sha)) {
if($cmd eq 'show') {
foreach my $k (sort keys(%$ref)) {
push(@MSG,[1, sprintf("%20s -> %s",$k,$ref->{$k})]);
}
}
elsif($cmd eq 'forget') {
$strg->ClipboardRemove($hkey);
push(@MSG, [1, "history for $sha has been removed"]);
}
else {
push(@MSG, [2, "unknown subcommand, see 'help history'"]);
}
}
else {
push(@MSG, [2,"queue item $sha has no history"]);
}
}
else {
push(@MSG, [2,"See 'help history'"]);
}
return({MSG=>\@MSG, SCRAP=>[], NOEXEC=>$NOEXEC});
}
##########################################################################
# Add a new item to queue (Also creates a new storage)
sub AddItem {
my($self, %args) = @_;
my $name = $args{Name};
my $chunks = $args{Chunks} or $self->panic("No chunks?!");
my $size = $args{Size};
my $overst = $args{Overshoot};
my $flayout = $args{FileLayout} or $self->panic("FileLayout missing");
my $shaname = ($args{ShaName} || unpack("H*", $self->{super}->Tools->sha1($name)));
my $owner = ref($args{Owner}) or $self->panic("No owner?");
my $sobj = 0;
my $history = $self->{super}->Configuration->GetValue('history');
if($size == 0 && $chunks != 1) {
$self->panic("Sorry: You can not create a dynamic storage with multiple chunks ($chunks != 1)");
}
if(!defined($name)) {
$self->panic("AddItem needs a name!");
}
if(length($shaname) != SHALEN) {
$self->panic("Invalid shaname: $shaname");
}
if($self->{super}->Storage->OpenStorage($shaname)) {
$@ = "$shaname: item exists in queue";
}
elsif($history && $self->GetHistory($shaname)) {
$@ = "$shaname: has already been downloaded. Use 'history $shaname forget' if you want do re-download it";
$self->warn($@);
}
elsif($sobj = $self->{super}->Storage->CreateStorage(StorageId => $shaname, Size=>$size, Chunks=>$chunks, Overshoot=>$overst, FileLayout=>$flayout)) {
$sobj->SetSetting('owner', $owner);
$sobj->SetSetting('name' , $name);
$sobj->SetSetting('createdat', $self->{super}->Network->GetTime);
if($history) {
$self->ModifyHistory($shaname, Name=>$name, Canceled=>'never', Started=>'',
Ended=>'never', Committed=>'never', FirstSeen=>$self->{super}->Network->GetTime);
}
}
else {
$self->panic("CreateStorage for $shaname failed");
}
return $sobj;
}
##########################################################################
# Removes an item from the queue + storage
sub RemoveItem {
my($self,$sid) = @_;
my $ret = $self->{super}->Storage->RemoveStorage($sid);
if(!$ret) {
$self->panic("Unable to remove storage-object $sid : $!");
}
delete($self->{statistics}->{$sid}) or $self->panic("Cannot remove non-existing statistics for $sid");
return 1;
}
##########################################################################
# Updates/creates on-disk history of given sid
# Note: Strings with length == 0 are replaced with the current time. Awkward.
sub ModifyHistory {
my($self,$sid, %args) = @_;
if($self->{super}->Storage->OpenStorage($sid)) {
my $old_ref = $self->GetHistory($sid);
foreach my $k (keys(%args)) {
my $v = $args{$k};
$v = "".localtime($self->{super}->Network->GetTime) if length($v) == 0;
$old_ref->{$k} = $v;
}
return $self->{super}->Storage->ClipboardSet(HPFX.$sid, $self->{super}->Tools->RefToCBx($old_ref));
}
else {
return 0;
}
}
##########################################################################
# Returns history of given sid
sub GetHistory {
my($self,$sid) = @_;
my $r = $self->{super}->Tools->CBxToRef($self->{super}->Storage->ClipboardGet(HPFX.$sid));
return $r;
}
##########################################################################
# Set private statistics
# You are supposed to set total_bytes, total_chunks, done_bytes, done_chunks,
# uploaded_bytes, clients, active_clients, last_recv
# ..and we do not save anything.. you'll need to do this on your own :-)
sub SetStats {
my($self, $id, $ref) = @_;
foreach my $xk (keys(%$ref)) {
$self->{statistics}->{$id}->{$xk} = $ref->{$xk};
}
}
##########################################################################
# Flushes all stats and sets all common fields to 0
sub InitializeStats {
my($self, $id) = @_;
return $self->SetStats($id, {total_bytes=>0, done_bytes=>0, uploaded_bytes=>0, active_clients=>0,
clients=>0, speed_upload =>0, speed_download => 0, last_recv => 0,
total_chunks=>0, done_chunks=>0});
}
sub IncrementStats {
my($self, $id, $ref) = @_;
foreach my $xk (keys(%$ref)) {
$self->SetStats($id,{$xk => $self->GetStat($id,$xk)+$ref->{$xk}});
}
}
sub DecrementStats {
my($self, $id, $ref) = @_;
foreach my $xk (keys(%$ref)) {
$self->SetStats($id,{$xk => $self->GetStat($id,$xk)-$ref->{$xk}});
}
}
##########################################################################
# Get private statistics
sub GetStats {
my($self,$id) = @_;
return $self->{statistics}->{$id};
}
##########################################################################
# Get single statistics key
sub GetStat {
my($self,$id,$key) = @_;
return $self->GetStats($id)->{$key};
}
##########################################################################
# Returns a list with all queue objects
sub GetQueueList {
my($self) = @_;
my $xh = ();
my $all_ids = $self->{super}->Storage->GetStorageItems();
foreach my $id (@$all_ids) {
my $so = $self->{super}->Storage->OpenStorage($id) or $self->panic("Unable to open $id");
my $name = $so->GetSetting('name');
my $type = ($so->GetSetting('type') or "????");
$xh->{$type}->{$id} = { name=>$name };
}
return $xh;
}
##########################################################################
# Returns true if download is marked as paused
sub IsPaused {
my($self,$sid) = @_;
my $so = $self->{super}->Storage->OpenStorage($sid) or $self->panic("$sid does not exist");
return ( $so->GetSetting('_paused') ? 1 : 0 );
}
##########################################################################
# Returns true if download is marked as *auto* paused
sub IsAutoPaused {
my($self,$sid) = @_;
my $so = $self->{super}->Storage->OpenStorage($sid) or $self->panic("$sid does not exist");
my $val = ($so->GetSetting('_paused') || 0);
return ( $val == STATE_AUTOPAUSED ? 1 : 0 );
}
##########################################################################
# Set autopause flag of specified SID
sub SetAutoPaused {
my($self,$sid) = @_;
my $so = $self->{super}->Storage->OpenStorage($sid) or $self->panic("$sid does not exist");
$so->SetSetting('_paused', STATE_AUTOPAUSED);
}
##########################################################################
# Set normal pause flag of specified SID
sub SetPaused {
my($self,$sid) = @_;
my $so = $self->{super}->Storage->OpenStorage($sid) or $self->panic("$sid does not exist");
$so->SetSetting('_paused', STATE_PAUSED);
}
##########################################################################
# Remove paused flag
sub SetUnPaused {
my($self,$sid) = @_;
my $so = $self->{super}->Storage->OpenStorage($sid) or $self->panic("$sid does not exist");
$so->SetSetting('_paused', 0);
}
sub debug { my($self, $msg) = @_; $self->{super}->debug("QueueMGR: ".$msg); }
sub info { my($self, $msg) = @_; $self->{super}->info("QueueMGR: ".$msg); }
sub warn { my($self, $msg) = @_; $self->{super}->warn("QueueMGR: ".$msg); }
sub panic { my($self, $msg) = @_; $self->{super}->panic("QueueMGR: ".$msg); }
sub stop { my($self, $msg) = @_; $self->{super}->stop("QueueMGR: ".$msg); }
1;
###############################################################################################################
# Bitflu Sammelsurium
package Bitflu::Tools;