aaaaRrData = new HashSet<>();
for (InetAddress ip : host.get().getInetAddresses()) {
if (ip instanceof Inet4Address) {
aRrData.add(ip.toString());
} else {
checkArgument(ip instanceof Inet6Address);
aaaaRrData.add(ip.toString());
}
}
if (!aRrData.isEmpty()) {
domainRecords.add(
new ResourceRecordSet()
.setName(absoluteHostName)
.setTtl((int) defaultATtl.getStandardSeconds())
.setType("A")
.setKind("dns#resourceRecordSet")
.setRrdatas(ImmutableList.copyOf(aRrData)));
}
if (!aaaaRrData.isEmpty()) {
domainRecords.add(
new ResourceRecordSet()
.setName(absoluteHostName)
.setTtl((int) defaultATtl.getStandardSeconds())
.setType("AAAA")
.setKind("dns#resourceRecordSet")
.setRrdatas(ImmutableList.copyOf(aaaaRrData)));
}
desiredRecords.put(absoluteHostName, domainRecords.build());
}
/**
* Publish A/AAAA records to Cloud DNS.
*
* Cloud DNS has no API for glue -- A/AAAA records are automatically matched to their
* corresponding NS records to serve glue.
*/
@Override
public void publishHost(String hostName) {
// Get the superordinate domain name of the host.
InternetDomainName host = InternetDomainName.from(hostName);
Optional tld = Registries.findTldForName(host);
// Host not managed by our registry, no need to update DNS.
if (!tld.isPresent()) {
logger.severefmt("publishHost called for invalid host %s", hostName);
return;
}
// Extract the superordinate domain name. The TLD and host may have several dots so this
// must calculate a sublist.
ImmutableList hostParts = host.parts();
ImmutableList tldParts = tld.get().parts();
ImmutableList domainParts =
hostParts.subList(hostParts.size() - tldParts.size() - 1, hostParts.size());
String domain = Joiner.on(".").join(domainParts);
// Refresh the superordinate domain, since we shouldn't be publishing glue records if we are not
// authoritative for the superordinate domain.
publishDomain(domain);
}
/**
* Sync changes in a zone requested by publishDomain and publishHost to Cloud DNS.
*
* The zone for the TLD must exist first in Cloud DNS and must be DNSSEC enabled.
*
*
The relevant resource records (including those of all subordinate hosts) will be retrieved
* and the operation will be retried until the state of the retrieved zone data matches the
* representation built via this writer.
*/
@Override
protected void commitUnchecked() {
retrier.callWithRetry(
getMutateZoneCallback(ImmutableMap.copyOf(desiredRecords)), ZoneStateException.class);
logger.info("Wrote to Cloud DNS");
}
/**
* Get a callback to mutate the zone with the provided {@code desiredRecords}.
*/
@VisibleForTesting
Callable getMutateZoneCallback(
final ImmutableMap> desiredRecords) {
return new Callable() {
@Override
public Void call() throws IOException, ZoneStateException {
// Fetch all existing records for names that this writer is trying to modify
Builder existingRecords = new Builder<>();
for (String domainName : desiredRecords.keySet()) {
List existingRecordsForDomain =
getResourceRecordsForDomain(domainName);
existingRecords.addAll(existingRecordsForDomain);
// Fetch glue records for in-bailiwick nameservers
for (ResourceRecordSet record : existingRecordsForDomain) {
if (!record.getType().equals("NS")) {
continue;
}
for (String hostName : record.getRrdatas()) {
if (hostName.endsWith(domainName) && !hostName.equals(domainName)) {
existingRecords.addAll(getResourceRecordsForDomain(hostName));
}
}
}
}
// Flatten the desired records into one set.
Builder flattenedDesiredRecords = new Builder<>();
for (ImmutableSet records : desiredRecords.values()) {
flattenedDesiredRecords.addAll(records);
}
// Delete all existing records and add back the desired records
updateResourceRecords(flattenedDesiredRecords.build(), existingRecords.build());
return null;
}
};
}
/**
* Fetch the {@link ResourceRecordSet}s for the given domain name under this zone.
*
* The provided domain should be in absolute form.
*
* @throws IOException if the operation could not be completed successfully
*/
private List getResourceRecordsForDomain(String domainName)
throws IOException {
logger.finefmt("Fetching records for %s", domainName);
Dns.ResourceRecordSets.List listRecordsRequest =
dnsConnection.resourceRecordSets().list(projectId, zoneName).setName(domainName);
rateLimiter.acquire();
return listRecordsRequest.execute().getRrsets();
}
/**
* Update {@link ResourceRecordSet}s under this zone.
*
* This call should be used in conjunction with getResourceRecordsForDomain in a get-and-set
* retry loop.
*
*
See {@link "https://cloud.google.com/dns/troubleshooting"} for a list of errors produced by
* the Google Cloud DNS API.
*
* @throws IOException if the operation could not be completed successfully due to an
* uncorrectable error.
* @throws ZoneStateException if the operation could not be completely successfully because the
* records to delete do not exist, already exist or have been modified with different
* attributes since being queried.
*/
private void updateResourceRecords(
ImmutableSet additions, ImmutableSet deletions)
throws IOException, ZoneStateException {
Change change = new Change().setAdditions(additions.asList()).setDeletions(deletions.asList());
rateLimiter.acquire();
try {
dnsConnection.changes().create(projectId, zoneName, change).execute();
} catch (GoogleJsonResponseException e) {
List errors = e.getDetails().getErrors();
// We did something really wrong here, just give up and re-throw
if (errors.size() > 1) {
throw e;
}
String errorReason = errors.get(0).getReason();
if (RETRYABLE_EXCEPTION_REASONS.contains(errorReason)) {
throw new ZoneStateException(errorReason);
} else {
throw e;
}
}
}
/**
* Returns the presentation format ending in a dot used for an absolute hostname.
*
* @param hostName the fully qualified hostname
*/
private static String getAbsoluteHostName(String hostName) {
return hostName.endsWith(".") ? hostName : hostName + ".";
}
/** Zone state on Cloud DNS does not match the expected state. */
static class ZoneStateException extends RuntimeException {
public ZoneStateException(String reason) {
super("Zone state on Cloud DNS does not match the expected state: " + reason);
}
}
}