blob: 842fd78ed2c4acb6ee1aa804f7afb2bbbfaa31b1 (
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
// 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.testutils;
import com.google.common.collect.ImmutableSet;
import com.yahoo.vespa.hosted.provision.persistence.NameResolver;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
/**
* A mock DNS resolver. Can be configured to only answer specific lookups or any lookup.
*
* @author mpolden
*/
public class MockNameResolver implements NameResolver {
private boolean allowInvocation = true;
private boolean mockAnyLookup = false;
private final Map<String, Set<String>> records = new HashMap<>();
public MockNameResolver addRecord(String hostname, String... ipAddress) {
Arrays.stream(ipAddress).forEach(Objects::requireNonNull);
records.put(hostname, ImmutableSet.copyOf(ipAddress));
return this;
}
public MockNameResolver reset() {
this.allowInvocation = true;
this.mockAnyLookup = false;
this.records.clear();
return this;
}
public MockNameResolver failIfInvoked() {
this.allowInvocation = false;
return this;
}
public MockNameResolver mockAnyLookup() {
this.mockAnyLookup = true;
return this;
}
@Override
public Set<String> getAllByNameOrThrow(String hostname) {
if (!allowInvocation) {
throw new IllegalStateException("Expected getAllByName to not be invoked for hostname: " + hostname);
}
if (records.containsKey(hostname)) {
return records.get(hostname);
}
if (mockAnyLookup) {
Set<String> ipAddresses = Collections.singleton(randomIpAddress());
records.put(hostname, ipAddresses);
}
throw new RuntimeException(new UnknownHostException("Could not resolve: " + hostname));
}
@Override
public Optional<String> getHostname(String ipAddress) {
for (String host : records.keySet()) {
if (records.get(host).contains(ipAddress)) return Optional.of(host);
}
return Optional.empty();
}
private static String randomIpAddress() {
// Generate a random IP in 127/8 (loopback block)
ThreadLocalRandom random = ThreadLocalRandom.current();
return String.format("127.%d.%d.%d",
random.nextInt(1, 255 + 1),
random.nextInt(1, 255 + 1),
random.nextInt(1, 255 + 1));
}
}
|