lib/Beekeeper/Worker.pm

filter: Statementstmt 13.4% 64 / 477 Branchbran 0.0% 0 / 164 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 46 Subroutinesub 22.8% 16 / 70 Podpod 42.8% 9 / 21 totaltotal 10.4% 89 / 851 CC 118 SCAR 59.1
CC
118
Cov
9%
__drain_task_queue
1640.0
__send_response
90.0
new
72.0
CRAP 368.5
↑ Summary lib/Beekeeper/Service/LogTail/Worker.pm »
1 package Beekeeper::Worker;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 our $VERSION = '0.10';
7  
8 1 ▶use Beekeeper::Client ':worker';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Beekeeper::Logger ':log_levels';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Beekeeper::JSONRPC;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Compress::Raw::Zlib ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Digest::MD5 'md5_base64';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 1 ▶use constant COMPILE_ERROR_EXIT_CODE => 99;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use constant BKPR_REQUEST_AUTHORIZED => int(rand(90000000)+10000000);
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 1 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 1 our @EXPORT = qw( BKPR_REQUEST_AUTHORIZED );
26  
27 1 our @EXPORT_OK = qw(
28 log_fatal
29 log_alert
30 log_critical
31 log_error
32 log_warn
33 log_warning
34 log_notice
35 log_info
36 log_debug
37 log_trace
38 log_level
39 );
40  
41 1 our %EXPORT_TAGS = ('log' => [ @EXPORT_OK, @EXPORT ]);
42  
43 0 ▶our $Logger = sub { warn(@_) }; # redefined later by __init_logger
Subroutine __ANON__: not called CC=1 SCAR=1.2
44 1 our $LogLevel = LOG_INFO;
45  
46 0 ▶sub log_fatal (@) { $LogLevel >= LOG_FATAL && $Logger->( LOG_FATAL, @_ ) }
Subroutine log_fatal: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 1 and &$Beekeeper::Worker::Logger(1, @_) 0 0 0
47 0 ▶sub log_alert (@) { $LogLevel >= LOG_ALERT && $Logger->( LOG_ALERT, @_ ) }
Subroutine log_alert: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 2 and &$Beekeeper::Worker::Logger(2, @_) 0 0 0
48 0 ▶sub log_critical (@) { $LogLevel >= LOG_CRIT && $Logger->( LOG_CRIT, @_ ) }
Subroutine log_critical: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 3 and &$Beekeeper::Worker::Logger(3, @_) 0 0 0
49 0 ▶sub log_error (@) { $LogLevel >= LOG_ERROR && $Logger->( LOG_ERROR, @_ ) }
Subroutine log_error: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 4 and &$Beekeeper::Worker::Logger(4, @_) 0 0 0
50 0 ▶sub log_warn (@) { $LogLevel >= LOG_WARN && $Logger->( LOG_WARN, @_ ) }
Subroutine log_warn: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 5 and &$Beekeeper::Worker::Logger(5, @_) 0 0 0
51 0 ▶sub log_warning (@) { $LogLevel >= LOG_WARN && $Logger->( LOG_WARN, @_ ) }
Subroutine log_warning: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 5 and &$Beekeeper::Worker::Logger(5, @_) 0 0 0
52 0 ▶sub log_notice (@) { $LogLevel >= LOG_NOTICE && $Logger->( LOG_NOTICE, @_ ) }
Subroutine log_notice: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 6 and &$Beekeeper::Worker::Logger(6, @_) 0 0 0
53 0 ▶sub log_info (@) { $LogLevel >= LOG_INFO && $Logger->( LOG_INFO, @_ ) }
Subroutine log_info: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 7 and &$Beekeeper::Worker::Logger(7, @_) 0 0 0
54 0 ▶sub log_debug (@) { $LogLevel >= LOG_DEBUG && $Logger->( LOG_DEBUG, @_ ) }
Subroutine log_debug: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 8 and &$Beekeeper::Worker::Logger(8, @_) 0 0 0
55 0 ▶sub log_trace (@) { $LogLevel >= LOG_TRACE && $Logger->( LOG_TRACE, @_ ) }
Subroutine log_trace: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
$Beekeeper::Worker::LogLevel >= 9 and &$Beekeeper::Worker::Logger(9, @_) 0 0 0
56 0 ▶sub log_level (;$) { $LogLevel = shift if scalar @_; return $LogLevel }
Subroutine log_level: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ 0 0 0
57  
58 1 our $BUSY_SINCE; *BUSY_SINCE = \$Beekeeper::MQTT::BUSY_SINCE;
59 1 our $BUSY_TIME; *BUSY_TIME = \$Beekeeper::MQTT::BUSY_TIME;
60  
61 1 our $REPORT_STATUS_PERIOD = 5;
62 1 our $UNSUBSCRIBE_LINGER = 2;
63  
64 1 my %AUTH_TOKENS;
65 my $DEFLATE;
66 1 my $JSON;
67  
68  
69 0 ▶sub new {
Subroutine new: not called CC=8 SCAR=42.8
Pod undocumented
70 0 my ($class, %args) = @_;
71  
72 # Parameters passed by WorkerPool->spawn_worker
73
74 0 my $self = {
75 _WORKER => undef,
76 _CLIENT => undef,
77 _BUS => undef,
78 _LOGGER => undef,
79 };
80  
81 0 bless $self, $class;
82  
83 $self->{_WORKER} = {
84 parent_pid => $args{'parent_pid'},
85 foreground => $args{'foreground'}, # --foreground option
86 debug => $args{'debug'}, # --debug option
87 bus_config => $args{'bus_config'}, # content of bus.config.json
88 pool_config => $args{'pool_config'}, # content of pool.config.json
89 pool_id => $args{'pool_id'},
90 bus_id => $args{'bus_id'},
91 0 config => $args{'config'},
92 hostname => Sys::Hostname::hostname(),
93 stop_cv => undef,
94 callbacks => {},
95 task_queue_high => [],
96 task_queue_low => [],
97 queued_tasks => 0,
98 in_progress => 0,
99 last_report => 0,
100 call_count => 0,
101 notif_count => 0,
102 error_count => 0,
103 busy_time => 0,
104 };
105  
106 0 $JSON = JSON::XS->new;
107 0 $JSON->utf8; # encode result as utf8
108 0 $JSON->allow_blessed; # encode blessed references as null
109 0 $JSON->convert_blessed; # use TO_JSON methods to serialize objects
110  
111 0 $DEFLATE = Compress::Raw::Zlib::Deflate->new( -AppendOutput => 1 );
112  
113 0 ▶ if (defined $SIG{TERM} && $SIG{TERM} eq 'DEFAULT') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $SIG{"TERM"} and $SIG{"TERM"} eq "DEFAULT") 0 0 0
Condition0%0/3
defined $SIG{"TERM"} and $SIG{"TERM"} eq "DEFAULT"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $SIG{"TERM"} and $SIG{"TERM"} eq "DEFAULT"
defined $SIG{"TERM"} $SIG{"TERM"} eq "DEFAULT"
Truth table0%0/3
A and B
A= defined $SIG{"TERM"}B= $SIG{"TERM"} eq "DEFAULT"
ABresult
0X0
100
111
114 # Stop working gracefully when TERM signal is received
115 0 ▶ $SIG{TERM} = sub { $self->stop_working };
Subroutine __ANON__: not called CC=1 SCAR=6.9
116 }
117  
118 0 ▶ if (defined $SIG{INT} && $SIG{INT} eq 'DEFAULT' && $args{'foreground'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $SIG{"INT"} and $SIG{"INT"} eq "DEFAULT" and $args{"foreground"}) 0 0 0
Condition0%0/6
defined $SIG{"INT"} and $SIG{"INT"} eq "DEFAULT" and $args{"foreground"}
!ll&&!rl&&r
000
defined $SIG{"INT"} and $SIG{"INT"} eq "DEFAULT"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $SIG{"INT"} and $SIG{"INT"} eq "DEFAULT" and $args{"foreground"}
defined $SIG{"INT"} $SIG{"INT"} eq "DEFAULT" $args{"foreground"}
Truth table0%0/4
A and B and C
A= defined $SIG{"INT"}B= $SIG{"INT"} eq "DEFAULT"C= $args{"foreground"}
ABCresult
0XX0
10X0
1100
1111
119 # In foreground mode also stop working gracefully when INT signal is received
120 0 ▶ $SIG{INT} = sub { $self->stop_working };
Subroutine __ANON__: not called CC=1 SCAR=6.9
121 }
122  
123 0 eval {
124  
125 # Init logger as soon as possible
126 0 $self->__init_logger;
127  
128 # Connect to broker
129 0 $self->__init_client;
130  
131 # Pass broker connection to logger
132 0 ▶ $self->{_LOGGER}->{_BUS} = $self->{_BUS} if (exists $self->{_LOGGER}->{_BUS});
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"_LOGGER"}{"_BUS"} 0 0 0
133  
134 0 $self->__init_auth_tokens;
135  
136 0 $self->__init_worker;
137 };
138  
139 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
140 0 log_fatal "Worker died while initialization: $@";
141 0 log_fatal "$class could not be started";
142 0 CORE::exit( COMPILE_ERROR_EXIT_CODE );
143 }
144  
145 0 return $self;
146 }
147  
148 0 ▶sub __init_auth_tokens {
Subroutine __init_auth_tokens: not called CC=1 SCAR=6.9
149 0 my ($self) = @_;
150  
151 # Using a hashing function makes harder to access the wrong worker pool by mistake,
152 # but it is not an effective access restriction: anyone with access to the backend
153 # bus credentials can easily inspect and clone auth data tokens
154  
155 0 my $salt = $self->{_CLIENT}->{auth_salt};
156  
157 0 $AUTH_TOKENS{'BKPR_SYSTEM'} = md5_base64('BKPR_SYSTEM'. $salt);
158 0 $AUTH_TOKENS{'BKPR_ADMIN'} = md5_base64('BKPR_ADMIN' . $salt);
159 0 $AUTH_TOKENS{'BKPR_ROUTER'} = md5_base64('BKPR_ROUTER'. $salt);
160 }
161  
162 0 ▶sub __has_authorization_token {
Subroutine __has_authorization_token: not called CC=5 SCAR=34.0
163 0 my ($self, $auth_level) = @_;
164  
165 0 my $auth_data = $self->{_CLIENT}->{auth_data};
166  
167 0 ▶ return 0 unless $auth_data && $auth_level;
Branch: 1 branch
BranchTrueFalseTotal
unless $auth_data and $auth_level 0 0 0
Condition0%0/3
$auth_data and $auth_level
!ll&&!rl&&r
000
MC/DC0%0/2
$auth_data and $auth_level
$auth_data $auth_level
Truth table0%0/3
A and B
A= $auth_dataB= $auth_level
ABresult
0X0
100
111
168 0 ▶ return 0 unless exists $AUTH_TOKENS{$auth_level};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $AUTH_TOKENS{$auth_level} 0 0 0
169 0 ▶ return 0 unless $AUTH_TOKENS{$auth_level} eq $auth_data;
Branch: 1 branch
BranchTrueFalseTotal
unless $AUTH_TOKENS{$auth_level} eq $auth_data 0 0 0
170  
171 0 return 1;
172 }
173  
174 0 ▶sub __init_logger {
Subroutine __init_logger: not called CC=3 SCAR=24.8
175 0 my $self = shift;
176  
177 # Honor --debug command line option and 'debug' config option from pool.config.json
178 0 ▶ $LogLevel = LOG_DEBUG if $self->{_WORKER}->{debug} || $self->{_WORKER}->{config}->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_WORKER"}{"debug"} or $self->{"_WORKER"}{"config"}{"debug"} 0 0 0
Condition0%0/3
$self->{"_WORKER"}{"debug"} or $self->{"_WORKER"}{"config"}{"debug"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_WORKER"}{"debug"} or $self->{"_WORKER"}{"config"}{"debug"}
$self->{"_WORKER"}{"debug"} $self->{"_WORKER"}{"config"}{"debug"}
Truth table0%0/3
A or B
A= $self->{"_WORKER"}{"debug"}B= $self->{"_WORKER"}{"config"}{"debug"}
ABresult
1X1
011
000
179  
180 0 my $log_handler = $self->log_handler;
181 0 $self->{_LOGGER} = $log_handler;
182  
183 0 ▶ $Logger = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
184 # ($level, @messages) = @_
185 0 $log_handler->log(@_);
186 0 };
187  
188 0 ▶ $SIG{__WARN__} = sub { $Logger->( LOG_WARN, @_ ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
189 }
190  
191 0 ▶sub log_handler {
Subroutine log_handler: not called CC=1 SCAR=6.9
Pod documented
192 0 my $self = shift;
193  
194 Beekeeper::Logger->new(
195 worker_class => ref $self,
196 foreground => $self->{_WORKER}->{foreground},
197 log_file => $self->{_WORKER}->{config}->{log_file},
198 host => $self->{_WORKER}->{hostname},
199 pool => $self->{_WORKER}->{pool_id},
200 _BUS => $self->{_BUS},
201 @_
202 0 );
203 }
204  
205 0 ▶sub __init_client {
Subroutine __init_client: not called CC=1 SCAR=6.9
206 0 my $self = shift;
207  
208 0 my $bus_id = $self->{_WORKER}->{bus_id};
209 0 my $config = $self->{_WORKER}->{bus_config}->{$bus_id};
210  
211 my $client = Beekeeper::Client->new(
212 %$config,
213 timeout => 0, # retry forever
214 0 ▶ on_error => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
215 0 ▶ my $errmsg = $_[0] || ""; $errmsg =~ s/\s+/ /sg;
Condition0%0/2
$_[0] || ''
l!l
00
MC/DC0%0/1
$_[0] || ''
$_[0]
Truth table0%0/2
A
A= $_[0]
Aresult
11
00
216 0 log_fatal "Connection to $bus_id failed: $errmsg";
217 0 $self->stop_working;
218 },
219 0 );
220  
221 0 $self->{_CLIENT} = $client->{_CLIENT};
222 0 $self->{_BUS} = $client->{_BUS};
223  
224 0 $Beekeeper::Client::singleton = $self;
225 }
226  
227 0 ▶sub __init_worker {
Subroutine __init_worker: not called CC=1 SCAR=6.9
228 0 my $self = shift;
229  
230 0 $self->on_startup;
231  
232 0 $self->__report_status;
233  
234 0 AnyEvent->now_update;
235  
236 $self->{_WORKER}->{report_status_timer} = AnyEvent->timer(
237 after => rand( $REPORT_STATUS_PERIOD ),
238 interval => $REPORT_STATUS_PERIOD,
239 0 ▶ cb => sub { $self->__report_status },
Subroutine __ANON__: not called CC=1 SCAR=6.9
240 0 );
241 }
242  
243  
244 0 ▶sub on_startup {
Subroutine on_startup: not called CC=1 SCAR=6.9
Pod documented
245 # Placeholder, intended to be overrided
246 0 my $class = ref $_[0];
247 0 log_fatal "Worker class $class doesn't define on_startup() method";
248 }
249  
250 0 ▶sub on_shutdown {
Subroutine on_shutdown: not called CC=1 SCAR=0.0
Pod documented
251 # Placeholder, can be overrided
252 }
253  
254 0 ▶sub authorize_request {
Subroutine authorize_request: not called CC=1 SCAR=6.9
Pod documented
255 # Placeholder, must to be overrided
256 0 my $class = ref $_[0];
257 0 log_fatal "Worker class $class doesn't define authorize_request() method";
258 0 return undef; # do not authorize
259 }
260  
261  
262 0 ▶sub accept_notifications {
Subroutine accept_notifications: not called CC=4 SCAR=30.0
Pod documented
263 0 my ($self, %args) = @_;
264  
265 0 my $worker = $self->{_WORKER};
266 0 my $callbacks = $worker->{callbacks};
267  
268 0 my ($file, $line) = (caller)[1,2];
269 0 my $at = "at $file line $line\n";
270  
271 0 foreach my $fq_meth (keys %args) {
272  
273 0 ▶ $fq_meth =~ m/^ ( [\w-]+ (?: \.[\w-]+ )* )
Branch: 1 branch
BranchTrueFalseTotal
$fq_meth =~ /^ ( [\w-]+ (?: \.[\w-]+ )* ) \. ( [\w-]+ | \* ) $/x or die "Invalid notification method '${fq_meth}' $at" 0 0 0
274 \. ( [\w-]+ | \* ) $/x or die "Invalid notification method '$fq_meth' $at";
275  
276 0 my ($service, $method) = ($1, $2);
277  
278 0 my $callback = $self->__get_cb_coderef($fq_meth, $args{$fq_meth});
279  
280 0 ▶ die "Already accepting notifications '$fq_meth' $at" if exists $callbacks->{"msg.$fq_meth"};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$callbacks{"msg.$fq_meth"} 0 0 0
281 0 $callbacks->{"msg.$fq_meth"} = $callback;
282  
283 0 my $local_bus = $self->{_BUS}->{bus_role};
284  
285 0 my $topic = "msg/$local_bus/$service/$method";
286 0 $topic =~ tr|.*|/#|;
287  
288 $self->{_BUS}->subscribe(
289 topic => $topic,
290 0 ▶ on_publish => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
291 # ($payload_ref, $properties) = @_;
292  
293 # Enqueue notification
294 0 push @{$worker->{task_queue_high}}, [ @_ ];
295  
296 0 ▶ unless ($worker->{queued_tasks}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($worker->{"queued_tasks"}) 0 0 0
297 0 $worker->{queued_tasks} = 1;
298 0 ▶ AnyEvent::postpone { $self->__drain_task_queue };
Subroutine __ANON__: not called CC=1 SCAR=6.9
299 }
300 },
301 0 ▶ on_suback => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
302 0 my ($success, $prop) = @_;
303 0 ▶ die "Could not subscribe to topic '$topic' $at" unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
304 }
305 0 );
306 }
307 }
308  
309 0 ▶sub __get_cb_coderef {
Subroutine __get_cb_coderef: not called CC=4 SCAR=26.1
310 0 my ($self, $method, $callback) = @_;
311  
312 0 ▶ if (ref $callback eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $callback eq 'CODE') { } 0 0 0
elsif (not ref $callback and $self->can($callback)) { } 0 0 0
313 # Already a coderef
314 0 return $callback;
315 }
316 ▶ elsif (!ref($callback) && $self->can($callback)) {
Condition0%0/3
not ref $callback and $self->can($callback)
!ll&&!rl&&r
000
MC/DC0%0/2
not ref $callback and $self->can($callback)
not ref $callback $self->can($callback)
Truth table0%0/3
not(A) and B
A= not ref $callbackB= $self->can($callback)
ABresult
0X0
100
111
317 # Return a reference to given method
318 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
319 0 my $class = ref $self;
320 0 return \&{"${class}::${callback}"};
321 }
322 else {
323 0 my ($file, $line) = (caller(1))[1,2];
324 0 my $at = "at $file line $line\n";
325 0 die "Invalid handler '$callback' for '$method' $at";
326 }
327 }
328  
329  
330 0 ▶sub accept_remote_calls {
Subroutine accept_remote_calls: not called CC=6 SCAR=37.4
Pod documented
331 0 my ($self, %args) = @_;
332  
333 0 my $worker = $self->{_WORKER};
334 0 my $callbacks = $worker->{callbacks};
335 0 my %subscribed_to;
336  
337 0 my ($file, $line) = (caller)[1,2];
338 0 my $at = "at $file line $line\n";
339  
340 0 foreach my $fq_meth (keys %args) {
341  
342 0 ▶ $fq_meth =~ m/^ ( [\w-]+ (?: \.[\w-]+ )* )
Branch: 1 branch
BranchTrueFalseTotal
$fq_meth =~ /^ ( [\w-]+ (?: \.[\w-]+ )* ) \. ( [\w-]+ | \* ) $/x or die "Invalid remote call method '${fq_meth}' $at" 0 0 0
343 \. ( [\w-]+ | \* ) $/x or die "Invalid remote call method '$fq_meth' $at";
344  
345 0 my ($service, $method) = ($1, $2);
346  
347 0 my $callback = $self->__get_cb_coderef($fq_meth, $args{$fq_meth});
348  
349 0 ▶ die "Already accepting remote calls '$fq_meth' $at" if exists $callbacks->{"req.$fq_meth"};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$callbacks{"req.$fq_meth"} 0 0 0
350 0 $callbacks->{"req.$fq_meth"} = $callback;
351  
352 0 ▶ next if $subscribed_to{$service};
Branch: 1 branch
BranchTrueFalseTotal
if $subscribed_to{$service} 0 0 0
353 0 $subscribed_to{$service} = 1;
354  
355 0 ▶ if (keys %subscribed_to == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %subscribed_to == 2) 0 0 0
356 0 log_warn "Running multiple services within a single worker hurts load balancing $at";
357 }
358  
359 0 my $local_bus = $self->{_BUS}->{bus_role};
360  
361 0 my $topic = "\$share/BKPR/req/$local_bus/$service";
362 0 $topic =~ tr|.*|/#|;
363  
364 $self->{_BUS}->subscribe(
365 topic => $topic,
366 maximum_qos => 1,
367 0 ▶ on_publish => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
368 # ($payload_ref, $mqtt_properties) = @_;
369  
370 # Enqueue request
371 0 push @{$worker->{task_queue_low}}, [ @_ ];
372  
373 0 ▶ unless ($worker->{queued_tasks}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($worker->{"queued_tasks"}) 0 0 0
374 0 $worker->{queued_tasks} = 1;
375 0 ▶ AnyEvent::postpone { $self->__drain_task_queue };
Subroutine __ANON__: not called CC=1 SCAR=6.9
376 }
377 },
378 0 ▶ on_suback => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
379 0 my ($success, $prop) = @_;
380 0 ▶ die "Could not subscribe to topic '$topic' $at" unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
381 }
382 0 );
383 }
384 }
385  
386 1 my $_TASK_QUEUE_DEPTH = 0;
387  
388 0 ▶sub __drain_task_queue {
Subroutine __drain_task_queue: not called CC=40 SCAR=74.0
389 0 my $self = shift;
390  
391 # Ensure that draining does not recurse
392 0 ▶ Carp::confess "Unexpected task queue processing recursion" if $_TASK_QUEUE_DEPTH;
Branch: 1 branch
BranchTrueFalseTotal
if $_TASK_QUEUE_DEPTH 0 0 0
393 0 $_TASK_QUEUE_DEPTH++;
394  
395 0 my $timing_tasks;
396  
397 0 ▶ unless (defined $BUSY_SINCE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Beekeeper::Worker::BUSY_SINCE) 0 0 0
398 # Measure time elapsed while processing requests
399 0 $BUSY_SINCE = Time::HiRes::time;
400 0 $timing_tasks = 1;
401 }
402  
403 0 my $worker = $self->{_WORKER};
404 0 my $client = $self->{_CLIENT};
405 0 my $task;
406  
407 # When requests or notifications are received these are not executed immediately
408 # because that could happen in the middle of the process of another request,
409 # so these tasks get queued until the worker is ready to process the next one.
410 #
411 # Callbacks are executed here, exception handling is done here, responses are
412 # sent back here. This is one of the most important methods of the framework.
413 #
414 # Notifications have higher priority and are processed first.
415  
416 DRAIN: {
417  
418 0 ▶ while ($task = shift @{$worker->{task_queue_high}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($task = shift @{$$worker{"task_queue_high"};}) 0 0 0
419  
420 ## Notification
421  
422 0 my ($payload_ref, $mqtt_properties) = @$task;
423  
424 0 $worker->{notif_count}++;
425  
426 0 eval {
427  
428 0 my $request = decode_json($$payload_ref);
429  
430 0 ▶ unless (ref $request eq 'HASH' && $request->{jsonrpc} eq '2.0') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0") 0 0 0
Condition0%0/3
ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0"
ref $request eq "HASH" $request->{"jsonrpc"} eq "2.0"
Truth table0%0/3
A and B
A= ref $request eq "HASH"B= $request->{"jsonrpc"} eq "2.0"
ABresult
0X0
100
111
431 0 log_error "Received invalid JSON-RPC 2.0 notification";
432 0 return;
433 }
434  
435 0 bless $request, 'Beekeeper::JSONRPC::Notification';
436 0 $request->{_mqtt_properties} = $mqtt_properties;
437  
438 0 my $method = $request->{method};
439  
440 0 ▶ unless (defined $method && $method =~ m/^([\.\w-]+)\.([\w-]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/) 0 0 0
Condition0%0/3
defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/
defined $method $method =~ /^([\.\w-]+)\.([\w-]+)$/
Truth table0%0/3
A and B
A= defined $methodB= $method =~ /^([\.\w-]+)\.([\w-]+)$/
ABresult
0X0
100
111
441 0 log_error "Received notification with invalid method '$method'";
442 0 return;
443 }
444  
445 my $cb = $worker->{callbacks}->{"msg.$1.$2"} ||
446 0 ▶ $worker->{callbacks}->{"msg.$1.*"};
Condition0%0/3
$worker->{'callbacks'}{"msg.$1.$2"} || $worker->{'callbacks'}{"msg.$1.*"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$worker->{'callbacks'}{"msg.$1.$2"} || $worker->{'callbacks'}{"msg.$1.*"}
$worker->{'callbacks'}{"msg.$1.$2"} $worker->{'callbacks'}{"msg.$1.*"}
Truth table0%0/3
A || B
A= $worker->{'callbacks'}{"msg.$1.$2"}B= $worker->{'callbacks'}{"msg.$1.*"}
ABresult
1X1
011
000
447  
448 0 local $client->{caller_id} = $mqtt_properties->{'clid'};
449 0 local $client->{caller_addr} = $mqtt_properties->{'addr'};
450 0 local $client->{auth_data} = $mqtt_properties->{'auth'};
451  
452 0 ▶ unless (($self->authorize_request($request) || "") eq BKPR_REQUEST_AUTHORIZED) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($self->authorize_request($request) || "") eq 15101572) 0 0 0
Condition0%0/2
$self->authorize_request($request) || ''
l!l
00
MC/DC0%0/1
$self->authorize_request($request) || ''
$self->authorize_request($request)
Truth table0%0/2
A
A= $self->authorize_request($request)
Aresult
11
00
453 0 log_error "Notification '$method' was not authorized";
454 0 return;
455 }
456  
457 0 ▶ unless ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cb) 0 0 0
458 0 log_error "No handler found for received notification '$method'";
459 0 return;
460 }
461  
462 0 $cb->($self, $request->{params}, $request);
463 };
464  
465 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
466 # Got an exception while processing message
467 0 log_error $@;
468 0 $worker->{error_count}++;
469 }
470 }
471  
472 0 ▶ if ($task = shift @{$worker->{task_queue_low}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($task = shift @{$$worker{"task_queue_low"};}) 0 0 0
473  
474 ## RPC Call
475  
476 0 my ($payload_ref, $mqtt_properties) = @$task;
477  
478 0 $worker->{call_count}++;
479 0 my ($request, $request_id, $result, $response);
480  
481 0 $result = eval {
482  
483 0 $request = decode_json($$payload_ref);
484  
485 0 ▶ unless (ref $request eq 'HASH' && $request->{jsonrpc} eq '2.0') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0") 0 0 0
Condition0%0/3
ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $request eq "HASH" and $request->{"jsonrpc"} eq "2.0"
ref $request eq "HASH" $request->{"jsonrpc"} eq "2.0"
Truth table0%0/3
A and B
A= ref $request eq "HASH"B= $request->{"jsonrpc"} eq "2.0"
ABresult
0X0
100
111
486 0 log_error "Received invalid JSON-RPC 2.0 request";
487 0 die Beekeeper::JSONRPC::Error->invalid_request;
488 }
489  
490 0 $request_id = $request->{id};
491 0 my $method = $request->{method};
492  
493 0 bless $request, 'Beekeeper::JSONRPC::Request';
494 0 $request->{_mqtt_properties} = $mqtt_properties;
495  
496 0 ▶ unless (defined $method && $method =~ m/^([\.\w-]+)\.([\w-]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/) 0 0 0
Condition0%0/3
defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $method and $method =~ /^([\.\w-]+)\.([\w-]+)$/
defined $method $method =~ /^([\.\w-]+)\.([\w-]+)$/
Truth table0%0/3
A and B
A= defined $methodB= $method =~ /^([\.\w-]+)\.([\w-]+)$/
ABresult
0X0
100
111
497 0 log_error "Received request with invalid method '$method'";
498 0 die Beekeeper::JSONRPC::Error->method_not_found;
499 }
500  
501 my $cb = $worker->{callbacks}->{"req.$1.$2"} ||
502 0 ▶ $worker->{callbacks}->{"req.$1.*"};
Condition0%0/3
$worker->{'callbacks'}{"req.$1.$2"} || $worker->{'callbacks'}{"req.$1.*"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$worker->{'callbacks'}{"req.$1.$2"} || $worker->{'callbacks'}{"req.$1.*"}
$worker->{'callbacks'}{"req.$1.$2"} $worker->{'callbacks'}{"req.$1.*"}
Truth table0%0/3
A || B
A= $worker->{'callbacks'}{"req.$1.$2"}B= $worker->{'callbacks'}{"req.$1.*"}
ABresult
1X1
011
000
503  
504 0 local $client->{caller_id} = $mqtt_properties->{'clid'};
505 0 local $client->{caller_addr} = $mqtt_properties->{'addr'};
506 0 local $client->{auth_data} = $mqtt_properties->{'auth'};
507  
508 0 ▶ unless (($self->authorize_request($request) || "") eq BKPR_REQUEST_AUTHORIZED) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($self->authorize_request($request) || "") eq 15101572) 0 0 0
Condition0%0/2
$self->authorize_request($request) || ''
l!l
00
MC/DC0%0/1
$self->authorize_request($request) || ''
$self->authorize_request($request)
Truth table0%0/2
A
A= $self->authorize_request($request)
Aresult
11
00
509 0 log_error "Request '$method' was not authorized";
510 0 die Beekeeper::JSONRPC::Error->request_not_authorized;
511 }
512  
513 0 ▶ unless ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cb) 0 0 0
514 0 log_error "No handler found for received request '$method'";
515 0 die Beekeeper::JSONRPC::Error->method_not_found;
516 }
517  
518 # Execute method handler
519 0 $cb->($self, $request->{params}, $request);
520 };
521  
522 0 ▶ if ($@) {
Branch: 3 branches
BranchTrueFalseTotal
if ($@) { } 0 0 0
elsif (builtin::blessed($result) and $result->isa('Beekeeper::JSONRPC::Error')) { } 0 0 0
elsif ($request->{'_async_response'}) { } 0 0 0
523 # Got an exception while executing method handler
524 0 ▶ if (blessed($@) && $@->isa('Beekeeper::JSONRPC::Error')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($@) and $@->isa('Beekeeper::JSONRPC::Error')) { } 0 0 0
Condition0%0/3
builtin::blessed($@) and $@->isa("Beekeeper::JSONRPC::Error")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($@) and $@->isa("Beekeeper::JSONRPC::Error")
builtin::blessed($@) $@->isa("Beekeeper::JSONRPC::Error")
Truth table0%0/3
A and B
A= builtin::blessed($@)B= $@->isa("Beekeeper::JSONRPC::Error")
ABresult
0X0
100
111
525 # Handled exception
526 0 $response = $@;
527 0 $worker->{error_count}++;
528 }
529 else {
530 # Unhandled exception
531 0 log_error $@;
532 0 $worker->{error_count}++;
533 0 $response = Beekeeper::JSONRPC::Error->server_error;
534 # Sending exact error to caller is very handy, but it is also a security risk
535 0 ▶ $response->{error}->{data} = $@ if $worker->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $worker->{"debug"} 0 0 0
536 0 $worker->{error_count}++;
537 }
538 }
539 ▶ elsif (blessed($result) && $result->isa('Beekeeper::JSONRPC::Error')) {
Condition0%0/3
builtin::blessed($result) and $result->isa("Beekeeper::JSONRPC::Error")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($result) and $result->isa("Beekeeper::JSONRPC::Error")
builtin::blessed($result) $result->isa("Beekeeper::JSONRPC::Error")
Truth table0%0/3
A and B
A= builtin::blessed($result)B= $result->isa("Beekeeper::JSONRPC::Error")
ABresult
0X0
100
111
540 # Explicit error response
541 0 $response = $result;
542 0 $worker->{error_count}++;
543 }
544 elsif ($request->{_async_response}) {
545 # Response was deferred and will be sent later
546 0 $worker->{in_progress}++;
547 0 $request->{_worker} = $self;
548 }
549 else {
550 # Build a success response
551 0 $response = {
552 jsonrpc => '2.0',
553 result => $result,
554 };
555 }
556  
557 0 ▶ if (defined $request_id && defined $response) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request_id and defined $response) { } 0 0 0
Condition0%0/3
defined $request_id and defined $response
!ll&&!rl&&r
000
MC/DC0%0/2
defined $request_id and defined $response
defined $request_id defined $response
Truth table0%0/3
A and B
A= defined $request_idB= defined $response
ABresult
0X0
100
111
558  
559 # Send back response to caller
560  
561 0 $response->{id} = $request_id;
562  
563 0 my $json = eval { $JSON->encode( $response ) };
564  
565 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
566 # Probably response contains blessed references
567 0 log_error "Couldn't serialize response as JSON: $@";
568 0 $response = Beekeeper::JSONRPC::Error->server_error;
569 0 $response->{id} = $request_id;
570 0 $json = $JSON->encode( $response );
571 }
572  
573 0 ▶ if ($request->{_deflate_response} && length($json) > $request->{_deflate_response}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}) 0 0 0
Condition0%0/3
$request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}
!ll&&!rl&&r
000
MC/DC0%0/2
$request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}
$request->{"_deflate_response"} length $json > $request->{"_deflate_response"}
Truth table0%0/3
A and B
A= $request->{"_deflate_response"}B= length $json > $request->{"_deflate_response"}
ABresult
0X0
100
111
574 0 my $compressed_json;
575 0 $DEFLATE->deflate(\$json, $compressed_json);
576 0 $DEFLATE->flush(\$compressed_json);
577 0 $DEFLATE->deflateReset;
578 0 $json = $compressed_json;
579 }
580  
581 # Request is acknowledged as received just after sending the response. So, if
582 # the process is abruptly interrupted here, the broker will send the request to
583 # another worker and it will be executed twice (acking the request just before
584 # processing it may cause unprocessed requests or undelivered responses)
585  
586 $self->{_BUS}->publish(
587 topic => $mqtt_properties->{'response_topic'},
588 0 addr => $mqtt_properties->{'addr'},
589 payload => \$json,
590 buffer_id => 'response',
591 );
592  
593 0 ▶ if (exists $mqtt_properties->{'packet_id'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $mqtt_properties->{'packet_id'}) { } 0 0 0
594  
595 $self->{_BUS}->puback(
596 0 packet_id => $mqtt_properties->{'packet_id'},
597 buffer_id => 'response',
598 );
599 }
600 else {
601 # Should not happen (clients must publish with QoS 1)
602 0 log_warn "Request published with QoS 0 to topic " . $mqtt_properties->{'topic'};
603 }
604  
605 0 $self->{_BUS}->flush_buffer( buffer_id => 'response' );
606 }
607 else {
608  
609 # Acknowledge requests that doesn't send a response right now (fire & forget calls
610 # and requests handled asynchronously), signaling the broker to send more requests
611  
612 $self->{_BUS}->puback(
613 0 packet_id => $mqtt_properties->{'packet_id'},
614 );
615 }
616 }
617  
618 0 ▶ redo DRAIN if (@{$worker->{task_queue_high}} || @{$worker->{task_queue_low}});
Branch: 1 branch
BranchTrueFalseTotal
if @{$worker->{"task_queue_high"};} or @{$worker->{"task_queue_low"};} 0 0 0
Condition0%0/3
@{$worker->{"task_queue_high"};} or @{$worker->{"task_queue_low"};}
l!l&&r!l&&!r
000
MC/DC0%0/2
@{$worker->{"task_queue_high"};} or @{$worker->{"task_queue_low"};}
@{$worker->{"task_queue_high"};} @{$worker->{"task_queue_low"};}
Truth table0%0/3
A or B
A= @{$worker->{"task_queue_high"};}B= @{$worker->{"task_queue_low"};}
ABresult
1X1
011
000
619  
620 # Execute tasks postponed until task queue is empty
621 0 ▶ if (exists $worker->{postponed}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $worker->{"postponed"}) 0 0 0
622 0 $_->() foreach @{$worker->{postponed}};
623 0 delete $worker->{postponed};
624 }
625 }
626  
627 0 $_TASK_QUEUE_DEPTH--;
628  
629 0 ▶ if (defined $timing_tasks) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timing_tasks) 0 0 0
630 0 $BUSY_TIME += Time::HiRes::time - $BUSY_SINCE;
631 0 undef $BUSY_SINCE;
632 }
633  
634 0 $worker->{queued_tasks} = 0;
635 }
636  
637 0 ▶sub __send_response {
Subroutine __send_response: not called CC=9 SCAR=45.0
638 0 my ($self, $request, $result) = @_;
639  
640 # Send back async response to caller
641  
642 0 my ($timing_tasks, $response);
643  
644 0 $self->{_WORKER}->{in_progress}--;
645  
646 # fire & forget calls doesn't expect responses
647 0 ▶ return unless defined $request->{id};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $request->{"id"} 0 0 0
648  
649 0 ▶ unless (defined $BUSY_SINCE) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Beekeeper::Worker::BUSY_SINCE) 0 0 0
650 0 $BUSY_SINCE = Time::HiRes::time;
651 0 $timing_tasks = 1;
652 }
653  
654 0 ▶ if (blessed($result) && $result->isa('Beekeeper::JSONRPC::Error')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->isa('Beekeeper::JSONRPC::Error')) { } 0 0 0
Condition0%0/3
builtin::blessed($result) and $result->isa("Beekeeper::JSONRPC::Error")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($result) and $result->isa("Beekeeper::JSONRPC::Error")
builtin::blessed($result) $result->isa("Beekeeper::JSONRPC::Error")
Truth table0%0/3
A and B
A= builtin::blessed($result)B= $result->isa("Beekeeper::JSONRPC::Error")
ABresult
0X0
100
111
655 # Explicit error response
656 0 $response = $result;
657 0 $self->{_WORKER}->{error_count}++;
658 }
659 else {
660 # Build a success response
661 0 $response = {
662 jsonrpc => '2.0',
663 result => $result,
664 };
665 }
666  
667 0 $response->{id} = $request->{id};
668  
669 0 local $@;
670 0 my $json = eval { $JSON->encode( $response ) };
671  
672 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
673 # Probably response contains blessed references
674 0 log_error "Couldn't serialize response as JSON: $@";
675 0 $response = Beekeeper::JSONRPC::Error->server_error;
676 0 $response->{id} = $request->{id};
677 0 $json = $JSON->encode( $response );
678 0 $self->{_WORKER}->{error_count}++;
679 }
680  
681 0 ▶ if ($request->{_deflate_response} && length($json) > $request->{_deflate_response}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}) 0 0 0
Condition0%0/3
$request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}
!ll&&!rl&&r
000
MC/DC0%0/2
$request->{"_deflate_response"} and length $json > $request->{"_deflate_response"}
$request->{"_deflate_response"} length $json > $request->{"_deflate_response"}
Truth table0%0/3
A and B
A= $request->{"_deflate_response"}B= length $json > $request->{"_deflate_response"}
ABresult
0X0
100
111
682 0 my $compressed_json;
683 0 $DEFLATE->deflate(\$json, $compressed_json);
684 0 $DEFLATE->flush(\$compressed_json);
685 0 $DEFLATE->deflateReset;
686 0 $json = $compressed_json;
687 }
688  
689 $self->{_BUS}->publish(
690 topic => $request->{_mqtt_properties}->{'response_topic'},
691 0 addr => $request->{_mqtt_properties}->{'addr'},
692 payload => \$json,
693 );
694  
695 0 ▶ if (defined $timing_tasks) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timing_tasks) 0 0 0
696 0 $BUSY_TIME += Time::HiRes::time - $BUSY_SINCE;
697 0 undef $BUSY_SINCE;
698 }
699 }
700  
701  
702 0 ▶sub stop_accepting_notifications {
Subroutine stop_accepting_notifications: not called CC=5 SCAR=34.0
Pod documented
703 0 my ($self, @methods) = @_;
704  
705 0 my ($file, $line) = (caller)[1,2];
706 0 my $at = "at $file line $line\n";
707  
708 0 ▶ die "No method specified $at" unless @methods;
Branch: 1 branch
BranchTrueFalseTotal
unless @methods 0 0 0
709  
710 0 foreach my $fq_meth (@methods) {
711  
712 0 ▶ $fq_meth =~ m/^ ( [\w-]+ (?: \.[\w-]+ )* )
Branch: 1 branch
BranchTrueFalseTotal
$fq_meth =~ /^ ( [\w-]+ (?: \.[\w-]+ )* ) \. ( [\w-]+ | \* ) $/x or die "Invalid method '${fq_meth}' $at" 0 0 0
713 \. ( [\w-]+ | \* ) $/x or die "Invalid method '$fq_meth' $at";
714  
715 0 my ($service, $method) = ($1, $2);
716  
717 0 my $worker = $self->{_WORKER};
718  
719 0 ▶ unless (defined $worker->{callbacks}->{"msg.$fq_meth"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $worker->{"callbacks"}{"msg.$fq_meth"}) 0 0 0
720 0 log_warn "Not previously accepting notifications '$fq_meth' $at";
721 0 next;
722 }
723  
724 0 my $local_bus = $self->{_BUS}->{bus_role};
725  
726 0 my $topic = "msg/$local_bus/$service/$method";
727 0 $topic =~ tr|.*|/#|;
728  
729 # Cannot remove callbacks right now, as new notifications could be in flight or be
730 # already queued. We must wait for unsubscription completion, and then until the
731 # notification queue is empty to ensure that all received ones were processed. And
732 # even then wait a bit more, as some brokers may send messages *after* unsubscription.
733 0 ▶ my $postpone = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
734  
735 0 my $unsub_tmr; $unsub_tmr = AnyEvent->timer(
736 0 ▶ after => $UNSUBSCRIBE_LINGER, cb => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
737  
738 0 delete $worker->{callbacks}->{"msg.$fq_meth"};
739 0 undef $unsub_tmr;
740 }
741 0 );
742 0 };
743  
744 $self->{_BUS}->unsubscribe(
745 topic => $topic,
746 0 ▶ on_unsuback => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
747 0 my ($success, $prop) = @_;
748  
749 0 ▶ log_error "Could not unsubscribe from topic '$topic' $at" unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
750  
751 0 ▶ my $postponed = $worker->{postponed} ||= [];
Condition0%0/2
$worker->{"postponed"} ||= []
l!l
00
MC/DC0%0/1
$worker->{"postponed"} ||= []
$worker->{"postponed"}
Truth table0%0/2
A
A= $worker->{"postponed"}
Aresult
11
00
752 0 push @$postponed, $postpone;
753  
754 0 ▶ AnyEvent::postpone { $self->__drain_task_queue };
Subroutine __ANON__: not called CC=1 SCAR=6.9
755 }
756 0 );
757 }
758 }
759  
760  
761 0 ▶sub stop_accepting_calls {
Subroutine stop_accepting_calls: not called CC=6 SCAR=37.4
Pod documented
762 0 my ($self, @methods) = @_;
763  
764 0 my ($file, $line) = (caller)[1,2];
765 0 my $at = "at $file line $line\n";
766  
767 0 ▶ die "No method specified $at" unless @methods;
Branch: 1 branch
BranchTrueFalseTotal
unless @methods 0 0 0
768  
769 0 foreach my $fq_meth (@methods) {
770  
771 0 ▶ $fq_meth =~ m/^ ( [\w-]+ (?: \.[\w-]+ )* )
Branch: 1 branch
BranchTrueFalseTotal
$fq_meth =~ /^ ( [\w-]+ (?: \.[\w-]+ )* ) \. ( [\w-]+ | \* ) $/x or die "Invalid remote call method '${fq_meth}' $at" 0 0 0
772 \. ( [\w-]+ | \* ) $/x or die "Invalid remote call method '$fq_meth' $at";
773  
774 0 my ($service, $method) = ($1, $2);
775  
776 0 ▶ unless ($method eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($method eq "*") 0 0 0
777 # Known limitation. As all calls for an entire service class are received
778 # through a single MQTT subscription (in order to load balance them), it is
779 # not possible to reject a single method. A workaround is to use a different
780 # class for each method that need to be individually rejected.
781 0 die "Cannot stop accepting individual methods, only '$service.*' is allowed $at";
782 }
783  
784 0 my $worker = $self->{_WORKER};
785 0 my $callbacks = $worker->{callbacks};
786  
787 0 my @cb_keys = grep { $_ =~ m/^req.\Q$service\E\b/ } keys %$callbacks;
788  
789 0 ▶ unless (@cb_keys) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cb_keys) 0 0 0
790 0 log_warn "Not previously accepting remote calls '$fq_meth' $at";
791 0 next;
792 }
793  
794 0 my $local_bus = $self->{_BUS}->{bus_role};
795  
796 0 my $topic = "\$share/BKPR/req/$local_bus/$service";
797 0 $topic =~ tr|.*|/#|;
798  
799 # Cannot remove callbacks right now, as new requests could be in flight or be already
800 # queued. We must wait for unsubscription completion, and then until the task queue
801 # is empty to ensure that all received requests were processed. And even then wait a
802 # bit more, as some brokers may send requests *after* unsubscription.
803 0 ▶ my $postpone = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
804  
805 0 $worker->{stop_cv}->begin;
806  
807 0 my $unsub_tmr; $unsub_tmr = AnyEvent->timer(
808 0 ▶ after => $UNSUBSCRIBE_LINGER, cb => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
809  
810 0 delete $worker->{callbacks}->{$_} foreach @cb_keys;
811 0 delete $worker->{subscriptions}->{$service};
812 0 undef $unsub_tmr;
813  
814 0 ▶ return unless $worker->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
unless $worker->{"shutting_down"} 0 0 0
815  
816 0 ▶ if ($worker->{in_progress} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($worker->{"in_progress"} > 0) 0 0 0
817  
818 # The task queue is empty now, but an asynchronous method handler is
819 # still busy processing some requests received previously. Wait for
820 # these requests to be completed before telling _work_forever to stop
821  
822 0 my $wait_time = 60;
823 0 $worker->{stop_cv}->begin;
824  
825 0 ▶ my $busy_tmr; $busy_tmr = AnyEvent->timer( after => 1, interval => 1, cb => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
826 0 ▶ unless ($worker->{in_progress} > 0 && --$wait_time > 0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($worker->{"in_progress"} > 0 and --$wait_time > 0) 0 0 0
Condition0%0/3
$worker->{"in_progress"} > 0 and --$wait_time > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$worker->{"in_progress"} > 0 and --$wait_time > 0
$worker->{"in_progress"} > 0 --$wait_time > 0
Truth table0%0/3
A and B
A= $worker->{"in_progress"} > 0B= --$wait_time > 0
ABresult
0X0
100
111
827 0 undef $busy_tmr;
828 0 $worker->{stop_cv}->end;
829 }
830 0 });
831 }
832  
833 # Tell _work_forever to stop
834 0 $worker->{stop_cv}->end;
835 }
836 0 );
837 0 };
838  
839 $self->{_BUS}->unsubscribe(
840 topic => $topic,
841 0 ▶ on_unsuback => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
842 0 my ($success, $prop) = @_;
843  
844 0 ▶ log_error "Could not unsubscribe from topic '$topic' $at" unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
845  
846 0 ▶ my $postponed = $worker->{postponed} ||= [];
Condition0%0/2
$worker->{"postponed"} ||= []
l!l
00
MC/DC0%0/1
$worker->{"postponed"} ||= []
$worker->{"postponed"}
Truth table0%0/2
A
A= $worker->{"postponed"}
Aresult
11
00
847 0 push @$postponed, $postpone;
848  
849 0 ▶ AnyEvent::postpone { $self->__drain_task_queue };
Subroutine __ANON__: not called CC=1 SCAR=6.9
850 }
851 0 );
852 }
853 }
854  
855  
856 0 ▶sub __work_forever {
Subroutine __work_forever: not called CC=3 SCAR=24.8
857 0 my $self = shift;
858  
859 # Called by WorkerPool->spawn_worker
860  
861 0 eval {
862  
863 0 my $worker = $self->{_WORKER};
864  
865 0 $worker->{stop_cv} = AnyEvent->condvar;
866  
867 # Blocks here until stop_working is called
868 0 $worker->{stop_cv}->recv;
869  
870 0 $self->on_shutdown;
871  
872 0 $self->__report_exit;
873 };
874  
875 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
876 0 log_fatal "Worker died: $@";
877 0 CORE::exit(255);
878 }
879  
880 0 ▶ if ($self->{_BUS}->{is_connected}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_BUS"}{"is_connected"}) 0 0 0
881 0 $self->{_BUS}->disconnect;
882 }
883 }
884  
885  
886 0 ▶sub stop_working {
Subroutine stop_working: not called CC=7 SCAR=40.3
Pod documented
887 0 my ($self, %args) = @_;
888  
889 0 my $worker = $self->{_WORKER};
890  
891 # This is the default handler for TERM signal
892  
893 0 ▶ return if $worker->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $worker->{"shutting_down"} 0 0 0
894 0 $worker->{shutting_down} = 1;
895  
896 0 ▶ unless (defined $worker->{stop_cv}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $worker->{"stop_cv"}) 0 0 0
897 # Worker did not completed initialization yet
898 0 CORE::exit(0);
899 }
900  
901 0 my %services;
902 0 foreach my $fq_meth (keys %{$worker->{callbacks}}) {
903 0 ▶ next unless $fq_meth =~ m/^req\.(?!_sync)(.*)\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $fq_meth =~ /^req\.(?!_sync)(.*)\./ 0 0 0
904 0 $services{$1} = 1;
905 }
906  
907 0 ▶ if (keys %services) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %services) { } 0 0 0
908  
909 # Cannot exit right now, as some requests could be in flight or already queued.
910 # So tell the broker to stop sending requests, and exit after the task queue is empty
911 0 foreach my $service (keys %services) {
912  
913 0 $self->stop_accepting_calls( $service . '.*' );
914 }
915 }
916 else {
917 # Tell _work_forever to stop
918 0 $worker->{stop_cv}->send;
919 }
920 }
921  
922  
923 0 ▶sub __report_status {
Subroutine __report_status: not called CC=4 SCAR=30.0
924 0 my $self = shift;
925  
926 0 my $worker = $self->{_WORKER};
927 0 my $client = $self->{_CLIENT};
928  
929 0 my $now = Time::HiRes::time;
930 0 ▶ my $period = $now - ($worker->{last_report} || ($now - 1));
Condition0%0/3
$worker->{'last_report'} || $now - 1
l!l&&r!l&&!r
000
MC/DC0%0/2
$worker->{'last_report'} || $now - 1
$worker->{'last_report'} $now - 1
Truth table0%0/3
A || B
A= $worker->{'last_report'}B= $now - 1
ABresult
1X1
011
000
931  
932 0 $worker->{last_report} = $now;
933  
934 # Average calls per second
935 0 my $cps = sprintf("%.2f", $worker->{call_count} / $period);
936 0 $worker->{call_count} = 0;
937  
938 # Average notifications per second
939 0 my $nps = sprintf("%.2f", $worker->{notif_count} / $period);
940 0 $worker->{notif_count} = 0;
941  
942 # Average errors per second
943 0 my $err = sprintf("%.2f", $worker->{error_count} / $period);
944 0 $worker->{error_count} = 0;
945  
946 # Average load as percentage of wall clock busy time (not cpu usage)
947 0 my $load = sprintf("%.2f", ($BUSY_TIME - $worker->{busy_time}) / $period * 100);
948 0 $worker->{busy_time} = $BUSY_TIME;
949  
950 # Queues
951 0 my %queues;
952 0 foreach my $queue (keys %{$worker->{callbacks}}) {
953 0 ▶ next unless $queue =~ m/^req\.(?!_sync)(.*)\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $queue =~ /^req\.(?!_sync)(.*)\./ 0 0 0
954 0 $queues{$1} = 1;
955 }
956  
957 0 local $client->{auth_data} = $AUTH_TOKENS{'BKPR_SYSTEM'};
958 0 local $client->{caller_id};
959  
960 # Tell any supervisor our stats
961 $self->fire_remote(
962 method => '_bkpr.supervisor.worker_status',
963 params => {
964 class => ref($self),
965 host => $worker->{hostname},
966 pool => $worker->{pool_id},
967 0 pid => $$,
968 cps => $cps,
969 nps => $nps,
970 err => $err,
971 load => $load,
972 queue => [ keys %queues ],
973 },
974 );
975 }
976  
977 0 ▶sub __report_exit {
Subroutine __report_exit: not called CC=2 SCAR=17.9
978 0 my $self = shift;
979  
980 0 ▶ return unless $self->{_BUS}->{is_connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_BUS"}{"is_connected"} 0 0 0
981  
982 0 my $worker = $self->{_WORKER};
983 0 my $client = $self->{_CLIENT};
984  
985 0 local $client->{auth_data} = $AUTH_TOKENS{'BKPR_SYSTEM'};
986 0 local $client->{caller_id};
987  
988 $self->fire_remote(
989 method => '_bkpr.supervisor.worker_exit',
990 params => {
991 class => ref($self),
992 host => $worker->{hostname},
993 pool => $worker->{pool_id},
994 0 pid => $$,
995 },
996 );
997 }
998  
999 1 1;
1000  
1001 __END__
↑ Summary lib/Beekeeper/Service/LogTail/Worker.pm »