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.common;
019    
020    import java.io.File;
021    import java.io.FileInputStream;
022    import java.io.FileOutputStream;
023    import java.io.IOException;
024    import java.io.RandomAccessFile;
025    import java.lang.management.ManagementFactory;
026    import java.nio.channels.FileLock;
027    import java.nio.channels.OverlappingFileLockException;
028    import java.util.ArrayList;
029    import java.util.List;
030    import java.util.Iterator;
031    import java.util.Properties;
032    
033    import org.apache.commons.logging.Log;
034    import org.apache.commons.logging.LogFactory;
035    import org.apache.hadoop.classification.InterfaceAudience;
036    import org.apache.hadoop.hdfs.protocol.HdfsConstants;
037    import org.apache.hadoop.hdfs.protocol.LayoutVersion;
038    import org.apache.hadoop.hdfs.protocol.LayoutVersion.Feature;
039    import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
040    import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
041    import org.apache.hadoop.fs.FileUtil;
042    import org.apache.hadoop.util.ToolRunner;
043    import org.apache.hadoop.util.VersionInfo;
044    
045    import com.google.common.base.Preconditions;
046    
047    import com.google.common.base.Charsets;
048    
049    
050    
051    /**
052     * Storage information file.
053     * <p>
054     * Local storage information is stored in a separate file VERSION.
055     * It contains type of the node, 
056     * the storage layout version, the namespace id, and 
057     * the fs state creation time.
058     * <p>
059     * Local storage can reside in multiple directories. 
060     * Each directory should contain the same VERSION file as the others.
061     * During startup Hadoop servers (name-node and data-nodes) read their local 
062     * storage information from them.
063     * <p>
064     * The servers hold a lock for each storage directory while they run so that 
065     * other nodes were not able to startup sharing the same storage.
066     * The locks are released when the servers stop (normally or abnormally).
067     * 
068     */
069    @InterfaceAudience.Private
070    public abstract class Storage extends StorageInfo {
071      public static final Log LOG = LogFactory.getLog(Storage.class.getName());
072    
073      // last layout version that did not support upgrades
074      public static final int LAST_PRE_UPGRADE_LAYOUT_VERSION = -3;
075      
076      // this corresponds to Hadoop-0.18
077      public static final int LAST_UPGRADABLE_LAYOUT_VERSION = -16;
078      protected static final String LAST_UPGRADABLE_HADOOP_VERSION = "Hadoop-0.18";
079      
080      /** Layout versions of 0.20.203 release */
081      public static final int[] LAYOUT_VERSIONS_203 = {-19, -31};
082    
083      public    static final String STORAGE_FILE_LOCK     = "in_use.lock";
084      protected static final String STORAGE_FILE_VERSION  = "VERSION";
085      public    static final String STORAGE_DIR_CURRENT   = "current";
086      public    static final String STORAGE_DIR_PREVIOUS  = "previous";
087      public    static final String STORAGE_TMP_REMOVED   = "removed.tmp";
088      public    static final String STORAGE_TMP_PREVIOUS  = "previous.tmp";
089      public    static final String STORAGE_TMP_FINALIZED = "finalized.tmp";
090      public    static final String STORAGE_TMP_LAST_CKPT = "lastcheckpoint.tmp";
091      public    static final String STORAGE_PREVIOUS_CKPT = "previous.checkpoint";
092      
093      /**
094       * The blocksBeingWritten directory which was used in some 1.x and earlier
095       * releases.
096       */
097      public static final String STORAGE_1_BBW = "blocksBeingWritten";
098      
099      public enum StorageState {
100        NON_EXISTENT,
101        NOT_FORMATTED,
102        COMPLETE_UPGRADE,
103        RECOVER_UPGRADE,
104        COMPLETE_FINALIZE,
105        COMPLETE_ROLLBACK,
106        RECOVER_ROLLBACK,
107        COMPLETE_CHECKPOINT,
108        RECOVER_CHECKPOINT,
109        NORMAL;
110      }
111      
112      /**
113       * An interface to denote storage directory type
114       * Implementations can define a type for storage directory by implementing
115       * this interface.
116       */
117      @InterfaceAudience.Private
118      public interface StorageDirType {
119        public StorageDirType getStorageDirType();
120        public boolean isOfType(StorageDirType type);
121      }
122      
123      protected NodeType storageType;    // Type of the node using this storage 
124      protected List<StorageDirectory> storageDirs = new ArrayList<StorageDirectory>();
125      
126      private class DirIterator implements Iterator<StorageDirectory> {
127        StorageDirType dirType;
128        int prevIndex; // for remove()
129        int nextIndex; // for next()
130        
131        DirIterator(StorageDirType dirType) {
132          this.dirType = dirType;
133          this.nextIndex = 0;
134          this.prevIndex = 0;
135        }
136        
137        @Override
138        public boolean hasNext() {
139          if (storageDirs.isEmpty() || nextIndex >= storageDirs.size())
140            return false;
141          if (dirType != null) {
142            while (nextIndex < storageDirs.size()) {
143              if (getStorageDir(nextIndex).getStorageDirType().isOfType(dirType))
144                break;
145              nextIndex++;
146            }
147            if (nextIndex >= storageDirs.size())
148             return false;
149          }
150          return true;
151        }
152        
153        @Override
154        public StorageDirectory next() {
155          StorageDirectory sd = getStorageDir(nextIndex);
156          prevIndex = nextIndex;
157          nextIndex++;
158          if (dirType != null) {
159            while (nextIndex < storageDirs.size()) {
160              if (getStorageDir(nextIndex).getStorageDirType().isOfType(dirType))
161                break;
162              nextIndex++;
163            }
164          }
165          return sd;
166        }
167        
168        @Override
169        public void remove() {
170          nextIndex = prevIndex; // restore previous state
171          storageDirs.remove(prevIndex); // remove last returned element
172          hasNext(); // reset nextIndex to correct place
173        }
174      }
175      
176      /**
177       * @return A list of the given File in every available storage directory,
178       * regardless of whether it might exist.
179       */
180      public List<File> getFiles(StorageDirType dirType, String fileName) {
181        ArrayList<File> list = new ArrayList<File>();
182        Iterator<StorageDirectory> it =
183          (dirType == null) ? dirIterator() : dirIterator(dirType);
184        for ( ;it.hasNext(); ) {
185          list.add(new File(it.next().getCurrentDir(), fileName));
186        }
187        return list;
188      }
189    
190    
191      /**
192       * Return default iterator
193       * This iterator returns all entries in storageDirs
194       */
195      public Iterator<StorageDirectory> dirIterator() {
196        return dirIterator(null);
197      }
198      
199      /**
200       * Return iterator based on Storage Directory Type
201       * This iterator selects entries in storageDirs of type dirType and returns
202       * them via the Iterator
203       */
204      public Iterator<StorageDirectory> dirIterator(StorageDirType dirType) {
205        return new DirIterator(dirType);
206      }
207      
208      public Iterable<StorageDirectory> dirIterable(final StorageDirType dirType) {
209        return new Iterable<StorageDirectory>() {
210          @Override
211          public Iterator<StorageDirectory> iterator() {
212            return dirIterator(dirType);
213          }
214        };
215      }
216      
217      
218      /**
219       * generate storage list (debug line)
220       */
221      public String listStorageDirectories() {
222        StringBuilder buf = new StringBuilder();
223        for (StorageDirectory sd : storageDirs) {
224          buf.append(sd.getRoot() + "(" + sd.getStorageDirType() + ");");
225        }
226        return buf.toString();
227      }
228      
229      /**
230       * One of the storage directories.
231       */
232      @InterfaceAudience.Private
233      public static class StorageDirectory implements FormatConfirmable {
234        final File root;              // root directory
235        final boolean useLock;        // flag to enable storage lock
236        final StorageDirType dirType; // storage dir type
237        FileLock lock;                // storage lock
238        
239        public StorageDirectory(File dir) {
240          // default dirType is null
241          this(dir, null, true);
242        }
243        
244        public StorageDirectory(File dir, StorageDirType dirType) {
245          this(dir, dirType, true);
246        }
247        
248        /**
249         * Constructor
250         * @param dir directory corresponding to the storage
251         * @param dirType storage directory type
252         * @param useLock true - enables locking on the storage directory and false
253         *          disables locking
254         */
255        public StorageDirectory(File dir, StorageDirType dirType, boolean useLock) {
256          this.root = dir;
257          this.lock = null;
258          this.dirType = dirType;
259          this.useLock = useLock;
260        }
261        
262        /**
263         * Get root directory of this storage
264         */
265        public File getRoot() {
266          return root;
267        }
268    
269        /**
270         * Get storage directory type
271         */
272        public StorageDirType getStorageDirType() {
273          return dirType;
274        }    
275    
276        public void read(File from, Storage storage) throws IOException {
277          Properties props = readPropertiesFile(from);
278          storage.setFieldsFromProperties(props, this);
279        }
280    
281        /**
282         * Clear and re-create storage directory.
283         * <p>
284         * Removes contents of the current directory and creates an empty directory.
285         * 
286         * This does not fully format storage directory. 
287         * It cannot write the version file since it should be written last after  
288         * all other storage type dependent files are written.
289         * Derived storage is responsible for setting specific storage values and
290         * writing the version file to disk.
291         * 
292         * @throws IOException
293         */
294        public void clearDirectory() throws IOException {
295          File curDir = this.getCurrentDir();
296          if (curDir.exists())
297            if (!(FileUtil.fullyDelete(curDir)))
298              throw new IOException("Cannot remove current directory: " + curDir);
299          if (!curDir.mkdirs())
300            throw new IOException("Cannot create directory " + curDir);
301        }
302    
303        /**
304         * Directory {@code current} contains latest files defining
305         * the file system meta-data.
306         * 
307         * @return the directory path
308         */
309        public File getCurrentDir() {
310          return new File(root, STORAGE_DIR_CURRENT);
311        }
312    
313        /**
314         * File {@code VERSION} contains the following fields:
315         * <ol>
316         * <li>node type</li>
317         * <li>layout version</li>
318         * <li>namespaceID</li>
319         * <li>fs state creation time</li>
320         * <li>other fields specific for this node type</li>
321         * </ol>
322         * The version file is always written last during storage directory updates.
323         * The existence of the version file indicates that all other files have
324         * been successfully written in the storage directory, the storage is valid
325         * and does not need to be recovered.
326         * 
327         * @return the version file path
328         */
329        public File getVersionFile() {
330          return new File(new File(root, STORAGE_DIR_CURRENT), STORAGE_FILE_VERSION);
331        }
332    
333        /**
334         * File {@code VERSION} from the {@code previous} directory.
335         * 
336         * @return the previous version file path
337         */
338        public File getPreviousVersionFile() {
339          return new File(new File(root, STORAGE_DIR_PREVIOUS), STORAGE_FILE_VERSION);
340        }
341    
342        /**
343         * Directory {@code previous} contains the previous file system state,
344         * which the system can be rolled back to.
345         * 
346         * @return the directory path
347         */
348        public File getPreviousDir() {
349          return new File(root, STORAGE_DIR_PREVIOUS);
350        }
351    
352        /**
353         * {@code previous.tmp} is a transient directory, which holds
354         * current file system state while the new state is saved into the new
355         * {@code current} during upgrade.
356         * If the saving succeeds {@code previous.tmp} will be moved to
357         * {@code previous}, otherwise it will be renamed back to 
358         * {@code current} by the recovery procedure during startup.
359         * 
360         * @return the directory path
361         */
362        public File getPreviousTmp() {
363          return new File(root, STORAGE_TMP_PREVIOUS);
364        }
365    
366        /**
367         * {@code removed.tmp} is a transient directory, which holds
368         * current file system state while the previous state is moved into
369         * {@code current} during rollback.
370         * If the moving succeeds {@code removed.tmp} will be removed,
371         * otherwise it will be renamed back to 
372         * {@code current} by the recovery procedure during startup.
373         * 
374         * @return the directory path
375         */
376        public File getRemovedTmp() {
377          return new File(root, STORAGE_TMP_REMOVED);
378        }
379    
380        /**
381         * {@code finalized.tmp} is a transient directory, which holds
382         * the {@code previous} file system state while it is being removed
383         * in response to the finalize request.
384         * Finalize operation will remove {@code finalized.tmp} when completed,
385         * otherwise the removal will resume upon the system startup.
386         * 
387         * @return the directory path
388         */
389        public File getFinalizedTmp() {
390          return new File(root, STORAGE_TMP_FINALIZED);
391        }
392    
393        /**
394         * {@code lastcheckpoint.tmp} is a transient directory, which holds
395         * current file system state while the new state is saved into the new
396         * {@code current} during regular namespace updates.
397         * If the saving succeeds {@code lastcheckpoint.tmp} will be moved to
398         * {@code previous.checkpoint}, otherwise it will be renamed back to 
399         * {@code current} by the recovery procedure during startup.
400         * 
401         * @return the directory path
402         */
403        public File getLastCheckpointTmp() {
404          return new File(root, STORAGE_TMP_LAST_CKPT);
405        }
406    
407        /**
408         * {@code previous.checkpoint} is a directory, which holds the previous
409         * (before the last save) state of the storage directory.
410         * The directory is created as a reference only, it does not play role
411         * in state recovery procedures, and is recycled automatically, 
412         * but it may be useful for manual recovery of a stale state of the system.
413         * 
414         * @return the directory path
415         */
416        public File getPreviousCheckpoint() {
417          return new File(root, STORAGE_PREVIOUS_CKPT);
418        }
419    
420        /**
421         * Check consistency of the storage directory
422         * 
423         * @param startOpt a startup option.
424         *  
425         * @return state {@link StorageState} of the storage directory 
426         * @throws InconsistentFSStateException if directory state is not 
427         * consistent and cannot be recovered.
428         * @throws IOException
429         */
430        public StorageState analyzeStorage(StartupOption startOpt, Storage storage)
431            throws IOException {
432          assert root != null : "root is null";
433          String rootPath = root.getCanonicalPath();
434          try { // check that storage exists
435            if (!root.exists()) {
436              // storage directory does not exist
437              if (startOpt != StartupOption.FORMAT) {
438                LOG.warn("Storage directory " + rootPath + " does not exist");
439                return StorageState.NON_EXISTENT;
440              }
441              LOG.info(rootPath + " does not exist. Creating ...");
442              if (!root.mkdirs())
443                throw new IOException("Cannot create directory " + rootPath);
444            }
445            // or is inaccessible
446            if (!root.isDirectory()) {
447              LOG.warn(rootPath + "is not a directory");
448              return StorageState.NON_EXISTENT;
449            }
450            if (!root.canWrite()) {
451              LOG.warn("Cannot access storage directory " + rootPath);
452              return StorageState.NON_EXISTENT;
453            }
454          } catch(SecurityException ex) {
455            LOG.warn("Cannot access storage directory " + rootPath, ex);
456            return StorageState.NON_EXISTENT;
457          }
458    
459          this.lock(); // lock storage if it exists
460    
461          if (startOpt == HdfsServerConstants.StartupOption.FORMAT)
462            return StorageState.NOT_FORMATTED;
463    
464          if (startOpt != HdfsServerConstants.StartupOption.IMPORT) {
465            storage.checkOldLayoutStorage(this);
466          }
467    
468          // check whether current directory is valid
469          File versionFile = getVersionFile();
470          boolean hasCurrent = versionFile.exists();
471    
472          // check which directories exist
473          boolean hasPrevious = getPreviousDir().exists();
474          boolean hasPreviousTmp = getPreviousTmp().exists();
475          boolean hasRemovedTmp = getRemovedTmp().exists();
476          boolean hasFinalizedTmp = getFinalizedTmp().exists();
477          boolean hasCheckpointTmp = getLastCheckpointTmp().exists();
478    
479          if (!(hasPreviousTmp || hasRemovedTmp
480              || hasFinalizedTmp || hasCheckpointTmp)) {
481            // no temp dirs - no recovery
482            if (hasCurrent)
483              return StorageState.NORMAL;
484            if (hasPrevious)
485              throw new InconsistentFSStateException(root,
486                                  "version file in current directory is missing.");
487            return StorageState.NOT_FORMATTED;
488          }
489    
490          if ((hasPreviousTmp?1:0) + (hasRemovedTmp?1:0)
491              + (hasFinalizedTmp?1:0) + (hasCheckpointTmp?1:0) > 1)
492            // more than one temp dirs
493            throw new InconsistentFSStateException(root,
494                                                   "too many temporary directories.");
495    
496          // # of temp dirs == 1 should either recover or complete a transition
497          if (hasCheckpointTmp) {
498            return hasCurrent ? StorageState.COMPLETE_CHECKPOINT
499                              : StorageState.RECOVER_CHECKPOINT;
500          }
501    
502          if (hasFinalizedTmp) {
503            if (hasPrevious)
504              throw new InconsistentFSStateException(root,
505                                                     STORAGE_DIR_PREVIOUS + " and " + STORAGE_TMP_FINALIZED
506                                                     + "cannot exist together.");
507            return StorageState.COMPLETE_FINALIZE;
508          }
509    
510          if (hasPreviousTmp) {
511            if (hasPrevious)
512              throw new InconsistentFSStateException(root,
513                                                     STORAGE_DIR_PREVIOUS + " and " + STORAGE_TMP_PREVIOUS
514                                                     + " cannot exist together.");
515            if (hasCurrent)
516              return StorageState.COMPLETE_UPGRADE;
517            return StorageState.RECOVER_UPGRADE;
518          }
519          
520          assert hasRemovedTmp : "hasRemovedTmp must be true";
521          if (!(hasCurrent ^ hasPrevious))
522            throw new InconsistentFSStateException(root,
523                                                   "one and only one directory " + STORAGE_DIR_CURRENT 
524                                                   + " or " + STORAGE_DIR_PREVIOUS 
525                                                   + " must be present when " + STORAGE_TMP_REMOVED
526                                                   + " exists.");
527          if (hasCurrent)
528            return StorageState.COMPLETE_ROLLBACK;
529          return StorageState.RECOVER_ROLLBACK;
530        }
531    
532        /**
533         * Complete or recover storage state from previously failed transition.
534         * 
535         * @param curState specifies what/how the state should be recovered
536         * @throws IOException
537         */
538        public void doRecover(StorageState curState) throws IOException {
539          File curDir = getCurrentDir();
540          String rootPath = root.getCanonicalPath();
541          switch(curState) {
542          case COMPLETE_UPGRADE:  // mv previous.tmp -> previous
543            LOG.info("Completing previous upgrade for storage directory " 
544                     + rootPath);
545            rename(getPreviousTmp(), getPreviousDir());
546            return;
547          case RECOVER_UPGRADE:   // mv previous.tmp -> current
548            LOG.info("Recovering storage directory " + rootPath
549                     + " from previous upgrade");
550            if (curDir.exists())
551              deleteDir(curDir);
552            rename(getPreviousTmp(), curDir);
553            return;
554          case COMPLETE_ROLLBACK: // rm removed.tmp
555            LOG.info("Completing previous rollback for storage directory "
556                     + rootPath);
557            deleteDir(getRemovedTmp());
558            return;
559          case RECOVER_ROLLBACK:  // mv removed.tmp -> current
560            LOG.info("Recovering storage directory " + rootPath
561                     + " from previous rollback");
562            rename(getRemovedTmp(), curDir);
563            return;
564          case COMPLETE_FINALIZE: // rm finalized.tmp
565            LOG.info("Completing previous finalize for storage directory "
566                     + rootPath);
567            deleteDir(getFinalizedTmp());
568            return;
569          case COMPLETE_CHECKPOINT: // mv lastcheckpoint.tmp -> previous.checkpoint
570            LOG.info("Completing previous checkpoint for storage directory " 
571                     + rootPath);
572            File prevCkptDir = getPreviousCheckpoint();
573            if (prevCkptDir.exists())
574              deleteDir(prevCkptDir);
575            rename(getLastCheckpointTmp(), prevCkptDir);
576            return;
577          case RECOVER_CHECKPOINT:  // mv lastcheckpoint.tmp -> current
578            LOG.info("Recovering storage directory " + rootPath
579                     + " from failed checkpoint");
580            if (curDir.exists())
581              deleteDir(curDir);
582            rename(getLastCheckpointTmp(), curDir);
583            return;
584          default:
585            throw new IOException("Unexpected FS state: " + curState);
586          }
587        }
588        
589        /**
590         * @return true if the storage directory should prompt the user prior
591         * to formatting (i.e if the directory appears to contain some data)
592         * @throws IOException if the SD cannot be accessed due to an IO error
593         */
594        @Override
595        public boolean hasSomeData() throws IOException {
596          // Its alright for a dir not to exist, or to exist (properly accessible)
597          // and be completely empty.
598          if (!root.exists()) return false;
599          
600          if (!root.isDirectory()) {
601            // a file where you expect a directory should not cause silent
602            // formatting
603            return true;
604          }
605          
606          if (FileUtil.listFiles(root).length == 0) {
607            // Empty dir can format without prompt.
608            return false;
609          }
610          
611          return true;
612        }
613    
614    
615        /**
616         * Lock storage to provide exclusive access.
617         * 
618         * <p> Locking is not supported by all file systems.
619         * E.g., NFS does not consistently support exclusive locks.
620         * 
621         * <p> If locking is supported we guarantee exclusive access to the
622         * storage directory. Otherwise, no guarantee is given.
623         * 
624         * @throws IOException if locking fails
625         */
626        public void lock() throws IOException {
627          if (!useLock) {
628            LOG.info("Locking is disabled");
629            return;
630          }
631          FileLock newLock = tryLock();
632          if (newLock == null) {
633            String msg = "Cannot lock storage " + this.root 
634              + ". The directory is already locked";
635            LOG.info(msg);
636            throw new IOException(msg);
637          }
638          // Don't overwrite lock until success - this way if we accidentally
639          // call lock twice, the internal state won't be cleared by the second
640          // (failed) lock attempt
641          lock = newLock;
642        }
643    
644        /**
645         * Attempts to acquire an exclusive lock on the storage.
646         * 
647         * @return A lock object representing the newly-acquired lock or
648         * <code>null</code> if storage is already locked.
649         * @throws IOException if locking fails.
650         */
651        FileLock tryLock() throws IOException {
652          boolean deletionHookAdded = false;
653          File lockF = new File(root, STORAGE_FILE_LOCK);
654          if (!lockF.exists()) {
655            lockF.deleteOnExit();
656            deletionHookAdded = true;
657          }
658          RandomAccessFile file = new RandomAccessFile(lockF, "rws");
659          String jvmName = ManagementFactory.getRuntimeMXBean().getName();
660          FileLock res = null;
661          try {
662            res = file.getChannel().tryLock();
663            file.write(jvmName.getBytes(Charsets.UTF_8));
664            LOG.info("Lock on " + lockF + " acquired by nodename " + jvmName);
665          } catch(OverlappingFileLockException oe) {
666            LOG.error("It appears that another namenode " + file.readLine() 
667                + " has already locked the storage directory");
668            file.close();
669            return null;
670          } catch(IOException e) {
671            LOG.error("Failed to acquire lock on " + lockF + ". If this storage directory is mounted via NFS, " 
672                + "ensure that the appropriate nfs lock services are running.", e);
673            file.close();
674            throw e;
675          }
676          if (res != null && !deletionHookAdded) {
677            // If the file existed prior to our startup, we didn't
678            // call deleteOnExit above. But since we successfully locked
679            // the dir, we can take care of cleaning it up.
680            lockF.deleteOnExit();
681          }
682          return res;
683        }
684    
685        /**
686         * Unlock storage.
687         * 
688         * @throws IOException
689         */
690        public void unlock() throws IOException {
691          if (this.lock == null)
692            return;
693          this.lock.release();
694          lock.channel().close();
695          lock = null;
696        }
697        
698        @Override
699        public String toString() {
700          return "Storage Directory " + this.root;
701        }
702    
703        /**
704         * Check whether underlying file system supports file locking.
705         * 
706         * @return <code>true</code> if exclusive locks are supported or
707         *         <code>false</code> otherwise.
708         * @throws IOException
709         * @see StorageDirectory#lock()
710         */
711        public boolean isLockSupported() throws IOException {
712          FileLock firstLock = null;
713          FileLock secondLock = null;
714          try {
715            firstLock = lock;
716            if(firstLock == null) {
717              firstLock = tryLock();
718              if(firstLock == null)
719                return true;
720            }
721            secondLock = tryLock();
722            if(secondLock == null)
723              return true;
724          } finally {
725            if(firstLock != null && firstLock != lock) {
726              firstLock.release();
727              firstLock.channel().close();
728            }
729            if(secondLock != null) {
730              secondLock.release();
731              secondLock.channel().close();
732            }
733          }
734          return false;
735        }
736      }
737    
738      /**
739       * Create empty storage info of the specified type
740       */
741      protected Storage(NodeType type) {
742        super();
743        this.storageType = type;
744      }
745      
746      protected Storage(NodeType type, StorageInfo storageInfo) {
747        super(storageInfo);
748        this.storageType = type;
749      }
750      
751      public int getNumStorageDirs() {
752        return storageDirs.size();
753      }
754      
755      public StorageDirectory getStorageDir(int idx) {
756        return storageDirs.get(idx);
757      }
758      
759      /**
760       * @return the storage directory, with the precondition that this storage
761       * has exactly one storage directory
762       */
763      public StorageDirectory getSingularStorageDir() {
764        Preconditions.checkState(storageDirs.size() == 1);
765        return storageDirs.get(0);
766      }
767      
768      protected void addStorageDir(StorageDirectory sd) {
769        storageDirs.add(sd);
770      }
771    
772      /**
773       * Return true if the layout of the given storage directory is from a version
774       * of Hadoop prior to the introduction of the "current" and "previous"
775       * directories which allow upgrade and rollback.
776       */
777      public abstract boolean isPreUpgradableLayout(StorageDirectory sd)
778      throws IOException;
779    
780      /**
781       * Check if the given storage directory comes from a version of Hadoop
782       * prior to when the directory layout changed (ie 0.13). If this is
783       * the case, this method throws an IOException.
784       */
785      private void checkOldLayoutStorage(StorageDirectory sd) throws IOException {
786        if (isPreUpgradableLayout(sd)) {
787          checkVersionUpgradable(0);
788        }
789      }
790    
791      /**
792       * Checks if the upgrade from the given old version is supported. If
793       * no upgrade is supported, it throws IncorrectVersionException.
794       * 
795       * @param oldVersion
796       */
797      public static void checkVersionUpgradable(int oldVersion) 
798                                         throws IOException {
799        if (oldVersion > LAST_UPGRADABLE_LAYOUT_VERSION) {
800          String msg = "*********** Upgrade is not supported from this " +
801                       " older version " + oldVersion + 
802                       " of storage to the current version." + 
803                       " Please upgrade to " + LAST_UPGRADABLE_HADOOP_VERSION +
804                       " or a later version and then upgrade to current" +
805                       " version. Old layout version is " + 
806                       (oldVersion == 0 ? "'too old'" : (""+oldVersion)) +
807                       " and latest layout version this software version can" +
808                       " upgrade from is " + LAST_UPGRADABLE_LAYOUT_VERSION +
809                       ". ************";
810          LOG.error(msg);
811          throw new IOException(msg); 
812        }
813        
814      }
815      
816      /**
817       * Iterate over each of the {@link FormatConfirmable} objects,
818       * potentially checking with the user whether it should be formatted.
819       * 
820       * If running in interactive mode, will prompt the user for each
821       * directory to allow them to format anyway. Otherwise, returns
822       * false, unless 'force' is specified.
823       * 
824       * @param force format regardless of whether dirs exist
825       * @param interactive prompt the user when a dir exists
826       * @return true if formatting should proceed
827       * @throws IOException if some storage cannot be accessed
828       */
829      public static boolean confirmFormat(
830          Iterable<? extends FormatConfirmable> items,
831          boolean force, boolean interactive) throws IOException {
832        for (FormatConfirmable item : items) {
833          if (!item.hasSomeData())
834            continue;
835          if (force) { // Don't confirm, always format.
836            System.err.println(
837                "Data exists in " + item + ". Formatting anyway.");
838            continue;
839          }
840          if (!interactive) { // Don't ask - always don't format
841            System.err.println(
842                "Running in non-interactive mode, and data appears to exist in " +
843                item + ". Not formatting.");
844            return false;
845          }
846          if (!ToolRunner.confirmPrompt("Re-format filesystem in " + item + " ?")) {
847            System.err.println("Format aborted in " + item);
848            return false;
849          }
850        }
851        
852        return true;
853      }
854      
855      /**
856       * Interface for classes which need to have the user confirm their
857       * formatting during NameNode -format and other similar operations.
858       * 
859       * This is currently a storage directory or journal manager.
860       */
861      @InterfaceAudience.Private
862      public interface FormatConfirmable {
863        /**
864         * @return true if the storage seems to have some valid data in it,
865         * and the user should be required to confirm the format. Otherwise,
866         * false.
867         * @throws IOException if the storage cannot be accessed at all.
868         */
869        public boolean hasSomeData() throws IOException;
870        
871        /**
872         * @return a string representation of the formattable item, suitable
873         * for display to the user inside a prompt
874         */
875        public String toString();
876      }
877      
878      /**
879       * Get common storage fields.
880       * Should be overloaded if additional fields need to be get.
881       * 
882       * @param props
883       * @throws IOException
884       */
885      protected void setFieldsFromProperties(
886          Properties props, StorageDirectory sd) throws IOException {
887        setLayoutVersion(props, sd);
888        setNamespaceID(props, sd);
889        setStorageType(props, sd);
890        setcTime(props, sd);
891        setClusterId(props, layoutVersion, sd);
892      }
893      
894      /**
895       * Set common storage fields into the given properties object.
896       * Should be overloaded if additional fields need to be set.
897       * 
898       * @param props the Properties object to write into
899       */
900      protected void setPropertiesFromFields(Properties props, 
901                                             StorageDirectory sd)
902          throws IOException {
903        props.setProperty("layoutVersion", String.valueOf(layoutVersion));
904        props.setProperty("storageType", storageType.toString());
905        props.setProperty("namespaceID", String.valueOf(namespaceID));
906        // Set clusterID in version with federation support
907        if (versionSupportsFederation()) {
908          props.setProperty("clusterID", clusterID);
909        }
910        props.setProperty("cTime", String.valueOf(cTime));
911      }
912    
913      /**
914       * Read properties from the VERSION file in the given storage directory.
915       */
916      public void readProperties(StorageDirectory sd) throws IOException {
917        Properties props = readPropertiesFile(sd.getVersionFile());
918        setFieldsFromProperties(props, sd);
919      }
920    
921      /**
922       * Read properties from the the previous/VERSION file in the given storage directory.
923       */
924      public void readPreviousVersionProperties(StorageDirectory sd)
925          throws IOException {
926        Properties props = readPropertiesFile(sd.getPreviousVersionFile());
927        setFieldsFromProperties(props, sd);
928      }
929    
930      /**
931       * Write properties to the VERSION file in the given storage directory.
932       */
933      public void writeProperties(StorageDirectory sd) throws IOException {
934        writeProperties(sd.getVersionFile(), sd);
935      }
936    
937      public void writeProperties(File to, StorageDirectory sd) throws IOException {
938        Properties props = new Properties();
939        setPropertiesFromFields(props, sd);
940        RandomAccessFile file = new RandomAccessFile(to, "rws");
941        FileOutputStream out = null;
942        try {
943          file.seek(0);
944          out = new FileOutputStream(file.getFD());
945          /*
946           * If server is interrupted before this line, 
947           * the version file will remain unchanged.
948           */
949          props.store(out, null);
950          /*
951           * Now the new fields are flushed to the head of the file, but file 
952           * length can still be larger then required and therefore the file can 
953           * contain whole or corrupted fields from its old contents in the end.
954           * If server is interrupted here and restarted later these extra fields
955           * either should not effect server behavior or should be handled
956           * by the server correctly.
957           */
958          file.setLength(out.getChannel().position());
959        } finally {
960          if (out != null) {
961            out.close();
962          }
963          file.close();
964        }
965      }
966      
967      public static Properties readPropertiesFile(File from) throws IOException {
968        RandomAccessFile file = new RandomAccessFile(from, "rws");
969        FileInputStream in = null;
970        Properties props = new Properties();
971        try {
972          in = new FileInputStream(file.getFD());
973          file.seek(0);
974          props.load(in);
975        } finally {
976          if (in != null) {
977            in.close();
978          }
979          file.close();
980        }
981        return props;
982      }
983    
984      public static void rename(File from, File to) throws IOException {
985        if (!from.renameTo(to))
986          throw new IOException("Failed to rename " 
987                                + from.getCanonicalPath() + " to " + to.getCanonicalPath());
988      }
989    
990      /**
991       * Recursively delete all the content of the directory first and then 
992       * the directory itself from the local filesystem.
993       * @param dir The directory to delete
994       * @throws IOException
995       */
996      public static void deleteDir(File dir) throws IOException {
997        if (!FileUtil.fullyDelete(dir))
998          throw new IOException("Failed to delete " + dir.getCanonicalPath());
999      }
1000      
1001      /**
1002       * Write all data storage files.
1003       * @throws IOException
1004       */
1005      public void writeAll() throws IOException {
1006        this.layoutVersion = HdfsConstants.LAYOUT_VERSION;
1007        for (Iterator<StorageDirectory> it = storageDirs.iterator(); it.hasNext();) {
1008          writeProperties(it.next());
1009        }
1010      }
1011    
1012      /**
1013       * Unlock all storage directories.
1014       * @throws IOException
1015       */
1016      public void unlockAll() throws IOException {
1017        for (Iterator<StorageDirectory> it = storageDirs.iterator(); it.hasNext();) {
1018          it.next().unlock();
1019        }
1020      }
1021    
1022      public static String getBuildVersion() {
1023        return VersionInfo.getRevision();
1024      }
1025    
1026      public static String getRegistrationID(StorageInfo storage) {
1027        return "NS-" + Integer.toString(storage.getNamespaceID())
1028          + "-" + storage.getClusterID()
1029          + "-" + Integer.toString(storage.getLayoutVersion())
1030          + "-" + Long.toString(storage.getCTime());
1031      }
1032      
1033      String getProperty(Properties props, StorageDirectory sd,
1034          String name) throws InconsistentFSStateException {
1035        String property = props.getProperty(name);
1036        if (property == null) {
1037          throw new InconsistentFSStateException(sd.root, "file "
1038              + STORAGE_FILE_VERSION + " has " + name + " missing.");
1039        }
1040        return property;
1041      }
1042      
1043      /** Validate and set storage type from {@link Properties}*/
1044      protected void setStorageType(Properties props, StorageDirectory sd)
1045          throws InconsistentFSStateException {
1046        NodeType type = NodeType.valueOf(getProperty(props, sd, "storageType"));
1047        if (!storageType.equals(type)) {
1048          throw new InconsistentFSStateException(sd.root,
1049              "node type is incompatible with others.");
1050        }
1051        storageType = type;
1052      }
1053      
1054      /** Validate and set ctime from {@link Properties}*/
1055      protected void setcTime(Properties props, StorageDirectory sd)
1056          throws InconsistentFSStateException {
1057        cTime = Long.parseLong(getProperty(props, sd, "cTime"));
1058      }
1059    
1060      /** Validate and set clusterId from {@link Properties}*/
1061      protected void setClusterId(Properties props, int layoutVersion,
1062          StorageDirectory sd) throws InconsistentFSStateException {
1063        // Set cluster ID in version that supports federation
1064        if (LayoutVersion.supports(Feature.FEDERATION, layoutVersion)) {
1065          String cid = getProperty(props, sd, "clusterID");
1066          if (!(clusterID.equals("") || cid.equals("") || clusterID.equals(cid))) {
1067            throw new InconsistentFSStateException(sd.getRoot(),
1068                "cluster Id is incompatible with others.");
1069          }
1070          clusterID = cid;
1071        }
1072      }
1073      
1074      /** Validate and set layout version from {@link Properties}*/
1075      protected void setLayoutVersion(Properties props, StorageDirectory sd)
1076          throws IncorrectVersionException, InconsistentFSStateException {
1077        int lv = Integer.parseInt(getProperty(props, sd, "layoutVersion"));
1078        if (lv < HdfsConstants.LAYOUT_VERSION) { // future version
1079          throw new IncorrectVersionException(lv, "storage directory "
1080              + sd.root.getAbsolutePath());
1081        }
1082        layoutVersion = lv;
1083      }
1084      
1085      /** Validate and set namespaceID version from {@link Properties}*/
1086      protected void setNamespaceID(Properties props, StorageDirectory sd)
1087          throws InconsistentFSStateException {
1088        int nsId = Integer.parseInt(getProperty(props, sd, "namespaceID"));
1089        if (namespaceID != 0 && nsId != 0 && namespaceID != nsId) {
1090          throw new InconsistentFSStateException(sd.root,
1091              "namespaceID is incompatible with others.");
1092        }
1093        namespaceID = nsId;
1094      }
1095      
1096      public static boolean is203LayoutVersion(int layoutVersion) {
1097        for (int lv203 : LAYOUT_VERSIONS_203) {
1098          if (lv203 == layoutVersion) {
1099            return true;
1100          }
1101        }
1102        return false;
1103      }
1104    }