blib/lib/App/BrowserUtils.pm

filter: Statementstmt 16.9% 53 / 312 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 51 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 24.0% 6 / 25 Podpod 100% 8 / 8 totaltotal 11.7% 67 / 572 CC 108 SCAR 69.8
CC
108
Cov
10%
_do_browser
2150.3
_start_or_restart_browsers
1190.0
browsers_are_paused
72.0
CRAP 1079.4
↑ Summary
1 package App::BrowserUtils;
2  
3 1 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict 'subs', 'vars';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Log::ger;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use Hash::Subset qw(hash_subset);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
11 1 our $DATE = '2023-10-28'; # DATE
12 1 our $DIST = 'App-BrowserUtils'; # DIST
13 1 our $VERSION = '0.019'; # VERSION
14  
15 1 our %SPEC;
16  
17 1 $SPEC{':package'} = {
18 v => 1.1,
19 summary => 'Utilities related to browsers, particularly modern GUI ones',
20 };
21  
22 our %browsers = (
23 firefox => {
24 0 ▶ filter => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
25 0 my $p = shift;
26  
27 # when firefox is upgraded while an instance is still running, the
28 # exec field becomes empty and we need to use cmndline
29 0 ▶ my $prog = $p->{exec} || $p->{cmndline};
Condition0%0/3
$p->{'exec'} || $p->{'cmndline'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$p->{'exec'} || $p->{'cmndline'}
$p->{'exec'} $p->{'cmndline'}
Truth table0%0/3
A || B
A= $p->{'exec'}B= $p->{'cmndline'}
ABresult
1X1
011
000
30  
31 # in some OS like linux the binary is firefox-bin or firefox-esr,
32 # while in some other like FreeBSD, it's firefox.
33 0 ▶ do { $p->{_note} = "program is firefox binary"; goto FOUND } if $prog =~ m![/\\](firefox-bin|firefox-esr|firefox)(\z|\s)!;
Branch: 1 branch
BranchTrueFalseTotal
if ($prog =~ m([/\\](firefox-bin|firefox-esr|firefox)(\z|\s))) 0 0 0
34 0 ▶ do { $p->{_note} = "fname looks like firefox"; goto FOUND } if $p->{fname} =~ /\A(Web Content|WebExtensions|firefox-bin|firefox-esr|firefox)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"fname"} =~ /\A(Web Content|WebExtensions|firefox-bin|firefox-esr|firefox)\z/) 0 0 0
35 0 goto NOT_FOUND;
36 FOUND:
37 0 log_trace "Found firefox process (PID=%d, prog (exec|cmndline)=%s, note=%s)", $p->{pid}, $prog, $p->{_note};
38 0 return 1;
39 0 NOT_FOUND:
40 0;
41 },
42 },
43 chrome => {
44 0 ▶ filter => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
45 0 my $p = shift;
46 0 ▶ do { $p->{_note} = "fname looks like chrome"; goto FOUND } if $p->{fname} =~ /\A(chrome)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"fname"} =~ /\A(chrome)\z/) 0 0 0
47 0 goto NOT_FOUND;
48 FOUND:
49 0 log_trace "Found chrome process (PID=%d, cmdline=%s, note=%s)", $p->{pid}, $p->{cmndline}, $p->{_note};
50 0 return 1;
51 0 NOT_FOUND:
52 0;
53 },
54 },
55 opera => {
56 0 ▶ filter => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
57 0 my $p = shift;
58 0 ▶ do { $p->{_note} = "fname looks like opera"; goto FOUND } if $p->{fname} =~ /\A(opera)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"fname"} =~ /\A(opera)\z/) 0 0 0
59 0 goto NOT_FOUND;
60 FOUND:
61 0 log_trace "Found opera process (PID=%d, cmdline=%s, note=%s)", $p->{pid}, $p->{cmndline}, $p->{_note};
62 0 return 1;
63 0 NOT_FOUND:
64 0;
65 },
66 },
67 vivaldi => {
68 0 ▶ filter => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
69 0 my $p = shift;
70 0 ▶ do { $p->{_note} = "fname looks like vivaldi"; goto FOUND } if $p->{fname} =~ /\A(vivaldi-bin)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"fname"} =~ /\A(vivaldi-bin)\z/) 0 0 0
71 0 goto NOT_FOUND;
72 FOUND:
73 0 log_trace "Found vivaldi process (PID=%d, cmdline=%s, note=%s)", $p->{pid}, $p->{cmndline}, $p->{_note};
74 0 return 1;
75 0 NOT_FOUND:
76 0;
77 },
78 },
79 brave => {
80 0 ▶ filter => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
81 0 my $p = shift;
82 0 ▶ do { $p->{_note} = "fname looks like brave"; goto FOUND } if $p->{fname} =~ /\A(brave)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"fname"} =~ /\A(brave)\z/) 0 0 0
83 0 goto NOT_FOUND;
84 FOUND:
85 0 log_trace "Found brave process (PID=%d, cmdline=%s, note=%s)", $p->{pid}, $p->{cmndline}, $p->{_note};
86 0 return 1;
87 0 NOT_FOUND:
88 0;
89 },
90 },
91 1 );
92  
93 1 our $sch_cmd = ['any*', of=>[ ['array*',of=>'str*',min_len=>1], ['str*'] ]];
94  
95 1 our %argopt_firefox_cmd = (
96 firefox_cmd => {
97 schema => $sch_cmd,
98 default => 'firefox',
99 },
100 );
101  
102 1 our %argopt_chrome_cmd = (
103 chrome_cmd => {
104 schema => $sch_cmd,
105 default => 'google-chrome',
106 },
107 );
108  
109 1 our %argopt_opera_cmd = (
110 opera_cmd => {
111 schema => $sch_cmd,
112 default => 'opera',
113 },
114 );
115  
116 1 our %argopt_vivaldi_cmd = (
117 vivaldi_cmd => {
118 schema => $sch_cmd,
119 default => 'vivaldi',
120 },
121 );
122  
123 1 our %argsopt_browser_cmd = (
124 %argopt_firefox_cmd,
125 %argopt_chrome_cmd,
126 %argopt_opera_cmd,
127 %argopt_vivaldi_cmd,
128 );
129  
130 1 our %argsopt_browser_start = (
131 start_firefox => {
132 schema => 'bool*',
133 },
134 start_chrome => {
135 schema => 'bool*',
136 },
137 start_opera => {
138 schema => 'bool*',
139 },
140 start_vivaldi => {
141 schema => 'bool*',
142 },
143 start_brave => {
144 schema => 'bool*',
145 },
146 );
147  
148 1 our %argsopt_browser_restart = (
149 restart_firefox => {
150 schema => 'bool*',
151 },
152 restart_chrome => {
153 schema => 'bool*',
154 },
155 restart_opera => {
156 schema => 'bool*',
157 },
158 restart_vivaldi => {
159 schema => 'bool*',
160 },
161 restart_brave => {
162 schema => 'bool*',
163 },
164 );
165  
166 1 our %argopt_users = (
167 users => {
168 'x.name.is_plural' => 1,
169 'x.name.singular' => 'user',
170 summary => 'Kill browser processes that belong to certain user(s) only',
171 schema => ['array*', of=>'unix::uid::exists*', 'x.perl.coerce_rules' => ['From_str::comma_sep']],
172 },
173 );
174  
175 1 our %argopt_quiet = (
176 quiet => {
177 schema => 'true*',
178 cmdline_aliases => {q=>{}},
179 },
180 );
181  
182 1 our %argopt_signal = (
183 signal => {
184 schema=>'unix::signal*',
185 cmdline_aliases => {s=>{}},
186 },
187 );
188  
189 1 our %argopt_periods = (
190 periods => {
191 'x.name.is_plural' => 1,
192 'x.name.singular' => 'period',
193 summary => 'Pause and unpause times, in seconds',
194 schema => ['array*', {
195 of=>'duration',
196 min_len=>2,
197 #'x.perl.coerce_rules'=>['From_str::comma_sep'], # not working yet
198 }],
199 description => <<'MARKDOWN',
200  
201 For example, to pause for 5 minutes, then unpause 10 seconds, then pause for 2
202 minutes, then unpause for 30 seconds (then repeat the pattern), you can use:
203  
204 300,10,120,30
205  
206 MARKDOWN
207 },
208 );
209  
210 1 my $desc_pat = <<'MARKDOWN';
211  
212 If one of the `*-pat` options are specified, then instead of the default
213 heuristic rules to find the browser processes, these `*-pat` options are solely
214 used to determine which processes are the browser processes.
215  
216 MARKDOWN
217  
218 1 my %argopt_cmndline_pat = (
219 cmndline_pat => {
220 summary => 'Filter processes using regex against their cmndline',
221 schema => 're_from_str*',
222 description => $desc_pat,
223 tags => ['category:filtering'],
224 },
225 );
226  
227 1 my %argopt_exec_pat = (
228 exec_pat => {
229 summary => 'Filter processes using regex against their exec',
230 schema => 're_from_str*',
231 description => $desc_pat,
232 tags => ['category:filtering'],
233 },
234 );
235  
236 1 my %argopt_fname_pat = (
237 fname_pat => {
238 summary => 'Filter processes using regex against their fname',
239 schema => 're_from_str*',
240 description => $desc_pat,
241 tags => ['category:filtering'],
242 },
243 );
244  
245 1 my %argopt_pid_pat = (
246 pid_pat => {
247 summary => 'Filter processes using regex against their pid',
248 schema => 're_from_str*',
249 description => $desc_pat,
250 tags => ['category:filtering'],
251 },
252 );
253  
254 1 our %args_common = (
255 %argopt_users,
256 %argopt_cmndline_pat,
257 %argopt_exec_pat,
258 %argopt_fname_pat,
259 %argopt_pid_pat,
260 );
261  
262 1 our $desc_pause = <<'MARKDOWN';
263  
264 A modern browser now runs complex web pages and applications. Despite browser's
265 power management feature, these pages/tabs on the browser often still eat
266 considerable CPU cycles even though they only run in the background. Pausing
267 (kill -STOP) the browser processes is a simple and effective way to stop CPU
268 eating on Unix and prolong your laptop battery life. It can be performed
269 whenever you are not using your browser for a little while, e.g. when you are
270 typing on an editor or watching a movie. When you want to use your browser
271 again, simply unpause (kill -CONT) it.
272  
273 MARKDOWN
274  
275 1 our $desc_pause_and_unpause = $desc_pause . <<'MARKDOWN';
276 The `pause-and-unpause` action pause and unpause browser in an alternate
277 fashion, by default every 5 minutes and 30 seconds. This is a compromise to save
278 CPU time most of the time but then give time for web applications in the browser
279 to catch up during the unpause window (e.g. for WhatsApp Web to display new
280 messages and sound notification.) It can be used when you are not browsing but
281 still want to be notified by web applications from time to time.
282  
283 If you run this routine, it will start pausing and unpausing browser. When you
284 want to use the browser, press Ctrl-C to interrupt the routine. Then after you
285 are done with the browser and want to pause-and-unpause again, you can re-run
286 this routine.
287  
288 You can customize the periods via the `periods` option.
289  
290 MARKDOWN
291  
292 0 ▶sub _do_browser {
Subroutine _do_browser: not called CC=47 SCAR=76.7
293 0 require Proc::Find;
294  
295 0 my ($which_action, $which_browser, %args) = @_;
296  
297 my $browser_fname_pat = ($which_browser eq 'all known browsers' || $browsers{$which_browser}{filter})
298 0 ▶ or return [400, "Unknown browser '$which_browser'"];
Branch: 1 branch
BranchTrueFalseTotal
my $browser_fname_pat = $which_browser eq "all known browsers" || $App::BrowserUtils::browsers{$which_browser}{"filter"} or return [400, "Unknown browser '${which_browser}'"] 0 0 0
Condition0%0/3
$which_browser eq 'all known browsers' || $App::BrowserUtils::browsers{$which_browser}{'filter'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$which_browser eq 'all known browsers' || $App::BrowserUtils::browsers{$which_browser}{'filter'}
$which_browser eq 'all known browsers' $App::BrowserUtils::browsers{$which_browser}{'filter'}
Truth table0%0/3
A || B
A= $which_browser eq 'all known browsers'B= $App::BrowserUtils::browsers{$which_browser}{'filter'}
ABresult
1X1
011
000
299  
300 0 ▶ my @periods = @{ $args{periods} // [300,30] };
Condition0%0/2
$args{"periods"} // [300, 30]
l!l
00
MC/DC0%0/1
$args{"periods"} // [300, 30]
$args{"periods"}
Truth table0%0/2
A
A= $args{"periods"}
Aresult
11
00
301 0 my @stopped_pids;
302 0 my $period_idx = -1;
303  
304 0 ▶ local $SIG{INT} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
305 0 ▶ if (@stopped_pids) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stopped_pids) 0 0 0
306 0 log_info "Unpausing stopped PID(s) ...";
307 0 kill CONT => @stopped_pids;
308 }
309 0 log_info "Exiting ...";
310 0 exit 0;
311 0 };
312  
313 0 ▶ my $filter = (defined $args{cmndline_pat} || defined $args{exec_pat} || defined $args{fname_pat} || defined $args{pid_pat}) ? sub {
Subroutine __ANON__: not called CC=4 SCAR=25.0
314 0 my $p = shift;
315 1 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
316 0 for my $f (qw(cmndline exec fname pid)) {
317 0 ▶ if (defined $args{"${f}_pat"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"${f}_pat"}) 0 0 0
318 0 ▶ if ($p->{$f} =~ /$args{"${f}_pat"}/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{$f} =~ /$args{"${f}_pat"}/) { } 0 0 0
319 0 log_trace "Process %s '%s' matches pattern '%s'", $f, $p->{$f}, $args{"${f}_pat"};
320 } else {
321 0 log_trace "Process %s '%s' does NOT match pattern '%s'", $f, $p->{$f}, $args{"${f}_pat"};
322 0 return 0;
323 }
324 }
325 }
326 0 1;
327 0 ▶ } : $which_browser eq 'all known browsers' ? sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
328 0 for my $br (keys %browsers) {
329 0 ▶ return 1 if $browsers{$br}{filter}->(@_);
Branch: 1 branch
BranchTrueFalseTotal
if $App::BrowserUtils::browsers{$br}{"filter"}->(@_) 0 0 0
330 }
331 0 0;
332 0 ▶ } : $browsers{$which_browser}{filter};
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'cmndline_pat'} || defined $args{'exec_pat'} || defined $args{'fname_pat'} || defined $args{'pid_pat'} ? : 0 0 0
$which_browser eq 'all known browsers' ? : 0 0 0
Condition0%0/9
defined $args{"cmndline_pat"} or defined $args{"exec_pat"} or defined $args{"fname_pat"} or defined $args{"pid_pat"}
l!l&&r!l&&!r
000
defined $args{"cmndline_pat"} or defined $args{"exec_pat"} or defined $args{"fname_pat"}
l!l&&r!l&&!r
000
defined $args{"cmndline_pat"} or defined $args{"exec_pat"}
l!l&&r!l&&!r
000
MC/DC0%0/4
defined $args{"cmndline_pat"} or defined $args{"exec_pat"} or defined $args{"fname_pat"} or defined $args{"pid_pat"}
defined $args{"cmndline_pat"} defined $args{"exec_pat"} defined $args{"fname_pat"} defined $args{"pid_pat"}
Truth table0%0/5
A or B or C or D
A= defined $args{"cmndline_pat"}B= defined $args{"exec_pat"}C= defined $args{"fname_pat"}D= defined $args{"pid_pat"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
333  
334 0 while (1) {
335 0 my $procs = Proc::Find::find_proc(
336 detail => 1,
337 filter => $filter,
338 );
339  
340 0 my @pids = map { $_->{pid} } @$procs;
341  
342 0 ▶ if ($which_action eq 'ps') {
Branch: 6 branches
BranchTrueFalseTotal
if ($which_action eq 'ps') { } 0 0 0
elsif ($which_action eq 'pause') { } 0 0 0
elsif ($which_action eq 'unpause') { } 0 0 0
elsif ($which_action eq 'terminate') { } 0 0 0
elsif ($which_action eq 'has_processes' or $which_action eq 'is_paused' or $which_action eq 'is_running') { } 0 0 0
elsif ($which_action eq 'pause_and_unpause') { } 0 0 0
343 0 ▶ if ($args{-cmdline_r} && (!defined($args{-cmdline_r}{format}) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-cmdline_r"} and !defined($args{"-cmdline_r"}{"format"}) || $args{"-cmdline_r"}{"format"} =~ /text/) 0 0 0
Condition0%0/6
$args{"-cmdline_r"} and !defined($args{"-cmdline_r"}{"format"}) || $args{"-cmdline_r"}{"format"} =~ /text/
!ll&&!rl&&r
000
not defined $args{"-cmdline_r"}{"format"} or $args{"-cmdline_r"}{"format"} =~ /text/
l!l&&r!l&&!r
000
MC/DC0%0/3
$args{"-cmdline_r"} and !defined($args{"-cmdline_r"}{"format"}) || $args{"-cmdline_r"}{"format"} =~ /text/
$args{"-cmdline_r"} not defined $args{"-cmdline_r"}{"format"} $args{"-cmdline_r"}{"format"} =~ /text/
Truth table0%0/4
A and not(B) or C
A= $args{"-cmdline_r"}B= not defined $args{"-cmdline_r"}{"format"}C= $args{"-cmdline_r"}{"format"} =~ /text/
ABCresult
0XX0
1000
11X1
1011
344 $args{-cmdline_r}{format} =~ /text/)) {
345 # convert arrayrefs etc so the result can still be rendered as
346 # simple 2d table
347 0 for my $proc (@$procs) {
348 # too big
349 0 delete $proc->{environ};
350 0 delete $proc->{cmndline}; # duplicate info with cmdline
351  
352 0 for my $key (keys %$proc) {
353 0 $proc->{$key} = join(" ", @{ $proc->{$key} })
354 0 ▶ if ref $proc->{$key} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $proc->{$key} eq "ARRAY" 0 0 0
355 }
356 }
357 }
358 0 return [200, "OK", $procs, {'table.fields'=>[qw/pid uid euid state cmdline/]}];
359 } elsif ($which_action eq 'pause') {
360 0 kill STOP => @pids;
361 0 return [200, "OK", "", {"func.pids" => \@pids}];
362 } elsif ($which_action eq 'unpause') {
363 0 kill CONT => @pids;
364 0 return [200, "OK", "", {"func.pids" => \@pids}];
365 } elsif ($which_action eq 'terminate') {
366 0 my $signal;
367 0 ▶ if (defined $args{signal}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'signal'}) { } 0 0 0
368 0 log_info "Sending %s signal to $which_browser ...", $args{signal};
369 0 $signal = $args{signal};
370 } else {
371 0 log_info "Terminating $which_browser ...";
372 0 $signal = 'KILL';
373 }
374 0 kill $signal => @pids;
375 0 return [200, "OK", "", {"func.pids" => \@pids}];
376 ▶ } elsif ($which_action eq 'has_processes' || $which_action eq 'is_paused' || $which_action eq 'is_running') {
Condition0%0/6
$which_action eq "has_processes" or $which_action eq "is_paused" or $which_action eq "is_running"
l!l&&r!l&&!r
000
$which_action eq "has_processes" or $which_action eq "is_paused"
l!l&&r!l&&!r
000
MC/DC0%0/3
$which_action eq "has_processes" or $which_action eq "is_paused" or $which_action eq "is_running"
$which_action eq "has_processes" $which_action eq "is_paused" $which_action eq "is_running"
Truth table0%0/4
A or B or C
A= $which_action eq "has_processes"B= $which_action eq "is_paused"C= $which_action eq "is_running"
ABCresult
1XX1
01X1
0011
0000
377 0 my $num_stopped = 0;
378 0 my $num_unstopped = 0;
379 0 my $num_total = 0;
380 0 for my $proc (@$procs) {
381 0 $num_total++;
382 0 ▶ if ($proc->{state} eq 'stop') { $num_stopped++ } else { $num_unstopped++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($proc->{'state'} eq 'stop') { } 0 0 0
383 }
384 0 ▶ if ($which_action eq 'has_processes') {
Branch: 2 branches
BranchTrueFalseTotal
if ($which_action eq 'has_processes') { } 0 0 0
elsif ($which_action eq 'is_paused') { } 0 0 0
385 0 ▶ my $has_processes = $num_total > 0 ? 1:0;
Branch: 1 branch
BranchTrueFalseTotal
$num_total > 0 ? : 0 0 0
386 0 ▶ my $msg = $has_processes ? "$which_browser has processes" : "$which_browser does NOT have processes";
Branch: 1 branch
BranchTrueFalseTotal
$has_processes ? : 0 0 0
387 return [200, "OK", $has_processes, {
388 "cmdline.exit_code" => $has_processes ? 0:1,
389 0 ▶ "cmdline.result" => $args{quiet} ? '' : $msg,
Branch: 2 branches
BranchTrueFalseTotal
$has_processes ? : 0 0 0
$args{'quiet'} ? : 0 0 0
390 }];
391 } elsif ($which_action eq 'is_paused') {
392 0 ▶ my $is_paused = $num_total == 0 ? undef : $num_stopped == $num_total ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$num_total == 0 ? : 0 0 0
$num_stopped == $num_total ? : 0 0 0
393 0 ▶ my $msg = $num_total == 0 ? "There are NO $which_browser processes" :
Branch: 3 branches
BranchTrueFalseTotal
$num_total == 0 ? : 0 0 0
$num_stopped == $num_total ? : 0 0 0
$num_unstopped == $num_total ? : 0 0 0
394 $num_stopped == $num_total ? "$which_browser is paused (all processes are in stop state)" :
395 $num_unstopped == $num_total ? "$which_browser is NOT paused (all processes are not in stop state)" :
396 "$which_browser is NOT paused (some processes are not in stop state)";
397 return [200, "OK", $is_paused, {
398 'cmdline.exit_code' => $is_paused ? 0:1,
399 0 ▶ 'cmdline.result' => $args{quiet} ? '' : $msg,
Branch: 2 branches
BranchTrueFalseTotal
$is_paused ? : 0 0 0
$args{'quiet'} ? : 0 0 0
400 }];
401 } else {
402 0 ▶ my $is_running = $num_total == 0 ? undef : $num_unstopped > 0 ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$num_total == 0 ? : 0 0 0
$num_unstopped > 0 ? : 0 0 0
403 0 ▶ my $msg = $num_total == 0 ? "There are NO $which_browser processes" :
Branch: 2 branches
BranchTrueFalseTotal
$num_total == 0 ? : 0 0 0
$num_unstopped > 0 ? : 0 0 0
404 $num_unstopped > 0 ? "$which_browser is running (some processes are not in stop state)" :
405 "$which_browser exists but is NOT running (all processes are in stop state)";
406 return [200, "OK", $is_running, {
407 'cmdline.exit_code' => $is_running ? 0:1,
408 0 ▶ 'cmdline.result' => $args{quiet} ? '' : $msg,
Branch: 2 branches
BranchTrueFalseTotal
$is_running ? : 0 0 0
$args{'quiet'} ? : 0 0 0
409 }];
410 }
411 } elsif ($which_action eq 'pause_and_unpause') {
412 0 $period_idx++;
413 0 ▶ $period_idx = 0 if $period_idx >= @periods;
Branch: 1 branch
BranchTrueFalseTotal
if $period_idx >= @periods 0 0 0
414 0 my $period = $periods[$period_idx];
415 0 ▶ if ($period_idx == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($period_idx == 0) { } 0 0 0
416 0 log_info "Pausing $which_browser for $period second(s) ...";
417 0 kill STOP => @pids;
418 0 @stopped_pids = @pids;
419 } else {
420 0 log_info "Unpausing $which_browser for $period second(s) ...";
421 0 kill CONT => @stopped_pids;
422 0 @stopped_pids = ();
423 }
424 0 sleep $period;
425 } else {
426 0 die "BUG: unknown command";
427 }
428 } # while 1
429 }
430  
431 $SPEC{ps_browsers} = {
432 1 v => 1.1,
433 summary => "List browser processes",
434 args => {
435 %args_common,
436 },
437 };
438 0 ▶sub ps_browsers {
Subroutine ps_browsers: not called CC=3 SCAR=24.8
Pod documented
439 0 my %args = @_;
440  
441 0 my @rows;
442 0 for my $browser (sort keys %browsers) {
443 0 my $res = _do_browser('ps', $browser, %args);
444 0 ▶ return $res unless $res->[0] == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->[0] == 200 0 0 0
445 0 push @rows, @{$res->[2]}; # XXX remove duplicate?
446 }
447 0 [200, "OK", \@rows];
448 }
449  
450 $SPEC{pause_browsers} = {
451 1 v => 1.1,
452 summary => "Pause (kill -STOP) browsers",
453 description => $desc_pause .
454 "See also the `unpause_browsers` and the `pause_and_unpause_browsers` routines.\n\n",
455 args => {
456 %args_common,
457 },
458 };
459 0 ▶sub pause_browsers {
Subroutine pause_browsers: not called CC=3 SCAR=24.8
Pod documented
460 0 my %args = @_;
461  
462 0 my @pids;
463 0 for my $browser (sort keys %browsers) {
464 0 my $res = _do_browser('pause', $browser, %args);
465 0 ▶ return $res unless $res->[0] == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->[0] == 200 0 0 0
466 0 push @pids, @{$res->[3]{'func.pids'}};
467 }
468 0 [200, "OK", undef, {"func.pids" => \@pids}];
469 }
470  
471 $SPEC{unpause_browsers} = {
472 1 v => 1.1,
473 summary => "Unpause (resume, continue, kill -CONT) browsers",
474 description => <<'MARKDOWN',
475  
476 See also the `pause_browsers` and the `pause_and_unpause_browsers` routines.
477  
478 MARKDOWN
479 args => {
480 %args_common,
481 },
482 };
483 0 ▶sub unpause_browsers {
Subroutine unpause_browsers: not called CC=3 SCAR=24.8
Pod documented
484 0 my %args = @_;
485  
486 0 my @pids;
487 0 for my $browser (sort keys %browsers) {
488 0 my $res = _do_browser('unpause', $browser, %args);
489 0 ▶ return $res unless $res->[0] == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->[0] == 200 0 0 0
490 0 push @pids, @{$res->[3]{'func.pids'}};
491 }
492 0 [200, "OK", undef, {"func.pids" => \@pids}];
493 }
494  
495 $SPEC{pause_and_unpause_browsers} = {
496 1 v => 1.1,
497 summary => "Pause and unpause browsers alternately",
498 description => $desc_pause_and_unpause .
499 "See also the separate `pause_browsers` and the `unpause_browsers` routines.\n\n",
500 args => {
501 %args_common,
502 %argopt_periods,
503 },
504 };
505 0 ▶sub pause_and_unpause_browsers {
Subroutine pause_and_unpause_browsers: not called CC=1 SCAR=6.9
Pod documented
506 0 my %args = @_;
507  
508 0 _do_browser('pause_and_unpause', 'all known browsers', %args);
509 }
510  
511 $SPEC{browsers_are_paused} = {
512 1 v => 1.1,
513 summary => "Check whether browsers are paused",
514 description => <<'MARKDOWN',
515  
516 Browser is defined as paused if *all* of its processes are in 'stop' state.
517  
518 MARKDOWN
519 args => {
520 %args_common,
521 %argopt_quiet,
522 },
523 };
524 0 ▶sub browsers_are_paused {
Subroutine browsers_are_paused: not called CC=8 SCAR=42.8
Pod documented
525 0 my %args = @_;
526  
527 0 my $has_processes = 0;
528 0 for my $browser (sort keys %browsers) {
529 0 my $res = _do_browser('is_paused', $browser, %args);
530 0 ▶ return $res unless $res->[0] == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->[0] == 200 0 0 0
531 0 ▶ return $res if defined $res->[2] && !$res->[2];
Branch: 1 branch
BranchTrueFalseTotal
if defined $res->[2] and not $res->[2] 0 0 0
Condition0%0/3
defined $res->[2] and not $res->[2]
!ll&&!rl&&r
000
MC/DC0%0/2
defined $res->[2] and not $res->[2]
defined $res->[2] not $res->[2]
Truth table0%0/3
A and not(B)
A= defined $res->[2]B= not $res->[2]
ABresult
0X0
100
111
532 0 ▶ $has_processes++ if defined $res->[2];
Branch: 1 branch
BranchTrueFalseTotal
if defined $res->[2] 0 0 0
533 }
534 0 ▶ my $msg = !$has_processes ? "There are no browser processes" :
Branch: 1 branch
BranchTrueFalseTotal
!$has_processes ? : 0 0 0
535 "Browsers are paused (all processes are in stop state)";
536 return [200, "OK", 1, {
537 'cmdline.exit_code' => 0,
538 0 ▶ 'cmdline.result' => $args{quiet} ? '' : $msg,
Branch: 1 branch
BranchTrueFalseTotal
$args{'quiet'} ? : 0 0 0
539 }];
540 }
541  
542 $SPEC{terminate_browsers} = {
543 1 v => 1.1,
544 summary => "Terminate browsers (by default with -KILL)",
545 args => {
546 %args_common,
547 %argopt_signal,
548 },
549 };
550 0 ▶sub terminate_browsers {
Subroutine terminate_browsers: not called CC=3 SCAR=24.8
Pod documented
551 0 my %args = @_;
552  
553 0 my @pids;
554 0 for my $browser (sort keys %browsers) {
555 0 my $res = _do_browser('terminate', $browser, %args);
556 0 ▶ return $res unless $res->[0] == 200;
Branch: 1 branch
BranchTrueFalseTotal
unless $res->[0] == 200 0 0 0
557 0 push @pids, @{$res->[3]{'func.pids'}};
558 }
559 0 [200, "OK", undef, {"func.pids" => \@pids}];
560 }
561  
562 0 ▶sub _start_or_restart_browsers {
Subroutine _start_or_restart_browsers: not called CC=34 SCAR=70.8
563 0 require Capture::Tiny;
564 0 require Proc::Background;
565  
566 0 my ($which_action, %args) = @_;
567 0 my %pbs; # key=browser name, val=Proc::Background objects
568 my %outputs; # key=browser name, val=output
569  
570 0 my %started; # key=browser name, val=1
571 0 my %fail; # key=browser name, val=reason
572 0 my %has_processes; # key=browser name, val=1
573 0 my %terminated; # key=browser name, val=1
574  
575 0 my $num_start_requests = 0;
576 0 for my $browser (sort keys %browsers) {
577 0 ▶ next if $which_action eq 'start' && !$args{"start_$browser"};
Branch: 1 branch
BranchTrueFalseTotal
if $which_action eq "start" and not $args{"start_$browser"} 0 0 0
Condition0%0/3
$which_action eq "start" and not $args{"start_$browser"}
!ll&&!rl&&r
000
MC/DC0%0/2
$which_action eq "start" and not $args{"start_$browser"}
$which_action eq "start" not $args{"start_$browser"}
Truth table0%0/3
A and not(B)
A= $which_action eq "start"B= not $args{"start_$browser"}
ABresult
0X0
100
111
578 0 ▶ next if $which_action eq 'restart' && !$args{"restart_$browser"};
Branch: 1 branch
BranchTrueFalseTotal
if $which_action eq "restart" and not $args{"restart_$browser"} 0 0 0
Condition0%0/3
$which_action eq "restart" and not $args{"restart_$browser"}
!ll&&!rl&&r
000
MC/DC0%0/2
$which_action eq "restart" and not $args{"restart_$browser"}
$which_action eq "restart" not $args{"restart_$browser"}
Truth table0%0/3
A and not(B)
A= $which_action eq "restart"B= not $args{"restart_$browser"}
ABresult
0X0
100
111
579 0 $num_start_requests++;
580  
581 # TODO: cache? we are running ps once for each browser
582 #log_trace "Checking whether $browser has processes ...";
583 0 my $res_hp = _do_browser('has_processes', $browser, users=>[$>]);
584 0 ▶ if ($res_hp->[0] != 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res_hp->[0] != 200) 0 0 0
585 0 log_error "Can't check whether $browser has processes: $res_hp->[0] - $res_hp->[1], skipped";
586 0 ▶ $fail{$browser} //= "Can't check for processes";
Condition0%0/2
$fail{$browser} //= "Can't check for processes"
l!l
00
MC/DC0%0/1
$fail{$browser} //= "Can't check for processes"
$fail{$browser}
Truth table0%0/2
A
A= $fail{$browser}
Aresult
11
00
587 0 next;
588 }
589 0 my $has_processes = $res_hp->[2];
590 0 ▶ if ($which_action eq 'start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($which_action eq 'start') { } 0 0 0
591 0 ▶ if ($has_processes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_processes) 0 0 0
592 0 $has_processes{$browser}++;
593 0 next;
594 }
595 } else { # restart
596 0 my $res_term;
597 TERMINATE: {
598 0 ▶ last unless $has_processes;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_processes 0 0 0
599 0 ▶ if ($args{-dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-dry_run"}) 0 0 0
600 0 log_info "[DRY] Terminating $browser ...";
601 0 $terminated{$browser}++;
602 0 last;
603 }
604  
605 0 $res_term = _do_browser('terminate', $browser, users=>[$>]);
606 0 ▶ if ($res_term->[0] != 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res_term->[0] != 200) 0 0 0
607 0 log_error "Can't terminate $browser: $res_term->[0] - $res_term->[1], skipped";
608 0 ▶ $fail{$browser} //= "Can't terminate";
Condition0%0/2
$fail{$browser} //= "Can't terminate"
l!l
00
MC/DC0%0/1
$fail{$browser} //= "Can't terminate"
$fail{$browser}
Truth table0%0/2
A
A= $fail{$browser}
Aresult
11
00
609 0 next;
610 }
611  
612 0 sleep 3;
613  
614 0 $res_hp = _do_browser('has_processes', $browser, users=>[$>]);
615 0 ▶ if ($res_hp->[0] != 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res_hp->[0] != 200) 0 0 0
616 0 log_error "Can't check whether $browser has processes (after terminatign): $res_hp->[0] - $res_hp->[1], skipped";
617 0 ▶ $fail{$browser} //= "Can't check for processes (after terminating)";
Condition0%0/2
$fail{$browser} //= "Can't check for processes (after terminating)"
l!l
00
MC/DC0%0/1
$fail{$browser} //= "Can't check for processes (after terminating)"
$fail{$browser}
Truth table0%0/2
A
A= $fail{$browser}
Aresult
11
00
618 0 next;
619 }
620 0 $has_processes = $res_hp->[2];
621 0 ▶ if ($has_processes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_processes) 0 0 0
622 0 log_error "$browser still has processes after terminating, skipped";
623 0 ▶ $fail{$browser} //= "Still has process after terminating";
Condition0%0/2
$fail{$browser} //= "Still has process after terminating"
l!l
00
MC/DC0%0/1
$fail{$browser} //= "Still has process after terminating"
$fail{$browser}
Truth table0%0/2
A
A= $fail{$browser}
Aresult
11
00
624 0 next;
625 }
626 0 $terminated{$browser}++;
627 } # TERMINATE
628 }
629  
630 START: {
631 0 my $cmd = $args{"${browser}_cmd"} //
632 0 ▶ $argsopt_browser_start{"${browser}_cmd"}{default};
Condition0%0/3
$args{"${browser}_cmd"} // $App::BrowserUtils::argsopt_browser_start{"${browser}_cmd"}{"default"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"${browser}_cmd"} // $App::BrowserUtils::argsopt_browser_start{"${browser}_cmd"}{"default"}
$args{"${browser}_cmd"} $App::BrowserUtils::argsopt_browser_start{"${browser}_cmd"}{"default"}
Truth table0%0/3
A // B
A= $args{"${browser}_cmd"}B= $App::BrowserUtils::argsopt_browser_start{"${browser}_cmd"}{"default"}
ABresult
1X1
011
000
633  
634 0 ▶ if ($args{-dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-dry_run"}) 0 0 0
635 0 log_info "[DRY] Starting %s (cmd: %s) ...", $browser, $cmd;
636 0 $started{$browser}++;
637 0 last;
638 }
639  
640 0 log_info "Starting %s (cmd: %s) ...", $browser, $cmd;
641 $outputs{$browser} = Capture::Tiny::capture_merged(
642 0 ▶ sub { $pbs{$browser} = Proc::Background->new($cmd) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
643 0 $started{$browser}++;
644 }
645 }
646  
647 0 my $num_started = keys %started;
648 0 ▶ if ($num_started == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($num_started == 0) 0 0 0
649 0 ▶ return [304,
Branch: 1 branch
BranchTrueFalseTotal
$num_start_requests ? : 0 0 0
650 $num_start_requests ? "All browsers already have processes" :
651 "Not ${which_action}ing any browsers"];
652 }
653  
654 0 my (%alive, %not_alive);
655 0 ▶ if ($args{-dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-dry_run'}) { } 0 0 0
656 0 %alive = %started;
657 } else {
658 0 for my $wait_time (2, 5, 10) {
659 0 %alive = ();
660 0 %not_alive = ();
661 0 log_trace "Checking if the started browsers are alive ...";
662 0 for my $browser (keys %pbs) {
663 0 ▶ if ($pbs{$browser}->alive) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pbs{$browser}->alive) { } 0 0 0
664 0 $alive{$browser}++;
665 } else {
666 0 $not_alive{$browser}++;
667 }
668 }
669 0 ▶ last if scalar(keys %alive) == $num_started;
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %alive == $num_started 0 0 0
670 }
671 }
672  
673 0 my $num_alive = keys %alive;
674 0 my $num_not_alive = keys %not_alive;
675  
676 0 my $status;
677 my $reason;
678 0 my $msg;
679 0 ▶ my $verb_started = $which_action eq 'restart' ? 'Started/restarted' : 'Started';
Branch: 1 branch
BranchTrueFalseTotal
$which_action eq 'restart' ? : 0 0 0
680 0 ▶ if ($num_alive == $num_started) {
Branch: 2 branches
BranchTrueFalseTotal
if ($num_alive == $num_started) { } 0 0 0
elsif ($num_alive == 0) { } 0 0 0
681 0 $status = 200;
682 0 $reason = "OK";
683 0 $msg = "$verb_started ".join(", ", sort keys %alive);
684 } elsif ($num_alive == 0) {
685 0 $status = 500;
686 0 $reason = $msg = "Can't start any browser (".join(", ", %not_alive).")";
687 } else {
688 0 $status = 200;
689 0 $reason = "OK";
690 0 $msg = "$verb_started ".join(", ", sort keys %alive)."; but failed to start ".
691 join(", ", sort keys %not_alive);
692 }
693  
694 0 ▶ $fail{$_} //= "Can't start" for keys %not_alive;
Condition0%0/2
$fail{$_} //= "Can't start"
l!l
00
MC/DC0%0/1
$fail{$_} //= "Can't start"
$fail{$_}
Truth table0%0/2
A
A= $fail{$_}
Aresult
11
00
695  
696 [$status, $msg, undef, {
697 'func.outputs' => \%outputs,
698 ($which_action eq 'start' ? ('func.has_processes' => [sort keys %has_processes]) : ()),
699 0 ▶ 'func.started' => [sort grep {!$terminated{$_}} keys %alive],
Branch: 1 branch
BranchTrueFalseTotal
$which_action eq 'restart' ? : 0 0 0
700 0 ▶ ($which_action eq 'restart' ? ('func.restarted' => [sort grep {$terminated{$_}} keys %alive]) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$which_action eq 'start' ? : 0 0 0
701 'func.fail' => [sort keys %fail],
702 }];
703 }
704  
705 $SPEC{start_browsers} = {
706 1 v => 1.1,
707 summary => "Start browsers",
708 description => <<'MARKDOWN',
709  
710 For each of the requested browser, check whether browser processes (that run as
711 the current user) exist and if not then start the browser. If browser processes
712 exist, even if all are paused, then no new instance of the browser will be
713 started.
714  
715 when starting each browser, console output will be captured and returned in
716 function metadata. Will wait for 2/5/10 seconds and check if the browsers have
717 been started. If all browsers can't be started, will return 500; otherwise will
718 return 200 but report the browsers that failed to start to the STDERR.
719  
720 Example on the CLI:
721  
722 % start-browsers --start-firefox
723  
724 To customize command to use to start:
725  
726 % start-browsers --start-firefox --firefox-cmd 'firefox -P myprofile'
727  
728 MARKDOWN
729 args => {
730 # args_common is not relevant here, for now (unless we want to start
731 # browsers as other users)
732  
733 %argsopt_browser_start,
734 %argsopt_browser_cmd,
735 %argopt_quiet,
736 },
737 features => {
738 dry_run => 1,
739 },
740 };
741 0 ▶sub start_browsers {
Subroutine start_browsers: not called CC=1 SCAR=6.9
Pod documented
742 0 _start_or_restart_browsers('start', @_);
743 }
744  
745 $SPEC{restart_browsers} = {
746 1 v => 1.1,
747 summary => "Restart browsers",
748 description => <<'MARKDOWN',
749  
750 For each of the requested browser, first check whether browser processes (that
751 run the current user) exist. If they do then terminate the browser first. After
752 that, start the browser again.
753  
754 Example on the CLI:
755  
756 % restart-browsers --restart-firefox
757  
758 To customize command:
759  
760 % restart-browsers --start-firefox --firefox-cmd 'firefox -P myprofile'
761  
762 when starting each browser, console output will be captured and returned in
763 function metadata. Will wait for 2/5/10 seconds and check if the browsers have
764 been started. If all browsers can't be started, will return 500; otherwise will
765 return 200 but report the browsers that failed to start to the STDERR.
766  
767 MARKDOWN
768 args => {
769 # args_common is not relevant here, for now (unless we want to start
770 # browsers as other users)
771  
772 %argsopt_browser_restart,
773 %argsopt_browser_cmd,
774 %argopt_quiet,
775 },
776 features => {
777 dry_run => 1,
778 },
779 };
780 0 ▶sub restart_browsers {
Subroutine restart_browsers: not called CC=1 SCAR=6.9
Pod documented
781 0 _start_or_restart_browsers('restart', @_);
782 }
783  
784 1 1;
785 # ABSTRACT: Utilities related to browsers, particularly modern GUI ones
786  
787 __END__
↑ Summary