diff options
author | Jon Marius Venstad <venstad@gmail.com> | 2022-03-31 11:52:40 +0200 |
---|---|---|
committer | Jon Marius Venstad <venstad@gmail.com> | 2022-03-31 11:53:33 +0200 |
commit | 2430b74a942659d549771cb4dd8b81d77692d905 (patch) | |
tree | c79b8b48bf150bea00ab9e0c6ad594740709d4fa /vespajlib/src/main/java/com/yahoo/net/HostName.java | |
parent | 168f767ec12253f43ace27946dc530fde9e37d5e (diff) |
Rename back to HostName, and merge the value class and utilities
Diffstat (limited to 'vespajlib/src/main/java/com/yahoo/net/HostName.java')
-rw-r--r-- | vespajlib/src/main/java/com/yahoo/net/HostName.java | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/vespajlib/src/main/java/com/yahoo/net/HostName.java b/vespajlib/src/main/java/com/yahoo/net/HostName.java new file mode 100644 index 00000000000..47bd8246bb3 --- /dev/null +++ b/vespajlib/src/main/java/com/yahoo/net/HostName.java @@ -0,0 +1,58 @@ +// 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.validation.PatternedStringWrapper; + +import java.util.Optional; + +import static ai.vespa.validation.Validation.requireLength; + +/** + * Hostnames match {@link DomainName#domainNamePattern}, but 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> { + + private static HostName preferredHostName = null; + + private HostName(String value) { + super(requireLength(value, "hostname length", 1, 64), DomainName.domainNamePattern, "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); + } + +} |