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 */
018package org.apache.hadoop.hdfs.qjournal.server;
019
020import java.io.Closeable;
021import java.io.File;
022import java.io.FileInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.OutputStreamWriter;
026import java.net.URL;
027import java.security.PrivilegedExceptionAction;
028import java.util.Iterator;
029import java.util.List;
030import java.util.concurrent.TimeUnit;
031
032import org.apache.commons.logging.Log;
033import org.apache.commons.logging.LogFactory;
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.fs.FileUtil;
036import org.apache.hadoop.hdfs.protocol.HdfsConstants;
037import org.apache.hadoop.hdfs.qjournal.protocol.JournalNotFormattedException;
038import org.apache.hadoop.hdfs.qjournal.protocol.JournalOutOfSyncException;
039import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocol;
040import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos;
041import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.NewEpochResponseProto;
042import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.PersistedRecoveryPaxosData;
043import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.PrepareRecoveryResponseProto;
044import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.SegmentStateProto;
045import org.apache.hadoop.hdfs.qjournal.protocol.RequestInfo;
046import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
047import org.apache.hadoop.hdfs.server.common.StorageErrorReporter;
048import org.apache.hadoop.hdfs.server.common.StorageInfo;
049import org.apache.hadoop.hdfs.server.namenode.EditLogOutputStream;
050import org.apache.hadoop.hdfs.server.namenode.FileJournalManager;
051import org.apache.hadoop.hdfs.server.namenode.FileJournalManager.EditLogFile;
052import org.apache.hadoop.hdfs.server.namenode.JournalManager;
053import org.apache.hadoop.hdfs.server.namenode.TransferFsImage;
054import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
055import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog;
056import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest;
057import org.apache.hadoop.hdfs.util.AtomicFileOutputStream;
058import org.apache.hadoop.hdfs.util.BestEffortLongFile;
059import org.apache.hadoop.hdfs.util.PersistentLongFile;
060import org.apache.hadoop.io.IOUtils;
061import org.apache.hadoop.ipc.Server;
062import org.apache.hadoop.security.SecurityUtil;
063import org.apache.hadoop.security.UserGroupInformation;
064
065import com.google.common.annotations.VisibleForTesting;
066import com.google.common.base.Charsets;
067import com.google.common.base.Preconditions;
068import com.google.common.base.Stopwatch;
069import com.google.common.collect.ImmutableList;
070import com.google.common.collect.Range;
071import com.google.common.collect.Ranges;
072import com.google.protobuf.TextFormat;
073
074/**
075 * A JournalNode can manage journals for several clusters at once.
076 * Each such journal is entirely independent despite being hosted by
077 * the same JVM.
078 */
079public class Journal implements Closeable {
080  static final Log LOG = LogFactory.getLog(Journal.class);
081
082
083  // Current writing state
084  private EditLogOutputStream curSegment;
085  private long curSegmentTxId = HdfsConstants.INVALID_TXID;
086  private long nextTxId = HdfsConstants.INVALID_TXID;
087  private long highestWrittenTxId = 0;
088  
089  private final String journalId;
090  
091  private final JNStorage storage;
092
093  /**
094   * When a new writer comes along, it asks each node to promise
095   * to ignore requests from any previous writer, as identified
096   * by epoch number. In order to make such a promise, the epoch
097   * number of that writer is stored persistently on disk.
098   */
099  private PersistentLongFile lastPromisedEpoch;
100
101  /**
102   * Each IPC that comes from a given client contains a serial number
103   * which only increases from the client's perspective. Whenever
104   * we switch epochs, we reset this back to -1. Whenever an IPC
105   * comes from a client, we ensure that it is strictly higher
106   * than any previous IPC. This guards against any bugs in the IPC
107   * layer that would re-order IPCs or cause a stale retry from an old
108   * request to resurface and confuse things.
109   */
110  private long currentEpochIpcSerial = -1;
111  
112  /**
113   * The epoch number of the last writer to actually write a transaction.
114   * This is used to differentiate log segments after a crash at the very
115   * beginning of a segment. See the the 'testNewerVersionOfSegmentWins'
116   * test case.
117   */
118  private PersistentLongFile lastWriterEpoch;
119  
120  /**
121   * Lower-bound on the last committed transaction ID. This is not
122   * depended upon for correctness, but acts as a sanity check
123   * during the recovery procedures, and as a visibility mark
124   * for clients reading in-progress logs.
125   */
126  private BestEffortLongFile committedTxnId;
127  
128  public static final String LAST_PROMISED_FILENAME = "last-promised-epoch";
129  public static final String LAST_WRITER_EPOCH = "last-writer-epoch";
130  private static final String COMMITTED_TXID_FILENAME = "committed-txid";
131  
132  private final FileJournalManager fjm;
133
134  private final JournalMetrics metrics;
135
136  /**
137   * Time threshold for sync calls, beyond which a warning should be logged to the console.
138   */
139  private static final int WARN_SYNC_MILLIS_THRESHOLD = 1000;
140
141  Journal(Configuration conf, File logDir, String journalId,
142      StartupOption startOpt, StorageErrorReporter errorReporter)
143      throws IOException {
144    storage = new JNStorage(conf, logDir, startOpt, errorReporter);
145    this.journalId = journalId;
146
147    refreshCachedData();
148    
149    this.fjm = storage.getJournalManager();
150    
151    this.metrics = JournalMetrics.create(this);
152    
153    EditLogFile latest = scanStorageForLatestEdits();
154    if (latest != null) {
155      updateHighestWrittenTxId(latest.getLastTxId());
156    }
157  }
158
159  /**
160   * Reload any data that may have been cached. This is necessary
161   * when we first load the Journal, but also after any formatting
162   * operation, since the cached data is no longer relevant.
163   */
164  private synchronized void refreshCachedData() {
165    IOUtils.closeStream(committedTxnId);
166    
167    File currentDir = storage.getSingularStorageDir().getCurrentDir();
168    this.lastPromisedEpoch = new PersistentLongFile(
169        new File(currentDir, LAST_PROMISED_FILENAME), 0);
170    this.lastWriterEpoch = new PersistentLongFile(
171        new File(currentDir, LAST_WRITER_EPOCH), 0);
172    this.committedTxnId = new BestEffortLongFile(
173        new File(currentDir, COMMITTED_TXID_FILENAME),
174        HdfsConstants.INVALID_TXID);
175  }
176  
177  /**
178   * Scan the local storage directory, and return the segment containing
179   * the highest transaction.
180   * @return the EditLogFile with the highest transactions, or null
181   * if no files exist.
182   */
183  private synchronized EditLogFile scanStorageForLatestEdits() throws IOException {
184    if (!fjm.getStorageDirectory().getCurrentDir().exists()) {
185      return null;
186    }
187    
188    LOG.info("Scanning storage " + fjm);
189    List<EditLogFile> files = fjm.getLogFiles(0);
190    
191    while (!files.isEmpty()) {
192      EditLogFile latestLog = files.remove(files.size() - 1);
193      latestLog.scanLog();
194      LOG.info("Latest log is " + latestLog);
195      if (latestLog.getLastTxId() == HdfsConstants.INVALID_TXID) {
196        // the log contains no transactions
197        LOG.warn("Latest log " + latestLog + " has no transactions. " +
198            "moving it aside and looking for previous log");
199        latestLog.moveAsideEmptyFile();
200      } else {
201        return latestLog;
202      }
203    }
204    
205    LOG.info("No files in " + fjm);
206    return null;
207  }
208
209  /**
210   * Format the local storage with the given namespace.
211   */
212  void format(NamespaceInfo nsInfo) throws IOException {
213    Preconditions.checkState(nsInfo.getNamespaceID() != 0,
214        "can't format with uninitialized namespace info: %s",
215        nsInfo);
216    LOG.info("Formatting " + this + " with namespace info: " +
217        nsInfo);
218    storage.format(nsInfo);
219    refreshCachedData();
220  }
221
222  /**
223   * Unlock and release resources.
224   */
225  @Override // Closeable
226  public void close() throws IOException {
227    storage.close();
228    IOUtils.closeStream(committedTxnId);
229    IOUtils.closeStream(curSegment);
230  }
231  
232  JNStorage getStorage() {
233    return storage;
234  }
235  
236  String getJournalId() {
237    return journalId;
238  }
239
240  /**
241   * @return the last epoch which this node has promised not to accept
242   * any lower epoch, or 0 if no promises have been made.
243   */
244  synchronized long getLastPromisedEpoch() throws IOException {
245    checkFormatted();
246    return lastPromisedEpoch.get();
247  }
248
249  synchronized public long getLastWriterEpoch() throws IOException {
250    checkFormatted();
251    return lastWriterEpoch.get();
252  }
253  
254  synchronized long getCommittedTxnIdForTests() throws IOException {
255    return committedTxnId.get();
256  }
257  
258  synchronized long getCurrentLagTxns() throws IOException {
259    long committed = committedTxnId.get();
260    if (committed == 0) {
261      return 0;
262    }
263    
264    return Math.max(committed - highestWrittenTxId, 0L);
265  }
266  
267  synchronized long getHighestWrittenTxId() {
268    return highestWrittenTxId;
269  }
270
271  /**
272   * Update the highest Tx ID that has been written to the journal. Also update
273   * the {@link FileJournalManager#lastReadableTxId} of the underlying fjm.
274   * @param val The new value
275   */
276  private void updateHighestWrittenTxId(long val) {
277    highestWrittenTxId = val;
278    fjm.setLastReadableTxId(val);
279  }
280
281  @VisibleForTesting
282  JournalMetrics getMetricsForTests() {
283    return metrics;
284  }
285
286  /**
287   * Try to create a new epoch for this journal.
288   * @param nsInfo the namespace, which is verified for consistency or used to
289   * format, if the Journal has not yet been written to.
290   * @param epoch the epoch to start
291   * @return the status information necessary to begin recovery
292   * @throws IOException if the node has already made a promise to another
293   * writer with a higher epoch number, if the namespace is inconsistent,
294   * or if a disk error occurs.
295   */
296  synchronized NewEpochResponseProto newEpoch(
297      NamespaceInfo nsInfo, long epoch) throws IOException {
298
299    checkFormatted();
300    storage.checkConsistentNamespace(nsInfo);
301
302    // Check that the new epoch being proposed is in fact newer than
303    // any other that we've promised. 
304    if (epoch <= getLastPromisedEpoch()) {
305      throw new IOException("Proposed epoch " + epoch + " <= last promise " +
306          getLastPromisedEpoch());
307    }
308    
309    updateLastPromisedEpoch(epoch);
310    abortCurSegment();
311    
312    NewEpochResponseProto.Builder builder =
313        NewEpochResponseProto.newBuilder();
314
315    EditLogFile latestFile = scanStorageForLatestEdits();
316
317    if (latestFile != null) {
318      builder.setLastSegmentTxId(latestFile.getFirstTxId());
319    }
320    
321    return builder.build();
322  }
323
324  private void updateLastPromisedEpoch(long newEpoch) throws IOException {
325    LOG.info("Updating lastPromisedEpoch from " + lastPromisedEpoch.get() +
326        " to " + newEpoch + " for client " + Server.getRemoteIp());
327    lastPromisedEpoch.set(newEpoch);
328    
329    // Since we have a new writer, reset the IPC serial - it will start
330    // counting again from 0 for this writer.
331    currentEpochIpcSerial = -1;
332  }
333
334  private void abortCurSegment() throws IOException {
335    if (curSegment == null) {
336      return;
337    }
338    
339    curSegment.abort();
340    curSegment = null;
341    curSegmentTxId = HdfsConstants.INVALID_TXID;
342  }
343
344  /**
345   * Write a batch of edits to the journal.
346   * {@see QJournalProtocol#journal(RequestInfo, long, long, int, byte[])}
347   */
348  synchronized void journal(RequestInfo reqInfo,
349      long segmentTxId, long firstTxnId,
350      int numTxns, byte[] records) throws IOException {
351    checkFormatted();
352    checkWriteRequest(reqInfo);
353
354    checkSync(curSegment != null,
355        "Can't write, no segment open");
356    
357    if (curSegmentTxId != segmentTxId) {
358      // Sanity check: it is possible that the writer will fail IPCs
359      // on both the finalize() and then the start() of the next segment.
360      // This could cause us to continue writing to an old segment
361      // instead of rolling to a new one, which breaks one of the
362      // invariants in the design. If it happens, abort the segment
363      // and throw an exception.
364      JournalOutOfSyncException e = new JournalOutOfSyncException(
365          "Writer out of sync: it thinks it is writing segment " + segmentTxId
366          + " but current segment is " + curSegmentTxId);
367      abortCurSegment();
368      throw e;
369    }
370      
371    checkSync(nextTxId == firstTxnId,
372        "Can't write txid " + firstTxnId + " expecting nextTxId=" + nextTxId);
373    
374    long lastTxnId = firstTxnId + numTxns - 1;
375    if (LOG.isTraceEnabled()) {
376      LOG.trace("Writing txid " + firstTxnId + "-" + lastTxnId);
377    }
378
379    // If the edit has already been marked as committed, we know
380    // it has been fsynced on a quorum of other nodes, and we are
381    // "catching up" with the rest. Hence we do not need to fsync.
382    boolean isLagging = lastTxnId <= committedTxnId.get();
383    boolean shouldFsync = !isLagging;
384    
385    curSegment.writeRaw(records, 0, records.length);
386    curSegment.setReadyToFlush();
387    Stopwatch sw = new Stopwatch();
388    sw.start();
389    curSegment.flush(shouldFsync);
390    sw.stop();
391    
392    metrics.addSync(sw.elapsedTime(TimeUnit.MICROSECONDS));
393    if (sw.elapsedTime(TimeUnit.MILLISECONDS) > WARN_SYNC_MILLIS_THRESHOLD) {
394      LOG.warn("Sync of transaction range " + firstTxnId + "-" + lastTxnId +
395               " took " + sw.elapsedTime(TimeUnit.MILLISECONDS) + "ms");
396    }
397
398    if (isLagging) {
399      // This batch of edits has already been committed on a quorum of other
400      // nodes. So, we are in "catch up" mode. This gets its own metric.
401      metrics.batchesWrittenWhileLagging.incr(1);
402    }
403    
404    metrics.batchesWritten.incr(1);
405    metrics.bytesWritten.incr(records.length);
406    metrics.txnsWritten.incr(numTxns);
407    
408    updateHighestWrittenTxId(lastTxnId);
409    nextTxId = lastTxnId + 1;
410  }
411
412  public void heartbeat(RequestInfo reqInfo) throws IOException {
413    checkRequest(reqInfo);
414  }
415  
416  /**
417   * Ensure that the given request is coming from the correct writer and in-order.
418   * @param reqInfo the request info
419   * @throws IOException if the request is invalid.
420   */
421  private synchronized void checkRequest(RequestInfo reqInfo) throws IOException {
422    // Invariant 25 from ZAB paper
423    if (reqInfo.getEpoch() < lastPromisedEpoch.get()) {
424      throw new IOException("IPC's epoch " + reqInfo.getEpoch() +
425          " is less than the last promised epoch " +
426          lastPromisedEpoch.get());
427    } else if (reqInfo.getEpoch() > lastPromisedEpoch.get()) {
428      // A newer client has arrived. Fence any previous writers by updating
429      // the promise.
430      updateLastPromisedEpoch(reqInfo.getEpoch());
431    }
432    
433    // Ensure that the IPCs are arriving in-order as expected.
434    checkSync(reqInfo.getIpcSerialNumber() > currentEpochIpcSerial,
435        "IPC serial %s from client %s was not higher than prior highest " +
436        "IPC serial %s", reqInfo.getIpcSerialNumber(),
437        Server.getRemoteIp(),
438        currentEpochIpcSerial);
439    currentEpochIpcSerial = reqInfo.getIpcSerialNumber();
440
441    if (reqInfo.hasCommittedTxId()) {
442      Preconditions.checkArgument(
443          reqInfo.getCommittedTxId() >= committedTxnId.get(),
444          "Client trying to move committed txid backward from " +
445          committedTxnId.get() + " to " + reqInfo.getCommittedTxId());
446      
447      committedTxnId.set(reqInfo.getCommittedTxId());
448    }
449  }
450  
451  private synchronized void checkWriteRequest(RequestInfo reqInfo) throws IOException {
452    checkRequest(reqInfo);
453    
454    if (reqInfo.getEpoch() != lastWriterEpoch.get()) {
455      throw new IOException("IPC's epoch " + reqInfo.getEpoch() +
456          " is not the current writer epoch  " +
457          lastWriterEpoch.get());
458    }
459  }
460  
461  public synchronized boolean isFormatted() {
462    return storage.isFormatted();
463  }
464
465  private void checkFormatted() throws JournalNotFormattedException {
466    if (!isFormatted()) {
467      throw new JournalNotFormattedException("Journal " +
468          storage.getSingularStorageDir() + " not formatted");
469    }
470  }
471
472  /**
473   * @throws JournalOutOfSyncException if the given expression is not true.
474   * The message of the exception is formatted using the 'msg' and
475   * 'formatArgs' parameters.
476   */
477  private void checkSync(boolean expression, String msg,
478      Object... formatArgs) throws JournalOutOfSyncException {
479    if (!expression) {
480      throw new JournalOutOfSyncException(String.format(msg, formatArgs));
481    }
482  }
483
484  /**
485   * @throws AssertionError if the given expression is not true.
486   * The message of the exception is formatted using the 'msg' and
487   * 'formatArgs' parameters.
488   * 
489   * This should be used in preference to Java's built-in assert in
490   * non-performance-critical paths, where a failure of this invariant
491   * might cause the protocol to lose data. 
492   */
493  private void alwaysAssert(boolean expression, String msg,
494      Object... formatArgs) {
495    if (!expression) {
496      throw new AssertionError(String.format(msg, formatArgs));
497    }
498  }
499  
500  /**
501   * Start a new segment at the given txid. The previous segment
502   * must have already been finalized.
503   */
504  public synchronized void startLogSegment(RequestInfo reqInfo, long txid,
505      int layoutVersion) throws IOException {
506    assert fjm != null;
507    checkFormatted();
508    checkRequest(reqInfo);
509    
510    if (curSegment != null) {
511      LOG.warn("Client is requesting a new log segment " + txid + 
512          " though we are already writing " + curSegment + ". " +
513          "Aborting the current segment in order to begin the new one.");
514      // The writer may have lost a connection to us and is now
515      // re-connecting after the connection came back.
516      // We should abort our own old segment.
517      abortCurSegment();
518    }
519
520    // Paranoid sanity check: we should never overwrite a finalized log file.
521    // Additionally, if it's in-progress, it should have at most 1 transaction.
522    // This can happen if the writer crashes exactly at the start of a segment.
523    EditLogFile existing = fjm.getLogFile(txid);
524    if (existing != null) {
525      if (!existing.isInProgress()) {
526        throw new IllegalStateException("Already have a finalized segment " +
527            existing + " beginning at " + txid);
528      }
529      
530      // If it's in-progress, it should only contain one transaction,
531      // because the "startLogSegment" transaction is written alone at the
532      // start of each segment. 
533      existing.scanLog();
534      if (existing.getLastTxId() != existing.getFirstTxId()) {
535        throw new IllegalStateException("The log file " +
536            existing + " seems to contain valid transactions");
537      }
538    }
539    
540    long curLastWriterEpoch = lastWriterEpoch.get();
541    if (curLastWriterEpoch != reqInfo.getEpoch()) {
542      LOG.info("Updating lastWriterEpoch from " + curLastWriterEpoch +
543          " to " + reqInfo.getEpoch() + " for client " +
544          Server.getRemoteIp());
545      lastWriterEpoch.set(reqInfo.getEpoch());
546    }
547
548    // The fact that we are starting a segment at this txid indicates
549    // that any previous recovery for this same segment was aborted.
550    // Otherwise, no writer would have started writing. So, we can
551    // remove the record of the older segment here.
552    purgePaxosDecision(txid);
553    
554    curSegment = fjm.startLogSegment(txid, layoutVersion);
555    curSegmentTxId = txid;
556    nextTxId = txid;
557  }
558  
559  /**
560   * Finalize the log segment at the given transaction ID.
561   */
562  public synchronized void finalizeLogSegment(RequestInfo reqInfo, long startTxId,
563      long endTxId) throws IOException {
564    checkFormatted();
565    checkRequest(reqInfo);
566
567    boolean needsValidation = true;
568
569    // Finalizing the log that the writer was just writing.
570    if (startTxId == curSegmentTxId) {
571      if (curSegment != null) {
572        curSegment.close();
573        curSegment = null;
574        curSegmentTxId = HdfsConstants.INVALID_TXID;
575      }
576      
577      checkSync(nextTxId == endTxId + 1,
578          "Trying to finalize in-progress log segment %s to end at " +
579          "txid %s but only written up to txid %s",
580          startTxId, endTxId, nextTxId - 1);
581      // No need to validate the edit log if the client is finalizing
582      // the log segment that it was just writing to.
583      needsValidation = false;
584    }
585    
586    FileJournalManager.EditLogFile elf = fjm.getLogFile(startTxId);
587    if (elf == null) {
588      throw new JournalOutOfSyncException("No log file to finalize at " +
589          "transaction ID " + startTxId);
590    }
591
592    if (elf.isInProgress()) {
593      if (needsValidation) {
594        LOG.info("Validating log segment " + elf.getFile() + " about to be " +
595            "finalized");
596        elf.scanLog();
597  
598        checkSync(elf.getLastTxId() == endTxId,
599            "Trying to finalize in-progress log segment %s to end at " +
600            "txid %s but log %s on disk only contains up to txid %s",
601            startTxId, endTxId, elf.getFile(), elf.getLastTxId());
602      }
603      fjm.finalizeLogSegment(startTxId, endTxId);
604    } else {
605      Preconditions.checkArgument(endTxId == elf.getLastTxId(),
606          "Trying to re-finalize already finalized log " +
607              elf + " with different endTxId " + endTxId);
608    }
609
610    // Once logs are finalized, a different length will never be decided.
611    // During recovery, we treat a finalized segment the same as an accepted
612    // recovery. Thus, we no longer need to keep track of the previously-
613    // accepted decision. The existence of the finalized log segment is enough.
614    purgePaxosDecision(elf.getFirstTxId());
615  }
616  
617  /**
618   * @see JournalManager#purgeLogsOlderThan(long)
619   */
620  public synchronized void purgeLogsOlderThan(RequestInfo reqInfo,
621      long minTxIdToKeep) throws IOException {
622    checkFormatted();
623    checkRequest(reqInfo);
624    
625    storage.purgeDataOlderThan(minTxIdToKeep);
626  }
627  
628  /**
629   * Remove the previously-recorded 'accepted recovery' information
630   * for a given log segment, once it is no longer necessary. 
631   * @param segmentTxId the transaction ID to purge
632   * @throws IOException if the file could not be deleted
633   */
634  private void purgePaxosDecision(long segmentTxId) throws IOException {
635    File paxosFile = storage.getPaxosFile(segmentTxId);
636    if (paxosFile.exists()) {
637      if (!paxosFile.delete()) {
638        throw new IOException("Unable to delete paxos file " + paxosFile);
639      }
640    }
641  }
642
643  /**
644   * @see QJournalProtocol#getEditLogManifest(String, long, boolean)
645   */
646  public RemoteEditLogManifest getEditLogManifest(long sinceTxId,
647      boolean inProgressOk) throws IOException {
648    // No need to checkRequest() here - anyone may ask for the list
649    // of segments.
650    checkFormatted();
651    
652    List<RemoteEditLog> logs = fjm.getRemoteEditLogs(sinceTxId, inProgressOk);
653    
654    if (inProgressOk) {
655      RemoteEditLog log = null;
656      for (Iterator<RemoteEditLog> iter = logs.iterator(); iter.hasNext();) {
657        log = iter.next();
658        if (log.isInProgress()) {
659          iter.remove();
660          break;
661        }
662      }
663      if (log != null && log.isInProgress()) {
664        logs.add(new RemoteEditLog(log.getStartTxId(), getHighestWrittenTxId(),
665            true));
666      }
667    }
668    
669    return new RemoteEditLogManifest(logs);
670  }
671
672  /**
673   * @return the current state of the given segment, or null if the
674   * segment does not exist.
675   */
676  @VisibleForTesting
677  SegmentStateProto getSegmentInfo(long segmentTxId)
678      throws IOException {
679    EditLogFile elf = fjm.getLogFile(segmentTxId);
680    if (elf == null) {
681      return null;
682    }
683    if (elf.isInProgress()) {
684      elf.scanLog();
685    }
686    if (elf.getLastTxId() == HdfsConstants.INVALID_TXID) {
687      LOG.info("Edit log file " + elf + " appears to be empty. " +
688          "Moving it aside...");
689      elf.moveAsideEmptyFile();
690      return null;
691    }
692    SegmentStateProto ret = SegmentStateProto.newBuilder()
693        .setStartTxId(segmentTxId)
694        .setEndTxId(elf.getLastTxId())
695        .setIsInProgress(elf.isInProgress())
696        .build();
697    LOG.info("getSegmentInfo(" + segmentTxId + "): " + elf + " -> " +
698        TextFormat.shortDebugString(ret));
699    return ret;
700  }
701
702  /**
703   * @see QJournalProtocol#prepareRecovery(RequestInfo, long)
704   */
705  public synchronized PrepareRecoveryResponseProto prepareRecovery(
706      RequestInfo reqInfo, long segmentTxId) throws IOException {
707    checkFormatted();
708    checkRequest(reqInfo);
709    
710    abortCurSegment();
711    
712    PrepareRecoveryResponseProto.Builder builder =
713        PrepareRecoveryResponseProto.newBuilder();
714
715    PersistedRecoveryPaxosData previouslyAccepted = getPersistedPaxosData(segmentTxId);
716    completeHalfDoneAcceptRecovery(previouslyAccepted);
717
718    SegmentStateProto segInfo = getSegmentInfo(segmentTxId);
719    boolean hasFinalizedSegment = segInfo != null && !segInfo.getIsInProgress();
720
721    if (previouslyAccepted != null && !hasFinalizedSegment) {
722      SegmentStateProto acceptedState = previouslyAccepted.getSegmentState();
723      assert acceptedState.getEndTxId() == segInfo.getEndTxId() :
724            "prev accepted: " + TextFormat.shortDebugString(previouslyAccepted)+ "\n" +
725            "on disk:       " + TextFormat.shortDebugString(segInfo);
726            
727      builder.setAcceptedInEpoch(previouslyAccepted.getAcceptedInEpoch())
728        .setSegmentState(previouslyAccepted.getSegmentState());
729    } else {
730      if (segInfo != null) {
731        builder.setSegmentState(segInfo);
732      }
733    }
734    
735    builder.setLastWriterEpoch(lastWriterEpoch.get());
736    if (committedTxnId.get() != HdfsConstants.INVALID_TXID) {
737      builder.setLastCommittedTxId(committedTxnId.get());
738    }
739    
740    PrepareRecoveryResponseProto resp = builder.build();
741    LOG.info("Prepared recovery for segment " + segmentTxId + ": " +
742        TextFormat.shortDebugString(resp));
743    return resp;
744  }
745  
746  /**
747   * @see QJournalProtocol#acceptRecovery(RequestInfo, QJournalProtocolProtos.SegmentStateProto, URL)
748   */
749  public synchronized void acceptRecovery(RequestInfo reqInfo,
750      SegmentStateProto segment, URL fromUrl)
751      throws IOException {
752    checkFormatted();
753    checkRequest(reqInfo);
754    
755    abortCurSegment();
756
757    long segmentTxId = segment.getStartTxId();
758
759    // Basic sanity checks that the segment is well-formed and contains
760    // at least one transaction.
761    Preconditions.checkArgument(segment.getEndTxId() > 0 &&
762        segment.getEndTxId() >= segmentTxId,
763        "bad recovery state for segment %s: %s",
764        segmentTxId, TextFormat.shortDebugString(segment));
765    
766    PersistedRecoveryPaxosData oldData = getPersistedPaxosData(segmentTxId);
767    PersistedRecoveryPaxosData newData = PersistedRecoveryPaxosData.newBuilder()
768        .setAcceptedInEpoch(reqInfo.getEpoch())
769        .setSegmentState(segment)
770        .build();
771    
772    // If we previously acted on acceptRecovery() from a higher-numbered writer,
773    // this call is out of sync. We should never actually trigger this, since the
774    // checkRequest() call above should filter non-increasing epoch numbers.
775    if (oldData != null) {
776      alwaysAssert(oldData.getAcceptedInEpoch() <= reqInfo.getEpoch(),
777          "Bad paxos transition, out-of-order epochs.\nOld: %s\nNew: %s\n",
778          oldData, newData);
779    }
780    
781    File syncedFile = null;
782    
783    SegmentStateProto currentSegment = getSegmentInfo(segmentTxId);
784    if (currentSegment == null ||
785        currentSegment.getEndTxId() != segment.getEndTxId()) {
786      if (currentSegment == null) {
787        LOG.info("Synchronizing log " + TextFormat.shortDebugString(segment) +
788            ": no current segment in place");
789        
790        // Update the highest txid for lag metrics
791        updateHighestWrittenTxId(Math.max(segment.getEndTxId(),
792            highestWrittenTxId));
793      } else {
794        LOG.info("Synchronizing log " + TextFormat.shortDebugString(segment) +
795            ": old segment " + TextFormat.shortDebugString(currentSegment) +
796            " is not the right length");
797        
798        // Paranoid sanity check: if the new log is shorter than the log we
799        // currently have, we should not end up discarding any transactions
800        // which are already Committed.
801        if (txnRange(currentSegment).contains(committedTxnId.get()) &&
802            !txnRange(segment).contains(committedTxnId.get())) {
803          throw new AssertionError(
804              "Cannot replace segment " +
805              TextFormat.shortDebugString(currentSegment) +
806              " with new segment " +
807              TextFormat.shortDebugString(segment) + 
808              ": would discard already-committed txn " +
809              committedTxnId.get());
810        }
811        
812        // Another paranoid check: we should not be asked to synchronize a log
813        // on top of a finalized segment.
814        alwaysAssert(currentSegment.getIsInProgress(),
815            "Should never be asked to synchronize a different log on top of an " +
816            "already-finalized segment");
817        
818        // If we're shortening the log, update our highest txid
819        // used for lag metrics.
820        if (txnRange(currentSegment).contains(highestWrittenTxId)) {
821          updateHighestWrittenTxId(segment.getEndTxId());
822        }
823      }
824      syncedFile = syncLog(reqInfo, segment, fromUrl);
825      
826    } else {
827      LOG.info("Skipping download of log " +
828          TextFormat.shortDebugString(segment) +
829          ": already have up-to-date logs");
830    }
831    
832    // This is one of the few places in the protocol where we have a single
833    // RPC that results in two distinct actions:
834    //
835    // - 1) Downloads the new log segment data (above)
836    // - 2) Records the new Paxos data about the synchronized segment (below)
837    //
838    // These need to be treated as a transaction from the perspective
839    // of any external process. We do this by treating the persistPaxosData()
840    // success as the "commit" of an atomic transaction. If we fail before
841    // this point, the downloaded edit log will only exist at a temporary
842    // path, and thus not change any externally visible state. If we fail
843    // after this point, then any future prepareRecovery() call will see
844    // the Paxos data, and by calling completeHalfDoneAcceptRecovery() will
845    // roll forward the rename of the referenced log file.
846    //
847    // See also: HDFS-3955
848    //
849    // The fault points here are exercised by the randomized fault injection
850    // test case to ensure that this atomic "transaction" operates correctly.
851    JournalFaultInjector.get().beforePersistPaxosData();
852    persistPaxosData(segmentTxId, newData);
853    JournalFaultInjector.get().afterPersistPaxosData();
854
855    if (syncedFile != null) {
856      FileUtil.replaceFile(syncedFile,
857          storage.getInProgressEditLog(segmentTxId));
858    }
859
860    LOG.info("Accepted recovery for segment " + segmentTxId + ": " +
861        TextFormat.shortDebugString(newData));
862  }
863
864  private Range<Long> txnRange(SegmentStateProto seg) {
865    Preconditions.checkArgument(seg.hasEndTxId(),
866        "invalid segment: %s", seg);
867    return Ranges.closed(seg.getStartTxId(), seg.getEndTxId());
868  }
869
870  /**
871   * Synchronize a log segment from another JournalNode. The log is
872   * downloaded from the provided URL into a temporary location on disk,
873   * which is named based on the current request's epoch.
874   *
875   * @return the temporary location of the downloaded file
876   */
877  private File syncLog(RequestInfo reqInfo,
878      final SegmentStateProto segment, final URL url) throws IOException {
879    final File tmpFile = storage.getSyncLogTemporaryFile(
880        segment.getStartTxId(), reqInfo.getEpoch());
881    final List<File> localPaths = ImmutableList.of(tmpFile);
882
883    LOG.info("Synchronizing log " +
884        TextFormat.shortDebugString(segment) + " from " + url);
885    SecurityUtil.doAsLoginUser(
886        new PrivilegedExceptionAction<Void>() {
887          @Override
888          public Void run() throws IOException {
889            // We may have lost our ticket since last checkpoint, log in again, just in case
890            if (UserGroupInformation.isSecurityEnabled()) {
891              UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
892            }
893
894            boolean success = false;
895            try {
896              TransferFsImage.doGetUrl(url, localPaths, storage, true);
897              assert tmpFile.exists();
898              success = true;
899            } finally {
900              if (!success) {
901                if (!tmpFile.delete()) {
902                  LOG.warn("Failed to delete temporary file " + tmpFile);
903                }
904              }
905            }
906            return null;
907          }
908        });
909    return tmpFile;
910  }
911  
912
913  /**
914   * In the case the node crashes in between downloading a log segment
915   * and persisting the associated paxos recovery data, the log segment
916   * will be left in its temporary location on disk. Given the paxos data,
917   * we can check if this was indeed the case, and &quot;roll forward&quot;
918   * the atomic operation.
919   * 
920   * See the inline comments in
921   * {@link #acceptRecovery(RequestInfo, SegmentStateProto, URL)} for more
922   * details.
923   *
924   * @throws IOException if the temporary file is unable to be renamed into
925   * place
926   */
927  private void completeHalfDoneAcceptRecovery(
928      PersistedRecoveryPaxosData paxosData) throws IOException {
929    if (paxosData == null) {
930      return;
931    }
932
933    long segmentId = paxosData.getSegmentState().getStartTxId();
934    long epoch = paxosData.getAcceptedInEpoch();
935    
936    File tmp = storage.getSyncLogTemporaryFile(segmentId, epoch);
937    
938    if (tmp.exists()) {
939      File dst = storage.getInProgressEditLog(segmentId);
940      LOG.info("Rolling forward previously half-completed synchronization: " +
941          tmp + " -> " + dst);
942      FileUtil.replaceFile(tmp, dst);
943    }
944  }
945
946  /**
947   * Retrieve the persisted data for recovering the given segment from disk.
948   */
949  private PersistedRecoveryPaxosData getPersistedPaxosData(long segmentTxId)
950      throws IOException {
951    File f = storage.getPaxosFile(segmentTxId);
952    if (!f.exists()) {
953      // Default instance has no fields filled in (they're optional)
954      return null;
955    }
956    
957    InputStream in = new FileInputStream(f);
958    try {
959      PersistedRecoveryPaxosData ret = PersistedRecoveryPaxosData.parseDelimitedFrom(in);
960      Preconditions.checkState(ret != null &&
961          ret.getSegmentState().getStartTxId() == segmentTxId,
962          "Bad persisted data for segment %s: %s",
963          segmentTxId, ret);
964      return ret;
965    } finally {
966      IOUtils.closeStream(in);
967    }
968  }
969
970  /**
971   * Persist data for recovering the given segment from disk.
972   */
973  private void persistPaxosData(long segmentTxId,
974      PersistedRecoveryPaxosData newData) throws IOException {
975    File f = storage.getPaxosFile(segmentTxId);
976    boolean success = false;
977    AtomicFileOutputStream fos = new AtomicFileOutputStream(f);
978    try {
979      newData.writeDelimitedTo(fos);
980      fos.write('\n');
981      // Write human-readable data after the protobuf. This is only
982      // to assist in debugging -- it's not parsed at all.
983      OutputStreamWriter writer = new OutputStreamWriter(fos, Charsets.UTF_8);
984      
985      writer.write(String.valueOf(newData));
986      writer.write('\n');
987      writer.flush();
988      
989      fos.flush();
990      success = true;
991    } finally {
992      if (success) {
993        IOUtils.closeStream(fos);
994      } else {
995        fos.abort();
996      }
997    }
998  }
999
1000  synchronized void discardSegments(long startTxId) throws IOException {
1001    storage.getJournalManager().discardSegments(startTxId);
1002    // we delete all the segments after the startTxId. let's reset committedTxnId 
1003    committedTxnId.set(startTxId - 1);
1004  }
1005
1006  public synchronized void doPreUpgrade() throws IOException {
1007    // Do not hold file lock on committedTxnId, because the containing
1008    // directory will be renamed.  It will be reopened lazily on next access.
1009    IOUtils.cleanup(LOG, committedTxnId);
1010    storage.getJournalManager().doPreUpgrade();
1011  }
1012
1013  public synchronized void doUpgrade(StorageInfo sInfo) throws IOException {
1014    long oldCTime = storage.getCTime();
1015    storage.cTime = sInfo.cTime;
1016    int oldLV = storage.getLayoutVersion();
1017    storage.layoutVersion = sInfo.layoutVersion;
1018    LOG.info("Starting upgrade of edits directory: "
1019        + ".\n   old LV = " + oldLV
1020        + "; old CTime = " + oldCTime
1021        + ".\n   new LV = " + storage.getLayoutVersion()
1022        + "; new CTime = " + storage.getCTime());
1023    storage.getJournalManager().doUpgrade(storage);
1024    storage.createPaxosDir();
1025    
1026    // Copy over the contents of the epoch data files to the new dir.
1027    File currentDir = storage.getSingularStorageDir().getCurrentDir();
1028    File previousDir = storage.getSingularStorageDir().getPreviousDir();
1029    
1030    PersistentLongFile prevLastPromisedEpoch = new PersistentLongFile(
1031        new File(previousDir, LAST_PROMISED_FILENAME), 0);
1032    PersistentLongFile prevLastWriterEpoch = new PersistentLongFile(
1033        new File(previousDir, LAST_WRITER_EPOCH), 0);
1034    BestEffortLongFile prevCommittedTxnId = new BestEffortLongFile(
1035        new File(previousDir, COMMITTED_TXID_FILENAME),
1036        HdfsConstants.INVALID_TXID);
1037
1038    lastPromisedEpoch = new PersistentLongFile(
1039        new File(currentDir, LAST_PROMISED_FILENAME), 0);
1040    lastWriterEpoch = new PersistentLongFile(
1041        new File(currentDir, LAST_WRITER_EPOCH), 0);
1042    committedTxnId = new BestEffortLongFile(
1043        new File(currentDir, COMMITTED_TXID_FILENAME),
1044        HdfsConstants.INVALID_TXID);
1045
1046    try {
1047      lastPromisedEpoch.set(prevLastPromisedEpoch.get());
1048      lastWriterEpoch.set(prevLastWriterEpoch.get());
1049      committedTxnId.set(prevCommittedTxnId.get());
1050    } finally {
1051      IOUtils.cleanup(LOG, prevCommittedTxnId);
1052    }
1053  }
1054
1055  public synchronized void doFinalize() throws IOException {
1056    LOG.info("Finalizing upgrade for journal " 
1057          + storage.getRoot() + "."
1058          + (storage.getLayoutVersion()==0 ? "" :
1059            "\n   cur LV = " + storage.getLayoutVersion()
1060            + "; cur CTime = " + storage.getCTime()));
1061    storage.getJournalManager().doFinalize();
1062  }
1063
1064  public Boolean canRollBack(StorageInfo storage, StorageInfo prevStorage,
1065      int targetLayoutVersion) throws IOException {
1066    return this.storage.getJournalManager().canRollBack(storage, prevStorage,
1067        targetLayoutVersion);
1068  }
1069
1070  public synchronized void doRollback() throws IOException {
1071    // Do not hold file lock on committedTxnId, because the containing
1072    // directory will be renamed.  It will be reopened lazily on next access.
1073    IOUtils.cleanup(LOG, committedTxnId);
1074    storage.getJournalManager().doRollback();
1075  }
1076
1077  public Long getJournalCTime() throws IOException {
1078    return storage.getJournalManager().getJournalCTime();
1079  }
1080}