Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 12b63b3

Browse files
bug #45281 [Cache] Fix connecting to Redis via a socket file (alebedev80)
This PR was merged into the 4.4 branch. Discussion ---------- [Cache] Fix connecting to Redis via a socket file | Q | A | ------------- | --- | Branch? | 4.4 | Bug fix? | yes | New feature? | no | Deprecations? | no | Tickets | #45277 | License | MIT | Doc PR | In the [commit](99b4885) was done follow changes in Traits/RedisTrait.php(188) Old code: ```$port = $hosts[0]['port'] ?? null;``` New code: ```$port = $hosts[0]['port'] ?? 6379;``` With DSN "redis:///var/run/redis/redis.sock" raise an error: ``` Redis connection "redis:///var/run/redis/redis.sock?dbindex=5" failed: php_network_getaddresses: getaddrinfo failed: Name or service not known ``` Because phpredis doesn't allow socket connections with a port ``` (new Redis)->connect('/var/run/redis/redis.sock', 6379); ``` **Error** ``` PHP Warning: Redis::connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /root/test_redis.php on line 5 PHP Fatal error: Uncaught RedisException: php_network_getaddresses: getaddrinfo failed: Name or service not known in /root/test_redis.php:5 Stack trace: #0 /root/test_redis.php(5): Redis->connect() #1 {main} thrown in /root/test_redis.php on line 5 ``` I added additional validation of connection type (by host or socket). Also I fixed condition when RedisSentinel connection call as it supports connections by host only. Commits ------- 214fdd1 [Cache] Fix connecting to Redis via a socket file
2 parents 1b695a9 + 214fdd1 commit 12b63b3

22 files changed

+64
-35
lines changed

.github/workflows/integration-tests.yml

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ jobs:
3333
redis:
3434
image: redis:6.0.0
3535
ports:
36-
- 6379:6379
36+
- 16379:6379
3737
redis-cluster:
3838
image: grokzen/redis-cluster:5.0.4
3939
ports:
@@ -67,6 +67,19 @@ jobs:
6767
- name: Checkout
6868
uses: actions/checkout@v2
6969

70+
- name: Install system dependencies
71+
run: |
72+
echo "::group::apt-get update"
73+
sudo apt-get update
74+
echo "::endgroup::"
75+
76+
echo "::group::install tools & libraries"
77+
sudo apt-get install redis-server
78+
sudo -- sh -c 'echo unixsocket /var/run/redis/redis-server.sock >> /etc/redis/redis.conf'
79+
sudo -- sh -c 'echo unixsocketperm 777 >> /etc/redis/redis.conf'
80+
sudo service redis-server restart
81+
echo "::endgroup::"
82+
7083
- name: Setup PHP
7184
uses: shivammathur/setup-php@v2
7285
with:
@@ -99,6 +112,7 @@ jobs:
99112
- name: Run tests
100113
run: ./phpunit --group integration -v
101114
env:
115+
REDIS_HOST: 'localhost:16379'
102116
REDIS_CLUSTER_HOSTS: 'localhost:7000 localhost:7001 localhost:7002 localhost:7003 localhost:7004 localhost:7005'
103117
REDIS_SENTINEL_HOSTS: 'localhost:26379'
104118
REDIS_SENTINEL_SERVICE: redis_sentinel

phpunit.xml.dist

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
<env name="LDAP_HOST" value="localhost" />
1919
<env name="LDAP_PORT" value="3389" />
2020
<env name="REDIS_HOST" value="localhost" />
21+
<env name="REDIS_SOCKET" value="/var/run/redis/redis-server.sock" />
2122
<env name="MESSENGER_REDIS_DSN" value="redis://localhost/messages" />
2223
<env name="MEMCACHED_HOST" value="localhost" />
2324
<env name="MONGODB_HOST" value="localhost" />

