Skip to content

Add a class implementing DNS Discovery #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions src/SrvDiscoverer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

namespace ActiveCollab\Etcd;

/**
* @package ActiveCollab\Etcd
*/
class SrvDiscoverer
{

/**
* @var string
*/
private $domain;

/**
* @param string $domain
*/
public function __construct($domain)
{
$this->domain = $domain;
}

/**
* Fetch the servers with a DNS SRV request
*
* @return array
*/
public function getServers()
{
$records = dns_get_record($this->domain, DNS_SRV);
$result = [];
foreach ($records as $record) {
$result[] = [
'target' => $record['target'],
'port' => $record['port'],
'pri' => $record['pri'],
'weight' => $record['weight'],
];
}

return $result;
}

/**
* Pick a server according to the priority fields.
* Note that weight is currently ignored.
*
* @param array $servers from getServers
* @return array|bool
*/
public function pickServer(array $servers)
{
if (!$servers) {
return false;
}
$by_prio = [];
foreach ($servers as $server) {
$by_prio[$server['pri']][] = $server;
}

$min = min(array_keys($by_prio));
if (count($by_prio[$min]) == 1) {
return $by_prio[$min][0];
} else {
// Choose randomly
$rand = mt_rand(0, count($by_prio[$min])-1);
return $by_prio[$min][$rand];
}
}
}