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