src/Symfony/Bundle/FrameworkBundle/Tests/Functional/CachePoolsTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ protected static function createKernel(array $options = []): KernelInterface
121121
private function skipIfRedisUnavailable()
122122
{
123123
try {
124-
(new \Redis())->connect(getenv('REDIS_HOST'));
124+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
125125
} catch (\Exception $e) {
126126
self::markTestSkipped($e->getMessage());
127127
}

src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/CachePools/redis_custom_config.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ services:
88
cache.test_redis_connection:
99
public: false
1010
class: Redis
11-
calls:
12-
- [connect, ['%env(REDIS_HOST)%']]
11+
factory: ['Symfony\Component\Cache\Adapter\RedisAdapter', 'createConnection']
12+
arguments: ['redis://%env(REDIS_HOST)%']
1313

1414
cache.app:
1515
parent: cache.adapter.redis

src/Symfony/Component/Cache/Tests/Adapter/AbstractRedisAdapterTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ public static function setUpBeforeClass(): void
3636
throw new SkippedTestSuiteError('Extension redis required.');
3737
}
3838
try {
39-
(new \Redis())->connect(getenv('REDIS_HOST'));
39+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
4040
} catch (\Exception $e) {
41-
throw new SkippedTestSuiteError($e->getMessage());
41+
throw new SkippedTestSuiteError(getenv('REDIS_HOST').': '.$e->getMessage());
4242
}
4343
}
4444

src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class PredisAdapterTest extends AbstractRedisAdapterTest
2222
public static function setUpBeforeClass(): void
2323
{
2424
parent::setUpBeforeClass();
25-
self::$redis = new \Predis\Client(['host' => getenv('REDIS_HOST')], ['prefix' => 'prefix_']);
25+
self::$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => 6379]), ['prefix' => 'prefix_']);
2626
}
2727

2828
public function testCreateConnection()
@@ -35,10 +35,11 @@ public function testCreateConnection()
3535
$connection = $redis->getConnection();
3636
$this->assertInstanceOf(StreamConnection::class, $connection);
3737

38+
$redisHost = explode(':', $redisHost);
3839
$params = [
3940
'scheme' => 'tcp',
40-
'host' => $redisHost,
41-
'port' => 6379,
41+
'host' => $redisHost[0],
42+
'port' => (int) ($redisHost[1] ?? 6379),
4243
'persistent' => 0,
4344
'timeout' => 3,
4445
'read_write_timeout' => 0,

src/Symfony/Component/Cache/Tests/Adapter/PredisClusterAdapterTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class PredisClusterAdapterTest extends AbstractRedisAdapterTest
1919
public static function setUpBeforeClass(): void
2020
{
2121
parent::setUpBeforeClass();
22-
self::$redis = new \Predis\Client([['host' => getenv('REDIS_HOST')]], ['prefix' => 'prefix_']);
22+
self::$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => 6379]), ['prefix' => 'prefix_']);
2323
}
2424

2525
public static function tearDownAfterClass(): void

src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,30 +40,42 @@ public function createCachePool(int $defaultLifetime = 0, string $testMethod = n
4040
return $adapter;
4141
}
4242

43-
public function testCreateConnection()
43+
public function testCreateHostConnection()
4444
{
4545
$redis = RedisAdapter::createConnection('redis:?host[h1]&host[h2]&host[/foo:]');
4646
$this->assertInstanceOf(\RedisArray::class, $redis);
4747
$this->assertSame(['h1:6379', 'h2:6379', '/foo'], $redis->_hosts());
4848
@$redis = null; // some versions of phpredis connect on destruct, let's silence the warning
4949

50-
$redisHost = getenv('REDIS_HOST');
50+
$this->doTestCreateConnection(getenv('REDIS_HOST'));
51+
}
52+
53+
public function testCreateSocketConnection()
54+
{
55+
if (!getenv('REDIS_SOCKET') || !file_exists(getenv('REDIS_SOCKET'))) {
56+
$this->markTestSkipped('Redis socket not found');
57+
}
58+
59+
$this->doTestCreateConnection(getenv('REDIS_SOCKET'));
60+
}
5161

