Completed
Push — class-eventloop ( 51113e...323d1b )
by Vasily
04:01
created

IPC   B

Complexity

Total Complexity 54

Size/Duplication

Total Lines 341
Duplicated Lines 19.35 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 66
loc 341
rs 7.0642
wmc 54
lcom 1
cbo 8

15 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 32 5
C prepareSystemEnv() 39 55 17
A log() 0 4 1
A update() 0 9 3
D shutdown() 6 34 9
A sigint() 0 8 2
A sigterm() 0 8 2
A sigquit() 0 8 2
A sigtstp() 0 8 2
A sighup() 11 12 3
A sigusr1() 0 8 2
A sigusr2() 0 6 2
A sigttin() 0 3 1
A sigxfsz() 0 4 1
A sigunknown() 10 10 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like IPC often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use IPC, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace PHPDaemon\Thread;
3
4
use PHPDaemon\Core\AppInstance;
5
use PHPDaemon\Core\Daemon;
6
use PHPDaemon\Core\EventLoop;
7
use PHPDaemon\FS\FileSystem;
8
use PHPDaemon\FS\FileWatcher;
9
10
/**
11
 * Implementation of the IPC thread
12
 *
13
 * @package Core
14
 *
15
 * @author  Vasily Zorin <[email protected]>
16
 */
17
// @TODO: respawning IPCThread on unexpected failures
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
18
class IPC extends Generic
19
{
20
    /**
21
     * Event base
22
     * @var EventLoop
23
     */
24
    public $loop;
25
26
    /**
27
     * Break main loop?
28
     * @var boolean
29
     */
30
    protected $breakMainLoop = false;
31
32
    /**
33
     * Reload ready?
34
     * @var boolean
35
     */
36
    protected $reloadReady = false;
37
38
    /**
39
     * Update?
40
     * @var boolean
41
     */
42
    public $update = false;
43
44
45
    /**
46
     * If true, we do not register signals automatically at start
47
     * @var boolean
48
     */
49
    protected $delayedSigReg = true;
50
51
    /**
52
     * Instances count
53
     * @var array
54
     */
55
    public $instancesCount = [];
56
57
    /**
58
     * File watcher
59
     * @var FileWatcher
60
     */
61
    public $fileWatcher;
62
63
    /**
64
     * If true, we do not register signals automatically at start
65
     * @var boolean
66
     */
67
    public $reload = false;
68
69
    /** @var */
70
    public $IPCManager;
71
72
    /**
73
     * Runtime of Worker process.
74
     * @return void
75
     */
76
    protected function run()
77
    {
78
        if (Daemon::$process instanceof Master) {
79
            Daemon::$process->unregisterSignals();
0 ignored issues
show
Bug introduced by
The method unregisterSignals() cannot be called from this context as it is declared protected in class PHPDaemon\Thread\Generic.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
80
        }
81
        EventLoop::init();
82
        Daemon::$process = $this;
83
        if (Daemon::$logpointerAsync) {
84
            Daemon::$logpointerAsync->fd = null;
85
            Daemon::$logpointerAsync     = null;
86
        }
87
        class_exists('Timer');
88
89
        if (Daemon::$config->autogc->value > 0) {
90
            gc_enable();
91
        } else {
92
            gc_disable();
93
        }
94
        $this->prepareSystemEnv();
95
        $this->registerEventSignals();
96
        FileSystem::init(); // re-init
97
        FileSystem::initEvent();
98
        Daemon::openLogs();
99
100
        $this->fileWatcher = new FileWatcher();
101
        $this->IPCManager  = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
102
        if (!$this->IPCManager) {
103
            $this->log('cannot instantiate IPCManager');
104
        }
105
106
        $this->loop->run();
107
    }
108
109
    /**
110
     * Setup settings on start.
111
     * @return void
112
     */
113
    protected function prepareSystemEnv()
114
    {
115
        proc_nice(Daemon::$config->ipcthreadpriority->value);
116
        register_shutdown_function([$this, 'shutdown']);
117
118
        $this->setTitle(
119
            Daemon::$runName . ': IPC process'
120
            . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value
121
                    ? ' (' . Daemon::$config->pidfile->value . ')' : '')
122
        );
123
124
        if (isset(Daemon::$config->group->value)) {
125
            $sg = posix_getgrnam(Daemon::$config->group->value);
126
        }
127
128
        if (isset(Daemon::$config->user->value)) {
129
            $su = posix_getpwnam(Daemon::$config->user->value);
130
        }
131
132
        if (Daemon::$config->chroot->value !== '/') {
133 View Code Duplication
            if (posix_getuid() != 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
                $this->log('You must have the root privileges to change root.');
135
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
136
            } elseif (!chroot(Daemon::$config->chroot->value)) {
137
                Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.');
138
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
139
            }
140
        }
141
142 View Code Duplication
        if (isset(Daemon::$config->group->value)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
143
            if ($sg === false) {
144
                $this->log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 163 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
145
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
146
            } elseif (($sg['gid'] != posix_getgid())  && (!posix_setgid($sg['gid']))) {
0 ignored issues
show
Bug introduced by
The variable $sg does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
147
                $this->log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 175 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
148
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
149
            }
150
        }
151
152 View Code Duplication
        if (isset(Daemon::$config->user->value)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
            if ($su === false) {
154
                $this->log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 179 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
155
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
156
            } elseif (($su['uid'] != posix_getuid()) && (!posix_setuid($su['uid']))) {
0 ignored issues
show
Bug introduced by
The variable $su does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
157
                $this->log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 173 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
158
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method prepareSystemEnv() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
159
            }
160
        }
161
162 View Code Duplication
        if (Daemon::$config->cwd->value !== '.') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
            if (!@chdir(Daemon::$config->cwd->value)) {
164
                $this->log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.');
165
            }
166
        }
