MediaWiki master
DnsSrvDiscoverer.php
Go to the documentation of this file.
1<?php
30 private $service;
31
35 private $protocol;
36
40 private $domain;
41
45 private $resolver;
46
58 public function __construct(
59 string $service,
60 string $protocol = 'tcp',
61 ?string $domain = null,
62 ?callable $resolver = null
63 ) {
64 $this->service = $service;
65 $this->protocol = $protocol;
66 $this->domain = $domain;
67
68 $this->resolver = $resolver ?? static function ( $srv ) {
69 return dns_get_record( $srv, DNS_SRV );
70 };
71 }
72
80 public function getRecords() {
81 $result = [];
82
83 $records = ( $this->resolver )( $this->getSrvName() );
84
85 // Respect RFC 2782 with regard to a single '.' entry denoting a valid
86 // empty response
87 if (
88 !$records
89 || ( count( $records ) === 1 && $records[0]['target'] === '.' )
90 ) {
91 return $result;
92 }
93
94 foreach ( $records as $record ) {
95 $result[] = [
96 'target' => $record['target'],
97 'port' => (int)$record['port'],
98 'pri' => (int)$record['pri'],
99 'weight' => (int)$record['weight'],
100 ];
101 }
102
103 return $result;
104 }
105
113 public function getServers() {
114 $records = $this->getRecords();
115
116 usort( $records, static function ( $a, $b ) {
117 if ( $a['pri'] === $b['pri'] ) {
118 return mt_rand( 0, 1 ) ? 1 : -1;
119 }
120
121 return $a['pri'] - $b['pri'];
122 } );
123
124 $serversAndPorts = [];
125
126 foreach ( $records as $record ) {
127 $serversAndPorts[] = [ $record['target'], $record['port'] ];
128 }
129
130 return $serversAndPorts;
131 }
132
138 public function getSrvName(): string {
139 $srv = "_{$this->service}._{$this->protocol}";
140
141 if ( $this->domain === null || $this->domain === '' ) {
142 return $srv;
143 }
144
145 return "$srv.{$this->domain}";
146 }
147}
__construct(string $service, string $protocol='tcp', ?string $domain=null, ?callable $resolver=null)
Construct a new discoverer for the given domain, service, and protocol.
getRecords()
Queries the resolver for an SRV resource record matching the service, protocol, and domain and return...
getServers()
Performs discovery for the domain, service, and protocol, and returns a list of resolved server name/...
getSrvName()
Returns the SRV resource record name.