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.server.namenode;
019
020 import java.io.IOException;
021 import java.util.ArrayList;
022 import java.util.Collection;
023 import java.util.Collections;
024 import java.util.Comparator;
025 import java.util.LinkedList;
026 import java.util.List;
027 import java.util.PriorityQueue;
028 import java.util.SortedSet;
029 import java.util.concurrent.CopyOnWriteArrayList;
030
031 import org.apache.commons.logging.Log;
032 import org.apache.commons.logging.LogFactory;
033 import org.apache.hadoop.classification.InterfaceAudience;
034 import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
035 import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog;
036 import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest;
037
038 import static org.apache.hadoop.util.ExitUtil.terminate;
039
040 import com.google.common.annotations.VisibleForTesting;
041 import com.google.common.base.Preconditions;
042 import com.google.common.collect.ComparisonChain;
043 import com.google.common.collect.ImmutableList;
044 import com.google.common.collect.ImmutableListMultimap;
045 import com.google.common.collect.Lists;
046 import com.google.common.collect.Multimaps;
047 import com.google.common.collect.Sets;
048
049 /**
050 * Manages a collection of Journals. None of the methods are synchronized, it is
051 * assumed that FSEditLog methods, that use this class, use proper
052 * synchronization.
053 */
054 public class JournalSet implements JournalManager {
055
056 static final Log LOG = LogFactory.getLog(FSEditLog.class);
057
058 static final public Comparator<EditLogInputStream>
059 EDIT_LOG_INPUT_STREAM_COMPARATOR = new Comparator<EditLogInputStream>() {
060 @Override
061 public int compare(EditLogInputStream a, EditLogInputStream b) {
062 return ComparisonChain.start().
063 compare(a.getFirstTxId(), b.getFirstTxId()).
064 compare(b.getLastTxId(), a.getLastTxId()).
065 result();
066 }
067 };
068
069 /**
070 * Container for a JournalManager paired with its currently
071 * active stream.
072 *
073 * If a Journal gets disabled due to an error writing to its
074 * stream, then the stream will be aborted and set to null.
075 */
076 static class JournalAndStream implements CheckableNameNodeResource {
077 private final JournalManager journal;
078 private boolean disabled = false;
079 private EditLogOutputStream stream;
080 private boolean required = false;
081
082 public JournalAndStream(JournalManager manager, boolean required) {
083 this.journal = manager;
084 this.required = required;
085 }
086
087 public void startLogSegment(long txId) throws IOException {
088 Preconditions.checkState(stream == null);
089 disabled = false;
090 stream = journal.startLogSegment(txId);
091 }
092
093 /**
094 * Closes the stream, also sets it to null.
095 */
096 public void closeStream() throws IOException {
097 if (stream == null) return;
098 stream.close();
099 stream = null;
100 }
101
102 /**
103 * Close the Journal and Stream
104 */
105 public void close() throws IOException {
106 closeStream();
107
108 journal.close();
109 }
110
111 /**
112 * Aborts the stream, also sets it to null.
113 */
114 public void abort() {
115 if (stream == null) return;
116 try {
117 stream.abort();
118 } catch (IOException ioe) {
119 LOG.error("Unable to abort stream " + stream, ioe);
120 }
121 stream = null;
122 }
123
124 boolean isActive() {
125 return stream != null;
126 }
127
128 /**
129 * Should be used outside JournalSet only for testing.
130 */
131 EditLogOutputStream getCurrentStream() {
132 return stream;
133 }
134
135 @Override
136 public String toString() {
137 return "JournalAndStream(mgr=" + journal +
138 ", " + "stream=" + stream + ")";
139 }
140
141 void setCurrentStreamForTests(EditLogOutputStream stream) {
142 this.stream = stream;
143 }
144
145 JournalManager getManager() {
146 return journal;
147 }
148
149 boolean isDisabled() {
150 return disabled;
151 }
152
153 private void setDisabled(boolean disabled) {
154 this.disabled = disabled;
155 }
156
157 @Override
158 public boolean isResourceAvailable() {
159 return !isDisabled();
160 }
161
162 @Override
163 public boolean isRequired() {
164 return required;
165 }
166 }
167
168 // COW implementation is necessary since some users (eg the web ui) call
169 // getAllJournalStreams() and then iterate. Since this is rarely
170 // mutated, there is no performance concern.
171 private List<JournalAndStream> journals =
172 new CopyOnWriteArrayList<JournalSet.JournalAndStream>();
173 final int minimumRedundantJournals;
174
175 JournalSet(int minimumRedundantResources) {
176 this.minimumRedundantJournals = minimumRedundantResources;
177 }
178
179 @Override
180 public void format(NamespaceInfo nsInfo) throws IOException {
181 // The iteration is done by FSEditLog itself
182 throw new UnsupportedOperationException();
183 }
184
185 @Override
186 public boolean hasSomeData() throws IOException {
187 // This is called individually on the underlying journals,
188 // not on the JournalSet.
189 throw new UnsupportedOperationException();
190 }
191
192
193 @Override
194 public EditLogOutputStream startLogSegment(final long txId) throws IOException {
195 mapJournalsAndReportErrors(new JournalClosure() {
196 @Override
197 public void apply(JournalAndStream jas) throws IOException {
198 jas.startLogSegment(txId);
199 }
200 }, "starting log segment " + txId);
201 return new JournalSetOutputStream();
202 }
203
204 @Override
205 public void finalizeLogSegment(final long firstTxId, final long lastTxId)
206 throws IOException {
207 mapJournalsAndReportErrors(new JournalClosure() {
208 @Override
209 public void apply(JournalAndStream jas) throws IOException {
210 if (jas.isActive()) {
211 jas.closeStream();
212 jas.getManager().finalizeLogSegment(firstTxId, lastTxId);
213 }
214 }
215 }, "finalize log segment " + firstTxId + ", " + lastTxId);
216 }
217
218 @Override
219 public void close() throws IOException {
220 mapJournalsAndReportErrors(new JournalClosure() {
221 @Override
222 public void apply(JournalAndStream jas) throws IOException {
223 jas.close();
224 }
225 }, "close journal");
226 }
227
228 /**
229 * In this function, we get a bunch of streams from all of our JournalManager
230 * objects. Then we add these to the collection one by one.
231 *
232 * @param streams The collection to add the streams to. It may or
233 * may not be sorted-- this is up to the caller.
234 * @param fromTxId The transaction ID to start looking for streams at
235 * @param inProgressOk Should we consider unfinalized streams?
236 */
237 @Override
238 public void selectInputStreams(Collection<EditLogInputStream> streams,
239 long fromTxId, boolean inProgressOk) throws IOException {
240 final PriorityQueue<EditLogInputStream> allStreams =
241 new PriorityQueue<EditLogInputStream>(64,
242 EDIT_LOG_INPUT_STREAM_COMPARATOR);
243 for (JournalAndStream jas : journals) {
244 if (jas.isDisabled()) {
245 LOG.info("Skipping jas " + jas + " since it's disabled");
246 continue;
247 }
248 try {
249 jas.getManager().selectInputStreams(allStreams, fromTxId, inProgressOk);
250 } catch (IOException ioe) {
251 LOG.warn("Unable to determine input streams from " + jas.getManager() +
252 ". Skipping.", ioe);
253 }
254 }
255 chainAndMakeRedundantStreams(streams, allStreams, fromTxId, inProgressOk);
256 }
257
258 public static void chainAndMakeRedundantStreams(
259 Collection<EditLogInputStream> outStreams,
260 PriorityQueue<EditLogInputStream> allStreams,
261 long fromTxId, boolean inProgressOk) {
262 // We want to group together all the streams that start on the same start
263 // transaction ID. To do this, we maintain an accumulator (acc) of all
264 // the streams we've seen at a given start transaction ID. When we see a
265 // higher start transaction ID, we select a stream from the accumulator and
266 // clear it. Then we begin accumulating streams with the new, higher start
267 // transaction ID.
268 LinkedList<EditLogInputStream> acc =
269 new LinkedList<EditLogInputStream>();
270 EditLogInputStream elis;
271 while ((elis = allStreams.poll()) != null) {
272 if (acc.isEmpty()) {
273 acc.add(elis);
274 } else {
275 long accFirstTxId = acc.get(0).getFirstTxId();
276 if (accFirstTxId == elis.getFirstTxId()) {
277 acc.add(elis);
278 } else if (accFirstTxId < elis.getFirstTxId()) {
279 outStreams.add(new RedundantEditLogInputStream(acc, fromTxId));
280 acc.clear();
281 acc.add(elis);
282 } else if (accFirstTxId > elis.getFirstTxId()) {
283 throw new RuntimeException("sorted set invariants violated! " +
284 "Got stream with first txid " + elis.getFirstTxId() +
285 ", but the last firstTxId was " + accFirstTxId);
286 }
287 }
288 }
289 if (!acc.isEmpty()) {
290 outStreams.add(new RedundantEditLogInputStream(acc, fromTxId));
291 acc.clear();
292 }
293 }
294
295 /**
296 * Returns true if there are no journals, all redundant journals are disabled,
297 * or any required journals are disabled.
298 *
299 * @return True if there no journals, all redundant journals are disabled,
300 * or any required journals are disabled.
301 */
302 public boolean isEmpty() {
303 return !NameNodeResourcePolicy.areResourcesAvailable(journals,
304 minimumRedundantJournals);
305 }
306
307 /**
308 * Called when some journals experience an error in some operation.
309 */
310 private void disableAndReportErrorOnJournals(List<JournalAndStream> badJournals) {
311 if (badJournals == null || badJournals.isEmpty()) {
312 return; // nothing to do
313 }
314
315 for (JournalAndStream j : badJournals) {
316 LOG.error("Disabling journal " + j);
317 j.abort();
318 j.setDisabled(true);
319 }
320 }
321
322 /**
323 * Implementations of this interface encapsulate operations that can be
324 * iteratively applied on all the journals. For example see
325 * {@link JournalSet#mapJournalsAndReportErrors}.
326 */
327 private interface JournalClosure {
328 /**
329 * The operation on JournalAndStream.
330 * @param jas Object on which operations are performed.
331 * @throws IOException
332 */
333 public void apply(JournalAndStream jas) throws IOException;
334 }
335
336 /**
337 * Apply the given operation across all of the journal managers, disabling
338 * any for which the closure throws an IOException.
339 * @param closure {@link JournalClosure} object encapsulating the operation.
340 * @param status message used for logging errors (e.g. "opening journal")
341 * @throws IOException If the operation fails on all the journals.
342 */
343 private void mapJournalsAndReportErrors(
344 JournalClosure closure, String status) throws IOException{
345
346 List<JournalAndStream> badJAS = Lists.newLinkedList();
347 for (JournalAndStream jas : journals) {
348 try {
349 closure.apply(jas);
350 } catch (Throwable t) {
351 if (jas.isRequired()) {
352 final String msg = "Error: " + status + " failed for required journal ("
353 + jas + ")";
354 LOG.fatal(msg, t);
355 // If we fail on *any* of the required journals, then we must not
356 // continue on any of the other journals. Abort them to ensure that
357 // retry behavior doesn't allow them to keep going in any way.
358 abortAllJournals();
359 // the current policy is to shutdown the NN on errors to shared edits
360 // dir. There are many code paths to shared edits failures - syncs,
361 // roll of edits etc. All of them go through this common function
362 // where the isRequired() check is made. Applying exit policy here
363 // to catch all code paths.
364 terminate(1, msg);
365 } else {
366 LOG.error("Error: " + status + " failed for (journal " + jas + ")", t);
367 badJAS.add(jas);
368 }
369 }
370 }
371 disableAndReportErrorOnJournals(badJAS);
372 if (!NameNodeResourcePolicy.areResourcesAvailable(journals,
373 minimumRedundantJournals)) {
374 String message = status + " failed for too many journals";
375 LOG.error("Error: " + message);
376 throw new IOException(message);
377 }
378 }
379
380 /**
381 * Abort all of the underlying streams.
382 */
383 private void abortAllJournals() {
384 for (JournalAndStream jas : journals) {
385 if (jas.isActive()) {
386 jas.abort();
387 }
388 }
389 }
390
391 /**
392 * An implementation of EditLogOutputStream that applies a requested method on
393 * all the journals that are currently active.
394 */
395 private class JournalSetOutputStream extends EditLogOutputStream {
396
397 JournalSetOutputStream() throws IOException {
398 super();
399 }
400
401 @Override
402 public void write(final FSEditLogOp op)
403 throws IOException {
404 mapJournalsAndReportErrors(new JournalClosure() {
405 @Override
406 public void apply(JournalAndStream jas) throws IOException {
407 if (jas.isActive()) {
408 jas.getCurrentStream().write(op);
409 }
410 }
411 }, "write op");
412 }
413
414 @Override
415 public void writeRaw(final byte[] data, final int offset, final int length)
416 throws IOException {
417 mapJournalsAndReportErrors(new JournalClosure() {
418 @Override
419 public void apply(JournalAndStream jas) throws IOException {
420 if (jas.isActive()) {
421 jas.getCurrentStream().writeRaw(data, offset, length);
422 }
423 }
424 }, "write bytes");
425 }
426
427 @Override
428 public void create() throws IOException {
429 mapJournalsAndReportErrors(new JournalClosure() {
430 @Override
431 public void apply(JournalAndStream jas) throws IOException {
432 if (jas.isActive()) {
433 jas.getCurrentStream().create();
434 }
435 }
436 }, "create");
437 }
438
439 @Override
440 public void close() throws IOException {
441 mapJournalsAndReportErrors(new JournalClosure() {
442 @Override
443 public void apply(JournalAndStream jas) throws IOException {
444 jas.closeStream();
445 }
446 }, "close");
447 }
448
449 @Override
450 public void abort() throws IOException {
451 mapJournalsAndReportErrors(new JournalClosure() {
452 @Override
453 public void apply(JournalAndStream jas) throws IOException {
454 jas.abort();
455 }
456 }, "abort");
457 }
458
459 @Override
460 public void setReadyToFlush() throws IOException {
461 mapJournalsAndReportErrors(new JournalClosure() {
462 @Override
463 public void apply(JournalAndStream jas) throws IOException {
464 if (jas.isActive()) {
465 jas.getCurrentStream().setReadyToFlush();
466 }
467 }
468 }, "setReadyToFlush");
469 }
470
471 @Override
472 protected void flushAndSync(final boolean durable) throws IOException {
473 mapJournalsAndReportErrors(new JournalClosure() {
474 @Override
475 public void apply(JournalAndStream jas) throws IOException {
476 if (jas.isActive()) {
477 jas.getCurrentStream().flushAndSync(durable);
478 }
479 }
480 }, "flushAndSync");
481 }
482
483 @Override
484 public void flush() throws IOException {
485 mapJournalsAndReportErrors(new JournalClosure() {
486 @Override
487 public void apply(JournalAndStream jas) throws IOException {
488 if (jas.isActive()) {
489 jas.getCurrentStream().flush();
490 }
491 }
492 }, "flush");
493 }
494
495 @Override
496 public boolean shouldForceSync() {
497 for (JournalAndStream js : journals) {
498 if (js.isActive() && js.getCurrentStream().shouldForceSync()) {
499 return true;
500 }
501 }
502 return false;
503 }
504
505 @Override
506 protected long getNumSync() {
507 for (JournalAndStream jas : journals) {
508 if (jas.isActive()) {
509 return jas.getCurrentStream().getNumSync();
510 }
511 }
512 return 0;
513 }
514 }
515
516 @Override
517 public void setOutputBufferCapacity(final int size) {
518 try {
519 mapJournalsAndReportErrors(new JournalClosure() {
520 @Override
521 public void apply(JournalAndStream jas) throws IOException {
522 jas.getManager().setOutputBufferCapacity(size);
523 }
524 }, "setOutputBufferCapacity");
525 } catch (IOException e) {
526 LOG.error("Error in setting outputbuffer capacity");
527 }
528 }
529
530 List<JournalAndStream> getAllJournalStreams() {
531 return journals;
532 }
533
534 List<JournalManager> getJournalManagers() {
535 List<JournalManager> jList = new ArrayList<JournalManager>();
536 for (JournalAndStream j : journals) {
537 jList.add(j.getManager());
538 }
539 return jList;
540 }
541
542 void add(JournalManager j, boolean required) {
543 JournalAndStream jas = new JournalAndStream(j, required);
544 journals.add(jas);
545 }
546
547 void remove(JournalManager j) {
548 JournalAndStream jasToRemove = null;
549 for (JournalAndStream jas: journals) {
550 if (jas.getManager().equals(j)) {
551 jasToRemove = jas;
552 break;
553 }
554 }
555 if (jasToRemove != null) {
556 jasToRemove.abort();
557 journals.remove(jasToRemove);
558 }
559 }
560
561 @Override
562 public void purgeLogsOlderThan(final long minTxIdToKeep) throws IOException {
563 mapJournalsAndReportErrors(new JournalClosure() {
564 @Override
565 public void apply(JournalAndStream jas) throws IOException {
566 jas.getManager().purgeLogsOlderThan(minTxIdToKeep);
567 }
568 }, "purgeLogsOlderThan " + minTxIdToKeep);
569 }
570
571 @Override
572 public void recoverUnfinalizedSegments() throws IOException {
573 mapJournalsAndReportErrors(new JournalClosure() {
574 @Override
575 public void apply(JournalAndStream jas) throws IOException {
576 jas.getManager().recoverUnfinalizedSegments();
577 }
578 }, "recoverUnfinalizedSegments");
579 }
580
581 /**
582 * Return a manifest of what finalized edit logs are available. All available
583 * edit logs are returned starting from the transaction id passed.
584 *
585 * @param fromTxId Starting transaction id to read the logs.
586 * @return RemoteEditLogManifest object.
587 */
588 public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) {
589 // Collect RemoteEditLogs available from each FileJournalManager
590 List<RemoteEditLog> allLogs = Lists.newArrayList();
591 for (JournalAndStream j : journals) {
592 if (j.getManager() instanceof FileJournalManager) {
593 FileJournalManager fjm = (FileJournalManager)j.getManager();
594 try {
595 allLogs.addAll(fjm.getRemoteEditLogs(fromTxId));
596 } catch (Throwable t) {
597 LOG.warn("Cannot list edit logs in " + fjm, t);
598 }
599 }
600 }
601
602 // Group logs by their starting txid
603 ImmutableListMultimap<Long, RemoteEditLog> logsByStartTxId =
604 Multimaps.index(allLogs, RemoteEditLog.GET_START_TXID);
605 long curStartTxId = fromTxId;
606
607 List<RemoteEditLog> logs = Lists.newArrayList();
608 while (true) {
609 ImmutableList<RemoteEditLog> logGroup = logsByStartTxId.get(curStartTxId);
610 if (logGroup.isEmpty()) {
611 // we have a gap in logs - for example because we recovered some old
612 // storage directory with ancient logs. Clear out any logs we've
613 // accumulated so far, and then skip to the next segment of logs
614 // after the gap.
615 SortedSet<Long> startTxIds = Sets.newTreeSet(logsByStartTxId.keySet());
616 startTxIds = startTxIds.tailSet(curStartTxId);
617 if (startTxIds.isEmpty()) {
618 break;
619 } else {
620 if (LOG.isDebugEnabled()) {
621 LOG.debug("Found gap in logs at " + curStartTxId + ": " +
622 "not returning previous logs in manifest.");
623 }
624 logs.clear();
625 curStartTxId = startTxIds.first();
626 continue;
627 }
628 }
629
630 // Find the one that extends the farthest forward
631 RemoteEditLog bestLog = Collections.max(logGroup);
632 logs.add(bestLog);
633 // And then start looking from after that point
634 curStartTxId = bestLog.getEndTxId() + 1;
635 }
636 RemoteEditLogManifest ret = new RemoteEditLogManifest(logs);
637
638 if (LOG.isDebugEnabled()) {
639 LOG.debug("Generated manifest for logs since " + fromTxId + ":"
640 + ret);
641 }
642 return ret;
643 }
644
645 /**
646 * Add sync times to the buffer.
647 */
648 String getSyncTimes() {
649 StringBuilder buf = new StringBuilder();
650 for (JournalAndStream jas : journals) {
651 if (jas.isActive()) {
652 buf.append(jas.getCurrentStream().getTotalSyncTime());
653 buf.append(" ");
654 }
655 }
656 return buf.toString();
657 }
658 }