Skip to content

Commit

Permalink
feat: check unix residency for gce when ping fails (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer authored Aug 22, 2023
1 parent dfd1439 commit 3c672f9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Credentials/GCECredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ class GCECredentials extends CredentialsLoader implements
*/
const FLAVOR_HEADER = 'Metadata-Flavor';

/**
* The Linux file which contains the product name.
*/
private const GKE_PRODUCT_NAME_FILE = '/sys/class/dmi/id/product_name';

/**
* Note: the explicit `timeout` and `tries` below is a workaround. The underlying
* issue is that resolving an unknown host on some networks will take
Expand Down Expand Up @@ -340,6 +345,22 @@ public static function onGce(callable $httpHandler = null)
} catch (ConnectException $e) {
}
}

if (PHP_OS === 'Windows') {
// @TODO: implement GCE residency detection on Windows
return false;
}

// Detect GCE residency on Linux
return self::detectResidencyLinux(self::GKE_PRODUCT_NAME_FILE);
}

private static function detectResidencyLinux(string $productNameFile): bool
{
if (file_exists($productNameFile)) {
$productName = trim((string) file_get_contents($productNameFile));
return 0 === strpos($productName, 'Google');
}
return false;
}

Expand Down
32 changes: 32 additions & 0 deletions tests/Credentials/GCECredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,38 @@ public function testOnGCEIsFalseOnServerErrorStatus()
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}

public function testCheckProductNameFile()
{
$tmpFile = tempnam(sys_get_temp_dir(), 'gce-test-product-name');

$method = (new \ReflectionClass(GCECredentials::class))
->getMethod('detectResidencyLinux');
$method->setAccessible(true);

$this->assertFalse($method->invoke(null, '/nonexistant/file'));

file_put_contents($tmpFile, 'Google');
$this->assertTrue($method->invoke(null, $tmpFile));

file_put_contents($tmpFile, 'Not Google');
$this->assertFalse($method->invoke(null, $tmpFile));
}

public function testOnGceWithResidency()
{
if (!GCECredentials::onGCE()) {
$this->markTestSkipped('This test only works while running on GCE');
}

// If calling metadata server fails, this will check the residency file.
$httpHandler = function () {
// Mock an exception, such as a ping timeout
throw $this->prophesize(ClientException::class)->reveal();
};

$this->assertTrue(GCECredentials::onGCE($httpHandler));
}

public function testOnGCEIsFalseOnOkStatusWithoutExpectedHeader()
{
$httpHandler = getHandler([
Expand Down

0 comments on commit 3c672f9

Please sign in to comment.