blob: 6ba42cad04408ac2a01e147883189537fae44887 [file] [log] [blame]
Eric Anderson56a29382016-06-11 11:55:49 -07001/*
2 * Copyright 2016, Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32package io.grpc;
33
34import com.google.common.annotations.VisibleForTesting;
Eric Andersonfe5b7e32016-06-27 12:02:09 -070035import com.google.common.base.Preconditions;
Eric Anderson56a29382016-06-11 11:55:49 -070036
37import java.net.URI;
38import java.util.ArrayList;
39import java.util.Collections;
40import java.util.Comparator;
41import java.util.List;
Eric Anderson4289aaf2016-07-19 17:52:43 -070042import java.util.ServiceConfigurationError;
Eric Anderson56a29382016-06-11 11:55:49 -070043import java.util.ServiceLoader;
44
45/**
46 * Provider of name resolvers for name agnostic consumption.
47 *
48 * <p>Implementations <em>should not</em> throw. If they do, it may interrupt class loading. If
49 * exceptions may reasonably occur for implementation-specific reasons, implementations should
50 * generally handle the exception gracefully and return {@code false} from {@link #isAvailable()}.
51 */
52@Internal
53public abstract class NameResolverProvider extends NameResolver.Factory {
54 /**
55 * The port number used in case the target or the underlying naming system doesn't provide a
56 * port number.
57 */
58 public static final Attributes.Key<Integer> PARAMS_DEFAULT_PORT =
59 NameResolver.Factory.PARAMS_DEFAULT_PORT;
60
61 private static final List<NameResolverProvider> providers
62 = load(getCorrectClassLoader());
63 private static final NameResolver.Factory factory = new NameResolverFactory(providers);
64
65 @VisibleForTesting
66 static List<NameResolverProvider> load(ClassLoader classLoader) {
Eric Anderson4289aaf2016-07-19 17:52:43 -070067 Iterable<NameResolverProvider> candidates;
68 if (isAndroid()) {
69 candidates = getCandidatesViaHardCoded(classLoader);
70 } else {
71 candidates = getCandidatesViaServiceLoader(classLoader);
72 }
Eric Anderson56a29382016-06-11 11:55:49 -070073 List<NameResolverProvider> list = new ArrayList<NameResolverProvider>();
Eric Anderson4289aaf2016-07-19 17:52:43 -070074 for (NameResolverProvider current : candidates) {
Eric Anderson56a29382016-06-11 11:55:49 -070075 if (!current.isAvailable()) {
76 continue;
77 }
78 list.add(current);
79 }
80 // Sort descending based on priority.
81 Collections.sort(list, Collections.reverseOrder(new Comparator<NameResolverProvider>() {
82 @Override
83 public int compare(NameResolverProvider f1, NameResolverProvider f2) {
84 return f1.priority() - f2.priority();
85 }
86 }));
87 return Collections.unmodifiableList(list);
88 }
89
Eric Anderson4289aaf2016-07-19 17:52:43 -070090 @VisibleForTesting
91 public static Iterable<NameResolverProvider> getCandidatesViaServiceLoader(
92 ClassLoader classLoader) {
93 return ServiceLoader.load(NameResolverProvider.class, classLoader);
94 }
95
96 /**
97 * Load providers from a hard-coded list. This avoids using getResource(), which has performance
98 * problems on Android (see https://github.com/grpc/grpc-java/issues/2037). Any provider that may
99 * be used on Android is free to be added here.
100 */
101 @VisibleForTesting
102 public static Iterable<NameResolverProvider> getCandidatesViaHardCoded(ClassLoader classLoader) {
103 List<NameResolverProvider> list = new ArrayList<NameResolverProvider>();
104 try {
105 list.add(create(
106 Class.forName("io.grpc.internal.DnsNameResolverProvider", true, classLoader)));
107 } catch (ClassNotFoundException ex) {
108 // ignore
109 }
110 return list;
111 }
112
113 @VisibleForTesting
114 static NameResolverProvider create(Class<?> rawClass) {
115 try {
ZHANG Dapenge70f7b42016-11-16 19:15:16 -0800116 return rawClass.asSubclass(NameResolverProvider.class).getConstructor().newInstance();
Eric Anderson4289aaf2016-07-19 17:52:43 -0700117 } catch (Throwable t) {
118 throw new ServiceConfigurationError(
119 "Provider " + rawClass.getName() + " could not be instantiated: " + t, t);
120 }
121 }
122
Eric Anderson56a29382016-06-11 11:55:49 -0700123 /**
124 * Returns non-{@code null} ClassLoader-wide providers, in preference order.
125 */
126 public static List<NameResolverProvider> providers() {
127 return providers;
128 }
129
130 public static NameResolver.Factory asFactory() {
131 return factory;
132 }
133
134 @VisibleForTesting
135 static NameResolver.Factory asFactory(List<NameResolverProvider> providers) {
136 return new NameResolverFactory(providers);
137 }
138
139 private static ClassLoader getCorrectClassLoader() {
Eric Andersonb7ed8832016-06-20 14:35:21 -0700140 if (isAndroid()) {
Eric Anderson56a29382016-06-11 11:55:49 -0700141 // When android:sharedUserId or android:process is used, Android will setup a dummy
142 // ClassLoader for the thread context (http://stackoverflow.com/questions/13407006),
143 // instead of letting users to manually set context class loader, we choose the
144 // correct class loader here.
145 return NameResolverProvider.class.getClassLoader();
146 }
147 return Thread.currentThread().getContextClassLoader();
148 }
149
Eric Andersonb7ed8832016-06-20 14:35:21 -0700150 private static boolean isAndroid() {
151 try {
152 Class.forName("android.app.Application", /*initialize=*/ false, null);
153 return true;
154 } catch (Exception e) {
155 // If Application isn't loaded, it might as well not be Android.
156 return false;
157 }
158 }
159
Eric Anderson56a29382016-06-11 11:55:49 -0700160 /**
161 * Whether this provider is available for use, taking the current environment into consideration.
162 * If {@code false}, no other methods are safe to be called.
163 */
164 protected abstract boolean isAvailable();
165
166 /**
167 * A priority, from 0 to 10 that this provider should be used, taking the current environment into
168 * consideration. 5 should be considered the default, and then tweaked based on environment
169 * detection. A priority of 0 does not imply that the provider wouldn't work; just that it should
170 * be last in line.
171 */
172 protected abstract int priority();
173
174 private static class NameResolverFactory extends NameResolver.Factory {
175 private final List<NameResolverProvider> providers;
176
177 public NameResolverFactory(List<NameResolverProvider> providers) {
178 this.providers = providers;
179 }
180
181 @Override
182 public NameResolver newNameResolver(URI targetUri, Attributes params) {
Eric Andersonfe5b7e32016-06-27 12:02:09 -0700183 checkForProviders();
Eric Anderson56a29382016-06-11 11:55:49 -0700184 for (NameResolverProvider provider : providers) {
185 NameResolver resolver = provider.newNameResolver(targetUri, params);
186 if (resolver != null) {
187 return resolver;
188 }
189 }
190 return null;
191 }
192
193 @Override
194 public String getDefaultScheme() {
Eric Andersonfe5b7e32016-06-27 12:02:09 -0700195 checkForProviders();
Eric Anderson56a29382016-06-11 11:55:49 -0700196 return providers.get(0).getDefaultScheme();
197 }
Eric Andersonfe5b7e32016-06-27 12:02:09 -0700198
199 private void checkForProviders() {
200 Preconditions.checkState(!providers.isEmpty(),
201 "No NameResolverProviders found via ServiceLoader, including for DNS. "
202 + "This is probably due to a broken build. If using ProGuard, check your configuration");
203 }
Eric Anderson56a29382016-06-11 11:55:49 -0700204 }
205}