Commit | Line | Data |
---|---|---|
b5c0ad9a TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
b5c0ad9a | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
b5c0ad9a | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
b5c0ad9a TO |
11 | |
12 | /** | |
b5c0ad9a | 13 | * @package CRM |
ca5cec67 | 14 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
b5c0ad9a TO |
15 | */ |
16 | ||
17 | /** | |
18 | * Simple static helpers for network operations | |
19 | */ | |
20 | class CRM_Utils_Network { | |
6714d8d2 | 21 | |
b5c0ad9a TO |
22 | /** |
23 | * Try connecting to a TCP service; if it fails, retry. Repeat until serverStartupTimeOut elapses. | |
24 | * | |
f4aaa82a EM |
25 | * @param $host |
26 | * @param $port | |
77855840 TO |
27 | * @param int $serverStartupTimeOut |
28 | * Seconds. | |
29 | * @param float $interval | |
30 | * Seconds to wait in between pollings. | |
f4aaa82a | 31 | * |
a6c01b45 CW |
32 | * @return bool |
33 | * TRUE if service is online | |
b5c0ad9a TO |
34 | */ |
35 | public static function waitForServiceStartup($host, $port, $serverStartupTimeOut, $interval = 0.333) { | |
36 | $start = time(); | |
37 | $end = $start + $serverStartupTimeOut; | |
38 | $found = FALSE; | |
39 | $interval_usec = (int) 1000000 * $interval; | |
40 | ||
41 | while (!$found && $end >= time()) { | |
42 | $found = self::checkService($host, $port, $end - time()); | |
43 | if ($found) { | |
44 | return TRUE; | |
45 | } | |
46 | usleep($interval_usec); | |
47 | } | |
48 | return FALSE; | |
49 | } | |
50 | ||
51 | /** | |
3bdf1f3a | 52 | * Check whether a TCP service is available on $host and $port. |
53 | * | |
54 | * @param string $host | |
55 | * @param string $port | |
56 | * @param string $serverConnectionTimeOut | |
57 | * | |
58 | * @return bool | |
b5c0ad9a TO |
59 | */ |
60 | public static function checkService($host, $port, $serverConnectionTimeOut) { | |
61 | $old_error_reporting = error_reporting(); | |
62 | error_reporting($old_error_reporting & ~E_WARNING); | |
63 | try { | |
64 | $fh = fsockopen($host, $port, $errno, $errstr, $serverConnectionTimeOut); | |
65 | if ($fh) { | |
66 | fclose($fh); | |
67 | error_reporting($old_error_reporting); | |
68 | return TRUE; | |
69 | } | |
0db6c3e1 TO |
70 | } |
71 | catch (Exception $e) { | |
b5c0ad9a TO |
72 | } |
73 | error_reporting($old_error_reporting); | |
74 | return FALSE; | |
75 | } | |
96025800 | 76 | |
232624b1 | 77 | } |