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