summaryrefslogtreecommitdiffstats
path: root/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/DnsNameResolver.java
blob: 6486343150c27a1dcd569960872b19825eda95fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.persistence;

import com.google.common.collect.ImmutableSet;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Optional;
import java.util.Set;

/**
 * Implementation of a name resolver that always uses a DNS server to resolve the given name. The intention is to avoid
 * possibly incorrect/incomplete records in /etc/hosts.
 *
 * @author mpolden
 */
public class DnsNameResolver implements NameResolver {

    /** Resolve IP addresses for given host name */
    @Override
    public Set<String> getAllByNameOrThrow(String hostname) {
        try {
            Optional<String> cname = lookupName(hostname, Type.CNAME);
            if (cname.isPresent()) {
                hostname = cname.get();
            }
            Optional<String> inet4Address = lookupName(hostname, Type.A);
            Optional<String> inet6Address = lookupName(hostname, Type.AAAA);

            ImmutableSet.Builder<String> ipAddresses = ImmutableSet.builder();
            inet4Address.ifPresent(ipAddresses::add);
            inet6Address.ifPresent(ipAddresses::add);
            return ipAddresses.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Optional<String> lookupName(String name, Type type) throws NamingException {
        DirContext ctx = new InitialDirContext();
        Attributes attributes = ctx.getAttributes("dns:/" + name, new String[]{type.value});
        Optional<Attribute> attribute = Optional.ofNullable(attributes.get(type.value));
        if (attribute.isPresent()) {
            return Optional.ofNullable(attribute.get().get()).map(Object::toString);
        }
        return Optional.empty();
    }

    private enum Type {

        A("A"),
        AAAA("AAAA"),
        CNAME("CNAME");

        private final String value;

        Type(String value) {
            this.value = value;
        }
    }

}