aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/net/HostName.java
blob: 20f1008055ea8896d24b037944da7cfe0e6c96b6 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.net;

import ai.vespa.http.DomainName;
import ai.vespa.validation.PatternedStringWrapper;

import java.util.Optional;
import java.util.regex.Pattern;

import static ai.vespa.validation.Validation.requireLength;

/**
 * Hostnames match {@link #hostNamePattern}, and are restricted to 64 characters in length.
 *
 * This class also has utilities for getting the hostname of the system running the JVM.
 * Detection of the hostname is now done before starting any Vespa
 * programs and provided in the environment variable VESPA_HOSTNAME;
 * if that variable isn't set a default of "localhost" is always returned.
 *
 * @author arnej
 * @author jonmv
 */
public class HostName extends PatternedStringWrapper<HostName> {

    static final Pattern labelPattern = Pattern.compile("([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])");
    static final Pattern hostNamePattern = Pattern.compile("(" + labelPattern + "\\.)*" + labelPattern);

    private static HostName preferredHostName = null;

    private HostName(String value) {
        super(requireLength(value, "hostname length", 1, 64), hostNamePattern, "hostname");
    }

    public static HostName of(String value) {
        return new HostName(value);
    }

    /**
     * Return a public and fully qualified hostname for localhost that
     * resolves to an IP address on a network interface.
     *
     * @return the preferred name of localhost
     */
    public static synchronized String getLocalhost() {
        if (preferredHostName == null) {
            preferredHostName = getPreferredHostName();
        }
        return preferredHostName.value();
    }

    static private HostName getPreferredHostName() {
        Optional<String> vespaHostEnv = Optional.ofNullable(System.getenv("VESPA_HOSTNAME"));
        if (vespaHostEnv.isPresent() && ! vespaHostEnv.get().trim().isEmpty()) {
            return of(vespaHostEnv.get().trim());
        }
        return of("localhost");
    }

    public static void setHostNameForTestingOnly(String hostName) {
        preferredHostName = HostName.of(hostName);
    }

}