Engine.pm untested

filter: Statementstmt 0.0% 0 / 204 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 8 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 295 CC 24 SCAR 46.7
CC
24
Cov
0%
start
306.0
new
42.0
stop_selector
6.0
CRAP 106.3
1 #!/usr/bin/perl
2 package Service::Engine;
3  
4 use 5.010;
5 use strict;
6 use warnings;
7  
8 use Carp;
9 use Data::Dumper;
10 use File::Pid;
11 use threads;
12 use threads::shared;
13 use Thread::Queue;
14 use Module::Runtime qw(require_module);
15  
16 use Service::Engine::Logging;
17 use Service::Engine::Data;
18 use Service::Engine::Config;
19 use Service::Engine::Threads;
20 use Service::Engine::Alerting;
21 use Service::Engine::Health;
22 use Service::Engine::Admin;
23 use Service::Engine::Admin::Server;
24 use Service::Engine::Throughput;
25 use Service::Engine::API;
26 use Service::Engine::API::Server;
27  
28 =head1 NAME
29  
30 Service::Engine - a framework for getting things done!
31  
32 =head1 VERSION
33  
34 Version 0.46
35  
36 0.45 -- Adding Elasticsearch
37 0.46 -- Updating Mysql to use utf8mb4
38  
39 =cut
40  
41 # shared variables
42 # any module can set/get them e.g. $Service::Engine::Debug = 1;
43 our $Config;
44 our $Log;
45 our $Data;
46 our $EngineName;
47 our $EngineInstance;
48 our $EngineConfig;
49 our $VERSION = '0.46';
50 our $Modules = {};
51 our $ModuleMethods = {};
52 our $Alert;
53 our $Admin;
54 our $API;
55 our $Threads;
56 our $Health;
57 our $Throughput;
58 our $Engine;
59 our $Shutdown = 0;
60  
61 share($Shutdown);
62 share($Threads);
63 share($Log);
64 share($Admin);
65 share($API);
66 share($Health);
67 share($Throughput);
68  
69 =head1 SYNOPSIS
70  
71 A Service Engine performs two basic functions:
72  
73 Select itmes to process
74 Work on the items selected
75  
76 What is selected is definded in Modules::Selector
77 The work performed is defined in Modules::Worker
78  
79 To make a service engine:
80 - duplicate an example
81 - rename the directory
82 - modify config.pl
83 - customize Modules::Selector and Modules::Worker
84 - start the new engine: ./start-engine.pl
85  
86 To connect to the admin console, telnet to the ip and port defined in config.pl
87  
88 To connect to the REST API, browse to http://yourIP:yourPort/Health/api_overview,
89 or other endooints you define in your config file.
90  
91 =head1 SUBROUTINES/METHODS
92  
93 =head2 new
94  
95 =cut
96  
97 sub new {
98
99 my ($class,$options) = @_;
100
101 # set some defaults
102 my $attributes = {};
103
104 # load options
105 if (ref($options) eq 'HASH') {
106 foreach my $option (keys %{$options}) {
107 $attributes->{$option} = $options->{$option};
108 }
109 }
110
111 # load configuration into a shared variable
112 # access $Config->get_config('logging')->{'log_level'}
113 $Config = Service::Engine::Config->new({'config_file'=>$attributes->{config_file}});
114
115 # make sure we have an EngineName
116 if (ref($Config->get_config('engine')) eq 'HASH') {
117 $EngineName = $Config->get_config('engine')->{'name'};
118 $EngineName =~ s/[^\w]//g;
119 if (!$EngineName) {
120 croak('engine name not valid');
121 }
122 $EngineInstance = $Config->get_config('engine')->{'instance'};
123 $EngineInstance =~ s/[^\w]//g;
124 if (!$EngineInstance) {
125 croak('engine instance not valid');
126 }
127 } else {
128 croak('engine config not found');
129 }
130
131 $EngineConfig = $Config->get_config($EngineName);
132 if (ref($EngineConfig) ne 'HASH') {
133 croak($EngineName . ' config not found');
134 }
135
136 # set up Logging
137 $Log = shared_clone(Service::Engine::Logging->new());
138
139 # set up data for use outside of threads
140 # Each thread gets it own set of connections in Threads.pm
141 $Data = Service::Engine::Data->new();
142
143 $Alert = Service::Engine::Alerting->new();
144
145 my $self = bless $attributes, $class;
146 $Engine = $self;
147
148 $Log->log({msg=>"finished initializing engine",level=>2});
149
150 return $self;
151  
152 }
153  
154 sub data {
155 my $self = shift;
156 return $self->{data};
157 }
158  
159 =head2 start
160  
161 =cut
162  
163 sub start {
164  
165 my $self = shift;
166
167 my $sleep = $Config->get_config('engine')->{'sleep'};
168 $sleep ||= 0;
169  
170 $Log->log({msg=>"starting engine",level=>2});
171
172 # write pidfile
173 # Write the current process id to a file
174 # so that the service start and stop commands work :)
175 my $pidfile = File::Pid->new({
176 file => '/var/run/' . lc $EngineName . '.pid'
177 });
178  
179 $pidfile->write;
180
181 # initialize our selector and worker modules
182 my $modules = $EngineConfig->{'required_modules'};
183 if (ref($modules) ne 'HASH') {
184 croak('required_modules not found in config' );
185 } elsif (!$modules->{'selector'} || !$modules->{'worker'}) {
186 croak('selector and worker modules are required in config' );
187 }
188
189 foreach my $module (keys %{$modules}) {
190 my $module_name = $modules->{$module}->{'name'};
191 $ModuleMethods->{$module} = {'method'=>$modules->{$module}->{'method'}};
192 $Log->log({msg=>"loading module $module_name",level=>2});
193 my $package = $EngineName . '::Modules::' . $module_name;
194 my $res = eval { require_module($package) };
195 if ($@) {
196 $Log->log({msg=>"error loading $package: $@",level=>1});
197 } else {
198 $Modules->{$module} = $package->new($modules->{$module}->{'config'});
199 $Log->log({msg=>"loaded $package",level=>3});
200 }
201 }
202
203 # we need Throughput initialized before Threads
204 if ($Config->get_config('health')->{'enabled'}) {
205 if ($Config->get_config('health')->{'modules'}->{'Throughput'}->{'enabled'} && $Config->get_config('health')->{'memcached'}->{'enabled'}) {
206 $Throughput = shared_clone(Service::Engine::Throughput->new());
207 }
208 }
209
210 # initialize threads
211 $Threads = shared_clone(Service::Engine::Threads->new());
212 my $method = $ModuleMethods->{'selector'}->{'method'};
213
214 # initialize admin
215 if ($Config->get_config('admin')->{'enabled'}) {
216 $Admin = shared_clone(Service::Engine::Admin->new());
217 }
218
219 # initialize API
220 if ($Config->get_config('api')->{'enabled'}) {
221 $API = shared_clone(Service::Engine::API->new());
222 }
223
224 # initialize health monitoring
225 # we do this after admin, because we need access to the Admin object to adjust menus
226 if ($Config->get_config('health')->{'enabled'}) {
227 $Health = shared_clone(Service::Engine::Health->new());
228 my $health_monitoring_thread = threads->create('start_health_monitoring');
229 }
230
231 if ($Config->get_config('admin')->{'enabled'}) {
232 my $api_thread = threads->create('start_api');
233 }
234
235 # we have to start Admin last, since it needs access to all other modules
236 if ($Config->get_config('admin')->{'enabled'}) {
237 my $admin_thread = threads->create('start_admin');
238 }
239
240 $Log->log({msg=>"finished starting engine",level=>2});
241
242 while (1) {
243
244 my $queue = [];
245 # some items to process unless we are shutting down
246 $queue = $Modules->{'selector'}->$method() unless $Shutdown;
247
248 if (ref($queue) ne 'ARRAY') {
249 croak('the queue must be an array reference' );
250 }
251
252 # enqueue
253 if (scalar(@{$queue})) {
254 foreach my $item (@{$queue}) {
255 $Log->log({msg=>"received empty item, skipping",level=>3}) unless $item;
256 next unless $item;
257 if ($Throughput) {
258 $Throughput->add(1);
259 }
260 my $thread = $Threads->get_thread();
261 $thread->enqueue( $item );
262 }
263 }
264
265 sleep($sleep);
266  
267 }
268  
269 }
270  
271 sub start_admin {
272 my $self = shift;
273 $Log->log({msg=>"starting admin",level=>3});
274 my $service = $Admin->start_admin_server();
275 }
276  
277 sub start_api {
278 my $self = shift;
279 $Log->log({msg=>"starting api",level=>3});
280 my $service = $API->start_api_server();
281 }
282  
283 sub start_health_monitoring {
284 my $self = shift;
285 $Log->log({msg=>"starting health monitoring",level=>3});
286 my $service = $Health->start();
287 }
288  
289 sub stop_selector {
290 my ($self,$fh) = @_;
291 $fh->write("stopping selector process\n") unless !$fh;
292 $Log->log({msg=>"stopping selector",level=>3});
293 $Shutdown = 1;
294 }
295  
296 sub start_selector {
297 my ($self,$fh) = @_;
298 $fh->write("starting selector process\n") unless !$fh;
299 $Log->log({msg=>"starting selector",level=>3});
300 $Shutdown = 0;
301 }
302  
303 =head1 AUTHOR
304  
305 Richard Bush, C<< <rbush at netsocialapp.com> >>
306  
307 =head1 SUPPORT
308  
309 You can find documentation for this module with the perldoc command.
310  
311 perldoc Service::Engine
312  
313 =head1 LICENSE AND COPYRIGHT
314  
315 Copyright 2020 Richard Bush.
316  
317 This program is free software; you can redistribute it and/or modify it
318 under the terms of the the Artistic License (2.0). You may obtain a
319 copy of the full license at:
320  
321 L<http://www.perlfoundation.org/artistic_license_2_0>
322  
323 Any use, modification, and distribution of the Standard or Modified
324 Versions is governed by this Artistic License. By using, modifying or
325 distributing the Package, you accept this license. Do not use, modify,
326 or distribute the Package, if you do not accept this license.
327  
328 If your Modified Version has been derived from a Modified Version made
329 by someone other than you, you are nevertheless required to ensure that
330 your Modified Version complies with the requirements of this license.
331  
332 This license does not grant you the right to use any trademark, service
333 mark, tradename, or logo of the Copyright Holder.
334  
335 This license includes the non-exclusive, worldwide, free-of-charge
336 patent license to make, have made, use, offer to sell, sell, import and
337 otherwise transfer the Package with respect to any patent claims
338 licensable by the Copyright Holder that are necessarily infringed by the
339 Package. If you institute patent litigation (including a cross-claim or
340 counterclaim) against any party alleging that the Package constitutes
341 direct or contributory patent infringement, then this Artistic License
342 to you shall terminate on the date that such litigation is filed.
343  
344 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
345 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
346 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
347 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
348 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
349 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
350 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
351 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
352  
353  
354 =cut
355
356 1;