52-
$redis = RedisAdapter::createConnection('redis://'.$redisHost);
62+
private function doTestCreateConnection(string $uri)
63+
{
64+
$redis = RedisAdapter::createConnection('redis://'.$uri);
5365
$this->assertInstanceOf(\Redis::class, $redis);
5466
$this->assertTrue($redis->isConnected());
5567
$this->assertSame(0, $redis->getDbNum());
5668

57-
$redis = RedisAdapter::createConnection('redis://'.$redisHost.'/2');
69+
$redis = RedisAdapter::createConnection('redis://'.$uri.'/2');
5870
$this->assertSame(2, $redis->getDbNum());
5971

60-
$redis = RedisAdapter::createConnection('redis://'.$redisHost, ['timeout' => 3]);
72+
$redis = RedisAdapter::createConnection('redis://'.$uri, ['timeout' => 3]);
6173
$this->assertEquals(3, $redis->getTimeout());
6274

63-
$redis = RedisAdapter::createConnection('redis://'.$redisHost.'?timeout=4');
75+
$redis = RedisAdapter::createConnection('redis://'.$uri.'?timeout=4');
6476
$this->assertEquals(4, $redis->getTimeout());
6577

66-
$redis = RedisAdapter::createConnection('redis://'.$redisHost, ['read_timeout' => 5]);
78+
$redis = RedisAdapter::createConnection('redis://'.$uri, ['read_timeout' => 5]);
6779
$this->assertEquals(5, $redis->getReadTimeout());
6880
}
6981

src/Symfony/Component/Cache/Tests/Simple/AbstractRedisCacheTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public static function setUpBeforeClass(): void
3939
throw new SkippedTestSuiteError('Extension redis required.');
4040
}
4141
try {
42-
(new \Redis())->connect(getenv('REDIS_HOST'));
42+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
4343
} catch (\Exception $e) {
4444
throw new SkippedTestSuiteError($e->getMessage());
4545
}

src/Symfony/Component/Cache/Traits/RedisTrait.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ public static function createConnection($dsn, array $options = [])
185185

186186
$initializer = static function ($redis) use ($connect, $params, $dsn, $auth, $hosts, $tls) {
187187
$host = $hosts[0]['host'] ?? $hosts[0]['path'];
188-
$port = $hosts[0]['port'] ?? 6379;
188+
$port = $hosts[0]['port'] ?? 0;
189189

190190
if (isset($hosts[0]['host']) && $tls) {
191191
$host = 'tls://'.$host;

src/Symfony/Component/Cache/phpunit.xml.dist

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
<php>
1212
<ini name="error_reporting" value="-1" />
1313
<env name="REDIS_HOST" value="localhost" />
14+
<env name="REDIS_SOCKET" value="/var/run/redis/redis-server.sock" />
1415
<env name="MEMCACHED_HOST" value="localhost" />
1516
</php>
1617

src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/AbstractRedisSessionHandlerTestCase.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ protected function setUp(): void
4545
self::markTestSkipped('Extension redis required.');
4646
}
4747
try {
48-
(new \Redis())->connect(getenv('REDIS_HOST'));
48+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
4949
} catch (\Exception $e) {
5050
self::markTestSkipped($e->getMessage());
5151
}

src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PredisClusterSessionHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,6 @@ class PredisClusterSessionHandlerTest extends AbstractRedisSessionHandlerTestCas
2020
{
2121
protected function createRedisClient(string $host): Client
2222
{
23-
return new Client([['host' => $host]]);
23+
return new Client([array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => 6379])]);
2424
}
2525
}

src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PredisSessionHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,6 @@ class PredisSessionHandlerTest extends AbstractRedisSessionHandlerTestCase
2020
{
2121
protected function createRedisClient(string $host): Client
2222
{
23-
return new Client(['host' => $host]);
23+
return new Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => 6379]));
2424
}
2525
}

src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/RedisSessionHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class RedisSessionHandlerTest extends AbstractRedisSessionHandlerTestCase
2222
protected function createRedisClient(string $host)
2323
{
2424
$client = new \Redis();
25-
$client->connect($host);
25+
$client->connect(...explode(':', $host));
2626

2727
return $client;
2828
}

