-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShellUtil.pm
1460 lines (1357 loc) · 43.6 KB
/
ShellUtil.pm
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
# Copyright (c) 2000-2012 bivio Software, Inc. All rights reserved.
# $Id$
package Bivio::ShellUtil;
use strict;
use Bivio::Base 'Collection.Attributes';
use File::Spec ();
use POSIX ();
# C<Bivio::ShellUtil> is the base class for command line utilities.
# All shell utilities take a I<command> as their first argument
# followed by zero or more arguments. I<command> must map to a
# method in the subclass. The arguments are parsed by the method.
#
# L<setup|"setup"> creates a request from the standard
# voptions (I<user>, I<db>, and I<realm>). It is called
# implicitly by L<get_request|"get_request">
#
# Options precede the command. See L<OPTIONS|"OPTIONS">. If the options
# contain references or are C<undef>, the value is used verbatim. If
# the option value is a string, it will be parsed with the C<from_literal>
# of the option's type.
#
# For an example, see L<Bivio::Biz::Util::File|Bivio::Biz::Util::File>
# and L<Bivio::Biz::Util::Filtrum|Bivio::Biz::Util::Filtrum> (less complex).
#
# When implementing a subclass, try to avoid assumptions about $self.
# For example, don't assume $self is a reference and instead load things
# on the request. As an example, in Bivio::Biz::Util::File, the volume
# is loaded on the request once it is parsed from $self if it is available.
#
# ShellUtils can't be subclassed and commands may not begin with "handle_".
# See _method_ok() below.
#
#
#
# argv : array_ref
#
# Unmodified argument vector.
#
# db : string [undef]
#
# Name of database to connect to.
#
# detach : boolean [0]
#
# Detach the process from standard output. Output will receive all output.
#
# email : string [undef]
#
# Where to mail the output. Uses I<result_subject>, I<result_type> and
# I<result_name>, if available. If there is an exception, will email
# the die as a string instead of the text result.
#
# force : boolean [0]
#
# If true, L<are_you_sure|"are_you_sure"> will always return true.
#
# input : string [-]
#
# Reads the input file. If C<->, reads from stdin. See
# L<read_input|"read_input">.
#
# input : string_ref
#
# The contents of the input file. Value is returned verbatim from
# L<read_input|"read_input">.
#
# noexecute : boolean [1]
#
# Won't execute any "modifying" operations. Will not call
# commit on termination.
#
# program : string
#
# Name of the program sans suffix and directory.
#
# output : string
#
# Name of the file to write the output to.
#
# realm : string [undef]
#
# The auth realm in which we are operating.
#
# req : Bivio::Agent::Request
#
# Request used for the call. Initialized by L<setup|"setup">.
#
# result_name : string []
#
# File name of the result as set by the caller I<command> method.
#
# result_type : string []
#
# MIME type of the result as set by the caller I<command> method.
#
# user : string [undef or first_admin]
#
# The auth user used to execute I<command>. If not set and
# I<realm> is set, will be implicitly set to the first_admin
# as defined by
# L<Bivio::Biz::Model::RealmAdminList|Bivio::Biz::Model::RealmAdminList>.
b_use('IO.Trace');
our($_TRACE);
my($_IDI) = __PACKAGE__->instance_data_index;
# Map of class to Attributes which contains result of _parse_options()
my(%_DEFAULT_OPTIONS);
my($_A) = b_use('IO.Alert');
my($_C) = b_use('IO.Config');
my($_CA) = b_use('Collection.Attributes');
my($_CL) = b_use('IO.ClassLoader');
my($_DIE) = b_use('Bivio.Die');
my($_F) = b_use('IO.File');
my($_FP) = b_use('Type.FilePath');
my($_L) = b_use('IO.Log');
my($_M) = b_use('Biz.Model');
my($_TE) = b_use('Bivio.TypeError');
my($_MAP_NAME) = 'ShellUtil';
$_C->register(my $_CFG = {
lock_directory => '/tmp',
$_C->NAMED => {
daemon_max_children => 1,
daemon_sleep_after_start => 60,
daemon_sleep_after_reap => 0,
daemon_max_child_run_seconds => 0,
daemon_max_child_term_seconds => 0,
daemon_log_file => $_C->REQUIRED,
},
});
my($_HANDLERS) = b_use('Biz.Registrar')->new;
sub OPTIONS {
# Returns a mapping of options to bivio types and default values.
#
# Boolean is treated specially, but all other options are parsed
# with L<Bivio::Type::from_literal|Bivio::Type/"from_literal">.
# If an option is C<undef>, it was passed but not set properly.
# If an option does not exist, it wasn't passed.
#
# You should always use L<getopt|"getopt">, because
# it will return C<undef> in all cases, even if called statically.
#
# If the default value is C<undef>, the option will not be set.
#
# If the option begins with a unique first letter, the single
# letter version is also supported.
return {
#TODO: Add option -query which sets the query on the request
db => ['Name', undef],
detach => ['Boolean', 0],
detach_log => ['Text', undef],
email => ['Text', undef],
force => ['Boolean', 0],
input => ['Text', '-'],
live => ['Boolean', 0],
noexecute => ['Boolean', 0],
realm => ['Line', undef],
user => ['Line', undef],
output => ['Line', undef],
verbose => ['Boolean', 0],
};
}
sub OPTIONS_USAGE {
return <<'EOF';
options:
-db - name of database connection
-detach - calls detach process before executing command
-detach_log - log file to use when detached
-email - who to mail the results to (may be a comma separated list)
-force - don't ask "are you sure?"
-input - a file to read from ("-" is STDIN)
-live - don't die on errors (used in weird circumstances)
-noexecute - don't commit
-output - a file to write the output to ("-" is STDOUT)
-realm - realm_id or realm name
-user - user_id or user name
EOF
}
sub USAGE {
my($proto) = @_;
# B<Subclasses may override this method to provide command details
# in which case they should return the complete usage string, e.g.
#
# usage: b-db-util [options] command [args...]
# commands:
# remote_sqlplus host db_login actions
# copy_logs_to_standby
# recover_standby
# sql2csv file.sql
# switch_logs_and_count_rows
die('abstract method')
if $proto->package_name eq __PACKAGE__;
return join("\n",
'usage: '._cleanup_command_name().' [options] command [args..]',
'commands:',
map(" $_", @{$proto->shell_commands}),
'');
}
sub are_you_sure {
my($self, $prompt) = @_;
# Writes I<prompt> (default: "Are you sure?") to STDERR. User must
# answer "yes", on STDIN or the routine throws an exception.
#
# Does not prompt if:
#
# * STDIN is not a tty (-t STDIN returns false)
# * self is not a reference (called statically)
# * -force option is true
#
# It is assumed STDERR is set up for autoflushing.
# Not a tty?
return unless -t STDIN;
# Not an instance?
return unless ref($self);
# Force?
return if $self->unsafe_get('force');
$prompt ||= 'Are you sure?';
$self->usage_error("Operation aborted")
unless $self->readline_stdin($prompt." (yes or no) ") eq 'yes';
# Yes answer
return;
}
sub arg_list {
my($proto, $args, $decls) = @_;
$_A->warn_deprecated('use name_args');
return $proto->name_args($decls, $args);
}
sub assert_dev {
return $_C->assert_dev;
}
sub assert_have_user {
my($self) = @_;
$self->usage_error('must select a user with -user')
unless $self->req('auth_user');
return;
}
sub assert_not_general {
my($self) = @_;
$self->usage_error('must select a realm with -realm')
if $self->req('auth_realm')->is_general;
return;
}
sub assert_not_root {
my($self) = @_;
# Ensure the current command-line user is not root.
$self->usage_error('this utility method may not be run as root')
if $> == 0;
return;
}
sub assert_test {
return $_C->assert_test;
}
sub command_line {
my($self) = @_;
# Returns the command line that was used to execute this command.
return ref($self)
? join(' ', $self->unsafe_get('program') || '',
map {
defined($_) ? $_ : '<undef>'
} @{$self->unsafe_get('argv') || []})
: 'N/A';
}
sub commit_or_rollback {
my($self, $abort) = @_;
my($method) = $self->unsafe_get('noexecute') || $abort
? 'rollback' : 'commit';
b_use('Agent.Task')->$method($self->req);
return;
}
sub convert_literal {
my($proto, $type) = (shift, shift);
# Calls L<Bivio::Type::from_literal_or_die|Bivio::Type/"from_literal_or_die">
# on I<value> by loading I<type> first.
return $proto->use('Type', $type)->from_literal_or_die(@_);
}
sub detach_process {
my($self) = @_;
my($pid) = fork;
die("fork: $!")
unless defined($pid);
return $pid
if $pid;
# Child
my($log) = $_F->absolute_path(_detach_log($self));
open(STDIN, '< /dev/null');
open(STDOUT, "+> $log");
open(STDERR, '>&STDOUT');
select(STDERR);
$| = 1;
select(STDOUT);
$| = 1;
$_A->set_printer('FILE', $log);
eval {
require POSIX;
POSIX::setsid();
};
return;
}
sub do_backticks {
my($self, $command, $ignore_exit_code) = @_;
my($res) = $self->piped_exec(
$command,
undef,
$ignore_exit_code,
);
return wantarray ? split(/(?<=\n)/, $$res) : $$res;
}
sub finish {
my($self, $abort) = @_;
# Calls L<commit_or_rollback|"commit_or_rollback"> and undoes setup.
my($fields) = $self->[$_IDI];
$self->commit_or_rollback($abort);
$self->get_request->call_process_cleanup;
b_use('SQL.Connection')->set_dbi_name($fields->{prior_db})
if $fields->{prior_db};
return;
}
sub shell_util_request_instance {
return b_use('Test.Request')->get_instance->put_durable(is_secure => 1);
}
sub get_request {
my($self) = @_;
return $self->unsafe_get('req') || $self->setup->get('req')
if ref($self);
my($req) = b_use('Agent.Request')->get_current;
$_DIE->die('no request') unless $req;
return $req;
}
sub group_args {
my($proto, $group_size, $args) = @_;
# Returns an array of I<group_size> tuples (array_refs). Calls
# L<usage_error|"usage_error"> if I<args> not modulo I<group_size>.
#
# I<args> is modified.
$proto->usage_error("arguments must come in $group_size-tuples")
unless @$args % $group_size == 0;
my($res) = [];
push(@$res, [splice(@$args, 0, $group_size)])
while @$args;
return $res;
}
sub handle_call_autoload {
my($proto) = shift;
b_die($proto, ': arguments not allowed')
if @_;
return $proto
unless !$proto->equals_class_name('ShellUtil')
and my $req = b_use('Agent.Request')->get_current;
return $proto->new(\@_, $req);
}
sub handle_config {
my(undef, $cfg) = @_;
# daemon_log_file : string (named, required)
#
# Name of the log file for the daemon process. Will be passed to
# L<Bivio::IO::Log::file_name|Bivio::IO::Log/"file_name">, so may be relative.
# The log file is openned at each write to avoid collisions and to make log
# rotation easier.
#
# daemon_max_children : int [1] (named)
#
# Number of children for the worker. This creates a single queue.
#
# daemon_max_child_run_seconds : int [0] (named)
#
# Maximum elapsed run-time in seconds for a single process. If zero, no maximum.
# If greater than zero, child will be killed with TERM after run-time exceeded.
#
# daemon_max_child_term_seconds : int [0] (named)
#
# Elapsed run-time after kill TERM, before kill KILL is sent to the child.
#
# daemon_sleep_after_reap : int [0] (named)
#
# If 0, then L<run_daemon|"run_daemon"> calls C<wait> and blocks forever
# until any children exit. This is normal behavior.
#
# If greater than 0, then childred are reaped by polling C<waitpid> with
# C<POSIX::WNOHANG>. After all children are reaped, the reaper (run_daemon)
# sleeps for I<daemon_sleep_after_reap> before doing anything else.
#
# daemon_sleep_after_start : int [60] (named)
#
# Sleep after starts and before retries.
#
# lock_directory : string [/tmp]
#
# Where L<lock_action|"lock_action"> directories are created. Must be absolute,
# writable directory.
$_DIE->die($cfg->{lock_directory}, ': not a writable directory')
unless length($cfg->{lock_directory})
&& -w $cfg->{lock_directory} && -d _;
$_DIE->die($cfg->{lock_directory}, ': not absolute')
unless File::Spec->file_name_is_absolute($cfg->{lock_directory});
$_CFG = $cfg;
return;
}
sub if_option_execute {
my($self, $op) = @_;
return $op->()
unless $self->unsafe_get('noexecute');
return;
}
sub initialize_fully {
# Same as initialize_ui(1).
return shift->initialize_ui(1);
}
sub initialize_ui {
my($self, $fully) = @_;
# Initializes the UI and sets up the default facade. This takes some time, so
# classes should use this sparingly. If I<fully> is true, initializes all
# facades. Otherwise, only initializes the default facade, and does not setup
# tasks for execution.
my($req) = $self->get_request;
if ($req->can('setup_all_facades')) {
b_use('Agent.Dispatcher')->initialize(!$fully);
$req->setup_all_facades
if $fully;
}
b_use('UI.Facade')->setup_request(undef, $req)
unless $req->unsafe_get('UI.Facade');
$req->put_durable(
task => b_use('Agent.Task')->get_by_id($req->get('task_id')))
if $req->unsafe_get('task_id');
return $req;
}
sub is_execute {
return shift->unsafe_get('noexecute') ? 0 : 1;
}
sub is_loadavg_ok {
my($line) = $_F->read('/proc/loadavg');
# Returns TRUE if the machine load is below a configurable
# threshold.
#
# TODO: Make threshold configurable
my(@load) = $$line =~ /^([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)/;
return $load[0] < 4 ? 1 : 0;
}
sub lock_action {
my($proto, $op, $name, $no_warn) = @_;
# Creates a file lock for I<name> in /tmp/. If I<name> is undef,
# uses C<caller> subroutine name. The usage is:
#
# sub my_action {
# my($self, ...) = @_;
# return Bivio::ShellUtil->lock_action(sub {
# do something;
# });
# }
#
# Prints a warning of the lock couldn't be obtained. If I<op> dies,
# rethrows die after removing lock.
#
# The lock is a directory, and is owned by process. If that process dies,
# the lock is removed and re-acquired by this process.
#
# Returns the result of $op if lock was obtained and I<op> executed without
# dying. Returns () if lock could not be acquired.
#
#
# B<DEPRECATED USAGE BELOW>
#
#
# Creates a file lock for I<action> in I<lock_directory>. If I<action> is undef,
# uses C<caller> sub. The usage is:
#
# sub my_action {
# my($self, ...) = @_;
# return
# unless $self->lock_action;
# }
#
# This method forks a new process and returns true in the child process.
# The parent waits for the child and returns. There is no timeout, so
# child must be designed to be robust.
#
# Catches TERM signal and resignals (to previous handler) bug first removes the
# lock.
return _deprecated_lock_action($op || (caller(1))[3])
unless ref($op) eq 'CODE';
my($lock_dir, $lock_pid) = _lock_files($name || (caller(1))[3]);
my($clean) = sub {
$_F->rm_rf($lock_dir);
return;
};
my($this_host) = b_use('Bivio.BConf')->bconf_host_name;
foreach my $retry (1, 0) {
last
if mkdir($lock_dir, 0700);
unless ($retry) {
b_warn($lock_dir, ': unable to delete lock for dead process');
_lock_warning($lock_dir)
unless $no_warn;
return;
}
my($pid, $host) = -r $lock_pid ? split(/\s+/, ${$_F->read($lock_pid)}) : ();
if (($host && $host ne $this_host) || _process_exists($pid)) {
_lock_warning($lock_dir)
unless $no_warn;
return;
}
b_warn($pid, ": process doesn't exist, removing ", $lock_dir);
# Don't test results, because there may be contention
$clean->();
}
# Write host after pid to be backwards compatible with just pid format.
$_F->write($lock_pid, $$ . ' ' . $this_host);
my($prev) = $SIG{TERM};
local($SIG{TERM}) = sub {
$clean->();
$SIG{TERM} = $prev;
kill('TERM', $$);
return;
};
return $_DIE->catch_and_rethrow($op, $clean);
}
sub lock_realm {
my($self) = @_;
# Locks the current realm. Dies if general realm is auth_realm.
# Handles re-locking existing realm.
my($req) = $self->get_request;
$_DIE->die("can't lock general realm")
if $req->get('auth_realm')->get('type')
== Bivio::Auth::RealmType->GENERAL();
b_use('Model.Lock')->execute_unless_acquired($req);
return;
}
sub main {
my($proto, @argv) = @_;
# Parses its arguments. If I<argv[0]> contains is a valid public
# method (definition: begins with a letter), will call it.
# The rest of the arguments are passed verbatim
# to this method. If an error occurs, L<usage|"usage"> is called.
#
# Global options precede the command and are set on the instance.
#
# Returns the result as a string_ref if there is a result and wantarray is true.
# This backward compatible feature was added to ease testing.
local($|) = 1;
my(@new_args);
unless (ref($proto)) {
push(@new_args, shift(@argv))
if $argv[0] && $argv[0] =~ /^[A-Z]/;
push(@new_args, \@argv);
}
# Forces a setup, if called as $self
my($self) = ref($proto) ? $proto->setup(_initialize($proto, \@argv))
: $proto->new(@new_args);
my($fields) = $self->[$_IDI];
$fields->{in_main} = 1;
if ($self->unsafe_get('db')) {
# Setup DBI connection to access a probably non-default database
$self->setup();
}
my($p) = $0 || '';
$p =~ s!.*/!!;
$p =~ s!\.\w+$!!;
$self->put(program => $p);
my($cmd, $res);
my($die) = $_DIE->catch(sub {
if (@argv and $cmd = _method_ok($self, $argv[0])) {
shift(@argv);
}
else {
$self->usage(@argv ? ($argv[0], ': unknown command')
: 'missing command');
}
return;
});
unless ($die) {
my($pid);
if ($self->unsafe_get('detach')) {
$_A->info('log=', _detach_log($self));
if ($pid = $self->detach_process) {
$res = "$pid\n";
$self->SUPER::delete(qw(output email req));
}
}
$die = $_DIE->catch(sub {
$res = $self->$cmd(@argv);
}) unless $pid;
}
$fields->{in_main} = 0;
# Don't finish if setup never called.
$self->finish($die ? 1 : 0)
if $self->unsafe_get('req');
if ($die) {
# Email error and re-throw
$self->put(result_type => undef,
result_subject => 'ERROR from: '.$self->command_line);
_result_email($self, $cmd, $die->as_string);
if ($self->unsafe_get('live')) {
$_A->warn($die);
return;
}
$die->throw();
# DOES NOT RETURN
}
return $res
if $res = $self->result($cmd, $res) and wantarray;
return;
}
sub model {
shift->get_request;
return $_M->new_other_with_query(@_);
}
sub name_args {
my($proto, $decls, $args) = @_;
my($last_decl) = $decls->[$#$decls];
my($res) = {};
return (
$proto,
@{$proto->map_together(sub {
my($arg, $decl) = @_;
$decl ||= $last_decl;
$decl = [$decl]
unless ref($decl);
my($name, $type, $default) = @$decl;
($default, $type) = ($type, undef)
if ref($type) eq 'CODE';
my($has_default) = $name =~ s/^\?// || defined($default)
|| @$decl > 2;
$type ||= $name;
$type = "Type.$type"
unless $type =~ /\W/;
$type = $proto->use($type);
my($v, $e) = $type->from_literal($arg);
return $res->{$name} = $v
if defined($v);
unless ($e) {
return $res->{$name} = ref($default) eq 'CODE'
? $default->($proto, $res) : $default
if $has_default;
$e = $_TE->NULL;
}
$proto->usage_error(
$arg, ': invalid ', $name, ': ',
$e->get_long_desc, '; see Type.', $type, "\n");
# DOES NOT RETURN
}, $args, $decls)},
);
return;
}
sub new {
my($proto, $class, $argv, $req) = @_;
# Initializes a new instance with these command line arguments.
if ($class && !ref($class)) {
$proto = _other($proto, $class);
}
else {
$argv = $class;
$_DIE->die($proto, ': must not be called as ShellUtil->new')
if $proto eq __PACKAGE__;
}
return _initialize($proto->SUPER::new, $argv, $req);
}
sub new_other {
my($self, $class) = @_;
# Instantiates a new ShellUtil, whose class is I<class>. Will load class
# dynamically (must be fully qualified). Passes standard options from I<self>
# to I<other>
# Calls I<put_request> on I<other> if there's a request on I<self>, i.e.
# L<get_request|"get_request"> has been called.
#
# If I<self> is not an instance, no options are passed (defaults will
# be used in I<other>).
#
# You can override options by calling I<put> on I<other> after this
# call returns.
# explicit die if not found
# ClassLoader calls throw_quietly() which has no output
my($c) = _other($self, $class);
my($options) = [];
if (ref($self)) {
my($standard) = __PACKAGE__->OPTIONS();
while (my($k, $v) = each(%$standard)) {
if ($v->[0] eq 'Boolean') {
push(@$options, '-'.$k) if $self->unsafe_get($k);
}
else {
# We don't pass undef options.
my($actual) = $self->unsafe_get($k);
push(@$options, '-'.$k, $actual)
if defined($actual) != defined($v)
|| defined($v) && $v ne $actual;
}
}
}
my($other) = $c->new($options);
$other->put_request($self->get_request)
if $self->unsafe_get('req');
$other->put(program => $self->unsafe_get('program'))
if ref($self) && $self->has_keys('program');
return $other;
}
sub piped_exec {
my(undef, $command, $input, $ignore_exit_code) = @_;
# Runs I<command> with I<input> (or empty input) and returns output.
# I<input> may be C<undef>.
#
# Throws exception if it can't write the input. Throws exception if the
# command returns a non-zero exit result unless ignore_exit_code is
# specified. The L<$_DIE|$_DIE> has an I<exit_code> attribute.
my($in) = ref($input) ? $input : \$input;
$$in = '' unless defined($$in);
my($pid) = open(IN, "-|");
defined($pid) || die("fork: $!");
#TODO: Use IO::File and $_F
unless ($pid) {
$_HANDLERS->call_fifo('handle_piped_exec_child');
(ref($command) eq 'ARRAY'
? open(OUT, '|-', @$command)
: open(OUT, "| exec $command")
) || $_DIE->die($command, ": open failed: $!");
print(OUT $$in);
close(OUT);
# If there is a signal, return 99. Otherwise, return exit code.
CORE::exit($? ? ($? >> 8) ? ($? >> 8) : 99 : 0);
}
my($res);
if ($_TRACE) {
_trace('START: ', $command);
while (defined(my $line = <IN>)) {
$res .= $line;
_trace($line);
}
_trace('END: ', $command);
}
else {
local($/) = undef;
$res = <IN>;
}
# May be undef
$res .= '';
unless (close(IN)) {
$_DIE->throw_die('DIE', {
message => 'command died with non-zero status',
entity => $command,
input => $in,
output => \$res,
exit_code => $?,
}) unless $ignore_exit_code;
}
return \$res;
}
sub piped_exec_remote {
my($self, $host, $command, $input, $ignore_exit_code) = @_;
# Run I<command> remotely using C<ssh>. Returns result. Assumes remote shell
# understands single quote escaping.
if (defined($host)) {
$command =~ s/'/'\''/g;
$command = "ssh $host '($command) && echo OK$$'";
}
my($res) = $self->piped_exec($command, $input, $ignore_exit_code);
$_DIE->throw_die('DIE', {
message => 'remote command failed',
host => $host,
entity => $command,
output => $res,
}) unless $$res =~ s/OK$$\n// || $ignore_exit_code;
return $res;
}
sub print {
# Writes output to STDERR. Returns result of print.
# This method may be overriden.
shift;
return print(STDERR @_);
}
sub print_line {
return shift->print(@_, "\n");
}
sub put {
my($self) = shift;
# If called statically, has no effect. Otherwise, just calls
# L<Bivio::Collection::Attributes::put|Bivio::Collection::Attributes/"put">.
return unless ref($self);
return $self->SUPER::put(@_);
}
sub put_request {
my($self, $req) = @_;
# Puts I<req> on I<self> and modifies other values appropriately.
# Sets the current request to I<req>.
return $self->put(req => $req);
}
sub read_input {
my($self) = @_;
# Returns the contents if I<input> argument. If no argument, reads
# from STDIN. If I<input> is a ref, just return that.
my($input) = $self->get('input');
return ref($input) ? $input : $_F->read($input);
}
sub readline_stdin {
my($self, $prompt) = @_;
# Prints I<prompt>, and returns answer stripped of leading and trailing
# whitespace.
$self->print($prompt);
my $answer = <STDIN>;
chomp($answer);
$answer =~ s/^\s+|\s+$//g;
return $answer;
}
sub ref_to_string {
return shift->use('IO.Ref')->to_string(@_);
}
sub register_handler {
shift;
$_HANDLERS->push_object(@_);
return;
}
sub required_main {
my($proto, $class, @args) = @_;
my($pkgs) = $_CL->list_simple_packages_in_map($_MAP_NAME);
$proto->usage_error(
join("\n",
'first argument must be a class name. Available classes:',
@$pkgs,
)
. "\n"
) unless $class;
if ($proto->is_simple_package_name($class)) {
my($c) = grep(/^\Q$class\E$/i, @$pkgs);
$proto->usage_error($class, ": class not found in $_MAP_NAME map")
unless $c;
$class = $c;
}
return ref($proto->new($_CL->map_require($_MAP_NAME => $class)))
->main(@args);
}
sub result {
my($self, $cmd, $res) = @_;
# Processes I<res> by sending via I<email> and writing to I<output>
# or printing to STDOUT. Returns a reference to result or undef.
$res = _result_ref($self, $res);
return undef
unless $res;
print(STDOUT $$res, $$res =~ /\n$/s ? () : "\n")
unless _result_email($self, $cmd, $res)
+ _result_output($self, $cmd, $res);
return $res;
}
sub run_daemon {
my($self, $next_command, $cfg_name) = @_;
# Starts a collection of processes using config defined by
# I<cfg_name> (see L<handle_config|"handle_config">.
$self->get_request;
my($cfg) = $_C->get($cfg_name);
# Makes log rotating simple: All processes share a log
$_A->set_printer('FILE', $_L->file_name($cfg->{daemon_log_file}))
if $cfg->{daemon_log_file};
_check_cfg($cfg, $cfg_name);
my($children) = {};
my($ref) = b_use('IO.Ref');
while (1) {
my($max_duplicates) = $cfg->{daemon_max_children};
while (keys(%$children) < $cfg->{daemon_max_children}) {
my($args) = $next_command->();
last unless $args;
_reap_daemon_children($children, 0, 0, $cfg);
if (grep(
$ref->nested_equals($args, $_->{args}),
values(%$children),
)) {
_trace('already running: ', $args) if $_TRACE;
# protects against infinite loop when daemon_max_children
# is greater than the number of jobs.
last if --$max_duplicates <= 0;
}
else {
$children->{_start_daemon_child($self, $args, $cfg)} = {
args => $args,
$cfg->{daemon_max_child_run_seconds} > 0
? (max_time =>
time + $cfg->{daemon_max_child_run_seconds})
: (),
};
sleep($cfg->{daemon_sleep_after_start});
}
}
return unless %$children;
_reap_daemon_children(
$children,
$cfg->{daemon_sleep_after_reap} > 0
? (0, $cfg->{daemon_sleep_after_reap})
: (wait, 0),
$cfg,
);
}
return;
}
sub send_mail {
my($self, $email, $subject, $body) = @_;
my($msg) = b_use('Mail.Outgoing')->new;
my($req) = $self->get_request;
$msg->set_recipients($email, $req);
$msg->set_header('Subject', $subject);
$msg->set_header('To', $email);
$msg->set_from_with_user($req);
if (ref($body) eq 'CODE') {
$body->($msg);
}
elsif ($_CL->was_required('Model.RealmFile')
&& b_use('Model.RealmFile')->is_blesser_of($body),
) {
$msg->set_content_type('multipart/mixed');
$msg->attach({
content => $body->get_content,
content_type => $body->get_content_type,
filename => $_FP->get_tail($body->get('path')),
});
}
elsif (ref($body) eq 'SCALAR') {
$msg->set_body($body);
}
else {
b_die($body, ': invalid message body type');
}
$msg->send($req)
unless $self->unsafe_get('noexecute');
return;
}
sub set_realm_and_user {
my($self, $realm, $user) = @_;
$realm = b_use('Auth.Realm')->get_general()
unless defined($realm);
my($req) = $self->get_request;
$req->set_realm($realm);
if (defined($user)) {
$req->set_user($user);
return $self;
}
$self->set_user_to_any
unless $req->get('auth_realm')->is_general;
return $self;
}
sub set_user_to_any {
return _any_user(unsafe_get_any_online_admin => @_);
}
sub set_user_to_any_online_admin {
return _any_user(get_any_online_admin => @_);