167
    }
168
169
    /**
170
     * Log something
171
     * @param string - Message.
172
     * @param string $message
173
     * @return void
174
     */
175
    public function log($message)
176
    {
177
        Daemon::log('I#' . $this->pid . ' ' . $message);
178
    }
179
180
    /**
181
     * Reloads additional config-files on-the-fly.
182
     * @return void
183
     */
184
    protected function update()
185
    {
186
        FileSystem::updateConfig();
187
        foreach (Daemon::$appInstances as $app) {
188
            foreach ($app as $appInstance) {
189
                $appInstance->handleStatus(AppInstance::EVENT_CONFIG_UPDATED);
190
            }
191
        }
192
    }
193
194
    /**
195
     * Shutdown thread
196
     * @param boolean - Hard? If hard, we shouldn't wait for graceful shutdown of the running applications.
197
     * @return boolean|null - Ready?
198
     */
199
    public function shutdown($hard = false)
200
    {
201
        $error = error_get_last();
202 View Code Duplication
        if ($error) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $error of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
            if ($error['type'] === E_ERROR) {
204
                $this->log('crashed by error \'' . $error['message'] . '\' at ' . $error['file'] . ':' . $error['line']);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
205
            }
206
        }
207
        if (Daemon::$config->logevents->value) {
208
            $this->log('event shutdown(' . ($hard ? 'HARD' : '') . ') invoked.');
209
        }
210
211
        if (Daemon::$config->throwexceptiononshutdown->value) {
212
            throw new \Exception('event shutdown');
213
        }
214
215
        @ob_flush();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
216
217
        if ($this->terminated === true) {
218
            if ($hard) {
219
                exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method shutdown() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
220
            }
221
222
            return;
223
        }
224
225
        $this->terminated = true;
226
        if ($hard) {
227
            exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method shutdown() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
228
        }
229
        FileSystem::waitAllEvents(); // ensure that all I/O events completed before suicide
230
        posix_kill(posix_getppid(), SIGCHLD); // praying to Master
231
        exit(0); // R.I.P.
0 ignored issues
show
Coding Style Compatibility introduced by
The method shutdown() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
232
    }
233
234
    /**
235
     * Handler of the SIGINT (hard shutdown) signal in worker process.
236
     * @return void
237
     */
238
    protected function sigint()
239
    {
240
        if (Daemon::$config->logsignals->value) {
241
            $this->log('caught SIGINT.');
242
        }
243
244
        $this->shutdown(true);
245
    }
246
247
    /**
248
     * Handler of the SIGTERM (graceful shutdown) signal in worker process.
249
     * @return void
250
     */
251
    protected function sigterm()
252
    {
253
        if (Daemon::$config->logsignals->value) {
254
            $this->log('caught SIGTERM.');
255
        }
256
257
        $this->shutdown();
258
    }
259
260
    /**
261
     * Handler of the SIGQUIT (graceful shutdown) signal in worker process.
262
     * @return void
263
     */
264
    public function sigquit()
265
    {
266
        if (Daemon::$config->logsignals->value) {
267
            $this->log('caught SIGQUIT.');
268
        }
269
270
        parent::sigquit();
271
    }
272
273
    /**
274
     * Handler of the SIGTSTP (graceful stop) signal in worker process.
275
     * @return void
276
     */
277
    protected function sigtstp()
278
    {
279
        if (Daemon::$config->logsignals->value) {
280
            $this->log('Caught SIGTSTP (graceful stop all workers).');
281
        }
282
283
        $this->shutdown();
284
    }
285
286
    /**
287
     * Handler of the SIGHUP (reload config) signal in worker process.
288
     * @return void
289
     */
290 View Code Duplication
    public function sighup()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
291
    {
292
        if (Daemon::$config->logsignals->value) {
293
            $this->log('caught SIGHUP (reload config).');
294
        }
295
296
        if (isset(Daemon::$config->configfile->value)) {
297
            Daemon::loadConfig(Daemon::$config->configfile->value);
298
        }
299
300
        $this->update = true;
301
    }
302
303
    /**
304
     * Handler of the SIGUSR1 (re-open log-file) signal in worker process.
305
     * @return void
306
     */
307
    public function sigusr1()
308
    {
309
        if (Daemon::$config->logsignals->value) {
310
            $this->log('caught SIGUSR1 (re-open log-file).');
311
        }
312
313
        Daemon::openLogs();
314
    }
315
316
    /**
317
     * Handler of the SIGUSR2 (graceful shutdown for update) signal in worker process.
318
     * @return void
319
     */
320
    public function sigusr2()
321
    {
322
        if (Daemon::$config->logsignals->value) {
323
            $this->log('caught SIGUSR2 (graceful shutdown for update).');
324
        }
325
    }
326
327
    /**
328
     * Handler of the SIGTTIN signal in worker process.
329
     * @return void
330
     */
331
    public function sigttin()
332
    {
333
    }
334
335
    /**
336
     * Handler of the SIGXSFZ signal in worker process.
337
     * @return void
338
     */
339
    public function sigxfsz()
340
    {
341
        $this->log('SIGXFSZ.');
342
    }
343
344
    /**
345
     * Handler of non-known signals.
346
     * @return void
347
     */
348 View Code Duplication
    public function sigunknown($signo)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
349
    {
350
        if (isset(Generic::$signals[$signo])) {
351
            $sig = Generic::$signals[$signo];
352
        } else {
353
            $sig = 'UNKNOWN';
354
        }
355
356
        $this->log('caught signal #' . $signo . ' (' . $sig . ').');
357
    }
358
}
359