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    
019    package org.apache.hadoop.hdfs.security.token.delegation;
020    
021    import java.io.IOException;
022    import java.lang.ref.WeakReference;
023    import java.util.concurrent.DelayQueue;
024    import java.util.concurrent.Delayed;
025    import java.util.concurrent.TimeUnit;
026    
027    import org.apache.hadoop.classification.InterfaceAudience;
028    import org.apache.hadoop.fs.FileSystem;
029    import org.apache.hadoop.security.token.Token;
030    import org.apache.hadoop.security.token.TokenIdentifier;
031    
032    /**
033     * A daemon thread that waits for the next file system to renew.
034     */
035    @InterfaceAudience.Private
036    public class DelegationTokenRenewer<T extends FileSystem & DelegationTokenRenewer.Renewable>
037        extends Thread {
038      /** The renewable interface used by the renewer. */
039      public interface Renewable {
040        /** @return the renew token. */
041        public Token<?> getRenewToken();
042    
043        /** Set delegation token. */
044        public <T extends TokenIdentifier> void setDelegationToken(Token<T> token);
045      }
046    
047      /**
048       * An action that will renew and replace the file system's delegation 
049       * tokens automatically.
050       */
051      private static class RenewAction<T extends FileSystem & Renewable>
052          implements Delayed {
053        /** when should the renew happen */
054        private long renewalTime;
055        /** a weak reference to the file system so that it can be garbage collected */
056        private final WeakReference<T> weakFs;
057    
058        private RenewAction(final T fs) {
059          this.weakFs = new WeakReference<T>(fs);
060          updateRenewalTime();
061        }
062     
063        /** Get the delay until this event should happen. */
064        @Override
065        public long getDelay(final TimeUnit unit) {
066          final long millisLeft = renewalTime - System.currentTimeMillis();
067          return unit.convert(millisLeft, TimeUnit.MILLISECONDS);
068        }
069    
070        @Override
071        public int compareTo(final Delayed delayed) {
072          final RenewAction<?> that = (RenewAction<?>)delayed;
073          return this.renewalTime < that.renewalTime? -1
074              : this.renewalTime == that.renewalTime? 0: 1;
075        }
076    
077        @Override
078        public int hashCode() {
079          return (int)renewalTime ^ (int)(renewalTime >>> 32);
080        }
081    
082        @Override
083        public boolean equals(final Object that) {
084          if (that == null || !(that instanceof RenewAction)) {
085            return false;
086          }
087          return compareTo((Delayed)that) == 0;
088        }
089    
090        /**
091         * Set a new time for the renewal.
092         * It can only be called when the action is not in the queue.
093         * @param newTime the new time
094         */
095        private void updateRenewalTime() {
096          renewalTime = RENEW_CYCLE + System.currentTimeMillis();
097        }
098    
099        /**
100         * Renew or replace the delegation token for this file system.
101         * @return
102         * @throws IOException
103         */
104        private boolean renew() throws IOException, InterruptedException {
105          final T fs = weakFs.get();
106          final boolean b = fs != null;
107          if (b) {
108            synchronized(fs) {
109              try {
110                fs.getRenewToken().renew(fs.getConf());
111              } catch (IOException ie) {
112                try {
113                  Token<?>[] tokens = fs.addDelegationTokens(null, null);
114                  if (tokens.length == 0) {
115                    throw new IOException("addDelegationTokens returned no tokens");
116                  }
117                  fs.setDelegationToken(tokens[0]);
118                } catch (IOException ie2) {
119                  throw new IOException("Can't renew or get new delegation token ", ie);
120                }
121              }
122            }
123          }
124          return b;
125        }
126    
127        @Override
128        public String toString() {
129          Renewable fs = weakFs.get();
130          return fs == null? "evaporated token renew"
131              : "The token will be renewed in " + getDelay(TimeUnit.SECONDS)
132                + " secs, renewToken=" + fs.getRenewToken();
133        }
134      }
135    
136      /** Wait for 95% of a day between renewals */
137      private static final int RENEW_CYCLE = 24 * 60 * 60 * 950;
138    
139      private DelayQueue<RenewAction<T>> queue = new DelayQueue<RenewAction<T>>();
140    
141      public DelegationTokenRenewer(final Class<T> clazz) {
142        super(clazz.getSimpleName() + "-" + DelegationTokenRenewer.class.getSimpleName());
143        setDaemon(true);
144      }
145    
146      /** Add a renew action to the queue. */
147      public void addRenewAction(final T fs) {
148        queue.add(new RenewAction<T>(fs));
149      }
150    
151      @Override
152      public void run() {
153        for(;;) {
154          RenewAction<T> action = null;
155          try {
156            action = queue.take();
157            if (action.renew()) {
158              action.updateRenewalTime();
159              queue.add(action);
160            }
161          } catch (InterruptedException ie) {
162            return;
163          } catch (Exception ie) {
164            T.LOG.warn("Failed to renew token, action=" + action, ie);
165          }
166        }
167      }
168    }