001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.hadoop.hdfs;
019    
020    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX;
021    
022    import java.io.IOException;
023    import java.lang.reflect.Constructor;
024    import java.net.InetSocketAddress;
025    import java.net.URI;
026    import java.util.HashMap;
027    import java.util.Map;
028    import java.util.concurrent.TimeUnit;
029    
030    import org.apache.commons.logging.Log;
031    import org.apache.commons.logging.LogFactory;
032    import org.apache.hadoop.conf.Configuration;
033    import org.apache.hadoop.hdfs.DFSClient.Conf;
034    import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
035    import org.apache.hadoop.hdfs.protocol.ClientProtocol;
036    import org.apache.hadoop.hdfs.protocol.HdfsConstants;
037    import org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolPB;
038    import org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB;
039    import org.apache.hadoop.hdfs.protocolPB.GetUserMappingsProtocolClientSideTranslatorPB;
040    import org.apache.hadoop.hdfs.protocolPB.GetUserMappingsProtocolPB;
041    import org.apache.hadoop.hdfs.protocolPB.JournalProtocolPB;
042    import org.apache.hadoop.hdfs.protocolPB.JournalProtocolTranslatorPB;
043    import org.apache.hadoop.hdfs.protocolPB.NamenodeProtocolPB;
044    import org.apache.hadoop.hdfs.protocolPB.NamenodeProtocolTranslatorPB;
045    import org.apache.hadoop.hdfs.protocolPB.RefreshAuthorizationPolicyProtocolClientSideTranslatorPB;
046    import org.apache.hadoop.hdfs.protocolPB.RefreshAuthorizationPolicyProtocolPB;
047    import org.apache.hadoop.hdfs.protocolPB.RefreshUserMappingsProtocolClientSideTranslatorPB;
048    import org.apache.hadoop.hdfs.protocolPB.RefreshUserMappingsProtocolPB;
049    import org.apache.hadoop.hdfs.server.namenode.NameNode;
050    import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
051    import org.apache.hadoop.hdfs.server.protocol.JournalProtocol;
052    import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
053    import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
054    import org.apache.hadoop.io.Text;
055    import org.apache.hadoop.io.retry.DefaultFailoverProxyProvider;
056    import org.apache.hadoop.io.retry.FailoverProxyProvider;
057    import org.apache.hadoop.io.retry.RetryPolicies;
058    import org.apache.hadoop.io.retry.RetryPolicy;
059    import org.apache.hadoop.io.retry.RetryProxy;
060    import org.apache.hadoop.io.retry.RetryUtils;
061    import org.apache.hadoop.ipc.ProtobufRpcEngine;
062    import org.apache.hadoop.ipc.RPC;
063    import org.apache.hadoop.ipc.RemoteException;
064    import org.apache.hadoop.net.NetUtils;
065    import org.apache.hadoop.security.RefreshUserMappingsProtocol;
066    import org.apache.hadoop.security.SecurityUtil;
067    import org.apache.hadoop.security.UserGroupInformation;
068    import org.apache.hadoop.security.authorize.RefreshAuthorizationPolicyProtocol;
069    import org.apache.hadoop.tools.GetUserMappingsProtocol;
070    
071    import com.google.common.base.Preconditions;
072    
073    /**
074     * Create proxy objects to communicate with a remote NN. All remote access to an
075     * NN should be funneled through this class. Most of the time you'll want to use
076     * {@link NameNodeProxies#createProxy(Configuration, URI, Class)}, which will
077     * create either an HA- or non-HA-enabled client proxy as appropriate.
078     */
079    public class NameNodeProxies {
080      
081      private static final Log LOG = LogFactory.getLog(NameNodeProxies.class);
082    
083      /**
084       * Wrapper for a client proxy as well as its associated service ID.
085       * This is simply used as a tuple-like return type for
086       * {@link NameNodeProxies#createProxy} and
087       * {@link NameNodeProxies#createNonHAProxy}.
088       */
089      public static class ProxyAndInfo<PROXYTYPE> {
090        private final PROXYTYPE proxy;
091        private final Text dtService;
092        
093        public ProxyAndInfo(PROXYTYPE proxy, Text dtService) {
094          this.proxy = proxy;
095          this.dtService = dtService;
096        }
097        
098        public PROXYTYPE getProxy() {
099          return proxy;
100        }
101        
102        public Text getDelegationTokenService() {
103          return dtService;
104        }
105      }
106    
107      /**
108       * Creates the namenode proxy with the passed protocol. This will handle
109       * creation of either HA- or non-HA-enabled proxy objects, depending upon
110       * if the provided URI is a configured logical URI.
111       * 
112       * @param conf the configuration containing the required IPC
113       *        properties, client failover configurations, etc.
114       * @param nameNodeUri the URI pointing either to a specific NameNode
115       *        or to a logical nameservice.
116       * @param xface the IPC interface which should be created
117       * @return an object containing both the proxy and the associated
118       *         delegation token service it corresponds to
119       * @throws IOException if there is an error creating the proxy
120       **/
121      @SuppressWarnings("unchecked")
122      public static <T> ProxyAndInfo<T> createProxy(Configuration conf,
123          URI nameNodeUri, Class<T> xface) throws IOException {
124        Class<FailoverProxyProvider<T>> failoverProxyProviderClass =
125            getFailoverProxyProviderClass(conf, nameNodeUri, xface);
126      
127        if (failoverProxyProviderClass == null) {
128          // Non-HA case
129          return createNonHAProxy(conf, NameNode.getAddress(nameNodeUri), xface,
130              UserGroupInformation.getCurrentUser(), true);
131        } else {
132          // HA case
133          FailoverProxyProvider<T> failoverProxyProvider = NameNodeProxies
134              .createFailoverProxyProvider(conf, failoverProxyProviderClass, xface,
135                  nameNodeUri);
136          Conf config = new Conf(conf);
137          T proxy = (T) RetryProxy.create(xface, failoverProxyProvider, RetryPolicies
138              .failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL,
139                  config.maxFailoverAttempts, config.failoverSleepBaseMillis,
140                  config.failoverSleepMaxMillis));
141          
142          Text dtService = HAUtil.buildTokenServiceForLogicalUri(nameNodeUri);
143          return new ProxyAndInfo<T>(proxy, dtService);
144        }
145      }
146    
147      /**
148       * Creates an explicitly non-HA-enabled proxy object. Most of the time you
149       * don't want to use this, and should instead use {@link NameNodeProxies#createProxy}.
150       * 
151       * @param conf the configuration object
152       * @param nnAddr address of the remote NN to connect to
153       * @param xface the IPC interface which should be created
154       * @param ugi the user who is making the calls on the proxy object
155       * @param withRetries certain interfaces have a non-standard retry policy
156       * @return an object containing both the proxy and the associated
157       *         delegation token service it corresponds to
158       * @throws IOException
159       */
160      @SuppressWarnings("unchecked")
161      public static <T> ProxyAndInfo<T> createNonHAProxy(
162          Configuration conf, InetSocketAddress nnAddr, Class<T> xface,
163          UserGroupInformation ugi, boolean withRetries) throws IOException {
164        Text dtService = SecurityUtil.buildTokenService(nnAddr);
165      
166        T proxy;
167        if (xface == ClientProtocol.class) {
168          proxy = (T) createNNProxyWithClientProtocol(nnAddr, conf, ugi,
169              withRetries);
170        } else if (xface == JournalProtocol.class) {
171          proxy = (T) createNNProxyWithJournalProtocol(nnAddr, conf, ugi);
172        } else if (xface == NamenodeProtocol.class) {
173          proxy = (T) createNNProxyWithNamenodeProtocol(nnAddr, conf, ugi,
174              withRetries);
175        } else if (xface == GetUserMappingsProtocol.class) {
176          proxy = (T) createNNProxyWithGetUserMappingsProtocol(nnAddr, conf, ugi);
177        } else if (xface == RefreshUserMappingsProtocol.class) {
178          proxy = (T) createNNProxyWithRefreshUserMappingsProtocol(nnAddr, conf, ugi);
179        } else if (xface == RefreshAuthorizationPolicyProtocol.class) {
180          proxy = (T) createNNProxyWithRefreshAuthorizationPolicyProtocol(nnAddr,
181              conf, ugi);
182        } else {
183          String message = "Upsupported protocol found when creating the proxy " +
184              "connection to NameNode: " +
185              ((xface != null) ? xface.getClass().getName() : "null");
186          LOG.error(message);
187          throw new IllegalStateException(message);
188        }
189        return new ProxyAndInfo<T>(proxy, dtService);
190      }
191      
192      private static JournalProtocol createNNProxyWithJournalProtocol(
193          InetSocketAddress address, Configuration conf, UserGroupInformation ugi)
194          throws IOException {
195        JournalProtocolPB proxy = (JournalProtocolPB) createNameNodeProxy(address,
196            conf, ugi, JournalProtocolPB.class);
197        return new JournalProtocolTranslatorPB(proxy);
198      }
199    
200      private static RefreshAuthorizationPolicyProtocol
201          createNNProxyWithRefreshAuthorizationPolicyProtocol(InetSocketAddress address,
202              Configuration conf, UserGroupInformation ugi) throws IOException {
203        RefreshAuthorizationPolicyProtocolPB proxy = (RefreshAuthorizationPolicyProtocolPB)
204            createNameNodeProxy(address, conf, ugi, RefreshAuthorizationPolicyProtocolPB.class);
205        return new RefreshAuthorizationPolicyProtocolClientSideTranslatorPB(proxy);
206      }
207      
208      private static RefreshUserMappingsProtocol
209          createNNProxyWithRefreshUserMappingsProtocol(InetSocketAddress address,
210              Configuration conf, UserGroupInformation ugi) throws IOException {
211        RefreshUserMappingsProtocolPB proxy = (RefreshUserMappingsProtocolPB)
212            createNameNodeProxy(address, conf, ugi, RefreshUserMappingsProtocolPB.class);
213        return new RefreshUserMappingsProtocolClientSideTranslatorPB(proxy);
214      }
215    
216      private static GetUserMappingsProtocol createNNProxyWithGetUserMappingsProtocol(
217          InetSocketAddress address, Configuration conf, UserGroupInformation ugi)
218          throws IOException {
219        GetUserMappingsProtocolPB proxy = (GetUserMappingsProtocolPB)
220            createNameNodeProxy(address, conf, ugi, GetUserMappingsProtocolPB.class);
221        return new GetUserMappingsProtocolClientSideTranslatorPB(proxy);
222      }
223      
224      private static NamenodeProtocol createNNProxyWithNamenodeProtocol(
225          InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
226          boolean withRetries) throws IOException {
227        NamenodeProtocolPB proxy = (NamenodeProtocolPB) createNameNodeProxy(
228            address, conf, ugi, NamenodeProtocolPB.class);
229        if (withRetries) { // create the proxy with retries
230          RetryPolicy timeoutPolicy = RetryPolicies.exponentialBackoffRetry(5, 200,
231              TimeUnit.MILLISECONDS);
232          Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap 
233                         = new HashMap<Class<? extends Exception>, RetryPolicy>();
234          RetryPolicy methodPolicy = RetryPolicies.retryByException(timeoutPolicy,
235              exceptionToPolicyMap);
236          Map<String, RetryPolicy> methodNameToPolicyMap 
237                         = new HashMap<String, RetryPolicy>();
238          methodNameToPolicyMap.put("getBlocks", methodPolicy);
239          methodNameToPolicyMap.put("getAccessKeys", methodPolicy);
240          proxy = (NamenodeProtocolPB) RetryProxy.create(NamenodeProtocolPB.class,
241              proxy, methodNameToPolicyMap);
242        }
243        return new NamenodeProtocolTranslatorPB(proxy);
244      }
245      
246      private static ClientProtocol createNNProxyWithClientProtocol(
247          InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
248          boolean withRetries) throws IOException {
249        RPC.setProtocolEngine(conf, ClientNamenodeProtocolPB.class, ProtobufRpcEngine.class);
250    
251        final RetryPolicy defaultPolicy = 
252            RetryUtils.getDefaultRetryPolicy(
253                conf, 
254                DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_ENABLED_KEY, 
255                DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_ENABLED_DEFAULT, 
256                DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_SPEC_KEY,
257                DFSConfigKeys.DFS_CLIENT_RETRY_POLICY_SPEC_DEFAULT,
258                SafeModeException.class);
259        
260        final long version = RPC.getProtocolVersion(ClientNamenodeProtocolPB.class);
261        ClientNamenodeProtocolPB proxy = RPC.getProtocolProxy(
262            ClientNamenodeProtocolPB.class, version, address, ugi, conf,
263            NetUtils.getDefaultSocketFactory(conf),
264            org.apache.hadoop.ipc.Client.getTimeout(conf), defaultPolicy)
265                .getProxy();
266    
267        if (withRetries) { // create the proxy with retries
268    
269          RetryPolicy createPolicy = RetryPolicies
270              .retryUpToMaximumCountWithFixedSleep(5,
271                  HdfsConstants.LEASE_SOFTLIMIT_PERIOD, TimeUnit.MILLISECONDS);
272        
273          Map<Class<? extends Exception>, RetryPolicy> remoteExceptionToPolicyMap 
274                     = new HashMap<Class<? extends Exception>, RetryPolicy>();
275          remoteExceptionToPolicyMap.put(AlreadyBeingCreatedException.class,
276              createPolicy);
277        
278          Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap
279                     = new HashMap<Class<? extends Exception>, RetryPolicy>();
280          exceptionToPolicyMap.put(RemoteException.class, RetryPolicies
281              .retryByRemoteException(defaultPolicy,
282                  remoteExceptionToPolicyMap));
283          RetryPolicy methodPolicy = RetryPolicies.retryByException(
284              defaultPolicy, exceptionToPolicyMap);
285          Map<String, RetryPolicy> methodNameToPolicyMap 
286                     = new HashMap<String, RetryPolicy>();
287        
288          methodNameToPolicyMap.put("create", methodPolicy);
289        
290          proxy = (ClientNamenodeProtocolPB) RetryProxy.create(
291              ClientNamenodeProtocolPB.class,
292              new DefaultFailoverProxyProvider<ClientNamenodeProtocolPB>(
293                  ClientNamenodeProtocolPB.class, proxy),
294              methodNameToPolicyMap,
295              defaultPolicy);
296        }
297        return new ClientNamenodeProtocolTranslatorPB(proxy);
298      }
299      
300      @SuppressWarnings("unchecked")
301      private static Object createNameNodeProxy(InetSocketAddress address,
302          Configuration conf, UserGroupInformation ugi, Class xface)
303          throws IOException {
304        RPC.setProtocolEngine(conf, xface, ProtobufRpcEngine.class);
305        Object proxy = RPC.getProxy(xface, RPC.getProtocolVersion(xface), address,
306            ugi, conf, NetUtils.getDefaultSocketFactory(conf));
307        return proxy;
308      }
309    
310      /** Gets the configured Failover proxy provider's class */
311      private static <T> Class<FailoverProxyProvider<T>> getFailoverProxyProviderClass(
312          Configuration conf, URI nameNodeUri, Class<T> xface) throws IOException {
313        if (nameNodeUri == null) {
314          return null;
315        }
316        String host = nameNodeUri.getHost();
317      
318        String configKey = DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX + "."
319            + host;
320        try {
321          @SuppressWarnings("unchecked")
322          Class<FailoverProxyProvider<T>> ret = (Class<FailoverProxyProvider<T>>) conf
323              .getClass(configKey, null, FailoverProxyProvider.class);
324          if (ret != null) {
325            // If we found a proxy provider, then this URI should be a logical NN.
326            // Given that, it shouldn't have a non-default port number.
327            int port = nameNodeUri.getPort();
328            if (port > 0 && port != NameNode.DEFAULT_PORT) {
329              throw new IOException("Port " + port + " specified in URI "
330                  + nameNodeUri + " but host '" + host
331                  + "' is a logical (HA) namenode"
332                  + " and does not use port information.");
333            }
334          }
335          return ret;
336        } catch (RuntimeException e) {
337          if (e.getCause() instanceof ClassNotFoundException) {
338            throw new IOException("Could not load failover proxy provider class "
339                + conf.get(configKey) + " which is configured for authority "
340                + nameNodeUri, e);
341          } else {
342            throw e;
343          }
344        }
345      }
346    
347      /** Creates the Failover proxy provider instance*/
348      @SuppressWarnings("unchecked")
349      private static <T> FailoverProxyProvider<T> createFailoverProxyProvider(
350          Configuration conf, Class<FailoverProxyProvider<T>> failoverProxyProviderClass,
351          Class<T> xface, URI nameNodeUri) throws IOException {
352        Preconditions.checkArgument(
353            xface.isAssignableFrom(NamenodeProtocols.class),
354            "Interface %s is not a NameNode protocol", xface);
355        try {
356          Constructor<FailoverProxyProvider<T>> ctor = failoverProxyProviderClass
357              .getConstructor(Configuration.class, URI.class, Class.class);
358          FailoverProxyProvider<?> provider = ctor.newInstance(conf, nameNodeUri,
359              xface);
360          return (FailoverProxyProvider<T>) provider;
361        } catch (Exception e) {
362          String message = "Couldn't create proxy provider " + failoverProxyProviderClass;
363          if (LOG.isDebugEnabled()) {
364            LOG.debug(message, e);
365          }
366          if (e.getCause() instanceof IOException) {
367            throw (IOException) e.getCause();
368          } else {
369            throw new IOException(message, e);
370          }
371        }
372      }
373    
374    }