src/Symfony/Component/Lock/Tests/Store/CombinedStoreTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ protected function getClockDelay()
4141
*/
4242
public function getStore(): PersistingStoreInterface
4343
{
44-
$redis = new \Predis\Client('tcp://'.getenv('REDIS_HOST').':6379');
44+
$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]));
4545
try {
4646
$redis->connect();
4747
} catch (\Exception $e) {

src/Symfony/Component/Lock/Tests/Store/PredisStoreTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class PredisStoreTest extends AbstractRedisStoreTest
2121
{
2222
public static function setUpBeforeClass(): void
2323
{
24-
$redis = new \Predis\Client('tcp://'.getenv('REDIS_HOST').':6379');
24+
$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]));
2525
try {
2626
$redis->connect();
2727
} catch (\Exception $e) {
@@ -31,7 +31,7 @@ public static function setUpBeforeClass(): void
3131

3232
protected function getRedisConnection()
3333
{
34-
$redis = new \Predis\Client('tcp://'.getenv('REDIS_HOST').':6379');
34+
$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]));
3535
$redis->connect();
3636

3737
return $redis;

src/Symfony/Component/Lock/Tests/Store/RedisArrayStoreTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public static function setUpBeforeClass(): void
2727
throw new SkippedTestSuiteError('The RedisArray class is required.');
2828
}
2929
try {
30-
(new \Redis())->connect(getenv('REDIS_HOST'));
30+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
3131
} catch (\Exception $e) {
3232
throw new SkippedTestSuiteError($e->getMessage());
3333
}

src/Symfony/Component/Lock/Tests/Store/RedisStoreTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class RedisStoreTest extends AbstractRedisStoreTest
2626
public static function setUpBeforeClass(): void
2727
{
2828
try {
29-
(new \Redis())->connect(getenv('REDIS_HOST'));
29+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
3030
} catch (\Exception $e) {
3131
throw new SkippedTestSuiteError($e->getMessage());
3232
}
@@ -35,7 +35,7 @@ public static function setUpBeforeClass(): void
3535
protected function getRedisConnection()
3636
{
3737
$redis = new \Redis();
38-
$redis->connect(getenv('REDIS_HOST'));
38+
$redis->connect(...explode(':', getenv('REDIS_HOST')));
3939

4040
return $redis;
4141
}

src/Symfony/Component/Lock/Tests/Store/RetryTillSaveStoreTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class RetryTillSaveStoreTest extends AbstractStoreTest
2424

2525
public function getStore(): PersistingStoreInterface
2626
{
27-
$redis = new \Predis\Client('tcp://'.getenv('REDIS_HOST').':6379');
27+
$redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]));
2828
try {
2929
$redis->connect();
3030
} catch (\Exception $e) {

src/Symfony/Component/Messenger/Tests/Transport/RedisExt/RedisTransportFactoryTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public function testCreateTransport()
4848
private function skipIfRedisUnavailable()
4949
{
5050
try {
51-
(new \Redis())->connect(getenv('REDIS_HOST'));
51+
(new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
5252
} catch (\Exception $e) {
5353
self::markTestSkipped($e->getMessage());
5454
}

src/Symfony/Component/VarDumper/Tests/Caster/RedisCasterTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,19 @@ public function testNotConnected()
3838

3939
public function testConnected()
4040
{
41-
$redisHost = getenv('REDIS_HOST');
41+
$redisHost = explode(':', getenv('REDIS_HOST')) + [1 => 6379];
4242
$redis = new \Redis();
4343
try {
44-
$redis->connect($redisHost);
44+
$redis->connect(...$redisHost);
4545
} catch (\Exception $e) {
4646
self::markTestSkipped($e->getMessage());
4747
}
4848

4949
$xCast = <<<EODUMP
5050
Redis {%A
5151
isConnected: true
52-
host: "$redisHost"
53-
port: 6379
52+
host: "{$redisHost[0]}"
53+
port: {$redisHost[1]}
5454
auth: null
5555
mode: ATOMIC
5656
dbNum: 0

0 commit comments

Comments
 (0)