View Javadoc
1   /*
2    * Copyright 2018 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.resolver.dns;
17  
18  import io.netty.channel.EventLoop;
19  import io.netty.util.concurrent.Future;
20  import io.netty.util.concurrent.FutureListener;
21  
22  import java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.Iterator;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.Map.Entry;
28  import java.util.concurrent.ConcurrentHashMap;
29  import java.util.concurrent.ConcurrentMap;
30  import java.util.concurrent.Delayed;
31  import java.util.concurrent.ScheduledFuture;
32  import java.util.concurrent.TimeUnit;
33  import java.util.concurrent.atomic.AtomicReference;
34  import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
35  
36  import static java.util.Collections.singletonList;
37  
38  /**
39   * Abstract cache that automatically removes entries for a hostname once the TTL for an entry is reached.
40   *
41   * @param <E>
42   */
43  abstract class Cache<E> {
44      private static final AtomicReferenceFieldUpdater<Cache.Entries, ScheduledFuture> FUTURE_UPDATER =
45              AtomicReferenceFieldUpdater.newUpdater(Cache.Entries.class, ScheduledFuture.class, "expirationFuture");
46  
47      private static final ScheduledFuture<?> CANCELLED = new ScheduledFuture<Object>() {
48  
49          @Override
50          public boolean cancel(boolean mayInterruptIfRunning) {
51              return false;
52          }
53  
54          @Override
55          public long getDelay(TimeUnit unit) {
56              // We ignore unit and always return the minimum value to ensure the TTL of the cancelled marker is
57              // the smallest.
58              return Long.MIN_VALUE;
59          }
60  
61          @Override
62          public int compareTo(Delayed o) {
63              throw new UnsupportedOperationException();
64          }
65  
66          @Override
67          public boolean isCancelled() {
68              return true;
69          }
70  
71          @Override
72          public boolean isDone() {
73              return true;
74          }
75  
76          @Override
77          public Object get() {
78              throw new UnsupportedOperationException();
79          }
80  
81          @Override
82          public Object get(long timeout, TimeUnit unit) {
83              throw new UnsupportedOperationException();
84          }
85      };
86  
87      // Two years are supported by all our EventLoop implementations and so safe to use as maximum.
88      // See also: https://github.com/netty/netty/commit/b47fb817991b42ec8808c7d26538f3f2464e1fa6
89      static final int MAX_SUPPORTED_TTL_SECS = (int) TimeUnit.DAYS.toSeconds(365 * 2);
90  
91      private final ConcurrentMap<String, Entries> resolveCache = new ConcurrentHashMap<>();
92  
93      /**
94       * Remove everything from the cache.
95       */
96      final void clear() {
97          while (!resolveCache.isEmpty()) {
98              for (Iterator<Entry<String, Entries>> i = resolveCache.entrySet().iterator(); i.hasNext();) {
99                  Map.Entry<String, Entries> e = i.next();
100                 i.remove();
101 
102                 e.getValue().clearAndCancel();
103             }
104         }
105     }
106 
107     /**
108      * Clear all entries (if anything exists) for the given hostname and return {@code true} if anything was removed.
109      */
110     final boolean clear(String hostname) {
111         Entries entries = resolveCache.remove(hostname);
112         return entries != null && entries.clearAndCancel();
113     }
114 
115     /**
116      * Returns all caches entries for the given hostname.
117      */
118     final List<? extends E> get(String hostname) {
119         Entries entries = resolveCache.get(hostname);
120         return entries == null ? null : entries.get();
121     }
122 
123     /**
124      * Cache a value for the given hostname that will automatically expire once the TTL is reached.
125      */
126     final void cache(String hostname, E value, int ttl, EventLoop loop) {
127         Entries entries = resolveCache.get(hostname);
128         if (entries == null) {
129             entries = new Entries(hostname);
130             Entries oldEntries = resolveCache.putIfAbsent(hostname, entries);
131             if (oldEntries != null) {
132                 entries = oldEntries;
133             }
134         }
135         entries.add(value, ttl, loop);
136     }
137 
138     /**
139      * Return the number of hostnames for which we have cached something.
140      */
141     final int size() {
142         return resolveCache.size();
143     }
144 
145     /**
146      * Returns {@code true} if this entry should replace all other entries that are already cached for the hostname.
147      */
148     protected abstract boolean shouldReplaceAll(E entry);
149 
150     /**
151      * Sort the {@link List} for a {@code hostname} before caching these.
152      */
153     protected void sortEntries(
154             @SuppressWarnings("unused") String hostname, @SuppressWarnings("unused") List<E> entries) {
155         // NOOP.
156     }
157 
158     /**
159      * Returns {@code true} if both entries are equal.
160      */
161     protected abstract boolean equals(E entry, E otherEntry);
162 
163     // Directly extend AtomicReference for intrinsics and also to keep memory overhead low.
164     private final class Entries extends AtomicReference<List<E>> implements Runnable, FutureListener<Object> {
165 
166         private final String hostname;
167         // Needs to be package-private to be able to access it via the AtomicReferenceFieldUpdater
168         volatile ScheduledFuture<?> expirationFuture;
169 
170         Entries(String hostname) {
171             super(Collections.<E>emptyList());
172             this.hostname = hostname;
173         }
174 
175         void add(E e, int ttl, EventLoop loop) {
176             if (!shouldReplaceAll(e)) {
177                 for (;;) {
178                     List<E> entries = get();
179                     if (!entries.isEmpty()) {
180                         final E firstEntry = entries.get(0);
181                         if (shouldReplaceAll(firstEntry)) {
182                             assert entries.size() == 1;
183 
184                             if (compareAndSet(entries, singletonList(e))) {
185                                 scheduleCacheExpirationIfNeeded(ttl, loop);
186                                 return;
187                             } else {
188                                 // Need to try again as CAS failed
189                                 continue;
190                             }
191                         }
192 
193                         // Create a new List for COW semantics
194                         List<E> newEntries = new ArrayList<E>(entries.size() + 1);
195                         int i = 0;
196                         E replacedEntry = null;
197                         do {
198                             E entry = entries.get(i);
199                             // Only add old entry if the address is not the same as the one we try to add as well.
200                             // In this case we will skip it and just add the new entry as this may have
201                             // more up-to-date data and cancel the old after we were able to update the cache.
202                             if (!Cache.this.equals(e, entry)) {
203                                 newEntries.add(entry);
204                             } else {
205                                 replacedEntry = entry;
206                                 newEntries.add(e);
207 
208                                 ++i;
209                                 for (; i < entries.size(); ++i) {
210                                     newEntries.add(entries.get(i));
211                                 }
212                                 break;
213                             }
214                         } while (++i < entries.size());
215                         if (replacedEntry == null) {
216                             newEntries.add(e);
217                         }
218                         sortEntries(hostname, newEntries);
219 
220                         if (compareAndSet(entries, Collections.unmodifiableList(newEntries))) {
221                             scheduleCacheExpirationIfNeeded(ttl, loop);
222                             return;
223                         }
224                     } else if (compareAndSet(entries, singletonList(e))) {
225                         scheduleCacheExpirationIfNeeded(ttl, loop);
226                         return;
227                     }
228                 }
229             } else {
230                 set(singletonList(e));
231                 scheduleCacheExpirationIfNeeded(ttl, loop);
232             }
233         }
234 
235         private void scheduleCacheExpirationIfNeeded(int ttl, EventLoop loop) {
236             for (;;) {
237                 // We currently don't calculate a new TTL when we need to retry the CAS as we don't expect this to
238                 // be invoked very concurrently and also we use SECONDS anyway. If this ever becomes a problem
239                 // we can reconsider.
240                 ScheduledFuture<?> oldFuture = FUTURE_UPDATER.get(this);
241                 if (oldFuture == null || oldFuture.getDelay(TimeUnit.SECONDS) > ttl) {
242                     io.netty.util.concurrent.ScheduledFuture<?> newFuture = loop.schedule(this, ttl, TimeUnit.SECONDS);
243                     // It is possible that
244                     // 1. task will fire in between this line, or
245                     // 2. multiple timers may be set if there is concurrency
246                     // (1) Shouldn't be a problem because we will fail the CAS and then the next loop will see CANCELLED
247                     //     so the ttl will not be less, and we will bail out of the loop.
248                     // (2) This is a trade-off to avoid concurrency resulting in contention on a synchronized block.
249                     if (FUTURE_UPDATER.compareAndSet(this, oldFuture, newFuture)) {
250                         if (!newFuture.isDone()) {
251                             newFuture.addListener(this);
252                         }
253                         // The loop may have terminated before the listener was registered.
254                         removeIfCancelled(newFuture);
255                         if (oldFuture != null) {
256                             oldFuture.cancel(true);
257                         }
258                         break;
259                     } else {
260                         // There was something else scheduled in the meantime... Cancel and try again.
261                         newFuture.cancel(true);
262                     }
263                 } else {
264                     break;
265                 }
266             }
267         }
268 
269         @Override
270         public void operationComplete(Future<Object> future) {
271             removeIfCancelled((ScheduledFuture<?>) future);
272         }
273 
274         private void removeIfCancelled(ScheduledFuture<?> future) {
275             // Only evict if this is still the active timer, not one cancelled when shortening the TTL.
276             if (future.isCancelled() && FUTURE_UPDATER.compareAndSet(this, future, CANCELLED)) {
277                 run();
278             }
279         }
280 
281         boolean clearAndCancel() {
282             List<E> entries = getAndSet(Collections.<E>emptyList());
283             if (entries.isEmpty()) {
284                 return false;
285             }
286 
287             ScheduledFuture<?> expirationFuture = FUTURE_UPDATER.getAndSet(this, CANCELLED);
288             if (expirationFuture != null) {
289                 expirationFuture.cancel(false);
290             }
291 
292             return true;
293         }
294 
295         @Override
296         public void run() {
297             // We always remove all entries for a hostname once one entry expire. This is not the
298             // most efficient to do but this way we can guarantee that if a DnsResolver
299             // be configured to prefer one ip family over the other we will not return unexpected
300             // results to the enduser if one of the A or AAAA records has different TTL settings.
301             //
302             // As a TTL is just a hint of the maximum time a cache is allowed to cache stuff it's
303             // completely fine to remove the entry even if the TTL is not reached yet.
304             //
305             // See https://github.com/netty/netty/issues/7329
306             resolveCache.remove(hostname, this);
307 
308             clearAndCancel();
309         }
310     }
311 }