Merge remote-tracking branch 'friendica/stable' into develop
[friendica.git/.git] / bin / wait-for-connection
1 #!/usr/bin/php
2 <?php
3 /**
4  * @copyright Copyright (C) 2020, Friendica
5  *
6  * @license GNU AGPL version 3 or any later version
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Affero General Public License as
10  * published by the Free Software Foundation, either version 3 of the
11  * License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Affero General Public License for more details.
17  *
18  * You should have received a copy of the GNU Affero General Public License
19  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20  *
21  * This script tries to connect to a database for a given interval
22  * Useful in case of installation e.g. to wait for the database to not generate unnecessary errors
23  *
24  * Usage: php bin/wait-for-connection {HOST} {PORT} [{TIMEOUT}]
25  */
26
27 if (php_sapi_name() !== 'cli') {
28         header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden');
29         exit();
30 }
31
32 $timeout = 60;
33 switch ($argc) {
34         case 4:
35                 $timeout = (float)$argv[3];
36         case 3:
37                 $host = $argv[1];
38                 $port = (int)$argv[2];
39                 break;
40         default:
41                 fwrite(STDERR, 'Usage: '.$argv[0].' host port [timeout]'."\n");
42                 exit(2);
43 }
44 if ($timeout < 0) {
45         fwrite(STDERR, 'Timeout must be greater than zero'."\n");
46         exit(2);
47 }
48 if ($port < 1) {
49         fwrite(STDERR, 'Port must be an integer greater than zero'."\n");
50         exit(2);
51 }
52 $socketTimeout = (float)ini_get('default_socket_timeout');
53 if ($socketTimeout > $timeout) {
54         $socketTimeout = $timeout;
55 }
56 $stopTime = time() + $timeout;
57 do {
58         $sock = @fsockopen($host, $port, $errno, $errstr, $socketTimeout);
59         if ($sock !== false) {
60                 fclose($sock);
61                 fwrite(STDOUT, "\n");
62                 exit(0);
63         }
64         sleep(1);
65         fwrite(STDOUT, '.');
66 } while (time() < $stopTime);
67 fwrite(STDOUT, "\n");
68 exit(1);