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.server.namenode; 019 020import static org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion; 021import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_DEFAULT; 022import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_KEY; 023import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT; 024import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_KEY; 025import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT; 026import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY; 027import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT; 028import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY; 029import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT; 030import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CHECKSUM_TYPE_KEY; 031import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT; 032import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY; 033import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_DEFAULT; 034import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_KEY; 035import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_STANDBY_CHECKPOINTS_DEFAULT; 036import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_STANDBY_CHECKPOINTS_KEY; 037import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_DEFAULT; 038import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_ACCESSTIME_PRECISION_KEY; 039import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY; 040import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_ASYNC_DEFAULT; 041import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_ASYNC_KEY; 042import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_DEFAULT; 043import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_KEY; 044import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_AUTHORIZATION_PROVIDER_KEY; 045import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_DEFAULT; 046import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_TXNS_KEY; 047import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DEFAULT_AUDIT_LOGGER_NAME; 048import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT; 049import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_KEY; 050import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_DEFAULT; 051import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY; 052import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT; 053import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_KEY; 054import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT; 055import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY; 056import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY; 057import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_REQUIRED_KEY; 058import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDIT_LOG_AUTOROLL_CHECK_INTERVAL_MS; 059import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDIT_LOG_AUTOROLL_CHECK_INTERVAL_MS_DEFAULT; 060import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDIT_LOG_AUTOROLL_MULTIPLIER_THRESHOLD; 061import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_EDIT_LOG_AUTOROLL_MULTIPLIER_THRESHOLD_DEFAULT; 062import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_ENABLE_RETRY_CACHE_DEFAULT; 063import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_ENABLE_RETRY_CACHE_KEY; 064import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC; 065import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC_DEFAULT; 066import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_MAX_OBJECTS_DEFAULT; 067import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_MAX_OBJECTS_KEY; 068import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY; 069import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_DEFAULT; 070import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY; 071import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY; 072import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_DEFAULT; 073import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_KEY; 074import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_DEFAULT; 075import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_KEY; 076import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_DEFAULT; 077import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_KEY; 078import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_EXTENSION_KEY; 079import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT; 080import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY; 081import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT; 082import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY; 083import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY; 084import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERMISSIONS_ENABLED_DEFAULT; 085import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY; 086import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_DEFAULT; 087import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_KEY; 088import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_DEFAULT; 089import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_KEY; 090import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_STORAGE_POLICY_ENABLED_KEY; 091import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_STORAGE_POLICY_ENABLED_DEFAULT; 092import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_SUPPORT_APPEND_DEFAULT; 093import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_SUPPORT_APPEND_KEY; 094import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants.SECURITY_XATTR_UNREADABLE_BY_SUPERUSER; 095import static org.apache.hadoop.util.Time.now; 096 097import java.io.BufferedWriter; 098import java.io.ByteArrayInputStream; 099import java.io.DataInput; 100import java.io.DataInputStream; 101import java.io.DataOutputStream; 102import java.io.File; 103import java.io.FileNotFoundException; 104import java.io.FileOutputStream; 105import java.io.IOException; 106import java.io.OutputStreamWriter; 107import java.io.PrintWriter; 108import java.io.StringWriter; 109import java.lang.management.ManagementFactory; 110import java.net.InetAddress; 111import java.net.URI; 112import java.security.GeneralSecurityException; 113import java.security.NoSuchAlgorithmException; 114import java.util.ArrayList; 115import java.util.Arrays; 116import java.util.Collection; 117import java.util.Collections; 118import java.util.Date; 119import java.util.EnumSet; 120import java.util.HashMap; 121import java.util.HashSet; 122import java.util.Iterator; 123import java.util.LinkedHashSet; 124import java.util.List; 125import java.util.Map; 126import java.util.Set; 127import java.util.TreeMap; 128import java.util.concurrent.TimeUnit; 129import java.util.concurrent.locks.Condition; 130import java.util.concurrent.locks.ReentrantLock; 131import java.util.concurrent.locks.ReentrantReadWriteLock; 132 133import javax.management.NotCompliantMBeanException; 134import javax.management.ObjectName; 135import javax.management.StandardMBean; 136 137import org.apache.commons.logging.Log; 138import org.apache.commons.logging.LogFactory; 139import org.apache.commons.logging.impl.Log4JLogger; 140import org.apache.hadoop.HadoopIllegalArgumentException; 141import org.apache.hadoop.classification.InterfaceAudience; 142import org.apache.hadoop.conf.Configuration; 143import org.apache.hadoop.crypto.CipherSuite; 144import org.apache.hadoop.crypto.CryptoProtocolVersion; 145import org.apache.hadoop.crypto.key.KeyProvider; 146import org.apache.hadoop.crypto.CryptoCodec; 147import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension; 148import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries; 149import org.apache.hadoop.fs.CacheFlag; 150import org.apache.hadoop.fs.ContentSummary; 151import org.apache.hadoop.fs.CreateFlag; 152import org.apache.hadoop.fs.DirectoryListingStartAfterNotFoundException; 153import org.apache.hadoop.fs.FileAlreadyExistsException; 154import org.apache.hadoop.fs.FileEncryptionInfo; 155import org.apache.hadoop.fs.FileStatus; 156import org.apache.hadoop.fs.FileSystem; 157import org.apache.hadoop.fs.FsServerDefaults; 158import org.apache.hadoop.fs.InvalidPathException; 159import org.apache.hadoop.fs.Options; 160import org.apache.hadoop.fs.Options.Rename; 161import org.apache.hadoop.fs.ParentNotDirectoryException; 162import org.apache.hadoop.fs.Path; 163import org.apache.hadoop.fs.PathIsNotEmptyDirectoryException; 164import org.apache.hadoop.fs.UnresolvedLinkException; 165import org.apache.hadoop.fs.XAttr; 166import org.apache.hadoop.fs.XAttrSetFlag; 167import org.apache.hadoop.fs.permission.AclEntry; 168import org.apache.hadoop.fs.permission.AclStatus; 169import org.apache.hadoop.fs.permission.FsAction; 170import org.apache.hadoop.fs.permission.FsPermission; 171import org.apache.hadoop.fs.permission.PermissionStatus; 172import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; 173import org.apache.hadoop.ha.ServiceFailedException; 174import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy; 175import org.apache.hadoop.hdfs.DFSConfigKeys; 176import org.apache.hadoop.hdfs.DFSUtil; 177import org.apache.hadoop.hdfs.HAUtil; 178import org.apache.hadoop.hdfs.HdfsConfiguration; 179import org.apache.hadoop.hdfs.UnknownCryptoProtocolVersionException; 180import org.apache.hadoop.hdfs.XAttrHelper; 181import org.apache.hadoop.hdfs.protocol.AclException; 182import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; 183import org.apache.hadoop.hdfs.protocol.Block; 184import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry; 185import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo; 186import org.apache.hadoop.hdfs.protocol.CachePoolEntry; 187import org.apache.hadoop.hdfs.protocol.CachePoolInfo; 188import org.apache.hadoop.hdfs.protocol.ClientProtocol; 189import org.apache.hadoop.hdfs.protocol.DatanodeID; 190import org.apache.hadoop.hdfs.protocol.DatanodeInfo; 191import org.apache.hadoop.hdfs.protocol.DirectoryListing; 192import org.apache.hadoop.hdfs.protocol.EncryptionZone; 193import org.apache.hadoop.hdfs.protocol.ExtendedBlock; 194import org.apache.hadoop.hdfs.protocol.HdfsConstants; 195import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType; 196import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction; 197import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; 198import org.apache.hadoop.hdfs.protocol.LocatedBlock; 199import org.apache.hadoop.hdfs.protocol.LocatedBlocks; 200import org.apache.hadoop.hdfs.protocol.QuotaExceededException; 201import org.apache.hadoop.hdfs.protocol.RecoveryInProgressException; 202import org.apache.hadoop.hdfs.protocol.RollingUpgradeException; 203import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo; 204import org.apache.hadoop.hdfs.protocol.SnapshotAccessControlException; 205import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport; 206import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus; 207import org.apache.hadoop.hdfs.protocol.datatransfer.ReplaceDatanodeOnFailure; 208import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager; 209import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager.AccessMode; 210import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; 211import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager; 212import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager.SecretManagerState; 213import org.apache.hadoop.hdfs.server.blockmanagement.BlockCollection; 214import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo; 215import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfoUnderConstruction; 216import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager; 217import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor; 218import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager; 219import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStatistics; 220import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo; 221import org.apache.hadoop.hdfs.server.blockmanagement.OutOfV1GenerationStampsException; 222import org.apache.hadoop.hdfs.server.common.GenerationStamp; 223import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.BlockUCState; 224import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NamenodeRole; 225import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.RollingUpgradeStartupOption; 226import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption; 227import org.apache.hadoop.hdfs.server.common.Storage; 228import org.apache.hadoop.hdfs.server.common.Storage.StorageDirType; 229import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory; 230import org.apache.hadoop.hdfs.server.common.Util; 231import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SecretManagerSection; 232import org.apache.hadoop.hdfs.server.namenode.INode.BlocksMapUpdateInfo; 233import org.apache.hadoop.hdfs.server.namenode.JournalSet.JournalAndStream; 234import org.apache.hadoop.hdfs.server.namenode.LeaseManager.Lease; 235import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeFile; 236import org.apache.hadoop.hdfs.server.namenode.NameNode.OperationCategory; 237import org.apache.hadoop.hdfs.server.namenode.ha.EditLogTailer; 238import org.apache.hadoop.hdfs.server.namenode.ha.HAContext; 239import org.apache.hadoop.hdfs.server.namenode.ha.StandbyCheckpointer; 240import org.apache.hadoop.hdfs.server.namenode.metrics.FSNamesystemMBean; 241import org.apache.hadoop.hdfs.server.namenode.metrics.NameNodeMetrics; 242import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature; 243import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot; 244import org.apache.hadoop.hdfs.server.namenode.snapshot.SnapshotManager; 245import org.apache.hadoop.hdfs.server.namenode.startupprogress.Phase; 246import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress; 247import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress.Counter; 248import org.apache.hadoop.hdfs.server.namenode.startupprogress.Status; 249import org.apache.hadoop.hdfs.server.namenode.startupprogress.Step; 250import org.apache.hadoop.hdfs.server.namenode.startupprogress.StepType; 251import org.apache.hadoop.hdfs.server.namenode.top.TopAuditLogger; 252import org.apache.hadoop.hdfs.server.namenode.top.TopConf; 253import org.apache.hadoop.hdfs.server.namenode.top.metrics.TopMetrics; 254import org.apache.hadoop.hdfs.server.namenode.top.window.RollingWindowManager; 255import org.apache.hadoop.hdfs.server.namenode.web.resources.NamenodeWebHdfsMethods; 256import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand; 257import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; 258import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport; 259import org.apache.hadoop.hdfs.server.protocol.HeartbeatResponse; 260import org.apache.hadoop.hdfs.server.protocol.NNHAStatusHeartbeat; 261import org.apache.hadoop.hdfs.server.protocol.NamenodeCommand; 262import org.apache.hadoop.hdfs.server.protocol.NamenodeRegistration; 263import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; 264import org.apache.hadoop.hdfs.server.protocol.StorageReceivedDeletedBlocks; 265import org.apache.hadoop.hdfs.server.protocol.StorageReport; 266import org.apache.hadoop.hdfs.server.protocol.VolumeFailureSummary; 267import org.apache.hadoop.hdfs.StorageType; 268import org.apache.hadoop.io.EnumSetWritable; 269import org.apache.hadoop.io.IOUtils; 270import org.apache.hadoop.io.Text; 271import org.apache.hadoop.ipc.RetriableException; 272import org.apache.hadoop.ipc.RetryCache; 273import org.apache.hadoop.ipc.RetryCache.CacheEntry; 274import org.apache.hadoop.ipc.RetryCache.CacheEntryWithPayload; 275import org.apache.hadoop.ipc.Server; 276import org.apache.hadoop.ipc.StandbyException; 277import org.apache.hadoop.metrics2.annotation.Metric; 278import org.apache.hadoop.metrics2.annotation.Metrics; 279import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; 280import org.apache.hadoop.metrics2.util.MBeans; 281import org.apache.hadoop.net.NetworkTopology; 282import org.apache.hadoop.net.Node; 283import org.apache.hadoop.net.NodeBase; 284import org.apache.hadoop.security.AccessControlException; 285import org.apache.hadoop.security.UserGroupInformation; 286import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; 287import org.apache.hadoop.security.token.SecretManager.InvalidToken; 288import org.apache.hadoop.security.token.Token; 289import org.apache.hadoop.security.token.TokenIdentifier; 290import org.apache.hadoop.security.token.delegation.DelegationKey; 291import org.apache.hadoop.util.ChunkedArrayList; 292import org.apache.hadoop.util.Daemon; 293import org.apache.hadoop.util.DataChecksum; 294import org.apache.hadoop.util.ReflectionUtils; 295import org.apache.hadoop.util.StringUtils; 296import org.apache.hadoop.util.Time; 297import org.apache.hadoop.util.VersionInfo; 298import org.apache.log4j.Appender; 299import org.apache.log4j.AsyncAppender; 300import org.apache.log4j.Logger; 301import org.codehaus.jackson.map.ObjectMapper; 302import org.mortbay.util.ajax.JSON; 303 304import com.google.common.annotations.VisibleForTesting; 305import com.google.common.base.Charsets; 306import com.google.common.base.Preconditions; 307import com.google.common.collect.ImmutableMap; 308import com.google.common.collect.Lists; 309 310/*************************************************** 311 * FSNamesystem does the actual bookkeeping work for the 312 * DataNode. 313 * 314 * It tracks several important tables. 315 * 316 * 1) valid fsname --> blocklist (kept on disk, logged) 317 * 2) Set of all valid blocks (inverted #1) 318 * 3) block --> machinelist (kept in memory, rebuilt dynamically from reports) 319 * 4) machine --> blocklist (inverted #2) 320 * 5) LRU cache of updated-heartbeat machines 321 ***************************************************/ 322@InterfaceAudience.Private 323@Metrics(context="dfs") 324public class FSNamesystem implements Namesystem, FSClusterStats, 325 FSNamesystemMBean, NameNodeMXBean { 326 public static final Log LOG = LogFactory.getLog(FSNamesystem.class); 327 328 private static final ThreadLocal<StringBuilder> auditBuffer = 329 new ThreadLocal<StringBuilder>() { 330 @Override 331 protected StringBuilder initialValue() { 332 return new StringBuilder(); 333 } 334 }; 335 336 @VisibleForTesting 337 public boolean isAuditEnabled() { 338 return !isDefaultAuditLogger || auditLog.isInfoEnabled(); 339 } 340 341 private HdfsFileStatus getAuditFileInfo(String path, boolean resolveSymlink) 342 throws IOException { 343 return (isAuditEnabled() && isExternalInvocation()) 344 ? dir.getFileInfo(path, resolveSymlink, false, false) : null; 345 } 346 347 private void logAuditEvent(boolean succeeded, String cmd, String src) 348 throws IOException { 349 logAuditEvent(succeeded, cmd, src, null, null); 350 } 351 352 private void logAuditEvent(boolean succeeded, String cmd, String src, 353 String dst, HdfsFileStatus stat) throws IOException { 354 if (isAuditEnabled() && isExternalInvocation()) { 355 logAuditEvent(succeeded, getRemoteUser(), getRemoteIp(), 356 cmd, src, dst, stat); 357 } 358 } 359 360 private void logAuditEvent(boolean succeeded, 361 UserGroupInformation ugi, InetAddress addr, String cmd, String src, 362 String dst, HdfsFileStatus stat) { 363 FileStatus status = null; 364 if (stat != null) { 365 Path symlink = stat.isSymlink() ? new Path(stat.getSymlink()) : null; 366 Path path = dst != null ? new Path(dst) : new Path(src); 367 status = new FileStatus(stat.getLen(), stat.isDir(), 368 stat.getReplication(), stat.getBlockSize(), stat.getModificationTime(), 369 stat.getAccessTime(), stat.getPermission(), stat.getOwner(), 370 stat.getGroup(), symlink, path); 371 } 372 for (AuditLogger logger : auditLoggers) { 373 if (logger instanceof HdfsAuditLogger) { 374 HdfsAuditLogger hdfsLogger = (HdfsAuditLogger) logger; 375 hdfsLogger.logAuditEvent(succeeded, ugi.toString(), addr, cmd, src, dst, 376 status, ugi, dtSecretManager); 377 } else { 378 logger.logAuditEvent(succeeded, ugi.toString(), addr, 379 cmd, src, dst, status); 380 } 381 } 382 } 383 384 /** 385 * Logger for audit events, noting successful FSNamesystem operations. Emits 386 * to FSNamesystem.audit at INFO. Each event causes a set of tab-separated 387 * <code>key=value</code> pairs to be written for the following properties: 388 * <code> 389 * ugi=<ugi in RPC> 390 * ip=<remote IP> 391 * cmd=<command> 392 * src=<src path> 393 * dst=<dst path (optional)> 394 * perm=<permissions (optional)> 395 * </code> 396 */ 397 public static final Log auditLog = LogFactory.getLog( 398 FSNamesystem.class.getName() + ".audit"); 399 400 static final int DEFAULT_MAX_CORRUPT_FILEBLOCKS_RETURNED = 100; 401 static int BLOCK_DELETION_INCREMENT = 1000; 402 private final boolean isPermissionEnabled; 403 private final UserGroupInformation fsOwner; 404 private final String fsOwnerShortUserName; 405 private final String supergroup; 406 private final boolean standbyShouldCheckpoint; 407 408 // Scan interval is not configurable. 409 private static final long DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL = 410 TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); 411 final DelegationTokenSecretManager dtSecretManager; 412 private final boolean alwaysUseDelegationTokensForTests; 413 414 private static final Step STEP_AWAITING_REPORTED_BLOCKS = 415 new Step(StepType.AWAITING_REPORTED_BLOCKS); 416 417 // Tracks whether the default audit logger is the only configured audit 418 // logger; this allows isAuditEnabled() to return false in case the 419 // underlying logger is disabled, and avoid some unnecessary work. 420 private final boolean isDefaultAuditLogger; 421 private final List<AuditLogger> auditLoggers; 422 423 /** The namespace tree. */ 424 FSDirectory dir; 425 private final BlockManager blockManager; 426 private final SnapshotManager snapshotManager; 427 private final CacheManager cacheManager; 428 private final DatanodeStatistics datanodeStatistics; 429 430 // whether setStoragePolicy is allowed. 431 private final boolean isStoragePolicyEnabled; 432 433 private String nameserviceId; 434 435 private volatile RollingUpgradeInfo rollingUpgradeInfo = null; 436 /** 437 * A flag that indicates whether the checkpointer should checkpoint a rollback 438 * fsimage. The edit log tailer sets this flag. The checkpoint will create a 439 * rollback fsimage if the flag is true, and then change the flag to false. 440 */ 441 private volatile boolean needRollbackFsImage; 442 443 // Block pool ID used by this namenode 444 private String blockPoolId; 445 446 final LeaseManager leaseManager = new LeaseManager(this); 447 448 volatile Daemon smmthread = null; // SafeModeMonitor thread 449 450 Daemon nnrmthread = null; // NamenodeResourceMonitor thread 451 452 Daemon nnEditLogRoller = null; // NameNodeEditLogRoller thread 453 454 // A daemon to periodically clean up corrupt lazyPersist files 455 // from the name space. 456 Daemon lazyPersistFileScrubber = null; 457 /** 458 * When an active namenode will roll its own edit log, in # edits 459 */ 460 private final long editLogRollerThreshold; 461 /** 462 * Check interval of an active namenode's edit log roller thread 463 */ 464 private final int editLogRollerInterval; 465 466 /** 467 * How frequently we scan and unlink corrupt lazyPersist files. 468 * (In seconds) 469 */ 470 private final int lazyPersistFileScrubIntervalSec; 471 472 private volatile boolean hasResourcesAvailable = false; 473 private volatile boolean fsRunning = true; 474 475 /** The start time of the namesystem. */ 476 private final long startTime = now(); 477 478 /** The interval of namenode checking for the disk space availability */ 479 private final long resourceRecheckInterval; 480 481 // The actual resource checker instance. 482 NameNodeResourceChecker nnResourceChecker; 483 484 private final FsServerDefaults serverDefaults; 485 private final boolean supportAppends; 486 private final ReplaceDatanodeOnFailure dtpReplaceDatanodeOnFailure; 487 488 private volatile SafeModeInfo safeMode; // safe mode information 489 490 private final long maxFsObjects; // maximum number of fs objects 491 492 private final long minBlockSize; // minimum block size 493 private final long maxBlocksPerFile; // maximum # of blocks per file 494 495 /** 496 * The global generation stamp for legacy blocks with randomly 497 * generated block IDs. 498 */ 499 private final GenerationStamp generationStampV1 = new GenerationStamp(); 500 501 /** 502 * The global generation stamp for this file system. 503 */ 504 private final GenerationStamp generationStampV2 = new GenerationStamp(); 505 506 /** 507 * The value of the generation stamp when the first switch to sequential 508 * block IDs was made. Blocks with generation stamps below this value 509 * have randomly allocated block IDs. Blocks with generation stamps above 510 * this value had sequentially allocated block IDs. Read from the fsImage 511 * (or initialized as an offset from the V1 (legacy) generation stamp on 512 * upgrade). 513 */ 514 private long generationStampV1Limit = 515 GenerationStamp.GRANDFATHER_GENERATION_STAMP; 516 517 /** 518 * The global block ID space for this file system. 519 */ 520 @VisibleForTesting 521 private final SequentialBlockIdGenerator blockIdGenerator; 522 523 // precision of access times. 524 private final long accessTimePrecision; 525 526 /** Lock to protect FSNamesystem. */ 527 private final FSNamesystemLock fsLock; 528 529 /** 530 * Checkpoint lock to protect FSNamesystem modification on standby NNs. 531 * Unlike fsLock, it does not affect block updates. On active NNs, this lock 532 * does not provide proper protection, because there are operations that 533 * modify both block and name system state. Even on standby, fsLock is 534 * used when block state changes need to be blocked. 535 */ 536 private final ReentrantLock cpLock; 537 538 /** 539 * Used when this NN is in standby state to read from the shared edit log. 540 */ 541 private EditLogTailer editLogTailer = null; 542 543 /** 544 * Used when this NN is in standby state to perform checkpoints. 545 */ 546 private StandbyCheckpointer standbyCheckpointer; 547 548 /** 549 * Reference to the NN's HAContext object. This is only set once 550 * {@link #startCommonServices(Configuration, HAContext)} is called. 551 */ 552 private HAContext haContext; 553 554 private final boolean haEnabled; 555 556 /** flag indicating whether replication queues have been initialized */ 557 boolean initializedReplQueues = false; 558 559 /** 560 * Whether the namenode is in the middle of starting the active service 561 */ 562 private volatile boolean startingActiveService = false; 563 564 private INodeId inodeId; 565 566 private final RetryCache retryCache; 567 568 private final NNConf nnConf; 569 570 private KeyProviderCryptoExtension provider = null; 571 private KeyProvider.Options providerOptions = null; 572 573 private final CryptoCodec codec; 574 575 private volatile boolean imageLoaded = false; 576 private final Condition cond; 577 578 private final FSImage fsImage; 579 580 private final TopConf topConf; 581 private TopMetrics topMetrics; 582 583 /** 584 * Notify that loading of this FSDirectory is complete, and 585 * it is imageLoaded for use 586 */ 587 void imageLoadComplete() { 588 Preconditions.checkState(!imageLoaded, "FSDirectory already loaded"); 589 setImageLoaded(); 590 } 591 592 void setImageLoaded() { 593 if(imageLoaded) return; 594 writeLock(); 595 try { 596 setImageLoaded(true); 597 dir.markNameCacheInitialized(); 598 cond.signalAll(); 599 } finally { 600 writeUnlock(); 601 } 602 } 603 604 //This is for testing purposes only 605 @VisibleForTesting 606 boolean isImageLoaded() { 607 return imageLoaded; 608 } 609 610 // exposed for unit tests 611 protected void setImageLoaded(boolean flag) { 612 imageLoaded = flag; 613 } 614 615 private AuthorizationProvider authzProvider; 616 617 /** 618 * Block until the object is imageLoaded to be used. 619 */ 620 void waitForLoadingFSImage() { 621 if (!imageLoaded) { 622 writeLock(); 623 try { 624 while (!imageLoaded) { 625 try { 626 cond.await(5000, TimeUnit.MILLISECONDS); 627 } catch (InterruptedException ignored) { 628 } 629 } 630 } finally { 631 writeUnlock(); 632 } 633 } 634 } 635 636 /** 637 * Set the last allocated inode id when fsimage or editlog is loaded. 638 */ 639 public void resetLastInodeId(long newValue) throws IOException { 640 try { 641 inodeId.skipTo(newValue); 642 } catch(IllegalStateException ise) { 643 throw new IOException(ise); 644 } 645 } 646 647 /** Should only be used for tests to reset to any value */ 648 void resetLastInodeIdWithoutChecking(long newValue) { 649 inodeId.setCurrentValue(newValue); 650 } 651 652 /** @return the last inode ID. */ 653 public long getLastInodeId() { 654 return inodeId.getCurrentValue(); 655 } 656 657 /** Allocate a new inode ID. */ 658 public long allocateNewInodeId() { 659 return inodeId.nextValue(); 660 } 661 662 /** 663 * Clear all loaded data 664 */ 665 void clear() { 666 dir.reset(); 667 dtSecretManager.reset(); 668 generationStampV1.setCurrentValue(GenerationStamp.LAST_RESERVED_STAMP); 669 generationStampV2.setCurrentValue(GenerationStamp.LAST_RESERVED_STAMP); 670 blockIdGenerator.setCurrentValue( 671 SequentialBlockIdGenerator.LAST_RESERVED_BLOCK_ID); 672 generationStampV1Limit = GenerationStamp.GRANDFATHER_GENERATION_STAMP; 673 leaseManager.removeAllLeases(); 674 inodeId.setCurrentValue(INodeId.LAST_RESERVED_ID); 675 snapshotManager.clearSnapshottableDirs(); 676 cacheManager.clear(); 677 setImageLoaded(false); 678 blockManager.clear(); 679 } 680 681 @VisibleForTesting 682 LeaseManager getLeaseManager() { 683 return leaseManager; 684 } 685 686 boolean isHaEnabled() { 687 return haEnabled; 688 } 689 690 /** 691 * Check the supplied configuration for correctness. 692 * @param conf Supplies the configuration to validate. 693 * @throws IOException if the configuration could not be queried. 694 * @throws IllegalArgumentException if the configuration is invalid. 695 */ 696 private static void checkConfiguration(Configuration conf) 697 throws IOException { 698 699 final Collection<URI> namespaceDirs = 700 FSNamesystem.getNamespaceDirs(conf); 701 final Collection<URI> editsDirs = 702 FSNamesystem.getNamespaceEditsDirs(conf); 703 final Collection<URI> requiredEditsDirs = 704 FSNamesystem.getRequiredNamespaceEditsDirs(conf); 705 final Collection<URI> sharedEditsDirs = 706 FSNamesystem.getSharedEditsDirs(conf); 707 708 for (URI u : requiredEditsDirs) { 709 if (u.toString().compareTo( 710 DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_DEFAULT) == 0) { 711 continue; 712 } 713 714 // Each required directory must also be in editsDirs or in 715 // sharedEditsDirs. 716 if (!editsDirs.contains(u) && 717 !sharedEditsDirs.contains(u)) { 718 throw new IllegalArgumentException( 719 "Required edits directory " + u.toString() + " not present in " + 720 DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY + ". " + 721 DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_KEY + "=" + 722 editsDirs.toString() + "; " + 723 DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_REQUIRED_KEY + "=" + 724 requiredEditsDirs.toString() + ". " + 725 DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY + "=" + 726 sharedEditsDirs.toString() + "."); 727 } 728 } 729 730 if (namespaceDirs.size() == 1) { 731 LOG.warn("Only one image storage directory (" 732 + DFS_NAMENODE_NAME_DIR_KEY + ") configured. Beware of data loss" 733 + " due to lack of redundant storage directories!"); 734 } 735 if (editsDirs.size() == 1) { 736 LOG.warn("Only one namespace edits storage directory (" 737 + DFS_NAMENODE_EDITS_DIR_KEY + ") configured. Beware of data loss" 738 + " due to lack of redundant storage directories!"); 739 } 740 } 741 742 /** 743 * Instantiates an FSNamesystem loaded from the image and edits 744 * directories specified in the passed Configuration. 745 * 746 * @param conf the Configuration which specifies the storage directories 747 * from which to load 748 * @return an FSNamesystem which contains the loaded namespace 749 * @throws IOException if loading fails 750 */ 751 static FSNamesystem loadFromDisk(Configuration conf) throws IOException { 752 753 checkConfiguration(conf); 754 FSImage fsImage = new FSImage(conf, 755 FSNamesystem.getNamespaceDirs(conf), 756 FSNamesystem.getNamespaceEditsDirs(conf)); 757 FSNamesystem namesystem = new FSNamesystem(conf, fsImage, false); 758 StartupOption startOpt = NameNode.getStartupOption(conf); 759 if (startOpt == StartupOption.RECOVER) { 760 namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER); 761 } 762 763 long loadStart = now(); 764 try { 765 namesystem.loadFSImage(startOpt); 766 } catch (IOException ioe) { 767 LOG.warn("Encountered exception loading fsimage", ioe); 768 fsImage.close(); 769 throw ioe; 770 } 771 long timeTakenToLoadFSImage = now() - loadStart; 772 LOG.info("Finished loading FSImage in " + timeTakenToLoadFSImage + " msecs"); 773 NameNodeMetrics nnMetrics = NameNode.getNameNodeMetrics(); 774 if (nnMetrics != null) { 775 nnMetrics.setFsImageLoadTime((int) timeTakenToLoadFSImage); 776 } 777 return namesystem; 778 } 779 780 FSNamesystem(Configuration conf, FSImage fsImage) throws IOException { 781 this(conf, fsImage, false); 782 } 783 784 /** 785 * Create an FSNamesystem associated with the specified image. 786 * 787 * Note that this does not load any data off of disk -- if you would 788 * like that behavior, use {@link #loadFromDisk(Configuration)} 789 * 790 * @param conf configuration 791 * @param fsImage The FSImage to associate with 792 * @param ignoreRetryCache Whether or not should ignore the retry cache setup 793 * step. For Secondary NN this should be set to true. 794 * @throws IOException on bad configuration 795 */ 796 FSNamesystem(Configuration conf, FSImage fsImage, boolean ignoreRetryCache) 797 throws IOException { 798 provider = DFSUtil.createKeyProviderCryptoExtension(conf); 799 if (provider == null) { 800 LOG.info("No KeyProvider found."); 801 } else { 802 LOG.info("Found KeyProvider: " + provider.toString()); 803 } 804 providerOptions = KeyProvider.options(conf); 805 this.codec = CryptoCodec.getInstance(conf); 806 if (conf.getBoolean(DFS_NAMENODE_AUDIT_LOG_ASYNC_KEY, 807 DFS_NAMENODE_AUDIT_LOG_ASYNC_DEFAULT)) { 808 LOG.info("Enabling async auditlog"); 809 enableAsyncAuditLog(); 810 } 811 boolean fair = conf.getBoolean("dfs.namenode.fslock.fair", true); 812 LOG.info("fsLock is fair:" + fair); 813 fsLock = new FSNamesystemLock(fair); 814 cond = fsLock.writeLock().newCondition(); 815 cpLock = new ReentrantLock(); 816 817 this.fsImage = fsImage; 818 try { 819 resourceRecheckInterval = conf.getLong( 820 DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_KEY, 821 DFS_NAMENODE_RESOURCE_CHECK_INTERVAL_DEFAULT); 822 823 this.blockManager = new BlockManager(this, this, conf); 824 this.datanodeStatistics = blockManager.getDatanodeManager().getDatanodeStatistics(); 825 this.blockIdGenerator = new SequentialBlockIdGenerator(this.blockManager); 826 827 this.isStoragePolicyEnabled = 828 conf.getBoolean(DFS_STORAGE_POLICY_ENABLED_KEY, 829 DFS_STORAGE_POLICY_ENABLED_DEFAULT); 830 831 this.fsOwner = UserGroupInformation.getCurrentUser(); 832 this.fsOwnerShortUserName = fsOwner.getShortUserName(); 833 this.supergroup = conf.get(DFS_PERMISSIONS_SUPERUSERGROUP_KEY, 834 DFS_PERMISSIONS_SUPERUSERGROUP_DEFAULT); 835 this.isPermissionEnabled = conf.getBoolean(DFS_PERMISSIONS_ENABLED_KEY, 836 DFS_PERMISSIONS_ENABLED_DEFAULT); 837 LOG.info("fsOwner = " + fsOwner); 838 LOG.info("supergroup = " + supergroup); 839 LOG.info("isPermissionEnabled = " + isPermissionEnabled); 840 841 // block allocation has to be persisted in HA using a shared edits directory 842 // so that the standby has up-to-date namespace information 843 nameserviceId = DFSUtil.getNamenodeNameServiceId(conf); 844 this.haEnabled = HAUtil.isHAEnabled(conf, nameserviceId); 845 846 // Sanity check the HA-related config. 847 if (nameserviceId != null) { 848 LOG.info("Determined nameservice ID: " + nameserviceId); 849 } 850 LOG.info("HA Enabled: " + haEnabled); 851 if (!haEnabled && HAUtil.usesSharedEditsDir(conf)) { 852 LOG.warn("Configured NNs:\n" + DFSUtil.nnAddressesAsString(conf)); 853 throw new IOException("Invalid configuration: a shared edits dir " + 854 "must not be specified if HA is not enabled."); 855 } 856 857 // Get the checksum type from config 858 String checksumTypeStr = conf.get(DFS_CHECKSUM_TYPE_KEY, DFS_CHECKSUM_TYPE_DEFAULT); 859 DataChecksum.Type checksumType; 860 try { 861 checksumType = DataChecksum.Type.valueOf(checksumTypeStr); 862 } catch (IllegalArgumentException iae) { 863 throw new IOException("Invalid checksum type in " 864 + DFS_CHECKSUM_TYPE_KEY + ": " + checksumTypeStr); 865 } 866 867 this.serverDefaults = new FsServerDefaults( 868 conf.getLongBytes(DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE_DEFAULT), 869 conf.getInt(DFS_BYTES_PER_CHECKSUM_KEY, DFS_BYTES_PER_CHECKSUM_DEFAULT), 870 conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY, DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT), 871 (short) conf.getInt(DFS_REPLICATION_KEY, DFS_REPLICATION_DEFAULT), 872 conf.getInt(IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT), 873 conf.getBoolean(DFS_ENCRYPT_DATA_TRANSFER_KEY, DFS_ENCRYPT_DATA_TRANSFER_DEFAULT), 874 conf.getLong(FS_TRASH_INTERVAL_KEY, FS_TRASH_INTERVAL_DEFAULT), 875 checksumType); 876 877 this.maxFsObjects = conf.getLong(DFS_NAMENODE_MAX_OBJECTS_KEY, 878 DFS_NAMENODE_MAX_OBJECTS_DEFAULT); 879 880 this.minBlockSize = conf.getLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, 881 DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_DEFAULT); 882 this.maxBlocksPerFile = conf.getLong(DFSConfigKeys.DFS_NAMENODE_MAX_BLOCKS_PER_FILE_KEY, 883 DFSConfigKeys.DFS_NAMENODE_MAX_BLOCKS_PER_FILE_DEFAULT); 884 this.accessTimePrecision = conf.getLong(DFS_NAMENODE_ACCESSTIME_PRECISION_KEY, 885 DFS_NAMENODE_ACCESSTIME_PRECISION_DEFAULT); 886 this.supportAppends = conf.getBoolean(DFS_SUPPORT_APPEND_KEY, DFS_SUPPORT_APPEND_DEFAULT); 887 LOG.info("Append Enabled: " + supportAppends); 888 889 this.dtpReplaceDatanodeOnFailure = ReplaceDatanodeOnFailure.get(conf); 890 891 this.standbyShouldCheckpoint = conf.getBoolean( 892 DFS_HA_STANDBY_CHECKPOINTS_KEY, DFS_HA_STANDBY_CHECKPOINTS_DEFAULT); 893 // # edit autoroll threshold is a multiple of the checkpoint threshold 894 this.editLogRollerThreshold = (long) 895 (conf.getFloat( 896 DFS_NAMENODE_EDIT_LOG_AUTOROLL_MULTIPLIER_THRESHOLD, 897 DFS_NAMENODE_EDIT_LOG_AUTOROLL_MULTIPLIER_THRESHOLD_DEFAULT) * 898 conf.getLong( 899 DFS_NAMENODE_CHECKPOINT_TXNS_KEY, 900 DFS_NAMENODE_CHECKPOINT_TXNS_DEFAULT)); 901 this.editLogRollerInterval = conf.getInt( 902 DFS_NAMENODE_EDIT_LOG_AUTOROLL_CHECK_INTERVAL_MS, 903 DFS_NAMENODE_EDIT_LOG_AUTOROLL_CHECK_INTERVAL_MS_DEFAULT); 904 this.inodeId = new INodeId(); 905 906 this.lazyPersistFileScrubIntervalSec = conf.getInt( 907 DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC, 908 DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC_DEFAULT); 909 910 if (this.lazyPersistFileScrubIntervalSec == 0) { 911 throw new IllegalArgumentException( 912 DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC + " must be non-zero."); 913 } 914 915 // For testing purposes, allow the DT secret manager to be started regardless 916 // of whether security is enabled. 917 alwaysUseDelegationTokensForTests = conf.getBoolean( 918 DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, 919 DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_DEFAULT); 920 921 this.dtSecretManager = createDelegationTokenSecretManager(conf); 922 this.dir = new FSDirectory(this, conf); 923 this.snapshotManager = new SnapshotManager(dir); 924 this.cacheManager = new CacheManager(this, conf, blockManager); 925 this.safeMode = new SafeModeInfo(conf); 926 this.topConf = new TopConf(conf); 927 this.auditLoggers = initAuditLoggers(conf); 928 this.isDefaultAuditLogger = auditLoggers.size() == 1 && 929 auditLoggers.get(0) instanceof DefaultAuditLogger; 930 this.retryCache = ignoreRetryCache ? null : initRetryCache(conf); 931 this.nnConf = new NNConf(conf); 932 } catch(IOException e) { 933 LOG.error(getClass().getSimpleName() + " initialization failed.", e); 934 close(); 935 throw e; 936 } catch (RuntimeException re) { 937 LOG.error(getClass().getSimpleName() + " initialization failed.", re); 938 close(); 939 throw re; 940 } 941 } 942 943 @VisibleForTesting 944 public List<AuditLogger> getAuditLoggers() { 945 return auditLoggers; 946 } 947 948 @VisibleForTesting 949 public RetryCache getRetryCache() { 950 return retryCache; 951 } 952 953 void lockRetryCache() { 954 if (retryCache != null) { 955 retryCache.lock(); 956 } 957 } 958 959 void unlockRetryCache() { 960 if (retryCache != null) { 961 retryCache.unlock(); 962 } 963 } 964 965 /** Whether or not retry cache is enabled */ 966 boolean hasRetryCache() { 967 return retryCache != null; 968 } 969 970 void addCacheEntryWithPayload(byte[] clientId, int callId, Object payload) { 971 if (retryCache != null) { 972 retryCache.addCacheEntryWithPayload(clientId, callId, payload); 973 } 974 } 975 976 void addCacheEntry(byte[] clientId, int callId) { 977 if (retryCache != null) { 978 retryCache.addCacheEntry(clientId, callId); 979 } 980 } 981 982 @VisibleForTesting 983 public KeyProviderCryptoExtension getProvider() { 984 return provider; 985 } 986 987 @VisibleForTesting 988 static RetryCache initRetryCache(Configuration conf) { 989 boolean enable = conf.getBoolean(DFS_NAMENODE_ENABLE_RETRY_CACHE_KEY, 990 DFS_NAMENODE_ENABLE_RETRY_CACHE_DEFAULT); 991 LOG.info("Retry cache on namenode is " + (enable ? "enabled" : "disabled")); 992 if (enable) { 993 float heapPercent = conf.getFloat( 994 DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_KEY, 995 DFS_NAMENODE_RETRY_CACHE_HEAP_PERCENT_DEFAULT); 996 long entryExpiryMillis = conf.getLong( 997 DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_KEY, 998 DFS_NAMENODE_RETRY_CACHE_EXPIRYTIME_MILLIS_DEFAULT); 999 LOG.info("Retry cache will use " + heapPercent 1000 + " of total heap and retry cache entry expiry time is " 1001 + entryExpiryMillis + " millis"); 1002 long entryExpiryNanos = entryExpiryMillis * 1000 * 1000; 1003 return new RetryCache("NameNodeRetryCache", heapPercent, 1004 entryExpiryNanos); 1005 } 1006 return null; 1007 } 1008 1009 private List<AuditLogger> initAuditLoggers(Configuration conf) { 1010 // Initialize the custom access loggers if configured. 1011 Collection<String> alClasses = conf.getStringCollection(DFS_NAMENODE_AUDIT_LOGGERS_KEY); 1012 List<AuditLogger> auditLoggers = Lists.newArrayList(); 1013 if (alClasses != null && !alClasses.isEmpty()) { 1014 for (String className : alClasses) { 1015 try { 1016 AuditLogger logger; 1017 if (DFS_NAMENODE_DEFAULT_AUDIT_LOGGER_NAME.equals(className)) { 1018 logger = new DefaultAuditLogger(); 1019 } else { 1020 logger = (AuditLogger) Class.forName(className).newInstance(); 1021 } 1022 logger.initialize(conf); 1023 auditLoggers.add(logger); 1024 } catch (RuntimeException re) { 1025 throw re; 1026 } catch (Exception e) { 1027 throw new RuntimeException(e); 1028 } 1029 } 1030 } 1031 1032 // Make sure there is at least one logger installed. 1033 if (auditLoggers.isEmpty()) { 1034 auditLoggers.add(new DefaultAuditLogger()); 1035 } 1036 1037 // Add audit logger to calculate top users 1038 if (topConf.isEnabled) { 1039 topMetrics = new TopMetrics(conf, topConf.nntopReportingPeriodsMs); 1040 auditLoggers.add(new TopAuditLogger(topMetrics)); 1041 } 1042 1043 return Collections.unmodifiableList(auditLoggers); 1044 } 1045 1046 private void loadFSImage(StartupOption startOpt) throws IOException { 1047 final FSImage fsImage = getFSImage(); 1048 1049 // format before starting up if requested 1050 if (startOpt == StartupOption.FORMAT) { 1051 1052 fsImage.format(this, fsImage.getStorage().determineClusterId());// reuse current id 1053 1054 startOpt = StartupOption.REGULAR; 1055 } 1056 boolean success = false; 1057 writeLock(); 1058 try { 1059 // We shouldn't be calling saveNamespace if we've come up in standby state. 1060 MetaRecoveryContext recovery = startOpt.createRecoveryContext(); 1061 final boolean staleImage 1062 = fsImage.recoverTransitionRead(startOpt, this, recovery); 1063 if (RollingUpgradeStartupOption.ROLLBACK.matches(startOpt) || 1064 RollingUpgradeStartupOption.DOWNGRADE.matches(startOpt)) { 1065 rollingUpgradeInfo = null; 1066 } 1067 final boolean needToSave = staleImage && !haEnabled && !isRollingUpgrade(); 1068 LOG.info("Need to save fs image? " + needToSave 1069 + " (staleImage=" + staleImage + ", haEnabled=" + haEnabled 1070 + ", isRollingUpgrade=" + isRollingUpgrade() + ")"); 1071 if (needToSave) { 1072 fsImage.saveNamespace(this); 1073 } else { 1074 updateStorageVersionForRollingUpgrade(fsImage.getLayoutVersion(), 1075 startOpt); 1076 // No need to save, so mark the phase done. 1077 StartupProgress prog = NameNode.getStartupProgress(); 1078 prog.beginPhase(Phase.SAVING_CHECKPOINT); 1079 prog.endPhase(Phase.SAVING_CHECKPOINT); 1080 } 1081 // This will start a new log segment and write to the seen_txid file, so 1082 // we shouldn't do it when coming up in standby state 1083 if (!haEnabled || (haEnabled && startOpt == StartupOption.UPGRADE) 1084 || (haEnabled && startOpt == StartupOption.UPGRADEONLY)) { 1085 fsImage.openEditLogForWrite(); 1086 } 1087 success = true; 1088 } finally { 1089 if (!success) { 1090 fsImage.close(); 1091 } 1092 writeUnlock(); 1093 } 1094 imageLoadComplete(); 1095 } 1096 1097 private void updateStorageVersionForRollingUpgrade(final long layoutVersion, 1098 StartupOption startOpt) throws IOException { 1099 boolean rollingStarted = RollingUpgradeStartupOption.STARTED 1100 .matches(startOpt) && layoutVersion > HdfsConstants 1101 .NAMENODE_LAYOUT_VERSION; 1102 boolean rollingRollback = RollingUpgradeStartupOption.ROLLBACK 1103 .matches(startOpt); 1104 if (rollingRollback || rollingStarted) { 1105 fsImage.updateStorageVersion(); 1106 } 1107 } 1108 1109 private void startSecretManager() { 1110 if (dtSecretManager != null) { 1111 try { 1112 dtSecretManager.startThreads(); 1113 } catch (IOException e) { 1114 // Inability to start secret manager 1115 // can't be recovered from. 1116 throw new RuntimeException(e); 1117 } 1118 } 1119 } 1120 1121 private void startSecretManagerIfNecessary() { 1122 boolean shouldRun = shouldUseDelegationTokens() && 1123 !isInSafeMode() && getEditLog().isOpenForWrite(); 1124 boolean running = dtSecretManager.isRunning(); 1125 if (shouldRun && !running) { 1126 startSecretManager(); 1127 } 1128 } 1129 1130 private void stopSecretManager() { 1131 if (dtSecretManager != null) { 1132 dtSecretManager.stopThreads(); 1133 } 1134 } 1135 1136 /** 1137 * Start services common to both active and standby states 1138 */ 1139 void startCommonServices(Configuration conf, HAContext haContext) throws IOException { 1140 this.registerMBean(); // register the MBean for the FSNamesystemState 1141 writeLock(); 1142 this.haContext = haContext; 1143 try { 1144 nnResourceChecker = new NameNodeResourceChecker(conf); 1145 checkAvailableResources(); 1146 assert safeMode != null && !isPopulatingReplQueues(); 1147 StartupProgress prog = NameNode.getStartupProgress(); 1148 prog.beginPhase(Phase.SAFEMODE); 1149 prog.setTotal(Phase.SAFEMODE, STEP_AWAITING_REPORTED_BLOCKS, 1150 getCompleteBlocksTotal()); 1151 setBlockTotal(); 1152 blockManager.activate(conf); 1153 } finally { 1154 writeUnlock(); 1155 } 1156 1157 registerMXBean(); 1158 DefaultMetricsSystem.instance().register(this); 1159 snapshotManager.registerMXBean(); 1160 authzProvider = ReflectionUtils.newInstance(conf.getClass( 1161 DFS_NAMENODE_AUTHORIZATION_PROVIDER_KEY, 1162 DefaultAuthorizationProvider.class, 1163 AuthorizationProvider.class), conf); 1164 authzProvider.start(); 1165 AuthorizationProvider.set(authzProvider); 1166 snapshotManager.initAuthorizationProvider(); 1167 } 1168 1169 /** 1170 * Stop services common to both active and standby states 1171 */ 1172 void stopCommonServices() { 1173 writeLock(); 1174 if (authzProvider != null) { 1175 // format does not start common services 1176 authzProvider.stop(); 1177 } 1178 try { 1179 if (blockManager != null) blockManager.close(); 1180 } finally { 1181 writeUnlock(); 1182 } 1183 RetryCache.clear(retryCache); 1184 } 1185 1186 /** 1187 * Start services required in active state 1188 * @throws IOException 1189 */ 1190 void startActiveServices() throws IOException { 1191 startingActiveService = true; 1192 LOG.info("Starting services required for active state"); 1193 writeLock(); 1194 try { 1195 FSEditLog editLog = getFSImage().getEditLog(); 1196 1197 if (!editLog.isOpenForWrite()) { 1198 // During startup, we're already open for write during initialization. 1199 editLog.initJournalsForWrite(); 1200 // May need to recover 1201 editLog.recoverUnclosedStreams(); 1202 1203 LOG.info("Catching up to latest edits from old active before " + 1204 "taking over writer role in edits logs"); 1205 editLogTailer.catchupDuringFailover(); 1206 1207 blockManager.setPostponeBlocksFromFuture(false); 1208 blockManager.getDatanodeManager().markAllDatanodesStale(); 1209 blockManager.clearQueues(); 1210 blockManager.processAllPendingDNMessages(); 1211 1212 // Only need to re-process the queue, If not in SafeMode. 1213 if (!isInSafeMode()) { 1214 LOG.info("Reprocessing replication and invalidation queues"); 1215 initializeReplQueues(); 1216 } 1217 1218 if (LOG.isDebugEnabled()) { 1219 LOG.debug("NameNode metadata after re-processing " + 1220 "replication and invalidation queues during failover:\n" + 1221 metaSaveAsString()); 1222 } 1223 1224 long nextTxId = getFSImage().getLastAppliedTxId() + 1; 1225 LOG.info("Will take over writing edit logs at txnid " + 1226 nextTxId); 1227 editLog.setNextTxId(nextTxId); 1228 1229 getFSImage().editLog.openForWrite(); 1230 } 1231 1232 // Enable quota checks. 1233 dir.enableQuotaChecks(); 1234 if (haEnabled) { 1235 // Renew all of the leases before becoming active. 1236 // This is because, while we were in standby mode, 1237 // the leases weren't getting renewed on this NN. 1238 // Give them all a fresh start here. 1239 leaseManager.renewAllLeases(); 1240 } 1241 leaseManager.startMonitor(); 1242 startSecretManagerIfNecessary(); 1243 1244 //ResourceMonitor required only at ActiveNN. See HDFS-2914 1245 this.nnrmthread = new Daemon(new NameNodeResourceMonitor()); 1246 nnrmthread.start(); 1247 1248 nnEditLogRoller = new Daemon(new NameNodeEditLogRoller( 1249 editLogRollerThreshold, editLogRollerInterval)); 1250 nnEditLogRoller.start(); 1251 1252 if (lazyPersistFileScrubIntervalSec > 0) { 1253 lazyPersistFileScrubber = new Daemon(new LazyPersistFileScrubber( 1254 lazyPersistFileScrubIntervalSec)); 1255 lazyPersistFileScrubber.start(); 1256 } 1257 1258 cacheManager.startMonitorThread(); 1259 blockManager.getDatanodeManager().setShouldSendCachingCommands(true); 1260 } finally { 1261 startingActiveService = false; 1262 checkSafeMode(); 1263 writeUnlock(); 1264 } 1265 } 1266 1267 /** 1268 * Initialize replication queues. 1269 */ 1270 private void initializeReplQueues() { 1271 LOG.info("initializing replication queues"); 1272 blockManager.processMisReplicatedBlocks(); 1273 initializedReplQueues = true; 1274 } 1275 1276 private boolean inActiveState() { 1277 return haContext != null && 1278 haContext.getState().getServiceState() == HAServiceState.ACTIVE; 1279 } 1280 1281 /** 1282 * @return Whether the namenode is transitioning to active state and is in the 1283 * middle of the {@link #startActiveServices()} 1284 */ 1285 public boolean inTransitionToActive() { 1286 return haEnabled && inActiveState() && startingActiveService; 1287 } 1288 1289 private boolean shouldUseDelegationTokens() { 1290 return UserGroupInformation.isSecurityEnabled() || 1291 alwaysUseDelegationTokensForTests; 1292 } 1293 1294 /** 1295 * Stop services required in active state 1296 */ 1297 void stopActiveServices() { 1298 LOG.info("Stopping services started for active state"); 1299 writeLock(); 1300 try { 1301 stopSecretManager(); 1302 leaseManager.stopMonitor(); 1303 if (nnrmthread != null) { 1304 ((NameNodeResourceMonitor) nnrmthread.getRunnable()).stopMonitor(); 1305 nnrmthread.interrupt(); 1306 } 1307 if (nnEditLogRoller != null) { 1308 ((NameNodeEditLogRoller)nnEditLogRoller.getRunnable()).stop(); 1309 nnEditLogRoller.interrupt(); 1310 } 1311 if (lazyPersistFileScrubber != null) { 1312 ((LazyPersistFileScrubber) lazyPersistFileScrubber.getRunnable()).stop(); 1313 lazyPersistFileScrubber.interrupt(); 1314 } 1315 if (dir != null && getFSImage() != null) { 1316 if (getFSImage().editLog != null) { 1317 getFSImage().editLog.close(); 1318 } 1319 // Update the fsimage with the last txid that we wrote 1320 // so that the tailer starts from the right spot. 1321 getFSImage().updateLastAppliedTxIdFromWritten(); 1322 } 1323 if (cacheManager != null) { 1324 cacheManager.stopMonitorThread(); 1325 cacheManager.clearDirectiveStats(); 1326 } 1327 blockManager.getDatanodeManager().clearPendingCachingCommands(); 1328 blockManager.getDatanodeManager().setShouldSendCachingCommands(false); 1329 // Don't want to keep replication queues when not in Active. 1330 blockManager.clearQueues(); 1331 initializedReplQueues = false; 1332 } finally { 1333 writeUnlock(); 1334 } 1335 } 1336 1337 /** 1338 * Start services required in standby state 1339 * 1340 * @throws IOException 1341 */ 1342 void startStandbyServices(final Configuration conf) throws IOException { 1343 LOG.info("Starting services required for standby state"); 1344 if (!getFSImage().editLog.isOpenForRead()) { 1345 // During startup, we're already open for read. 1346 getFSImage().editLog.initSharedJournalsForRead(); 1347 } 1348 1349 blockManager.setPostponeBlocksFromFuture(true); 1350 1351 // Disable quota checks while in standby. 1352 dir.disableQuotaChecks(); 1353 editLogTailer = new EditLogTailer(this, conf); 1354 editLogTailer.start(); 1355 if (standbyShouldCheckpoint) { 1356 standbyCheckpointer = new StandbyCheckpointer(conf, this); 1357 standbyCheckpointer.start(); 1358 } 1359 } 1360 1361 /** 1362 * Called when the NN is in Standby state and the editlog tailer tails the 1363 * OP_ROLLING_UPGRADE_START. 1364 */ 1365 void triggerRollbackCheckpoint() { 1366 setNeedRollbackFsImage(true); 1367 if (standbyCheckpointer != null) { 1368 standbyCheckpointer.triggerRollbackCheckpoint(); 1369 } 1370 } 1371 1372 /** 1373 * Called while the NN is in Standby state, but just about to be 1374 * asked to enter Active state. This cancels any checkpoints 1375 * currently being taken. 1376 */ 1377 void prepareToStopStandbyServices() throws ServiceFailedException { 1378 if (standbyCheckpointer != null) { 1379 standbyCheckpointer.cancelAndPreventCheckpoints( 1380 "About to leave standby state"); 1381 } 1382 } 1383 1384 /** Stop services required in standby state */ 1385 void stopStandbyServices() throws IOException { 1386 LOG.info("Stopping services started for standby state"); 1387 if (standbyCheckpointer != null) { 1388 standbyCheckpointer.stop(); 1389 } 1390 if (editLogTailer != null) { 1391 editLogTailer.stop(); 1392 } 1393 if (dir != null && getFSImage() != null && getFSImage().editLog != null) { 1394 getFSImage().editLog.close(); 1395 } 1396 } 1397 1398 @Override 1399 public void checkOperation(OperationCategory op) throws StandbyException { 1400 if (haContext != null) { 1401 // null in some unit tests 1402 haContext.checkOperation(op); 1403 } 1404 } 1405 1406 /** 1407 * @throws RetriableException 1408 * If 1) The NameNode is in SafeMode, 2) HA is enabled, and 3) 1409 * NameNode is in active state 1410 * @throws SafeModeException 1411 * Otherwise if NameNode is in SafeMode. 1412 */ 1413 private void checkNameNodeSafeMode(String errorMsg) 1414 throws RetriableException, SafeModeException { 1415 if (isInSafeMode()) { 1416 SafeModeException se = new SafeModeException(errorMsg, safeMode); 1417 if (haEnabled && haContext != null 1418 && haContext.getState().getServiceState() == HAServiceState.ACTIVE 1419 && shouldRetrySafeMode(this.safeMode)) { 1420 throw new RetriableException(se); 1421 } else { 1422 throw se; 1423 } 1424 } 1425 } 1426 1427 /** 1428 * We already know that the safemode is on. We will throw a RetriableException 1429 * if the safemode is not manual or caused by low resource. 1430 */ 1431 private boolean shouldRetrySafeMode(SafeModeInfo safeMode) { 1432 if (safeMode == null) { 1433 return false; 1434 } else { 1435 return !safeMode.isManual() && !safeMode.areResourcesLow(); 1436 } 1437 } 1438 1439 public static Collection<URI> getNamespaceDirs(Configuration conf) { 1440 return getStorageDirs(conf, DFS_NAMENODE_NAME_DIR_KEY); 1441 } 1442 1443 /** 1444 * Get all edits dirs which are required. If any shared edits dirs are 1445 * configured, these are also included in the set of required dirs. 1446 * 1447 * @param conf the HDFS configuration. 1448 * @return all required dirs. 1449 */ 1450 public static Collection<URI> getRequiredNamespaceEditsDirs(Configuration conf) { 1451 Set<URI> ret = new HashSet<URI>(); 1452 ret.addAll(getStorageDirs(conf, DFS_NAMENODE_EDITS_DIR_REQUIRED_KEY)); 1453 ret.addAll(getSharedEditsDirs(conf)); 1454 return ret; 1455 } 1456 1457 private static Collection<URI> getStorageDirs(Configuration conf, 1458 String propertyName) { 1459 Collection<String> dirNames = conf.getTrimmedStringCollection(propertyName); 1460 StartupOption startOpt = NameNode.getStartupOption(conf); 1461 if(startOpt == StartupOption.IMPORT) { 1462 // In case of IMPORT this will get rid of default directories 1463 // but will retain directories specified in hdfs-site.xml 1464 // When importing image from a checkpoint, the name-node can 1465 // start with empty set of storage directories. 1466 Configuration cE = new HdfsConfiguration(false); 1467 cE.addResource("core-default.xml"); 1468 cE.addResource("core-site.xml"); 1469 cE.addResource("hdfs-default.xml"); 1470 Collection<String> dirNames2 = cE.getTrimmedStringCollection(propertyName); 1471 dirNames.removeAll(dirNames2); 1472 if(dirNames.isEmpty()) 1473 LOG.warn("!!! WARNING !!!" + 1474 "\n\tThe NameNode currently runs without persistent storage." + 1475 "\n\tAny changes to the file system meta-data may be lost." + 1476 "\n\tRecommended actions:" + 1477 "\n\t\t- shutdown and restart NameNode with configured \"" 1478 + propertyName + "\" in hdfs-site.xml;" + 1479 "\n\t\t- use Backup Node as a persistent and up-to-date storage " + 1480 "of the file system meta-data."); 1481 } else if (dirNames.isEmpty()) { 1482 dirNames = Collections.singletonList( 1483 DFSConfigKeys.DFS_NAMENODE_EDITS_DIR_DEFAULT); 1484 } 1485 return Util.stringCollectionAsURIs(dirNames); 1486 } 1487 1488 /** 1489 * Return an ordered list of edits directories to write to. 1490 * The list is ordered such that all shared edits directories 1491 * are ordered before non-shared directories, and any duplicates 1492 * are removed. The order they are specified in the configuration 1493 * is retained. 1494 * @return Collection of shared edits directories. 1495 * @throws IOException if multiple shared edits directories are configured 1496 */ 1497 public static List<URI> getNamespaceEditsDirs(Configuration conf) 1498 throws IOException { 1499 return getNamespaceEditsDirs(conf, true); 1500 } 1501 1502 public static List<URI> getNamespaceEditsDirs(Configuration conf, 1503 boolean includeShared) 1504 throws IOException { 1505 // Use a LinkedHashSet so that order is maintained while we de-dup 1506 // the entries. 1507 LinkedHashSet<URI> editsDirs = new LinkedHashSet<URI>(); 1508 1509 if (includeShared) { 1510 List<URI> sharedDirs = getSharedEditsDirs(conf); 1511 1512 // Fail until multiple shared edits directories are supported (HDFS-2782) 1513 if (sharedDirs.size() > 1) { 1514 throw new IOException( 1515 "Multiple shared edits directories are not yet supported"); 1516 } 1517 1518 // First add the shared edits dirs. It's critical that the shared dirs 1519 // are added first, since JournalSet syncs them in the order they are listed, 1520 // and we need to make sure all edits are in place in the shared storage 1521 // before they are replicated locally. See HDFS-2874. 1522 for (URI dir : sharedDirs) { 1523 if (!editsDirs.add(dir)) { 1524 LOG.warn("Edits URI " + dir + " listed multiple times in " + 1525 DFS_NAMENODE_SHARED_EDITS_DIR_KEY + ". Ignoring duplicates."); 1526 } 1527 } 1528 } 1529 // Now add the non-shared dirs. 1530 for (URI dir : getStorageDirs(conf, DFS_NAMENODE_EDITS_DIR_KEY)) { 1531 if (!editsDirs.add(dir)) { 1532 LOG.warn("Edits URI " + dir + " listed multiple times in " + 1533 DFS_NAMENODE_SHARED_EDITS_DIR_KEY + " and " + 1534 DFS_NAMENODE_EDITS_DIR_KEY + ". Ignoring duplicates."); 1535 } 1536 } 1537 1538 if (editsDirs.isEmpty()) { 1539 // If this is the case, no edit dirs have been explicitly configured. 1540 // Image dirs are to be used for edits too. 1541 return Lists.newArrayList(getNamespaceDirs(conf)); 1542 } else { 1543 return Lists.newArrayList(editsDirs); 1544 } 1545 } 1546 1547 /** 1548 * Returns edit directories that are shared between primary and secondary. 1549 * @param conf configuration 1550 * @return collection of edit directories from {@code conf} 1551 */ 1552 public static List<URI> getSharedEditsDirs(Configuration conf) { 1553 // don't use getStorageDirs here, because we want an empty default 1554 // rather than the dir in /tmp 1555 Collection<String> dirNames = conf.getTrimmedStringCollection( 1556 DFS_NAMENODE_SHARED_EDITS_DIR_KEY); 1557 return Util.stringCollectionAsURIs(dirNames); 1558 } 1559 1560 @Override 1561 public void readLock() { 1562 this.fsLock.readLock().lock(); 1563 } 1564 @Override 1565 public void readUnlock() { 1566 this.fsLock.readLock().unlock(); 1567 } 1568 @Override 1569 public void writeLock() { 1570 this.fsLock.writeLock().lock(); 1571 } 1572 @Override 1573 public void writeLockInterruptibly() throws InterruptedException { 1574 this.fsLock.writeLock().lockInterruptibly(); 1575 } 1576 @Override 1577 public void writeUnlock() { 1578 this.fsLock.writeLock().unlock(); 1579 } 1580 @Override 1581 public boolean hasWriteLock() { 1582 return this.fsLock.isWriteLockedByCurrentThread(); 1583 } 1584 @Override 1585 public boolean hasReadLock() { 1586 return this.fsLock.getReadHoldCount() > 0 || hasWriteLock(); 1587 } 1588 1589 public int getReadHoldCount() { 1590 return this.fsLock.getReadHoldCount(); 1591 } 1592 1593 public int getWriteHoldCount() { 1594 return this.fsLock.getWriteHoldCount(); 1595 } 1596 1597 /** Lock the checkpoint lock */ 1598 public void cpLock() { 1599 this.cpLock.lock(); 1600 } 1601 1602 /** Lock the checkpoint lock interrupibly */ 1603 public void cpLockInterruptibly() throws InterruptedException { 1604 this.cpLock.lockInterruptibly(); 1605 } 1606 1607 /** Unlock the checkpoint lock */ 1608 public void cpUnlock() { 1609 this.cpLock.unlock(); 1610 } 1611 1612 1613 NamespaceInfo getNamespaceInfo() { 1614 readLock(); 1615 try { 1616 return unprotectedGetNamespaceInfo(); 1617 } finally { 1618 readUnlock(); 1619 } 1620 } 1621 1622 /** 1623 * Version of @see #getNamespaceInfo() that is not protected by a lock. 1624 */ 1625 NamespaceInfo unprotectedGetNamespaceInfo() { 1626 return new NamespaceInfo(getFSImage().getStorage().getNamespaceID(), 1627 getClusterId(), getBlockPoolId(), 1628 getFSImage().getStorage().getCTime()); 1629 } 1630 1631 /** 1632 * Close down this file system manager. 1633 * Causes heartbeat and lease daemons to stop; waits briefly for 1634 * them to finish, but a short timeout returns control back to caller. 1635 */ 1636 void close() { 1637 fsRunning = false; 1638 try { 1639 stopCommonServices(); 1640 if (smmthread != null) smmthread.interrupt(); 1641 } finally { 1642 // using finally to ensure we also wait for lease daemon 1643 try { 1644 stopActiveServices(); 1645 stopStandbyServices(); 1646 } catch (IOException ie) { 1647 } finally { 1648 IOUtils.cleanup(LOG, dir); 1649 IOUtils.cleanup(LOG, fsImage); 1650 } 1651 } 1652 } 1653 1654 @Override 1655 public boolean isRunning() { 1656 return fsRunning; 1657 } 1658 1659 @Override 1660 public boolean isInStandbyState() { 1661 if (haContext == null || haContext.getState() == null) { 1662 // We're still starting up. In this case, if HA is 1663 // on for the cluster, we always start in standby. Otherwise 1664 // start in active. 1665 return haEnabled; 1666 } 1667 1668 return HAServiceState.STANDBY == haContext.getState().getServiceState(); 1669 } 1670 1671 /** 1672 * Dump all metadata into specified file 1673 */ 1674 void metaSave(String filename) throws IOException { 1675 checkSuperuserPrivilege(); 1676 checkOperation(OperationCategory.UNCHECKED); 1677 writeLock(); 1678 try { 1679 checkOperation(OperationCategory.UNCHECKED); 1680 File file = new File(System.getProperty("hadoop.log.dir"), filename); 1681 PrintWriter out = new PrintWriter(new BufferedWriter( 1682 new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8))); 1683 metaSave(out); 1684 out.flush(); 1685 out.close(); 1686 } finally { 1687 writeUnlock(); 1688 } 1689 } 1690 1691 private void metaSave(PrintWriter out) { 1692 assert hasWriteLock(); 1693 long totalInodes = this.dir.totalInodes(); 1694 long totalBlocks = this.getBlocksTotal(); 1695 out.println(totalInodes + " files and directories, " + totalBlocks 1696 + " blocks = " + (totalInodes + totalBlocks) + " total"); 1697 1698 blockManager.metaSave(out); 1699 } 1700 1701 private String metaSaveAsString() { 1702 StringWriter sw = new StringWriter(); 1703 PrintWriter pw = new PrintWriter(sw); 1704 metaSave(pw); 1705 pw.flush(); 1706 return sw.toString(); 1707 } 1708 1709 1710 long getDefaultBlockSize() { 1711 return serverDefaults.getBlockSize(); 1712 } 1713 1714 FsServerDefaults getServerDefaults() throws StandbyException { 1715 checkOperation(OperationCategory.READ); 1716 return serverDefaults; 1717 } 1718 1719 long getAccessTimePrecision() { 1720 return accessTimePrecision; 1721 } 1722 1723 private boolean isAccessTimeSupported() { 1724 return accessTimePrecision > 0; 1725 } 1726 1727 ///////////////////////////////////////////////////////// 1728 // 1729 // These methods are called by HadoopFS clients 1730 // 1731 ///////////////////////////////////////////////////////// 1732 /** 1733 * Set permissions for an existing file. 1734 * @throws IOException 1735 */ 1736 void setPermission(String src, FsPermission permission) 1737 throws AccessControlException, FileNotFoundException, SafeModeException, 1738 UnresolvedLinkException, IOException { 1739 try { 1740 setPermissionInt(src, permission); 1741 } catch (AccessControlException e) { 1742 logAuditEvent(false, "setPermission", src); 1743 throw e; 1744 } 1745 } 1746 1747 private void setPermissionInt(final String srcArg, FsPermission permission) 1748 throws AccessControlException, FileNotFoundException, SafeModeException, 1749 UnresolvedLinkException, IOException { 1750 String src = srcArg; 1751 HdfsFileStatus resultingStat = null; 1752 FSPermissionChecker pc = getPermissionChecker(); 1753 checkOperation(OperationCategory.WRITE); 1754 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 1755 writeLock(); 1756 try { 1757 checkOperation(OperationCategory.WRITE); 1758 checkNameNodeSafeMode("Cannot set permission for " + src); 1759 src = resolvePath(src, pathComponents); 1760 checkOwner(pc, src); 1761 dir.setPermission(src, permission); 1762 getEditLog().logSetPermissions(src, permission); 1763 resultingStat = getAuditFileInfo(src, false); 1764 } finally { 1765 writeUnlock(); 1766 } 1767 getEditLog().logSync(); 1768 logAuditEvent(true, "setPermission", srcArg, null, resultingStat); 1769 } 1770 1771 /** 1772 * Set owner for an existing file. 1773 * @throws IOException 1774 */ 1775 void setOwner(String src, String username, String group) 1776 throws AccessControlException, FileNotFoundException, SafeModeException, 1777 UnresolvedLinkException, IOException { 1778 try { 1779 setOwnerInt(src, username, group); 1780 } catch (AccessControlException e) { 1781 logAuditEvent(false, "setOwner", src); 1782 throw e; 1783 } 1784 } 1785 1786 private void setOwnerInt(final String srcArg, String username, String group) 1787 throws AccessControlException, FileNotFoundException, SafeModeException, 1788 UnresolvedLinkException, IOException { 1789 String src = srcArg; 1790 HdfsFileStatus resultingStat = null; 1791 FSPermissionChecker pc = getPermissionChecker(); 1792 checkOperation(OperationCategory.WRITE); 1793 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 1794 writeLock(); 1795 try { 1796 checkOperation(OperationCategory.WRITE); 1797 checkNameNodeSafeMode("Cannot set owner for " + src); 1798 src = resolvePath(src, pathComponents); 1799 checkOwner(pc, src); 1800 if (!pc.isSuperUser()) { 1801 if (username != null && !pc.getUser().equals(username)) { 1802 throw new AccessControlException("Non-super user cannot change owner"); 1803 } 1804 if (group != null && !pc.containsGroup(group)) { 1805 throw new AccessControlException("User does not belong to " + group); 1806 } 1807 } 1808 dir.setOwner(src, username, group); 1809 getEditLog().logSetOwner(src, username, group); 1810 resultingStat = getAuditFileInfo(src, false); 1811 } finally { 1812 writeUnlock(); 1813 } 1814 getEditLog().logSync(); 1815 logAuditEvent(true, "setOwner", srcArg, null, resultingStat); 1816 } 1817 1818 /** 1819 * Get block locations within the specified range. 1820 * @see ClientProtocol#getBlockLocations(String, long, long) 1821 */ 1822 LocatedBlocks getBlockLocations(String clientMachine, String src, 1823 long offset, long length) throws AccessControlException, 1824 FileNotFoundException, UnresolvedLinkException, IOException { 1825 LocatedBlocks blocks = getBlockLocations(src, offset, length, true, true, 1826 true); 1827 if (blocks != null) { 1828 blockManager.getDatanodeManager().sortLocatedBlocks(clientMachine, 1829 blocks.getLocatedBlocks()); 1830 1831 // lastBlock is not part of getLocatedBlocks(), might need to sort it too 1832 LocatedBlock lastBlock = blocks.getLastLocatedBlock(); 1833 if (lastBlock != null) { 1834 ArrayList<LocatedBlock> lastBlockList = 1835 Lists.newArrayListWithCapacity(1); 1836 lastBlockList.add(lastBlock); 1837 blockManager.getDatanodeManager().sortLocatedBlocks(clientMachine, 1838 lastBlockList); 1839 } 1840 } 1841 return blocks; 1842 } 1843 1844 /** 1845 * Get block locations within the specified range. 1846 * @see ClientProtocol#getBlockLocations(String, long, long) 1847 * @throws FileNotFoundException, UnresolvedLinkException, IOException 1848 */ 1849 LocatedBlocks getBlockLocations(String src, long offset, long length, 1850 boolean doAccessTime, boolean needBlockToken, boolean checkSafeMode) 1851 throws FileNotFoundException, UnresolvedLinkException, IOException { 1852 try { 1853 return getBlockLocationsInt(src, offset, length, doAccessTime, 1854 needBlockToken, checkSafeMode); 1855 } catch (AccessControlException e) { 1856 logAuditEvent(false, "open", src); 1857 throw e; 1858 } 1859 } 1860 1861 private LocatedBlocks getBlockLocationsInt(String src, long offset, 1862 long length, boolean doAccessTime, boolean needBlockToken, 1863 boolean checkSafeMode) 1864 throws FileNotFoundException, UnresolvedLinkException, IOException { 1865 if (offset < 0) { 1866 throw new HadoopIllegalArgumentException( 1867 "Negative offset is not supported. File: " + src); 1868 } 1869 if (length < 0) { 1870 throw new HadoopIllegalArgumentException( 1871 "Negative length is not supported. File: " + src); 1872 } 1873 final LocatedBlocks ret = getBlockLocationsUpdateTimes(src, 1874 offset, length, doAccessTime, needBlockToken); 1875 logAuditEvent(true, "open", src); 1876 if (checkSafeMode && isInSafeMode()) { 1877 for (LocatedBlock b : ret.getLocatedBlocks()) { 1878 // if safemode & no block locations yet then throw safemodeException 1879 if ((b.getLocations() == null) || (b.getLocations().length == 0)) { 1880 SafeModeException se = new SafeModeException( 1881 "Zero blocklocations for " + src, safeMode); 1882 if (haEnabled && haContext != null && 1883 haContext.getState().getServiceState() == HAServiceState.ACTIVE) { 1884 throw new RetriableException(se); 1885 } else { 1886 throw se; 1887 } 1888 } 1889 } 1890 } 1891 return ret; 1892 } 1893 1894 /* 1895 * Get block locations within the specified range, updating the 1896 * access times if necessary. 1897 */ 1898 private LocatedBlocks getBlockLocationsUpdateTimes(final String srcArg, 1899 long offset, long length, boolean doAccessTime, boolean needBlockToken) 1900 throws FileNotFoundException, 1901 UnresolvedLinkException, IOException { 1902 String src = srcArg; 1903 FSPermissionChecker pc = getPermissionChecker(); 1904 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 1905 for (int attempt = 0; attempt < 2; attempt++) { 1906 boolean isReadOp = (attempt == 0); 1907 if (isReadOp) { // first attempt is with readlock 1908 checkOperation(OperationCategory.READ); 1909 readLock(); 1910 } else { // second attempt is with write lock 1911 checkOperation(OperationCategory.WRITE); 1912 writeLock(); // writelock is needed to set accesstime 1913 } 1914 try { 1915 src = resolvePath(src, pathComponents); 1916 if (isReadOp) { 1917 checkOperation(OperationCategory.READ); 1918 } else { 1919 checkOperation(OperationCategory.WRITE); 1920 } 1921 if (isPermissionEnabled) { 1922 checkPathAccess(pc, src, FsAction.READ); 1923 } 1924 1925 // if the namenode is in safemode, then do not update access time 1926 if (isInSafeMode()) { 1927 doAccessTime = false; 1928 } 1929 1930 final INodesInPath iip = dir.getINodesInPath(src, true); 1931 final INode[] inodes = iip.getINodes(); 1932 final INodeFile inode = INodeFile.valueOf( 1933 inodes[inodes.length - 1], src); 1934 if (isPermissionEnabled) { 1935 checkUnreadableBySuperuser(pc, inode, iip.getPathSnapshotId()); 1936 } 1937 if (!iip.isSnapshot() //snapshots are readonly, so don't update atime. 1938 && doAccessTime && isAccessTimeSupported()) { 1939 final long now = now(); 1940 if (now > inode.getAccessTime() + getAccessTimePrecision()) { 1941 // if we have to set access time but we only have the readlock, then 1942 // restart this entire operation with the writeLock. 1943 if (isReadOp) { 1944 continue; 1945 } 1946 boolean changed = dir.setTimes(inode, -1, now, false, 1947 iip.getLatestSnapshotId()); 1948 if (changed) { 1949 getEditLog().logTimes(src, -1, now); 1950 } 1951 } 1952 } 1953 final long fileSize = iip.isSnapshot() ? 1954 inode.computeFileSize(iip.getPathSnapshotId()) 1955 : inode.computeFileSizeNotIncludingLastUcBlock(); 1956 boolean isUc = inode.isUnderConstruction(); 1957 if (iip.isSnapshot()) { 1958 // if src indicates a snapshot file, we need to make sure the returned 1959 // blocks do not exceed the size of the snapshot file. 1960 length = Math.min(length, fileSize - offset); 1961 isUc = false; 1962 } 1963 1964 final FileEncryptionInfo feInfo = 1965 FSDirectory.isReservedRawName(srcArg) ? 1966 null : dir.getFileEncryptionInfo(inode, iip.getPathSnapshotId(), 1967 iip); 1968 1969 final LocatedBlocks blocks = 1970 blockManager.createLocatedBlocks(inode.getBlocks(), fileSize, 1971 isUc, offset, length, needBlockToken, iip.isSnapshot(), feInfo); 1972 // Set caching information for the located blocks. 1973 for (LocatedBlock lb: blocks.getLocatedBlocks()) { 1974 cacheManager.setCachedLocations(lb); 1975 } 1976 return blocks; 1977 } finally { 1978 if (isReadOp) { 1979 readUnlock(); 1980 } else { 1981 writeUnlock(); 1982 } 1983 } 1984 } 1985 return null; // can never reach here 1986 } 1987 1988 /** 1989 * Moves all the blocks from {@code srcs} and appends them to {@code target} 1990 * To avoid rollbacks we will verify validity of ALL of the args 1991 * before we start actual move. 1992 * 1993 * This does not support ".inodes" relative path 1994 * @param target target to concat into 1995 * @param srcs file that will be concatenated 1996 * @throws IOException on error 1997 */ 1998 void concat(String target, String [] srcs) 1999 throws IOException, UnresolvedLinkException { 2000 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 2001 if (cacheEntry != null && cacheEntry.isSuccess()) { 2002 return; // Return previous response 2003 } 2004 2005 // Either there is no previous request in progress or it has failed 2006 if(FSNamesystem.LOG.isDebugEnabled()) { 2007 FSNamesystem.LOG.debug("concat " + Arrays.toString(srcs) + 2008 " to " + target); 2009 } 2010 2011 boolean success = false; 2012 try { 2013 concatInt(target, srcs, cacheEntry != null); 2014 success = true; 2015 } catch (AccessControlException e) { 2016 logAuditEvent(false, "concat", Arrays.toString(srcs), target, null); 2017 throw e; 2018 } finally { 2019 RetryCache.setState(cacheEntry, success); 2020 } 2021 } 2022 2023 private void concatInt(String target, String [] srcs, 2024 boolean logRetryCache) throws IOException, UnresolvedLinkException { 2025 // verify args 2026 if(target.isEmpty()) { 2027 throw new IllegalArgumentException("Target file name is empty"); 2028 } 2029 if(srcs == null || srcs.length == 0) { 2030 throw new IllegalArgumentException("No sources given"); 2031 } 2032 2033 // We require all files be in the same directory 2034 String trgParent = 2035 target.substring(0, target.lastIndexOf(Path.SEPARATOR_CHAR)); 2036 for (String s : srcs) { 2037 String srcParent = s.substring(0, s.lastIndexOf(Path.SEPARATOR_CHAR)); 2038 if (!srcParent.equals(trgParent)) { 2039 throw new IllegalArgumentException( 2040 "Sources and target are not in the same directory"); 2041 } 2042 } 2043 2044 HdfsFileStatus resultingStat = null; 2045 FSPermissionChecker pc = getPermissionChecker(); 2046 checkOperation(OperationCategory.WRITE); 2047 waitForLoadingFSImage(); 2048 writeLock(); 2049 try { 2050 checkOperation(OperationCategory.WRITE); 2051 checkNameNodeSafeMode("Cannot concat " + target); 2052 concatInternal(pc, target, srcs, logRetryCache); 2053 resultingStat = getAuditFileInfo(target, false); 2054 } finally { 2055 writeUnlock(); 2056 } 2057 getEditLog().logSync(); 2058 logAuditEvent(true, "concat", Arrays.toString(srcs), target, resultingStat); 2059 } 2060 2061 /** See {@link #concat(String, String[])} */ 2062 private void concatInternal(FSPermissionChecker pc, String target, 2063 String[] srcs, boolean logRetryCache) throws IOException, 2064 UnresolvedLinkException { 2065 assert hasWriteLock(); 2066 2067 // write permission for the target 2068 if (isPermissionEnabled) { 2069 checkPathAccess(pc, target, FsAction.WRITE); 2070 2071 // and srcs 2072 for(String aSrc: srcs) { 2073 checkPathAccess(pc, aSrc, FsAction.READ); // read the file 2074 checkParentAccess(pc, aSrc, FsAction.WRITE); // for delete 2075 } 2076 } 2077 2078 // to make sure no two files are the same 2079 Set<INode> si = new HashSet<INode>(); 2080 2081 // we put the following prerequisite for the operation 2082 // replication and blocks sizes should be the same for ALL the blocks 2083 2084 // check the target 2085 final INodesInPath trgIip = dir.getINodesInPath4Write(target); 2086 if (dir.getEZForPath(trgIip) != null) { 2087 throw new HadoopIllegalArgumentException( 2088 "concat can not be called for files in an encryption zone."); 2089 } 2090 final INodeFile trgInode = INodeFile.valueOf(trgIip.getLastINode(), 2091 target); 2092 if(trgInode.isUnderConstruction()) { 2093 throw new HadoopIllegalArgumentException("concat: target file " 2094 + target + " is under construction"); 2095 } 2096 // per design target shouldn't be empty and all the blocks same size 2097 if(trgInode.numBlocks() == 0) { 2098 throw new HadoopIllegalArgumentException("concat: target file " 2099 + target + " is empty"); 2100 } 2101 if (trgInode.isWithSnapshot()) { 2102 throw new HadoopIllegalArgumentException("concat: target file " 2103 + target + " is in a snapshot"); 2104 } 2105 2106 long blockSize = trgInode.getPreferredBlockSize(); 2107 2108 // check the end block to be full 2109 final BlockInfo last = trgInode.getLastBlock(); 2110 if(blockSize != last.getNumBytes()) { 2111 throw new HadoopIllegalArgumentException("The last block in " + target 2112 + " is not full; last block size = " + last.getNumBytes() 2113 + " but file block size = " + blockSize); 2114 } 2115 2116 si.add(trgInode); 2117 final short repl = trgInode.getFileReplication(); 2118 2119 // now check the srcs 2120 boolean endSrc = false; // final src file doesn't have to have full end block 2121 for(int i=0; i<srcs.length; i++) { 2122 String src = srcs[i]; 2123 if(i==srcs.length-1) 2124 endSrc=true; 2125 2126 final INodeFile srcInode = INodeFile.valueOf(dir.getINode4Write(src), src); 2127 if(src.isEmpty() 2128 || srcInode.isUnderConstruction() 2129 || srcInode.numBlocks() == 0) { 2130 throw new HadoopIllegalArgumentException("concat: source file " + src 2131 + " is invalid or empty or underConstruction"); 2132 } 2133 2134 // check replication and blocks size 2135 if(repl != srcInode.getBlockReplication()) { 2136 throw new HadoopIllegalArgumentException("concat: the source file " 2137 + src + " and the target file " + target 2138 + " should have the same replication: source replication is " 2139 + srcInode.getBlockReplication() 2140 + " but target replication is " + repl); 2141 } 2142 2143 //boolean endBlock=false; 2144 // verify that all the blocks are of the same length as target 2145 // should be enough to check the end blocks 2146 final BlockInfo[] srcBlocks = srcInode.getBlocks(); 2147 int idx = srcBlocks.length-1; 2148 if(endSrc) 2149 idx = srcBlocks.length-2; // end block of endSrc is OK not to be full 2150 if(idx >= 0 && srcBlocks[idx].getNumBytes() != blockSize) { 2151 throw new HadoopIllegalArgumentException("concat: the source file " 2152 + src + " and the target file " + target 2153 + " should have the same blocks sizes: target block size is " 2154 + blockSize + " but the size of source block " + idx + " is " 2155 + srcBlocks[idx].getNumBytes()); 2156 } 2157 2158 si.add(srcInode); 2159 } 2160 2161 // make sure no two files are the same 2162 if(si.size() < srcs.length+1) { // trg + srcs 2163 // it means at least two files are the same 2164 throw new HadoopIllegalArgumentException( 2165 "concat: at least two of the source files are the same"); 2166 } 2167 2168 if(NameNode.stateChangeLog.isDebugEnabled()) { 2169 NameNode.stateChangeLog.debug("DIR* NameSystem.concat: " + 2170 Arrays.toString(srcs) + " to " + target); 2171 } 2172 2173 long timestamp = now(); 2174 dir.concat(target, srcs, timestamp); 2175 getEditLog().logConcat(target, srcs, timestamp, logRetryCache); 2176 } 2177 2178 /** 2179 * stores the modification and access time for this inode. 2180 * The access time is precise up to an hour. The transaction, if needed, is 2181 * written to the edits log but is not flushed. 2182 */ 2183 void setTimes(String src, long mtime, long atime) 2184 throws IOException, UnresolvedLinkException { 2185 if (!isAccessTimeSupported() && atime != -1) { 2186 throw new IOException("Access time for hdfs is not configured. " + 2187 " Please set " + DFS_NAMENODE_ACCESSTIME_PRECISION_KEY + " configuration parameter."); 2188 } 2189 try { 2190 setTimesInt(src, mtime, atime); 2191 } catch (AccessControlException e) { 2192 logAuditEvent(false, "setTimes", src); 2193 throw e; 2194 } 2195 } 2196 2197 private void setTimesInt(final String srcArg, long mtime, long atime) 2198 throws IOException, UnresolvedLinkException { 2199 String src = srcArg; 2200 HdfsFileStatus resultingStat = null; 2201 FSPermissionChecker pc = getPermissionChecker(); 2202 checkOperation(OperationCategory.WRITE); 2203 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 2204 writeLock(); 2205 try { 2206 checkOperation(OperationCategory.WRITE); 2207 checkNameNodeSafeMode("Cannot set times " + src); 2208 src = resolvePath(src, pathComponents); 2209 2210 // Write access is required to set access and modification times 2211 if (isPermissionEnabled) { 2212 checkPathAccess(pc, src, FsAction.WRITE); 2213 } 2214 final INodesInPath iip = dir.getINodesInPath4Write(src); 2215 final INode inode = iip.getLastINode(); 2216 if (inode != null) { 2217 boolean changed = dir.setTimes(inode, mtime, atime, true, 2218 iip.getLatestSnapshotId()); 2219 if (changed) { 2220 getEditLog().logTimes(src, mtime, atime); 2221 } 2222 resultingStat = getAuditFileInfo(src, false); 2223 } else { 2224 throw new FileNotFoundException("File/Directory " + src + " does not exist."); 2225 } 2226 } finally { 2227 writeUnlock(); 2228 } 2229 logAuditEvent(true, "setTimes", srcArg, null, resultingStat); 2230 } 2231 2232 /** 2233 * Create a symbolic link. 2234 */ 2235 @SuppressWarnings("deprecation") 2236 void createSymlink(String target, String link, 2237 PermissionStatus dirPerms, boolean createParent) 2238 throws IOException, UnresolvedLinkException { 2239 if (!FileSystem.areSymlinksEnabled()) { 2240 throw new UnsupportedOperationException("Symlinks not supported"); 2241 } 2242 if (!DFSUtil.isValidName(link)) { 2243 throw new InvalidPathException("Invalid link name: " + link); 2244 } 2245 if (FSDirectory.isReservedName(target)) { 2246 throw new InvalidPathException("Invalid target name: " + target); 2247 } 2248 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 2249 if (cacheEntry != null && cacheEntry.isSuccess()) { 2250 return; // Return previous response 2251 } 2252 boolean success = false; 2253 try { 2254 createSymlinkInt(target, link, dirPerms, createParent, cacheEntry != null); 2255 success = true; 2256 } catch (AccessControlException e) { 2257 logAuditEvent(false, "createSymlink", link, target, null); 2258 throw e; 2259 } finally { 2260 RetryCache.setState(cacheEntry, success); 2261 } 2262 } 2263 2264 private void createSymlinkInt(String target, final String linkArg, 2265 PermissionStatus dirPerms, boolean createParent, boolean logRetryCache) 2266 throws IOException, UnresolvedLinkException { 2267 String link = linkArg; 2268 if (NameNode.stateChangeLog.isDebugEnabled()) { 2269 NameNode.stateChangeLog.debug("DIR* NameSystem.createSymlink: target=" 2270 + target + " link=" + link); 2271 } 2272 HdfsFileStatus resultingStat = null; 2273 FSPermissionChecker pc = getPermissionChecker(); 2274 checkOperation(OperationCategory.WRITE); 2275 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(link); 2276 writeLock(); 2277 try { 2278 checkOperation(OperationCategory.WRITE); 2279 checkNameNodeSafeMode("Cannot create symlink " + link); 2280 link = resolvePath(link, pathComponents); 2281 if (!createParent) { 2282 verifyParentDir(link); 2283 } 2284 if (!dir.isValidToCreate(link)) { 2285 throw new IOException("failed to create link " + link 2286 +" either because the filename is invalid or the file exists"); 2287 } 2288 if (isPermissionEnabled) { 2289 checkAncestorAccess(pc, link, FsAction.WRITE); 2290 } 2291 // validate that we have enough inodes. 2292 checkFsObjectLimit(); 2293 2294 // add symbolic link to namespace 2295 addSymlink(link, target, dirPerms, createParent, logRetryCache); 2296 resultingStat = getAuditFileInfo(link, false); 2297 } finally { 2298 writeUnlock(); 2299 } 2300 getEditLog().logSync(); 2301 logAuditEvent(true, "createSymlink", linkArg, target, resultingStat); 2302 } 2303 2304 /** 2305 * Set replication for an existing file. 2306 * 2307 * The NameNode sets new replication and schedules either replication of 2308 * under-replicated data blocks or removal of the excessive block copies 2309 * if the blocks are over-replicated. 2310 * 2311 * @see ClientProtocol#setReplication(String, short) 2312 * @param src file name 2313 * @param replication new replication 2314 * @return true if successful; 2315 * false if file does not exist or is a directory 2316 */ 2317 boolean setReplication(final String src, final short replication) 2318 throws IOException { 2319 try { 2320 return setReplicationInt(src, replication); 2321 } catch (AccessControlException e) { 2322 logAuditEvent(false, "setReplication", src); 2323 throw e; 2324 } 2325 } 2326 2327 private boolean setReplicationInt(final String srcArg, 2328 final short replication) throws IOException { 2329 String src = srcArg; 2330 blockManager.verifyReplication(src, replication, null); 2331 final boolean isFile; 2332 FSPermissionChecker pc = getPermissionChecker(); 2333 checkOperation(OperationCategory.WRITE); 2334 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 2335 waitForLoadingFSImage(); 2336 writeLock(); 2337 try { 2338 checkOperation(OperationCategory.WRITE); 2339 checkNameNodeSafeMode("Cannot set replication for " + src); 2340 src = resolvePath(src, pathComponents); 2341 if (isPermissionEnabled) { 2342 checkPathAccess(pc, src, FsAction.WRITE); 2343 } 2344 2345 final short[] blockRepls = new short[2]; // 0: old, 1: new 2346 final Block[] blocks = dir.setReplication(src, replication, blockRepls); 2347 isFile = blocks != null; 2348 if (isFile) { 2349 getEditLog().logSetReplication(src, replication); 2350 blockManager.setReplication(blockRepls[0], blockRepls[1], src, blocks); 2351 } 2352 } finally { 2353 writeUnlock(); 2354 } 2355 2356 getEditLog().logSync(); 2357 if (isFile) { 2358 logAuditEvent(true, "setReplication", srcArg); 2359 } 2360 return isFile; 2361 } 2362 2363 /** 2364 * Set the storage policy for a file or a directory. 2365 * 2366 * @param src file/directory path 2367 * @param policyName storage policy name 2368 */ 2369 void setStoragePolicy(String src, final String policyName) 2370 throws IOException { 2371 try { 2372 setStoragePolicyInt(src, policyName); 2373 } catch (AccessControlException e) { 2374 logAuditEvent(false, "setStoragePolicy", src); 2375 throw e; 2376 } 2377 } 2378 2379 private void setStoragePolicyInt(String src, final String policyName) 2380 throws IOException, UnresolvedLinkException, AccessControlException { 2381 2382 if (!isStoragePolicyEnabled) { 2383 throw new IOException("Failed to set storage policy since " 2384 + DFS_STORAGE_POLICY_ENABLED_KEY + " is set to false."); 2385 } 2386 FSPermissionChecker pc = null; 2387 if (isPermissionEnabled) { 2388 pc = getPermissionChecker(); 2389 } 2390 2391 checkOperation(OperationCategory.WRITE); 2392 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 2393 waitForLoadingFSImage(); 2394 HdfsFileStatus fileStat; 2395 writeLock(); 2396 try { 2397 checkOperation(OperationCategory.WRITE); 2398 checkNameNodeSafeMode("Cannot set storage policy for " + src); 2399 2400 if (pc != null) { 2401 checkPermission(pc, src, false, null, null, FsAction.WRITE, null, 2402 false, true); 2403 } 2404 2405 src = FSDirectory.resolvePath(src, pathComponents, dir); 2406 2407 // get the corresponding policy and make sure the policy name is valid 2408 BlockStoragePolicy policy = blockManager.getStoragePolicy(policyName); 2409 if (policy == null) { 2410 throw new HadoopIllegalArgumentException( 2411 "Cannot find a block policy with the name " + policyName); 2412 } 2413 dir.setStoragePolicy(src, policy.getId()); 2414 getEditLog().logSetStoragePolicy(src, policy.getId()); 2415 fileStat = getAuditFileInfo(src, false); 2416 } finally { 2417 writeUnlock(); 2418 } 2419 2420 getEditLog().logSync(); 2421 logAuditEvent(true, "setStoragePolicy", src, null, fileStat); 2422 } 2423 2424 /** 2425 * @return All the existing block storage policies 2426 */ 2427 BlockStoragePolicy[] getStoragePolicies() throws IOException { 2428 checkOperation(OperationCategory.READ); 2429 waitForLoadingFSImage(); 2430 readLock(); 2431 try { 2432 checkOperation(OperationCategory.READ); 2433 return blockManager.getStoragePolicies(); 2434 } finally { 2435 readUnlock(); 2436 } 2437 } 2438 2439 long getPreferredBlockSize(String filename) 2440 throws IOException, UnresolvedLinkException { 2441 FSPermissionChecker pc = getPermissionChecker(); 2442 checkOperation(OperationCategory.READ); 2443 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(filename); 2444 readLock(); 2445 try { 2446 checkOperation(OperationCategory.READ); 2447 filename = resolvePath(filename, pathComponents); 2448 if (isPermissionEnabled) { 2449 checkTraverse(pc, filename); 2450 } 2451 return dir.getPreferredBlockSize(filename); 2452 } finally { 2453 readUnlock(); 2454 } 2455 } 2456 2457 /** 2458 * Verify that parent directory of src exists. 2459 */ 2460 private void verifyParentDir(String src) throws FileNotFoundException, 2461 ParentNotDirectoryException, UnresolvedLinkException { 2462 assert hasReadLock(); 2463 Path parent = new Path(src).getParent(); 2464 if (parent != null) { 2465 final INode parentNode = dir.getINode(parent.toString()); 2466 if (parentNode == null) { 2467 throw new FileNotFoundException("Parent directory doesn't exist: " 2468 + parent); 2469 } else if (!parentNode.isDirectory() && !parentNode.isSymlink()) { 2470 throw new ParentNotDirectoryException("Parent path is not a directory: " 2471 + parent); 2472 } 2473 } 2474 } 2475 2476 /** 2477 * If the file is within an encryption zone, select the appropriate 2478 * CryptoProtocolVersion from the list provided by the client. Since the 2479 * client may be newer, we need to handle unknown versions. 2480 * 2481 * @param zone EncryptionZone of the file 2482 * @param supportedVersions List of supported protocol versions 2483 * @return chosen protocol version 2484 * @throws IOException 2485 */ 2486 private CryptoProtocolVersion chooseProtocolVersion(EncryptionZone zone, 2487 CryptoProtocolVersion[] supportedVersions) 2488 throws UnknownCryptoProtocolVersionException, UnresolvedLinkException, 2489 SnapshotAccessControlException { 2490 Preconditions.checkNotNull(zone); 2491 Preconditions.checkNotNull(supportedVersions); 2492 // Right now, we only support a single protocol version, 2493 // so simply look for it in the list of provided options 2494 final CryptoProtocolVersion required = zone.getVersion(); 2495 2496 for (CryptoProtocolVersion c : supportedVersions) { 2497 if (c.equals(CryptoProtocolVersion.UNKNOWN)) { 2498 if (LOG.isDebugEnabled()) { 2499 LOG.debug("Ignoring unknown CryptoProtocolVersion provided by " + 2500 "client: " + c.getUnknownValue()); 2501 } 2502 continue; 2503 } 2504 if (c.equals(required)) { 2505 return c; 2506 } 2507 } 2508 throw new UnknownCryptoProtocolVersionException( 2509 "No crypto protocol versions provided by the client are supported." 2510 + " Client provided: " + Arrays.toString(supportedVersions) 2511 + " NameNode supports: " + Arrays.toString(CryptoProtocolVersion 2512 .values())); 2513 } 2514 2515 /** 2516 * Invoke KeyProvider APIs to generate an encrypted data encryption key for an 2517 * encryption zone. Should not be called with any locks held. 2518 * 2519 * @param ezKeyName key name of an encryption zone 2520 * @return New EDEK, or null if ezKeyName is null 2521 * @throws IOException 2522 */ 2523 private EncryptedKeyVersion generateEncryptedDataEncryptionKey(String 2524 ezKeyName) throws IOException { 2525 if (ezKeyName == null) { 2526 return null; 2527 } 2528 EncryptedKeyVersion edek = null; 2529 try { 2530 edek = provider.generateEncryptedKey(ezKeyName); 2531 } catch (GeneralSecurityException e) { 2532 throw new IOException(e); 2533 } 2534 Preconditions.checkNotNull(edek); 2535 return edek; 2536 } 2537 2538 /** 2539 * Create a new file entry in the namespace. 2540 * 2541 * For description of parameters and exceptions thrown see 2542 * {@link ClientProtocol#create}, except it returns valid file status upon 2543 * success 2544 */ 2545 HdfsFileStatus startFile(String src, PermissionStatus permissions, 2546 String holder, String clientMachine, EnumSet<CreateFlag> flag, 2547 boolean createParent, short replication, long blockSize, 2548 CryptoProtocolVersion[] supportedVersions) 2549 throws AccessControlException, SafeModeException, 2550 FileAlreadyExistsException, UnresolvedLinkException, 2551 FileNotFoundException, ParentNotDirectoryException, IOException { 2552 HdfsFileStatus status = null; 2553 CacheEntryWithPayload cacheEntry = RetryCache.waitForCompletion(retryCache, 2554 null); 2555 if (cacheEntry != null && cacheEntry.isSuccess()) { 2556 return (HdfsFileStatus) cacheEntry.getPayload(); 2557 } 2558 2559 try { 2560 status = startFileInt(src, permissions, holder, clientMachine, flag, 2561 createParent, replication, blockSize, supportedVersions, 2562 cacheEntry != null); 2563 } catch (AccessControlException e) { 2564 logAuditEvent(false, "create", src); 2565 throw e; 2566 } finally { 2567 RetryCache.setState(cacheEntry, status != null, status); 2568 } 2569 return status; 2570 } 2571 2572 private HdfsFileStatus startFileInt(final String srcArg, 2573 PermissionStatus permissions, String holder, String clientMachine, 2574 EnumSet<CreateFlag> flag, boolean createParent, short replication, 2575 long blockSize, CryptoProtocolVersion[] supportedVersions, 2576 boolean logRetryCache) 2577 throws AccessControlException, SafeModeException, 2578 FileAlreadyExistsException, UnresolvedLinkException, 2579 FileNotFoundException, ParentNotDirectoryException, IOException { 2580 String src = srcArg; 2581 if (NameNode.stateChangeLog.isDebugEnabled()) { 2582 StringBuilder builder = new StringBuilder(); 2583 builder.append("DIR* NameSystem.startFile: src=" + src 2584 + ", holder=" + holder 2585 + ", clientMachine=" + clientMachine 2586 + ", createParent=" + createParent 2587 + ", replication=" + replication 2588 + ", createFlag=" + flag.toString() 2589 + ", blockSize=" + blockSize); 2590 builder.append(", supportedVersions="); 2591 if (supportedVersions != null) { 2592 builder.append(Arrays.toString(supportedVersions)); 2593 } else { 2594 builder.append("null"); 2595 } 2596 NameNode.stateChangeLog.debug(builder.toString()); 2597 } 2598 if (!DFSUtil.isValidName(src)) { 2599 throw new InvalidPathException(src); 2600 } 2601 blockManager.verifyReplication(src, replication, clientMachine); 2602 2603 boolean skipSync = false; 2604 HdfsFileStatus stat = null; 2605 FSPermissionChecker pc = getPermissionChecker(); 2606 checkOperation(OperationCategory.WRITE); 2607 if (blockSize < minBlockSize) { 2608 throw new IOException("Specified block size is less than configured" + 2609 " minimum value (" + DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY 2610 + "): " + blockSize + " < " + minBlockSize); 2611 } 2612 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 2613 boolean create = flag.contains(CreateFlag.CREATE); 2614 boolean overwrite = flag.contains(CreateFlag.OVERWRITE); 2615 boolean isLazyPersist = flag.contains(CreateFlag.LAZY_PERSIST); 2616 2617 waitForLoadingFSImage(); 2618 2619 /** 2620 * If the file is in an encryption zone, we optimistically create an 2621 * EDEK for the file by calling out to the configured KeyProvider. 2622 * Since this typically involves doing an RPC, we take the readLock 2623 * initially, then drop it to do the RPC. 2624 * 2625 * Since the path can flip-flop between being in an encryption zone and not 2626 * in the meantime, we need to recheck the preconditions when we retake the 2627 * lock to do the create. If the preconditions are not met, we throw a 2628 * special RetryStartFileException to ask the DFSClient to try the create 2629 * again later. 2630 */ 2631 CryptoProtocolVersion protocolVersion = null; 2632 CipherSuite suite = null; 2633 String ezKeyName = null; 2634 EncryptedKeyVersion edek = null; 2635 2636 if (provider != null) { 2637 readLock(); 2638 try { 2639 src = resolvePath(src, pathComponents); 2640 INodesInPath iip = dir.getINodesInPath4Write(src); 2641 // Nothing to do if the path is not within an EZ 2642 final EncryptionZone zone = dir.getEZForPath(iip); 2643 if (zone != null) { 2644 protocolVersion = chooseProtocolVersion(zone, supportedVersions); 2645 suite = zone.getSuite(); 2646 ezKeyName = zone.getKeyName(); 2647 2648 Preconditions.checkNotNull(protocolVersion); 2649 Preconditions.checkNotNull(suite); 2650 Preconditions.checkArgument(!suite.equals(CipherSuite.UNKNOWN), 2651 "Chose an UNKNOWN CipherSuite!"); 2652 Preconditions.checkNotNull(ezKeyName); 2653 } 2654 } finally { 2655 readUnlock(); 2656 } 2657 2658 Preconditions.checkState( 2659 (suite == null && ezKeyName == null) || 2660 (suite != null && ezKeyName != null), 2661 "Both suite and ezKeyName should both be null or not null"); 2662 2663 // Generate EDEK if necessary while not holding the lock 2664 edek = generateEncryptedDataEncryptionKey(ezKeyName); 2665 EncryptionFaultInjector.getInstance().startFileAfterGenerateKey(); 2666 } 2667 2668 // Proceed with the create, using the computed cipher suite and 2669 // generated EDEK 2670 BlocksMapUpdateInfo toRemoveBlocks = null; 2671 writeLock(); 2672 try { 2673 checkOperation(OperationCategory.WRITE); 2674 checkNameNodeSafeMode("Cannot create file" + src); 2675 src = resolvePath(src, pathComponents); 2676 toRemoveBlocks = startFileInternal(pc, src, permissions, holder, 2677 clientMachine, create, overwrite, createParent, replication, 2678 blockSize, isLazyPersist, suite, protocolVersion, edek, logRetryCache); 2679 stat = dir.getFileInfo(src, false, 2680 FSDirectory.isReservedRawName(srcArg), true); 2681 } catch (StandbyException se) { 2682 skipSync = true; 2683 throw se; 2684 } finally { 2685 writeUnlock(); 2686 // There might be transactions logged while trying to recover the lease. 2687 // They need to be sync'ed even when an exception was thrown. 2688 if (!skipSync) { 2689 getEditLog().logSync(); 2690 if (toRemoveBlocks != null) { 2691 removeBlocks(toRemoveBlocks); 2692 toRemoveBlocks.clear(); 2693 } 2694 } 2695 } 2696 2697 logAuditEvent(true, "create", srcArg, null, stat); 2698 return stat; 2699 } 2700 2701 /** 2702 * Create a new file or overwrite an existing file<br> 2703 * 2704 * Once the file is create the client then allocates a new block with the next 2705 * call using {@link ClientProtocol#addBlock}. 2706 * <p> 2707 * For description of parameters and exceptions thrown see 2708 * {@link ClientProtocol#create} 2709 */ 2710 private BlocksMapUpdateInfo startFileInternal(FSPermissionChecker pc, 2711 String src, PermissionStatus permissions, String holder, 2712 String clientMachine, boolean create, boolean overwrite, 2713 boolean createParent, short replication, long blockSize, 2714 boolean isLazyPersist, CipherSuite suite, CryptoProtocolVersion version, 2715 EncryptedKeyVersion edek, boolean logRetryEntry) 2716 throws FileAlreadyExistsException, AccessControlException, 2717 UnresolvedLinkException, FileNotFoundException, 2718 ParentNotDirectoryException, RetryStartFileException, IOException { 2719 assert hasWriteLock(); 2720 // Verify that the destination does not exist as a directory already. 2721 final INodesInPath iip = dir.getINodesInPath4Write(src); 2722 final INode inode = iip.getLastINode(); 2723 if (inode != null && inode.isDirectory()) { 2724 throw new FileAlreadyExistsException(src + 2725 " already exists as a directory"); 2726 } 2727 2728 FileEncryptionInfo feInfo = null; 2729 2730 final EncryptionZone zone = dir.getEZForPath(iip); 2731 if (zone != null) { 2732 // The path is now within an EZ, but we're missing encryption parameters 2733 if (suite == null || edek == null) { 2734 throw new RetryStartFileException(); 2735 } 2736 // Path is within an EZ and we have provided encryption parameters. 2737 // Make sure that the generated EDEK matches the settings of the EZ. 2738 final String ezKeyName = zone.getKeyName(); 2739 if (!ezKeyName.equals(edek.getEncryptionKeyName())) { 2740 throw new RetryStartFileException(); 2741 } 2742 feInfo = new FileEncryptionInfo(suite, version, 2743 edek.getEncryptedKeyVersion().getMaterial(), 2744 edek.getEncryptedKeyIv(), 2745 ezKeyName, edek.getEncryptionKeyVersionName()); 2746 Preconditions.checkNotNull(feInfo); 2747 } 2748 2749 final INodeFile myFile = INodeFile.valueOf(inode, src, true); 2750 if (isPermissionEnabled) { 2751 if (overwrite && myFile != null) { 2752 checkPathAccess(pc, src, FsAction.WRITE); 2753 } 2754 /* 2755 * To overwrite existing file, need to check 'w' permission 2756 * of parent (equals to ancestor in this case) 2757 */ 2758 checkAncestorAccess(pc, src, FsAction.WRITE); 2759 } 2760 2761 if (!createParent) { 2762 verifyParentDir(src); 2763 } 2764 2765 try { 2766 BlocksMapUpdateInfo toRemoveBlocks = null; 2767 if (myFile == null) { 2768 if (!create) { 2769 throw new FileNotFoundException("Can't overwrite non-existent " + 2770 src + " for client " + clientMachine); 2771 } 2772 } else { 2773 if (overwrite) { 2774 toRemoveBlocks = new BlocksMapUpdateInfo(); 2775 List<INode> toRemoveINodes = new ChunkedArrayList<INode>(); 2776 long ret = dir.delete(src, toRemoveBlocks, toRemoveINodes, now()); 2777 if (ret >= 0) { 2778 incrDeletedFileCount(ret); 2779 removePathAndBlocks(src, null, toRemoveINodes, true); 2780 } 2781 } else { 2782 // If lease soft limit time is expired, recover the lease 2783 recoverLeaseInternal(myFile, src, holder, clientMachine, false); 2784 throw new FileAlreadyExistsException(src + " for client " + 2785 clientMachine + " already exists"); 2786 } 2787 } 2788 2789 checkFsObjectLimit(); 2790 INodeFile newNode = null; 2791 2792 // Always do an implicit mkdirs for parent directory tree. 2793 Path parent = new Path(src).getParent(); 2794 if (parent != null && mkdirsRecursively(parent.toString(), 2795 permissions, true, now())) { 2796 newNode = dir.addFile(src, permissions, replication, blockSize, 2797 holder, clientMachine); 2798 } 2799 2800 if (newNode == null) { 2801 throw new IOException("Unable to add " + src + " to namespace"); 2802 } 2803 leaseManager.addLease(newNode.getFileUnderConstructionFeature() 2804 .getClientName(), src); 2805 2806 // Set encryption attributes if necessary 2807 if (feInfo != null) { 2808 dir.setFileEncryptionInfo(src, feInfo); 2809 newNode = dir.getInode(newNode.getId()).asFile(); 2810 } 2811 2812 setNewINodeStoragePolicy(newNode, iip, isLazyPersist); 2813 2814 // record file record in log, record new generation stamp 2815 getEditLog().logOpenFile(src, newNode, overwrite, logRetryEntry); 2816 if (NameNode.stateChangeLog.isDebugEnabled()) { 2817 NameNode.stateChangeLog.debug("DIR* NameSystem.startFile: added " + 2818 src + " inode " + newNode.getId() + " " + holder); 2819 } 2820 return toRemoveBlocks; 2821 } catch (IOException ie) { 2822 NameNode.stateChangeLog.warn("DIR* NameSystem.startFile: " + src + " " + 2823 ie.getMessage()); 2824 throw ie; 2825 } 2826 } 2827 2828 private void setNewINodeStoragePolicy(INodeFile inode, 2829 INodesInPath iip, 2830 boolean isLazyPersist) 2831 throws IOException { 2832 2833 if (isLazyPersist) { 2834 BlockStoragePolicy lpPolicy = 2835 blockManager.getStoragePolicy("LAZY_PERSIST"); 2836 2837 // Set LAZY_PERSIST storage policy if the flag was passed to 2838 // CreateFile. 2839 if (lpPolicy == null) { 2840 throw new HadoopIllegalArgumentException( 2841 "The LAZY_PERSIST storage policy has been disabled " + 2842 "by the administrator."); 2843 } 2844 inode.setStoragePolicyID(lpPolicy.getId(), 2845 iip.getLatestSnapshotId()); 2846 } else { 2847 BlockStoragePolicy effectivePolicy = 2848 blockManager.getStoragePolicy(inode.getStoragePolicyID()); 2849 2850 if (effectivePolicy != null && 2851 effectivePolicy.isCopyOnCreateFile()) { 2852 // Copy effective policy from ancestor directory to current file. 2853 inode.setStoragePolicyID(effectivePolicy.getId(), 2854 iip.getLatestSnapshotId()); 2855 } 2856 } 2857 } 2858 2859 /** 2860 * Append to an existing file for append. 2861 * <p> 2862 * 2863 * The method returns the last block of the file if this is a partial block, 2864 * which can still be used for writing more data. The client uses the returned 2865 * block locations to form the data pipeline for this block.<br> 2866 * The method returns null if the last block is full. The client then 2867 * allocates a new block with the next call using 2868 * {@link ClientProtocol#addBlock}. 2869 * <p> 2870 * 2871 * For description of parameters and exceptions thrown see 2872 * {@link ClientProtocol#append(String, String)} 2873 * 2874 * @return the last block locations if the block is partial or null otherwise 2875 */ 2876 private LocatedBlock appendFileInternal(FSPermissionChecker pc, String src, 2877 String holder, String clientMachine, boolean logRetryCache) 2878 throws AccessControlException, UnresolvedLinkException, 2879 FileNotFoundException, IOException { 2880 assert hasWriteLock(); 2881 // Verify that the destination does not exist as a directory already. 2882 final INodesInPath iip = dir.getINodesInPath4Write(src); 2883 final INode inode = iip.getLastINode(); 2884 if (inode != null && inode.isDirectory()) { 2885 throw new FileAlreadyExistsException("Cannot append to directory " + src 2886 + "; already exists as a directory."); 2887 } 2888 if (isPermissionEnabled) { 2889 checkPathAccess(pc, src, FsAction.WRITE); 2890 } 2891 2892 try { 2893 if (inode == null) { 2894 throw new FileNotFoundException("failed to append to non-existent file " 2895 + src + " for client " + clientMachine); 2896 } 2897 INodeFile myFile = INodeFile.valueOf(inode, src, true); 2898 final BlockStoragePolicy lpPolicy = 2899 blockManager.getStoragePolicy("LAZY_PERSIST"); 2900 2901 if (lpPolicy != null && 2902 lpPolicy.getId() == myFile.getStoragePolicyID()) { 2903 throw new UnsupportedOperationException( 2904 "Cannot append to lazy persist file " + src); 2905 } 2906 // Opening an existing file for write - may need to recover lease. 2907 recoverLeaseInternal(myFile, src, holder, clientMachine, false); 2908 2909 // recoverLeaseInternal may create a new InodeFile via 2910 // finalizeINodeFileUnderConstruction so we need to refresh 2911 // the referenced file. 2912 myFile = INodeFile.valueOf(dir.getINode(src), src, true); 2913 final BlockInfo lastBlock = myFile.getLastBlock(); 2914 // Check that the block has at least minimum replication. 2915 if(lastBlock != null && lastBlock.isComplete() && 2916 !getBlockManager().isSufficientlyReplicated(lastBlock)) { 2917 throw new IOException("append: lastBlock=" + lastBlock + 2918 " of src=" + src + " is not sufficiently replicated yet."); 2919 } 2920 return prepareFileForWrite(src, myFile, holder, clientMachine, true, 2921 iip.getLatestSnapshotId(), logRetryCache); 2922 } catch (IOException ie) { 2923 NameNode.stateChangeLog.warn("DIR* NameSystem.append: " +ie.getMessage()); 2924 throw ie; 2925 } 2926 } 2927 2928 /** 2929 * Replace current node with a INodeUnderConstruction. 2930 * Recreate in-memory lease record. 2931 * 2932 * @param src path to the file 2933 * @param file existing file object 2934 * @param leaseHolder identifier of the lease holder on this file 2935 * @param clientMachine identifier of the client machine 2936 * @param writeToEditLog whether to persist this change to the edit log 2937 * @param logRetryCache whether to record RPC ids in editlog for retry cache 2938 * rebuilding 2939 * @return the last block locations if the block is partial or null otherwise 2940 * @throws UnresolvedLinkException 2941 * @throws IOException 2942 */ 2943 LocatedBlock prepareFileForWrite(String src, INodeFile file, 2944 String leaseHolder, String clientMachine, 2945 boolean writeToEditLog, 2946 int latestSnapshot, boolean logRetryCache) 2947 throws IOException { 2948 final INodesInPath iip = dir.getINodesInPath4Write(src, true); 2949 final long dsDelta = verifyQuotaForUCBlock(file, iip); 2950 file.recordModification(latestSnapshot); 2951 final INodeFile cons = file.toUnderConstruction(leaseHolder, clientMachine); 2952 2953 leaseManager.addLease(cons.getFileUnderConstructionFeature() 2954 .getClientName(), src); 2955 2956 LocatedBlock ret = blockManager.convertLastBlockToUnderConstruction(cons); 2957 if (ret != null && dsDelta != 0) { 2958 dir.writeLock(); 2959 try { 2960 dir.updateCountNoQuotaCheck(iip, iip.length(), 0, dsDelta); 2961 } finally { 2962 dir.writeUnlock(); 2963 } 2964 } 2965 2966 if (writeToEditLog) { 2967 getEditLog().logOpenFile(src, cons, false, logRetryCache); 2968 } 2969 return ret; 2970 } 2971 2972 /** 2973 * Verify quota when using the preferred block size for UC block. This is 2974 * usually used by append and truncate 2975 * @throws QuotaExceededException when violating the storage quota 2976 * @return ds delta 2977 */ 2978 private long verifyQuotaForUCBlock(INodeFile file, INodesInPath iip) 2979 throws QuotaExceededException { 2980 if (!isImageLoaded() || dir.shouldSkipQuotaChecks()) { 2981 // Do not check quota if editlog is still being processed 2982 return 0; 2983 } 2984 if (file.getLastBlock() != null) { 2985 final long delta = computeQuotaDeltaForUCBlock(file); 2986 dir.readLock(); 2987 try { 2988 FSDirectory.verifyQuota(iip.getINodes(), iip.length() - 1, 0, delta, 2989 null); 2990 return delta; 2991 } finally { 2992 dir.readUnlock(); 2993 } 2994 } 2995 return 0; 2996 } 2997 2998 /** Compute quota change for converting a complete block to a UC block */ 2999 private long computeQuotaDeltaForUCBlock(INodeFile file) { 3000 final long delta = 0; 3001 final BlockInfo lastBlock = file.getLastBlock(); 3002 if (lastBlock != null) { 3003 final long diff = file.getPreferredBlockSize() - lastBlock.getNumBytes(); 3004 final short repl = file.getBlockReplication(); 3005 return (diff * repl); 3006 } 3007 return delta; 3008 } 3009 3010 /** 3011 * Recover lease; 3012 * Immediately revoke the lease of the current lease holder and start lease 3013 * recovery so that the file can be forced to be closed. 3014 * 3015 * @param src the path of the file to start lease recovery 3016 * @param holder the lease holder's name 3017 * @param clientMachine the client machine's name 3018 * @return true if the file is already closed 3019 * @throws IOException 3020 */ 3021 boolean recoverLease(String src, String holder, String clientMachine) 3022 throws IOException { 3023 if (!DFSUtil.isValidName(src)) { 3024 throw new IOException("Invalid file name: " + src); 3025 } 3026 3027 boolean skipSync = false; 3028 FSPermissionChecker pc = getPermissionChecker(); 3029 checkOperation(OperationCategory.WRITE); 3030 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3031 writeLock(); 3032 try { 3033 checkOperation(OperationCategory.WRITE); 3034 checkNameNodeSafeMode("Cannot recover the lease of " + src); 3035 src = resolvePath(src, pathComponents); 3036 final INodeFile inode = INodeFile.valueOf(dir.getINode(src), src); 3037 if (!inode.isUnderConstruction()) { 3038 return true; 3039 } 3040 if (isPermissionEnabled) { 3041 checkPathAccess(pc, src, FsAction.WRITE); 3042 } 3043 3044 recoverLeaseInternal(inode, src, holder, clientMachine, true); 3045 } catch (StandbyException se) { 3046 skipSync = true; 3047 throw se; 3048 } finally { 3049 writeUnlock(); 3050 // There might be transactions logged while trying to recover the lease. 3051 // They need to be sync'ed even when an exception was thrown. 3052 if (!skipSync) { 3053 getEditLog().logSync(); 3054 } 3055 } 3056 return false; 3057 } 3058 3059 private void recoverLeaseInternal(INodeFile fileInode, 3060 String src, String holder, String clientMachine, boolean force) 3061 throws IOException { 3062 assert hasWriteLock(); 3063 if (fileInode != null && fileInode.isUnderConstruction()) { 3064 // 3065 // If the file is under construction , then it must be in our 3066 // leases. Find the appropriate lease record. 3067 // 3068 Lease lease = leaseManager.getLease(holder); 3069 // 3070 // We found the lease for this file. And surprisingly the original 3071 // holder is trying to recreate this file. This should never occur. 3072 // 3073 3074 if (!force && lease != null) { 3075 Lease leaseFile = leaseManager.getLeaseByPath(src); 3076 if (leaseFile != null && leaseFile.equals(lease)) { 3077 throw new AlreadyBeingCreatedException( 3078 "failed to create file " + src + " for " + holder + 3079 " for client " + clientMachine + 3080 " because current leaseholder is trying to recreate file."); 3081 } 3082 } 3083 // 3084 // Find the original holder. 3085 // 3086 FileUnderConstructionFeature uc = fileInode.getFileUnderConstructionFeature(); 3087 String clientName = uc.getClientName(); 3088 lease = leaseManager.getLease(clientName); 3089 if (lease == null) { 3090 throw new AlreadyBeingCreatedException( 3091 "failed to create file " + src + " for " + holder + 3092 " for client " + clientMachine + 3093 " because pendingCreates is non-null but no leases found."); 3094 } 3095 if (force) { 3096 // close now: no need to wait for soft lease expiration and 3097 // close only the file src 3098 LOG.info("recoverLease: " + lease + ", src=" + src + 3099 " from client " + clientName); 3100 internalReleaseLease(lease, src, holder); 3101 } else { 3102 assert lease.getHolder().equals(clientName) : 3103 "Current lease holder " + lease.getHolder() + 3104 " does not match file creator " + clientName; 3105 // 3106 // If the original holder has not renewed in the last SOFTLIMIT 3107 // period, then start lease recovery. 3108 // 3109 if (lease.expiredSoftLimit()) { 3110 LOG.info("startFile: recover " + lease + ", src=" + src + " client " 3111 + clientName); 3112 boolean isClosed = internalReleaseLease(lease, src, null); 3113 if(!isClosed) 3114 throw new RecoveryInProgressException( 3115 "Failed to close file " + src + 3116 ". Lease recovery is in progress. Try again later."); 3117 } else { 3118 final BlockInfo lastBlock = fileInode.getLastBlock(); 3119 if (lastBlock != null 3120 && lastBlock.getBlockUCState() == BlockUCState.UNDER_RECOVERY) { 3121 throw new RecoveryInProgressException("Recovery in progress, file [" 3122 + src + "], " + "lease owner [" + lease.getHolder() + "]"); 3123 } else { 3124 throw new AlreadyBeingCreatedException("Failed to create file [" 3125 + src + "] for [" + holder + "] for client [" + clientMachine 3126 + "], because this file is already being created by [" 3127 + clientName + "] on [" 3128 + uc.getClientMachine() + "]"); 3129 } 3130 } 3131 } 3132 } 3133 } 3134 3135 /** 3136 * Append to an existing file in the namespace. 3137 */ 3138 LocatedBlock appendFile(String src, String holder, String clientMachine) 3139 throws AccessControlException, SafeModeException, 3140 FileAlreadyExistsException, FileNotFoundException, 3141 ParentNotDirectoryException, IOException { 3142 LocatedBlock lb = null; 3143 CacheEntryWithPayload cacheEntry = RetryCache.waitForCompletion(retryCache, 3144 null); 3145 if (cacheEntry != null && cacheEntry.isSuccess()) { 3146 return (LocatedBlock) cacheEntry.getPayload(); 3147 } 3148 3149 boolean success = false; 3150 try { 3151 lb = appendFileInt(src, holder, clientMachine, cacheEntry != null); 3152 success = true; 3153 return lb; 3154 } catch (AccessControlException e) { 3155 logAuditEvent(false, "append", src); 3156 throw e; 3157 } finally { 3158 RetryCache.setState(cacheEntry, success, lb); 3159 } 3160 } 3161 3162 private LocatedBlock appendFileInt(final String srcArg, String holder, 3163 String clientMachine, boolean logRetryCache) 3164 throws AccessControlException, SafeModeException, 3165 FileAlreadyExistsException, FileNotFoundException, 3166 ParentNotDirectoryException, IOException { 3167 String src = srcArg; 3168 if (NameNode.stateChangeLog.isDebugEnabled()) { 3169 NameNode.stateChangeLog.debug("DIR* NameSystem.appendFile: src=" + src 3170 + ", holder=" + holder 3171 + ", clientMachine=" + clientMachine); 3172 } 3173 boolean skipSync = false; 3174 if (!supportAppends) { 3175 throw new UnsupportedOperationException( 3176 "Append is not enabled on this NameNode. Use the " + 3177 DFS_SUPPORT_APPEND_KEY + " configuration option to enable it."); 3178 } 3179 3180 LocatedBlock lb = null; 3181 FSPermissionChecker pc = getPermissionChecker(); 3182 checkOperation(OperationCategory.WRITE); 3183 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3184 writeLock(); 3185 try { 3186 checkOperation(OperationCategory.WRITE); 3187 checkNameNodeSafeMode("Cannot append to file" + src); 3188 src = resolvePath(src, pathComponents); 3189 lb = appendFileInternal(pc, src, holder, clientMachine, logRetryCache); 3190 } catch (StandbyException se) { 3191 skipSync = true; 3192 throw se; 3193 } finally { 3194 writeUnlock(); 3195 // There might be transactions logged while trying to recover the lease. 3196 // They need to be sync'ed even when an exception was thrown. 3197 if (!skipSync) { 3198 getEditLog().logSync(); 3199 } 3200 } 3201 if (lb != null) { 3202 if (NameNode.stateChangeLog.isDebugEnabled()) { 3203 NameNode.stateChangeLog.debug("DIR* NameSystem.appendFile: file " 3204 +src+" for "+holder+" at "+clientMachine 3205 +" block " + lb.getBlock() 3206 +" block size " + lb.getBlock().getNumBytes()); 3207 } 3208 } 3209 logAuditEvent(true, "append", srcArg); 3210 return lb; 3211 } 3212 3213 ExtendedBlock getExtendedBlock(Block blk) { 3214 return new ExtendedBlock(blockPoolId, blk); 3215 } 3216 3217 void setBlockPoolId(String bpid) { 3218 blockPoolId = bpid; 3219 blockManager.setBlockPoolId(blockPoolId); 3220 } 3221 3222 /** 3223 * The client would like to obtain an additional block for the indicated 3224 * filename (which is being written-to). Return an array that consists 3225 * of the block, plus a set of machines. The first on this list should 3226 * be where the client writes data. Subsequent items in the list must 3227 * be provided in the connection to the first datanode. 3228 * 3229 * Make sure the previous blocks have been reported by datanodes and 3230 * are replicated. Will return an empty 2-elt array if we want the 3231 * client to "try again later". 3232 */ 3233 LocatedBlock getAdditionalBlock(String src, long fileId, String clientName, 3234 ExtendedBlock previous, Set<Node> excludedNodes, 3235 List<String> favoredNodes) 3236 throws LeaseExpiredException, NotReplicatedYetException, 3237 QuotaExceededException, SafeModeException, UnresolvedLinkException, 3238 IOException { 3239 final long blockSize; 3240 final int replication; 3241 final byte storagePolicyID; 3242 Node clientNode = null; 3243 String clientMachine = null; 3244 3245 if(NameNode.stateChangeLog.isDebugEnabled()) { 3246 NameNode.stateChangeLog.debug("BLOCK* NameSystem.getAdditionalBlock: " 3247 + src + " inodeId " + fileId + " for " + clientName); 3248 } 3249 3250 // Part I. Analyze the state of the file with respect to the input data. 3251 checkOperation(OperationCategory.READ); 3252 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3253 readLock(); 3254 try { 3255 checkOperation(OperationCategory.READ); 3256 src = resolvePath(src, pathComponents); 3257 LocatedBlock[] onRetryBlock = new LocatedBlock[1]; 3258 FileState fileState = analyzeFileState( 3259 src, fileId, clientName, previous, onRetryBlock); 3260 final INodeFile pendingFile = fileState.inode; 3261 src = fileState.path; 3262 3263 if (onRetryBlock[0] != null && onRetryBlock[0].getLocations().length > 0) { 3264 // This is a retry. Just return the last block if having locations. 3265 return onRetryBlock[0]; 3266 } 3267 if (pendingFile.getBlocks().length >= maxBlocksPerFile) { 3268 throw new IOException("File has reached the limit on maximum number of" 3269 + " blocks (" + DFSConfigKeys.DFS_NAMENODE_MAX_BLOCKS_PER_FILE_KEY 3270 + "): " + pendingFile.getBlocks().length + " >= " 3271 + maxBlocksPerFile); 3272 } 3273 blockSize = pendingFile.getPreferredBlockSize(); 3274 clientMachine = pendingFile.getFileUnderConstructionFeature() 3275 .getClientMachine(); 3276 clientNode = blockManager.getDatanodeManager().getDatanodeByHost( 3277 clientMachine); 3278 replication = pendingFile.getFileReplication(); 3279 storagePolicyID = pendingFile.getStoragePolicyID(); 3280 } finally { 3281 readUnlock(); 3282 } 3283 3284 if (clientNode == null) { 3285 clientNode = getClientNode(clientMachine); 3286 } 3287 3288 // choose targets for the new block to be allocated. 3289 final DatanodeStorageInfo targets[] = getBlockManager().chooseTarget4NewBlock( 3290 src, replication, clientNode, excludedNodes, blockSize, favoredNodes, 3291 storagePolicyID); 3292 3293 // Part II. 3294 // Allocate a new block, add it to the INode and the BlocksMap. 3295 Block newBlock = null; 3296 long offset; 3297 checkOperation(OperationCategory.WRITE); 3298 waitForLoadingFSImage(); 3299 writeLock(); 3300 try { 3301 checkOperation(OperationCategory.WRITE); 3302 // Run the full analysis again, since things could have changed 3303 // while chooseTarget() was executing. 3304 LocatedBlock[] onRetryBlock = new LocatedBlock[1]; 3305 FileState fileState = 3306 analyzeFileState(src, fileId, clientName, previous, onRetryBlock); 3307 final INodeFile pendingFile = fileState.inode; 3308 src = fileState.path; 3309 3310 if (onRetryBlock[0] != null) { 3311 if (onRetryBlock[0].getLocations().length > 0) { 3312 // This is a retry. Just return the last block if having locations. 3313 return onRetryBlock[0]; 3314 } else { 3315 // add new chosen targets to already allocated block and return 3316 BlockInfo lastBlockInFile = pendingFile.getLastBlock(); 3317 ((BlockInfoUnderConstruction) lastBlockInFile) 3318 .setExpectedLocations(targets); 3319 offset = pendingFile.computeFileSize(); 3320 return makeLocatedBlock(lastBlockInFile, targets, offset); 3321 } 3322 } 3323 3324 // commit the last block and complete it if it has minimum replicas 3325 commitOrCompleteLastBlock(pendingFile, 3326 ExtendedBlock.getLocalBlock(previous)); 3327 3328 // allocate new block, record block locations in INode. 3329 newBlock = createNewBlock(); 3330 INodesInPath inodesInPath = INodesInPath.fromINode(pendingFile); 3331 saveAllocatedBlock(src, inodesInPath, newBlock, targets); 3332 3333 persistNewBlock(src, pendingFile); 3334 offset = pendingFile.computeFileSize(); 3335 } finally { 3336 writeUnlock(); 3337 } 3338 getEditLog().logSync(); 3339 3340 // Return located block 3341 return makeLocatedBlock(newBlock, targets, offset); 3342 } 3343 3344 /* 3345 * Resolve clientmachine address to get a network location path 3346 */ 3347 private Node getClientNode(String clientMachine) { 3348 List<String> hosts = new ArrayList<String>(1); 3349 hosts.add(clientMachine); 3350 List<String> rName = getBlockManager().getDatanodeManager() 3351 .resolveNetworkLocation(hosts); 3352 Node clientNode = null; 3353 if (rName != null) { 3354 // Able to resolve clientMachine mapping. 3355 // Create a temp node to findout the rack local nodes 3356 clientNode = new NodeBase(rName.get(0) + NodeBase.PATH_SEPARATOR_STR 3357 + clientMachine); 3358 } 3359 return clientNode; 3360 } 3361 3362 static class FileState { 3363 public final INodeFile inode; 3364 public final String path; 3365 3366 public FileState(INodeFile inode, String fullPath) { 3367 this.inode = inode; 3368 this.path = fullPath; 3369 } 3370 } 3371 3372 FileState analyzeFileState(String src, 3373 long fileId, 3374 String clientName, 3375 ExtendedBlock previous, 3376 LocatedBlock[] onRetryBlock) 3377 throws IOException { 3378 assert hasReadLock(); 3379 3380 checkBlock(previous); 3381 onRetryBlock[0] = null; 3382 checkOperation(OperationCategory.WRITE); 3383 checkNameNodeSafeMode("Cannot add block to " + src); 3384 3385 // have we exceeded the configured limit of fs objects. 3386 checkFsObjectLimit(); 3387 3388 Block previousBlock = ExtendedBlock.getLocalBlock(previous); 3389 INode inode; 3390 if (fileId == INodeId.GRANDFATHER_INODE_ID) { 3391 // Older clients may not have given us an inode ID to work with. 3392 // In this case, we have to try to resolve the path and hope it 3393 // hasn't changed or been deleted since the file was opened for write. 3394 final INodesInPath iip = dir.getINodesInPath4Write(src); 3395 inode = iip.getLastINode(); 3396 } else { 3397 // Newer clients pass the inode ID, so we can just get the inode 3398 // directly. 3399 inode = dir.getInode(fileId); 3400 if (inode != null) src = inode.getFullPathName(); 3401 } 3402 final INodeFile pendingFile = checkLease(src, clientName, inode, fileId); 3403 BlockInfo lastBlockInFile = pendingFile.getLastBlock(); 3404 if (!Block.matchingIdAndGenStamp(previousBlock, lastBlockInFile)) { 3405 // The block that the client claims is the current last block 3406 // doesn't match up with what we think is the last block. There are 3407 // four possibilities: 3408 // 1) This is the first block allocation of an append() pipeline 3409 // which started appending exactly at or exceeding the block boundary. 3410 // In this case, the client isn't passed the previous block, 3411 // so it makes the allocateBlock() call with previous=null. 3412 // We can distinguish this since the last block of the file 3413 // will be exactly a full block. 3414 // 2) This is a retry from a client that missed the response of a 3415 // prior getAdditionalBlock() call, perhaps because of a network 3416 // timeout, or because of an HA failover. In that case, we know 3417 // by the fact that the client is re-issuing the RPC that it 3418 // never began to write to the old block. Hence it is safe to 3419 // to return the existing block. 3420 // 3) This is an entirely bogus request/bug -- we should error out 3421 // rather than potentially appending a new block with an empty 3422 // one in the middle, etc 3423 // 4) This is a retry from a client that timed out while 3424 // the prior getAdditionalBlock() is still being processed, 3425 // currently working on chooseTarget(). 3426 // There are no means to distinguish between the first and 3427 // the second attempts in Part I, because the first one hasn't 3428 // changed the namesystem state yet. 3429 // We run this analysis again in Part II where case 4 is impossible. 3430 3431 BlockInfo penultimateBlock = pendingFile.getPenultimateBlock(); 3432 if (previous == null && 3433 lastBlockInFile != null && 3434 lastBlockInFile.getNumBytes() >= pendingFile.getPreferredBlockSize() && 3435 lastBlockInFile.isComplete()) { 3436 // Case 1 3437 if (NameNode.stateChangeLog.isDebugEnabled()) { 3438 NameNode.stateChangeLog.debug( 3439 "BLOCK* NameSystem.allocateBlock: handling block allocation" + 3440 " writing to a file with a complete previous block: src=" + 3441 src + " lastBlock=" + lastBlockInFile); 3442 } 3443 } else if (Block.matchingIdAndGenStamp(penultimateBlock, previousBlock)) { 3444 if (lastBlockInFile.getNumBytes() != 0) { 3445 throw new IOException( 3446 "Request looked like a retry to allocate block " + 3447 lastBlockInFile + " but it already contains " + 3448 lastBlockInFile.getNumBytes() + " bytes"); 3449 } 3450 3451 // Case 2 3452 // Return the last block. 3453 NameNode.stateChangeLog.info("BLOCK* allocateBlock: " + 3454 "caught retry for allocation of a new block in " + 3455 src + ". Returning previously allocated block " + lastBlockInFile); 3456 long offset = pendingFile.computeFileSize(); 3457 onRetryBlock[0] = makeLocatedBlock(lastBlockInFile, 3458 ((BlockInfoUnderConstruction)lastBlockInFile).getExpectedStorageLocations(), 3459 offset); 3460 return new FileState(pendingFile, src); 3461 } else { 3462 // Case 3 3463 throw new IOException("Cannot allocate block in " + src + ": " + 3464 "passed 'previous' block " + previous + " does not match actual " + 3465 "last block in file " + lastBlockInFile); 3466 } 3467 } 3468 3469 // Check if the penultimate block is minimally replicated 3470 if (!checkFileProgress(pendingFile, false)) { 3471 throw new NotReplicatedYetException("Not replicated yet: " + src); 3472 } 3473 return new FileState(pendingFile, src); 3474 } 3475 3476 LocatedBlock makeLocatedBlock(Block blk, DatanodeStorageInfo[] locs, 3477 long offset) throws IOException { 3478 LocatedBlock lBlk = new LocatedBlock( 3479 getExtendedBlock(blk), locs, offset, false); 3480 getBlockManager().setBlockToken( 3481 lBlk, BlockTokenSecretManager.AccessMode.WRITE); 3482 return lBlk; 3483 } 3484 3485 /** @see ClientProtocol#getAdditionalDatanode */ 3486 LocatedBlock getAdditionalDatanode(String src, long fileId, 3487 final ExtendedBlock blk, final DatanodeInfo[] existings, 3488 final String[] storageIDs, 3489 final Set<Node> excludes, 3490 final int numAdditionalNodes, final String clientName 3491 ) throws IOException { 3492 //check if the feature is enabled 3493 dtpReplaceDatanodeOnFailure.checkEnabled(); 3494 3495 Node clientnode = null; 3496 String clientMachine; 3497 final long preferredblocksize; 3498 final byte storagePolicyID; 3499 final List<DatanodeStorageInfo> chosen; 3500 checkOperation(OperationCategory.READ); 3501 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3502 readLock(); 3503 try { 3504 checkOperation(OperationCategory.READ); 3505 //check safe mode 3506 checkNameNodeSafeMode("Cannot add datanode; src=" + src + ", blk=" + blk); 3507 src = resolvePath(src, pathComponents); 3508 3509 //check lease 3510 final INode inode; 3511 if (fileId == INodeId.GRANDFATHER_INODE_ID) { 3512 // Older clients may not have given us an inode ID to work with. 3513 // In this case, we have to try to resolve the path and hope it 3514 // hasn't changed or been deleted since the file was opened for write. 3515 inode = dir.getINode(src); 3516 } else { 3517 inode = dir.getInode(fileId); 3518 if (inode != null) src = inode.getFullPathName(); 3519 } 3520 final INodeFile file = checkLease(src, clientName, inode, fileId); 3521 clientMachine = file.getFileUnderConstructionFeature().getClientMachine(); 3522 clientnode = blockManager.getDatanodeManager().getDatanodeByHost(clientMachine); 3523 preferredblocksize = file.getPreferredBlockSize(); 3524 storagePolicyID = file.getStoragePolicyID(); 3525 3526 //find datanode storages 3527 final DatanodeManager dm = blockManager.getDatanodeManager(); 3528 chosen = Arrays.asList(dm.getDatanodeStorageInfos(existings, storageIDs)); 3529 } finally { 3530 readUnlock(); 3531 } 3532 3533 if (clientnode == null) { 3534 clientnode = getClientNode(clientMachine); 3535 } 3536 3537 // choose new datanodes. 3538 final DatanodeStorageInfo[] targets = blockManager.chooseTarget4AdditionalDatanode( 3539 src, numAdditionalNodes, clientnode, chosen, 3540 excludes, preferredblocksize, storagePolicyID); 3541 final LocatedBlock lb = new LocatedBlock(blk, targets); 3542 blockManager.setBlockToken(lb, AccessMode.COPY); 3543 return lb; 3544 } 3545 3546 /** 3547 * The client would like to let go of the given block 3548 */ 3549 boolean abandonBlock(ExtendedBlock b, long fileId, String src, String holder) 3550 throws LeaseExpiredException, FileNotFoundException, 3551 UnresolvedLinkException, IOException { 3552 if(NameNode.stateChangeLog.isDebugEnabled()) { 3553 NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " + b 3554 + "of file " + src); 3555 } 3556 checkOperation(OperationCategory.WRITE); 3557 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3558 waitForLoadingFSImage(); 3559 writeLock(); 3560 try { 3561 checkOperation(OperationCategory.WRITE); 3562 checkNameNodeSafeMode("Cannot abandon block " + b + " for file" + src); 3563 src = resolvePath(src, pathComponents); 3564 3565 final INode inode; 3566 if (fileId == INodeId.GRANDFATHER_INODE_ID) { 3567 // Older clients may not have given us an inode ID to work with. 3568 // In this case, we have to try to resolve the path and hope it 3569 // hasn't changed or been deleted since the file was opened for write. 3570 inode = dir.getINode(src); 3571 } else { 3572 inode = dir.getInode(fileId); 3573 if (inode != null) src = inode.getFullPathName(); 3574 } 3575 final INodeFile file = checkLease(src, holder, inode, fileId); 3576 3577 // 3578 // Remove the block from the pending creates list 3579 // 3580 boolean removed = dir.removeBlock(src, file, 3581 ExtendedBlock.getLocalBlock(b)); 3582 if (!removed) { 3583 return true; 3584 } 3585 if(NameNode.stateChangeLog.isDebugEnabled()) { 3586 NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " 3587 + b + " is removed from pendingCreates"); 3588 } 3589 persistBlocks(src, file, false); 3590 } finally { 3591 writeUnlock(); 3592 } 3593 getEditLog().logSync(); 3594 3595 return true; 3596 } 3597 3598 private INodeFile checkLease(String src, String holder, INode inode, 3599 long fileId) 3600 throws LeaseExpiredException, FileNotFoundException { 3601 assert hasReadLock(); 3602 final String ident = src + " (inode " + fileId + ")"; 3603 if (inode == null) { 3604 Lease lease = leaseManager.getLease(holder); 3605 throw new LeaseExpiredException( 3606 "No lease on " + ident + ": File does not exist. " 3607 + (lease != null ? lease.toString() 3608 : "Holder " + holder + " does not have any open files.")); 3609 } 3610 if (!inode.isFile()) { 3611 Lease lease = leaseManager.getLease(holder); 3612 throw new LeaseExpiredException( 3613 "No lease on " + ident + ": INode is not a regular file. " 3614 + (lease != null ? lease.toString() 3615 : "Holder " + holder + " does not have any open files.")); 3616 } 3617 final INodeFile file = inode.asFile(); 3618 if (!file.isUnderConstruction()) { 3619 Lease lease = leaseManager.getLease(holder); 3620 throw new LeaseExpiredException( 3621 "No lease on " + ident + ": File is not open for writing. " 3622 + (lease != null ? lease.toString() 3623 : "Holder " + holder + " does not have any open files.")); 3624 } 3625 // No further modification is allowed on a deleted file. 3626 // A file is considered deleted, if it is not in the inodeMap or is marked 3627 // as deleted in the snapshot feature. 3628 if (isFileDeleted(file)) { 3629 throw new FileNotFoundException(src); 3630 } 3631 String clientName = file.getFileUnderConstructionFeature().getClientName(); 3632 if (holder != null && !clientName.equals(holder)) { 3633 throw new LeaseExpiredException("Lease mismatch on " + ident + 3634 " owned by " + clientName + " but is accessed by " + holder); 3635 } 3636 return file; 3637 } 3638 3639 /** 3640 * Complete in-progress write to the given file. 3641 * @return true if successful, false if the client should continue to retry 3642 * (e.g if not all blocks have reached minimum replication yet) 3643 * @throws IOException on error (eg lease mismatch, file not open, file deleted) 3644 */ 3645 boolean completeFile(final String srcArg, String holder, 3646 ExtendedBlock last, long fileId) 3647 throws SafeModeException, UnresolvedLinkException, IOException { 3648 String src = srcArg; 3649 if (NameNode.stateChangeLog.isDebugEnabled()) { 3650 NameNode.stateChangeLog.debug("DIR* NameSystem.completeFile: " + 3651 src + " for " + holder); 3652 } 3653 checkBlock(last); 3654 boolean success = false; 3655 checkOperation(OperationCategory.WRITE); 3656 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 3657 waitForLoadingFSImage(); 3658 writeLock(); 3659 try { 3660 checkOperation(OperationCategory.WRITE); 3661 checkNameNodeSafeMode("Cannot complete file " + src); 3662 src = resolvePath(src, pathComponents); 3663 success = completeFileInternal(src, holder, 3664 ExtendedBlock.getLocalBlock(last), fileId); 3665 } finally { 3666 writeUnlock(); 3667 } 3668 getEditLog().logSync(); 3669 if (success) { 3670 NameNode.stateChangeLog.info("DIR* completeFile: " + srcArg 3671 + " is closed by " + holder); 3672 } 3673 return success; 3674 } 3675 3676 private boolean completeFileInternal(String src, 3677 String holder, Block last, long fileId) throws SafeModeException, 3678 UnresolvedLinkException, IOException { 3679 assert hasWriteLock(); 3680 final INodeFile pendingFile; 3681 try { 3682 final INode inode; 3683 if (fileId == INodeId.GRANDFATHER_INODE_ID) { 3684 // Older clients may not have given us an inode ID to work with. 3685 // In this case, we have to try to resolve the path and hope it 3686 // hasn't changed or been deleted since the file was opened for write. 3687 final INodesInPath iip = dir.getLastINodeInPath(src); 3688 inode = iip.getINode(0); 3689 } else { 3690 inode = dir.getInode(fileId); 3691 if (inode != null) src = inode.getFullPathName(); 3692 } 3693 pendingFile = checkLease(src, holder, inode, fileId); 3694 } catch (LeaseExpiredException lee) { 3695 final INode inode = dir.getINode(src); 3696 if (inode != null 3697 && inode.isFile() 3698 && !inode.asFile().isUnderConstruction()) { 3699 // This could be a retry RPC - i.e the client tried to close 3700 // the file, but missed the RPC response. Thus, it is trying 3701 // again to close the file. If the file still exists and 3702 // the client's view of the last block matches the actual 3703 // last block, then we'll treat it as a successful close. 3704 // See HDFS-3031. 3705 final Block realLastBlock = inode.asFile().getLastBlock(); 3706 if (Block.matchingIdAndGenStamp(last, realLastBlock)) { 3707 NameNode.stateChangeLog.info("DIR* completeFile: " + 3708 "request from " + holder + " to complete inode " + fileId + 3709 "(" + src + ") which is already closed. But, it appears to be " + 3710 "an RPC retry. Returning success"); 3711 return true; 3712 } 3713 } 3714 throw lee; 3715 } 3716 // Check the state of the penultimate block. It should be completed 3717 // before attempting to complete the last one. 3718 if (!checkFileProgress(pendingFile, false)) { 3719 return false; 3720 } 3721 3722 // commit the last block and complete it if it has minimum replicas 3723 commitOrCompleteLastBlock(pendingFile, last); 3724 3725 if (!checkFileProgress(pendingFile, true)) { 3726 return false; 3727 } 3728 3729 finalizeINodeFileUnderConstruction(src, pendingFile, 3730 Snapshot.CURRENT_STATE_ID); 3731 return true; 3732 } 3733 3734 /** 3735 * Save allocated block at the given pending filename 3736 * 3737 * @param src path to the file 3738 * @param inodesInPath representing each of the components of src. 3739 * The last INode is the INode for {@code src} file. 3740 * @param newBlock newly allocated block to be save 3741 * @param targets target datanodes where replicas of the new block is placed 3742 * @throws QuotaExceededException If addition of block exceeds space quota 3743 */ 3744 BlockInfo saveAllocatedBlock(String src, INodesInPath inodes, 3745 Block newBlock, DatanodeStorageInfo[] targets) 3746 throws IOException { 3747 assert hasWriteLock(); 3748 BlockInfo b = dir.addBlock(src, inodes, newBlock, targets); 3749 NameNode.stateChangeLog.info("BLOCK* allocateBlock: " + src + ". " 3750 + getBlockPoolId() + " " + b); 3751 DatanodeStorageInfo.incrementBlocksScheduled(targets); 3752 return b; 3753 } 3754 3755 /** 3756 * Create new block with a unique block id and a new generation stamp. 3757 */ 3758 Block createNewBlock() throws IOException { 3759 assert hasWriteLock(); 3760 Block b = new Block(nextBlockId(), 0, 0); 3761 // Increment the generation stamp for every new block. 3762 b.setGenerationStamp(nextGenerationStamp(false)); 3763 return b; 3764 } 3765 3766 /** 3767 * Check that the indicated file's blocks are present and 3768 * replicated. If not, return false. If checkall is true, then check 3769 * all blocks, otherwise check only penultimate block. 3770 */ 3771 boolean checkFileProgress(INodeFile v, boolean checkall) { 3772 readLock(); 3773 try { 3774 if (checkall) { 3775 // 3776 // check all blocks of the file. 3777 // 3778 for (BlockInfo block: v.getBlocks()) { 3779 if (!block.isComplete()) { 3780 LOG.info("BLOCK* checkFileProgress: " + block 3781 + " has not reached minimal replication " 3782 + blockManager.minReplication); 3783 return false; 3784 } 3785 } 3786 } else { 3787 // 3788 // check the penultimate block of this file 3789 // 3790 BlockInfo b = v.getPenultimateBlock(); 3791 if (b != null && !b.isComplete()) { 3792 LOG.warn("BLOCK* checkFileProgress: " + b 3793 + " has not reached minimal replication " 3794 + blockManager.minReplication); 3795 return false; 3796 } 3797 } 3798 return true; 3799 } finally { 3800 readUnlock(); 3801 } 3802 } 3803 3804 //////////////////////////////////////////////////////////////// 3805 // Here's how to handle block-copy failure during client write: 3806 // -- As usual, the client's write should result in a streaming 3807 // backup write to a k-machine sequence. 3808 // -- If one of the backup machines fails, no worries. Fail silently. 3809 // -- Before client is allowed to close and finalize file, make sure 3810 // that the blocks are backed up. Namenode may have to issue specific backup 3811 // commands to make up for earlier datanode failures. Once all copies 3812 // are made, edit namespace and return to client. 3813 //////////////////////////////////////////////////////////////// 3814 3815 /** 3816 * Change the indicated filename. 3817 * @deprecated Use {@link #renameTo(String, String, Options.Rename...)} instead. 3818 */ 3819 @Deprecated 3820 boolean renameTo(String src, String dst) 3821 throws IOException, UnresolvedLinkException { 3822 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 3823 if (cacheEntry != null && cacheEntry.isSuccess()) { 3824 return true; // Return previous response 3825 } 3826 boolean ret = false; 3827 try { 3828 ret = renameToInt(src, dst, cacheEntry != null); 3829 } catch (AccessControlException e) { 3830 logAuditEvent(false, "rename", src, dst, null); 3831 throw e; 3832 } finally { 3833 RetryCache.setState(cacheEntry, ret); 3834 } 3835 return ret; 3836 } 3837 3838 private boolean renameToInt(final String srcArg, final String dstArg, 3839 boolean logRetryCache) 3840 throws IOException, UnresolvedLinkException { 3841 String src = srcArg; 3842 String dst = dstArg; 3843 if (NameNode.stateChangeLog.isDebugEnabled()) { 3844 NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: " + src + 3845 " to " + dst); 3846 } 3847 if (!DFSUtil.isValidName(dst)) { 3848 throw new IOException("Invalid name: " + dst); 3849 } 3850 FSPermissionChecker pc = getPermissionChecker(); 3851 checkOperation(OperationCategory.WRITE); 3852 byte[][] srcComponents = FSDirectory.getPathComponentsForReservedPath(src); 3853 byte[][] dstComponents = FSDirectory.getPathComponentsForReservedPath(dst); 3854 boolean status = false; 3855 HdfsFileStatus resultingStat = null; 3856 writeLock(); 3857 try { 3858 checkOperation(OperationCategory.WRITE); 3859 checkNameNodeSafeMode("Cannot rename " + src); 3860 waitForLoadingFSImage(); 3861 src = resolvePath(src, srcComponents); 3862 dst = resolvePath(dst, dstComponents); 3863 checkOperation(OperationCategory.WRITE); 3864 status = renameToInternal(pc, src, dst, logRetryCache); 3865 if (status) { 3866 resultingStat = getAuditFileInfo(dst, false); 3867 } 3868 } finally { 3869 writeUnlock(); 3870 } 3871 getEditLog().logSync(); 3872 if (status) { 3873 logAuditEvent(true, "rename", srcArg, dstArg, resultingStat); 3874 } 3875 return status; 3876 } 3877 3878 /** @deprecated See {@link #renameTo(String, String)} */ 3879 @Deprecated 3880 private boolean renameToInternal(FSPermissionChecker pc, String src, 3881 String dst, boolean logRetryCache) throws IOException, 3882 UnresolvedLinkException { 3883 assert hasWriteLock(); 3884 String actualdst = dir.isDir(dst)? 3885 dst + Path.SEPARATOR + new Path(src).getName(): dst; 3886 if (isPermissionEnabled) { 3887 //We should not be doing this. This is move() not renameTo(). 3888 //but for now, 3889 //NOTE: yes, this is bad! it's assuming much lower level behavior 3890 // of rewriting the dst 3891 // Rename does not operates on link targets 3892 // Do not resolveLink when checking permissions of src and dst 3893 // Check write access to parent of src 3894 checkPermission(pc, src, false, null, FsAction.WRITE, null, null, 3895 false, false); 3896 // Check write access to ancestor of dst 3897 checkPermission(pc, actualdst, false, FsAction.WRITE, null, null, null, 3898 false, false); 3899 } 3900 3901 long mtime = now(); 3902 if (dir.renameTo(src, dst, mtime)) { 3903 getEditLog().logRename(src, actualdst, mtime, logRetryCache); 3904 return true; 3905 } 3906 return false; 3907 } 3908 3909 3910 /** Rename src to dst */ 3911 void renameTo(final String srcArg, final String dstArg, 3912 Options.Rename... options) throws IOException, UnresolvedLinkException { 3913 String src = srcArg; 3914 String dst = dstArg; 3915 if (NameNode.stateChangeLog.isDebugEnabled()) { 3916 NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: with options - " 3917 + src + " to " + dst); 3918 } 3919 if (!DFSUtil.isValidName(dst)) { 3920 throw new InvalidPathException("Invalid name: " + dst); 3921 } 3922 final FSPermissionChecker pc = getPermissionChecker(); 3923 3924 checkOperation(OperationCategory.WRITE); 3925 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 3926 if (cacheEntry != null && cacheEntry.isSuccess()) { 3927 return; // Return previous response 3928 } 3929 byte[][] srcComponents = FSDirectory.getPathComponentsForReservedPath(src); 3930 byte[][] dstComponents = FSDirectory.getPathComponentsForReservedPath(dst); 3931 HdfsFileStatus resultingStat = null; 3932 boolean success = false; 3933 writeLock(); 3934 BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo(); 3935 try { 3936 checkOperation(OperationCategory.WRITE); 3937 checkNameNodeSafeMode("Cannot rename " + src); 3938 src = resolvePath(src, srcComponents); 3939 dst = resolvePath(dst, dstComponents); 3940 renameToInternal(pc, src, dst, cacheEntry != null, 3941 collectedBlocks, options); 3942 resultingStat = getAuditFileInfo(dst, false); 3943 success = true; 3944 } finally { 3945 writeUnlock(); 3946 RetryCache.setState(cacheEntry, success); 3947 } 3948 getEditLog().logSync(); 3949 if (!collectedBlocks.getToDeleteList().isEmpty()) { 3950 removeBlocks(collectedBlocks); 3951 collectedBlocks.clear(); 3952 } 3953 if (resultingStat != null) { 3954 StringBuilder cmd = new StringBuilder("rename options="); 3955 for (Rename option : options) { 3956 cmd.append(option.value()).append(" "); 3957 } 3958 logAuditEvent(true, cmd.toString(), srcArg, dstArg, resultingStat); 3959 } 3960 } 3961 3962 private void renameToInternal(FSPermissionChecker pc, String src, 3963 String dst, boolean logRetryCache, BlocksMapUpdateInfo collectedBlocks, 3964 Options.Rename... options) throws IOException { 3965 assert hasWriteLock(); 3966 if (isPermissionEnabled) { 3967 // Rename does not operates on link targets 3968 // Do not resolveLink when checking permissions of src and dst 3969 // Check write access to parent of src 3970 checkPermission(pc, src, false, null, FsAction.WRITE, null, null, false, 3971 false); 3972 // Check write access to ancestor of dst 3973 checkPermission(pc, dst, false, FsAction.WRITE, null, null, null, false, 3974 false); 3975 } 3976 3977 waitForLoadingFSImage(); 3978 long mtime = now(); 3979 dir.renameTo(src, dst, mtime, collectedBlocks, options); 3980 getEditLog().logRename(src, dst, mtime, logRetryCache, options); 3981 } 3982 3983 /** 3984 * Remove the indicated file from namespace. 3985 * 3986 * @see ClientProtocol#delete(String, boolean) for detailed description and 3987 * description of exceptions 3988 */ 3989 boolean delete(String src, boolean recursive) 3990 throws AccessControlException, SafeModeException, 3991 UnresolvedLinkException, IOException { 3992 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 3993 if (cacheEntry != null && cacheEntry.isSuccess()) { 3994 return true; // Return previous response 3995 } 3996 boolean ret = false; 3997 try { 3998 ret = deleteInt(src, recursive, cacheEntry != null); 3999 } catch (AccessControlException e) { 4000 logAuditEvent(false, "delete", src); 4001 throw e; 4002 } finally { 4003 RetryCache.setState(cacheEntry, ret); 4004 } 4005 return ret; 4006 } 4007 4008 private boolean deleteInt(String src, boolean recursive, boolean logRetryCache) 4009 throws AccessControlException, SafeModeException, 4010 UnresolvedLinkException, IOException { 4011 if (NameNode.stateChangeLog.isDebugEnabled()) { 4012 NameNode.stateChangeLog.debug("DIR* NameSystem.delete: " + src); 4013 } 4014 boolean status = deleteInternal(src, recursive, true, logRetryCache); 4015 if (status) { 4016 logAuditEvent(true, "delete", src); 4017 } 4018 return status; 4019 } 4020 4021 private FSPermissionChecker getPermissionChecker() 4022 throws AccessControlException { 4023 try { 4024 return new FSPermissionChecker(fsOwnerShortUserName, supergroup, getRemoteUser()); 4025 } catch (IOException ioe) { 4026 throw new AccessControlException(ioe); 4027 } 4028 } 4029 4030 /** 4031 * Remove a file/directory from the namespace. 4032 * <p> 4033 * For large directories, deletion is incremental. The blocks under 4034 * the directory are collected and deleted a small number at a time holding 4035 * the {@link FSNamesystem} lock. 4036 * <p> 4037 * For small directory or file the deletion is done in one shot. 4038 * 4039 * @see ClientProtocol#delete(String, boolean) for description of exceptions 4040 */ 4041 private boolean deleteInternal(String src, boolean recursive, 4042 boolean enforcePermission, boolean logRetryCache) 4043 throws AccessControlException, SafeModeException, UnresolvedLinkException, 4044 IOException { 4045 BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo(); 4046 List<INode> removedINodes = new ChunkedArrayList<INode>(); 4047 FSPermissionChecker pc = getPermissionChecker(); 4048 checkOperation(OperationCategory.WRITE); 4049 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4050 boolean ret = false; 4051 4052 waitForLoadingFSImage(); 4053 writeLock(); 4054 try { 4055 checkOperation(OperationCategory.WRITE); 4056 checkNameNodeSafeMode("Cannot delete " + src); 4057 src = resolvePath(src, pathComponents); 4058 if (!recursive && dir.isNonEmptyDirectory(src)) { 4059 throw new PathIsNotEmptyDirectoryException(src + " is non empty"); 4060 } 4061 if (enforcePermission && isPermissionEnabled) { 4062 checkPermission(pc, src, false, null, FsAction.WRITE, null, 4063 FsAction.ALL, true, false); 4064 } 4065 4066 long mtime = now(); 4067 // Unlink the target directory from directory tree 4068 long filesRemoved = dir.delete(src, collectedBlocks, removedINodes, 4069 mtime); 4070 if (filesRemoved < 0) { 4071 return false; 4072 } 4073 getEditLog().logDelete(src, mtime, logRetryCache); 4074 incrDeletedFileCount(filesRemoved); 4075 // Blocks/INodes will be handled later 4076 removePathAndBlocks(src, null, removedINodes, true); 4077 ret = true; 4078 } finally { 4079 writeUnlock(); 4080 } 4081 getEditLog().logSync(); 4082 removeBlocks(collectedBlocks); // Incremental deletion of blocks 4083 collectedBlocks.clear(); 4084 4085 if (NameNode.stateChangeLog.isDebugEnabled()) { 4086 NameNode.stateChangeLog.debug("DIR* Namesystem.delete: " 4087 + src +" is removed"); 4088 } 4089 return ret; 4090 } 4091 4092 /** 4093 * From the given list, incrementally remove the blocks from blockManager 4094 * Writelock is dropped and reacquired every BLOCK_DELETION_INCREMENT to 4095 * ensure that other waiters on the lock can get in. See HDFS-2938 4096 * 4097 * @param blocks 4098 * An instance of {@link BlocksMapUpdateInfo} which contains a list 4099 * of blocks that need to be removed from blocksMap 4100 */ 4101 void removeBlocks(BlocksMapUpdateInfo blocks) { 4102 List<Block> toDeleteList = blocks.getToDeleteList(); 4103 Iterator<Block> iter = toDeleteList.iterator(); 4104 while (iter.hasNext()) { 4105 writeLock(); 4106 try { 4107 for (int i = 0; i < BLOCK_DELETION_INCREMENT && iter.hasNext(); i++) { 4108 blockManager.removeBlock(iter.next()); 4109 } 4110 } finally { 4111 writeUnlock(); 4112 } 4113 } 4114 } 4115 4116 /** 4117 * Remove leases, inodes and blocks related to a given path 4118 * @param src The given path 4119 * @param blocks Containing the list of blocks to be deleted from blocksMap 4120 * @param removedINodes Containing the list of inodes to be removed from 4121 * inodesMap 4122 * @param acquireINodeMapLock Whether to acquire the lock for inode removal 4123 */ 4124 void removePathAndBlocks(String src, BlocksMapUpdateInfo blocks, 4125 List<INode> removedINodes, final boolean acquireINodeMapLock) { 4126 assert hasWriteLock(); 4127 leaseManager.removeLeaseWithPrefixPath(src); 4128 // remove inodes from inodesMap 4129 if (removedINodes != null) { 4130 if (acquireINodeMapLock) { 4131 dir.writeLock(); 4132 } 4133 try { 4134 dir.removeFromInodeMap(removedINodes); 4135 } finally { 4136 if (acquireINodeMapLock) { 4137 dir.writeUnlock(); 4138 } 4139 } 4140 removedINodes.clear(); 4141 } 4142 if (blocks == null) { 4143 return; 4144 } 4145 4146 removeBlocksAndUpdateSafemodeTotal(blocks); 4147 } 4148 4149 /** 4150 * Removes the blocks from blocksmap and updates the safemode blocks total 4151 * 4152 * @param blocks 4153 * An instance of {@link BlocksMapUpdateInfo} which contains a list 4154 * of blocks that need to be removed from blocksMap 4155 */ 4156 void removeBlocksAndUpdateSafemodeTotal(BlocksMapUpdateInfo blocks) { 4157 assert hasWriteLock(); 4158 // In the case that we are a Standby tailing edits from the 4159 // active while in safe-mode, we need to track the total number 4160 // of blocks and safe blocks in the system. 4161 boolean trackBlockCounts = isSafeModeTrackingBlocks(); 4162 int numRemovedComplete = 0, numRemovedSafe = 0; 4163 4164 for (Block b : blocks.getToDeleteList()) { 4165 if (trackBlockCounts) { 4166 BlockInfo bi = getStoredBlock(b); 4167 if (bi.isComplete()) { 4168 numRemovedComplete++; 4169 if (bi.numNodes() >= blockManager.minReplication) { 4170 numRemovedSafe++; 4171 } 4172 } 4173 } 4174 blockManager.removeBlock(b); 4175 } 4176 if (trackBlockCounts) { 4177 if (LOG.isDebugEnabled()) { 4178 LOG.debug("Adjusting safe-mode totals for deletion." 4179 + "decreasing safeBlocks by " + numRemovedSafe 4180 + ", totalBlocks by " + numRemovedComplete); 4181 } 4182 adjustSafeModeBlockTotals(-numRemovedSafe, -numRemovedComplete); 4183 } 4184 } 4185 4186 /** 4187 * @see SafeModeInfo#shouldIncrementallyTrackBlocks 4188 */ 4189 private boolean isSafeModeTrackingBlocks() { 4190 if (!haEnabled) { 4191 // Never track blocks incrementally in non-HA code. 4192 return false; 4193 } 4194 SafeModeInfo sm = this.safeMode; 4195 return sm != null && sm.shouldIncrementallyTrackBlocks(); 4196 } 4197 4198 /** 4199 * Get the file info for a specific file. 4200 * 4201 * @param srcArg The string representation of the path to the file 4202 * @param resolveLink whether to throw UnresolvedLinkException 4203 * if src refers to a symlink 4204 * 4205 * @throws AccessControlException if access is denied 4206 * @throws UnresolvedLinkException if a symlink is encountered. 4207 * 4208 * @return object containing information regarding the file 4209 * or null if file not found 4210 * @throws StandbyException 4211 */ 4212 HdfsFileStatus getFileInfo(final String srcArg, boolean resolveLink) 4213 throws AccessControlException, UnresolvedLinkException, 4214 StandbyException, IOException { 4215 String src = srcArg; 4216 if (!DFSUtil.isValidName(src)) { 4217 throw new InvalidPathException("Invalid file name: " + src); 4218 } 4219 HdfsFileStatus stat = null; 4220 FSPermissionChecker pc = getPermissionChecker(); 4221 checkOperation(OperationCategory.READ); 4222 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4223 readLock(); 4224 try { 4225 checkOperation(OperationCategory.READ); 4226 src = resolvePath(src, pathComponents); 4227 boolean isSuperUser = true; 4228 if (isPermissionEnabled) { 4229 checkPermission(pc, src, false, null, null, null, null, false, 4230 resolveLink); 4231 isSuperUser = pc.isSuperUser(); 4232 } 4233 stat = dir.getFileInfo(src, resolveLink, 4234 FSDirectory.isReservedRawName(srcArg), isSuperUser); 4235 } catch (AccessControlException e) { 4236 logAuditEvent(false, "getfileinfo", srcArg); 4237 throw e; 4238 } finally { 4239 readUnlock(); 4240 } 4241 logAuditEvent(true, "getfileinfo", srcArg); 4242 return stat; 4243 } 4244 4245 /** 4246 * Returns true if the file is closed 4247 */ 4248 boolean isFileClosed(final String srcArg) 4249 throws AccessControlException, UnresolvedLinkException, 4250 StandbyException, IOException { 4251 String src = srcArg; 4252 FSPermissionChecker pc = getPermissionChecker(); 4253 checkOperation(OperationCategory.READ); 4254 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4255 readLock(); 4256 try { 4257 src = resolvePath(src, pathComponents); 4258 checkOperation(OperationCategory.READ); 4259 if (isPermissionEnabled) { 4260 checkTraverse(pc, src); 4261 } 4262 return !INodeFile.valueOf(dir.getINode(src), src).isUnderConstruction(); 4263 } catch (AccessControlException e) { 4264 if (isAuditEnabled() && isExternalInvocation()) { 4265 logAuditEvent(false, "isFileClosed", srcArg); 4266 } 4267 throw e; 4268 } finally { 4269 readUnlock(); 4270 } 4271 } 4272 4273 /** 4274 * Create all the necessary directories 4275 */ 4276 boolean mkdirs(String src, PermissionStatus permissions, 4277 boolean createParent) throws IOException, UnresolvedLinkException { 4278 boolean ret = false; 4279 try { 4280 ret = mkdirsInt(src, permissions, createParent); 4281 } catch (AccessControlException e) { 4282 logAuditEvent(false, "mkdirs", src); 4283 throw e; 4284 } 4285 return ret; 4286 } 4287 4288 private boolean mkdirsInt(final String srcArg, PermissionStatus permissions, 4289 boolean createParent) throws IOException, UnresolvedLinkException { 4290 String src = srcArg; 4291 if(NameNode.stateChangeLog.isDebugEnabled()) { 4292 NameNode.stateChangeLog.debug("DIR* NameSystem.mkdirs: " + src); 4293 } 4294 if (!DFSUtil.isValidName(src)) { 4295 throw new InvalidPathException(src); 4296 } 4297 FSPermissionChecker pc = getPermissionChecker(); 4298 checkOperation(OperationCategory.WRITE); 4299 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4300 HdfsFileStatus resultingStat = null; 4301 boolean status = false; 4302 writeLock(); 4303 try { 4304 checkOperation(OperationCategory.WRITE); 4305 checkNameNodeSafeMode("Cannot create directory " + src); 4306 src = resolvePath(src, pathComponents); 4307 status = mkdirsInternal(pc, src, permissions, createParent); 4308 if (status) { 4309 resultingStat = getAuditFileInfo(src, false); 4310 } 4311 } finally { 4312 writeUnlock(); 4313 } 4314 getEditLog().logSync(); 4315 if (status) { 4316 logAuditEvent(true, "mkdirs", srcArg, null, resultingStat); 4317 } 4318 return status; 4319 } 4320 4321 /** 4322 * Create all the necessary directories 4323 */ 4324 private boolean mkdirsInternal(FSPermissionChecker pc, String src, 4325 PermissionStatus permissions, boolean createParent) 4326 throws IOException, UnresolvedLinkException { 4327 assert hasWriteLock(); 4328 if (isPermissionEnabled) { 4329 checkTraverse(pc, src); 4330 } 4331 if (dir.isDirMutable(src)) { 4332 // all the users of mkdirs() are used to expect 'true' even if 4333 // a new directory is not created. 4334 return true; 4335 } 4336 if (isPermissionEnabled) { 4337 checkAncestorAccess(pc, src, FsAction.WRITE); 4338 } 4339 if (!createParent) { 4340 verifyParentDir(src); 4341 } 4342 4343 // validate that we have enough inodes. This is, at best, a 4344 // heuristic because the mkdirs() operation might need to 4345 // create multiple inodes. 4346 checkFsObjectLimit(); 4347 4348 if (!mkdirsRecursively(src, permissions, false, now())) { 4349 throw new IOException("Failed to create directory: " + src); 4350 } 4351 return true; 4352 } 4353 4354 /** 4355 * Create a directory 4356 * If ancestor directories do not exist, automatically create them. 4357 4358 * @param src string representation of the path to the directory 4359 * @param permissions the permission of the directory 4360 * @param inheritPermission if the permission of the directory should inherit 4361 * from its parent or not. u+wx is implicitly added to 4362 * the automatically created directories, and to the 4363 * given directory if inheritPermission is true 4364 * @param now creation time 4365 * @return true if the operation succeeds false otherwise 4366 * @throws QuotaExceededException if directory creation violates 4367 * any quota limit 4368 * @throws UnresolvedLinkException if a symlink is encountered in src. 4369 * @throws SnapshotAccessControlException if path is in RO snapshot 4370 */ 4371 private boolean mkdirsRecursively(String src, PermissionStatus permissions, 4372 boolean inheritPermission, long now) 4373 throws FileAlreadyExistsException, QuotaExceededException, 4374 UnresolvedLinkException, SnapshotAccessControlException, 4375 AclException { 4376 src = FSDirectory.normalizePath(src); 4377 String[] names = INode.getPathNames(src); 4378 byte[][] components = INode.getPathComponents(names); 4379 final int lastInodeIndex = components.length - 1; 4380 4381 dir.writeLock(); 4382 try { 4383 INodesInPath iip = dir.getExistingPathINodes(components); 4384 if (iip.isSnapshot()) { 4385 throw new SnapshotAccessControlException( 4386 "Modification on RO snapshot is disallowed"); 4387 } 4388 INode[] inodes = iip.getINodes(); 4389 4390 // find the index of the first null in inodes[] 4391 StringBuilder pathbuilder = new StringBuilder(); 4392 int i = 1; 4393 for(; i < inodes.length && inodes[i] != null; i++) { 4394 pathbuilder.append(Path.SEPARATOR).append(names[i]); 4395 if (!inodes[i].isDirectory()) { 4396 throw new FileAlreadyExistsException( 4397 "Parent path is not a directory: " 4398 + pathbuilder + " "+inodes[i].getLocalName()); 4399 } 4400 } 4401 4402 // default to creating parent dirs with the given perms 4403 PermissionStatus parentPermissions = permissions; 4404 4405 // if not inheriting and it's the last inode, there's no use in 4406 // computing perms that won't be used 4407 if (inheritPermission || (i < lastInodeIndex)) { 4408 // if inheriting (ie. creating a file or symlink), use the parent dir, 4409 // else the supplied permissions 4410 // NOTE: the permissions of the auto-created directories violate posix 4411 FsPermission parentFsPerm = inheritPermission 4412 ? inodes[i-1].getFsPermission() : permissions.getPermission(); 4413 4414 // ensure that the permissions allow user write+execute 4415 if (!parentFsPerm.getUserAction().implies(FsAction.WRITE_EXECUTE)) { 4416 parentFsPerm = new FsPermission( 4417 parentFsPerm.getUserAction().or(FsAction.WRITE_EXECUTE), 4418 parentFsPerm.getGroupAction(), 4419 parentFsPerm.getOtherAction() 4420 ); 4421 } 4422 4423 if (!parentPermissions.getPermission().equals(parentFsPerm)) { 4424 parentPermissions = new PermissionStatus( 4425 parentPermissions.getUserName(), 4426 parentPermissions.getGroupName(), 4427 parentFsPerm 4428 ); 4429 // when inheriting, use same perms for entire path 4430 if (inheritPermission) permissions = parentPermissions; 4431 } 4432 } 4433 4434 // create directories beginning from the first null index 4435 for(; i < inodes.length; i++) { 4436 pathbuilder.append(Path.SEPARATOR).append(names[i]); 4437 dir.unprotectedMkdir(allocateNewInodeId(), iip, i, components[i], 4438 (i < lastInodeIndex) ? parentPermissions : permissions, null, 4439 now); 4440 if (inodes[i] == null) { 4441 return false; 4442 } 4443 // Directory creation also count towards FilesCreated 4444 // to match count of FilesDeleted metric. 4445 NameNode.getNameNodeMetrics().incrFilesCreated(); 4446 4447 final String cur = pathbuilder.toString(); 4448 getEditLog().logMkDir(cur, inodes[i]); 4449 if(NameNode.stateChangeLog.isDebugEnabled()) { 4450 NameNode.stateChangeLog.debug( 4451 "mkdirs: created directory " + cur); 4452 } 4453 } 4454 } finally { 4455 dir.writeUnlock(); 4456 } 4457 return true; 4458 } 4459 4460 /** 4461 * Get the content summary for a specific file/dir. 4462 * 4463 * @param srcArg The string representation of the path to the file 4464 * 4465 * @throws AccessControlException if access is denied 4466 * @throws UnresolvedLinkException if a symlink is encountered. 4467 * @throws FileNotFoundException if no file exists 4468 * @throws StandbyException 4469 * @throws IOException for issues with writing to the audit log 4470 * 4471 * @return object containing information regarding the file 4472 * or null if file not found 4473 */ 4474 ContentSummary getContentSummary(final String srcArg) throws IOException { 4475 String src = srcArg; 4476 FSPermissionChecker pc = getPermissionChecker(); 4477 checkOperation(OperationCategory.READ); 4478 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4479 readLock(); 4480 boolean success = true; 4481 try { 4482 checkOperation(OperationCategory.READ); 4483 src = resolvePath(src, pathComponents); 4484 if (isPermissionEnabled) { 4485 checkPermission(pc, src, false, null, null, null, FsAction.READ_EXECUTE); 4486 } 4487 return dir.getContentSummary(src); 4488 4489 } catch (AccessControlException ace) { 4490 success = false; 4491 throw ace; 4492 } finally { 4493 readUnlock(); 4494 logAuditEvent(success, "contentSummary", srcArg); 4495 } 4496 } 4497 4498 /** 4499 * Set the namespace quota and diskspace quota for a directory. 4500 * See {@link ClientProtocol#setQuota(String, long, long)} for the 4501 * contract. 4502 * 4503 * Note: This does not support ".inodes" relative path. 4504 */ 4505 void setQuota(String path, long nsQuota, long dsQuota) 4506 throws IOException, UnresolvedLinkException { 4507 checkSuperuserPrivilege(); 4508 checkOperation(OperationCategory.WRITE); 4509 writeLock(); 4510 try { 4511 checkOperation(OperationCategory.WRITE); 4512 checkNameNodeSafeMode("Cannot set quota on " + path); 4513 INodeDirectory changed = dir.setQuota(path, nsQuota, dsQuota); 4514 if (changed != null) { 4515 final Quota.Counts q = changed.getQuotaCounts(); 4516 getEditLog().logSetQuota(path, 4517 q.get(Quota.NAMESPACE), q.get(Quota.DISKSPACE)); 4518 } 4519 } finally { 4520 writeUnlock(); 4521 } 4522 getEditLog().logSync(); 4523 } 4524 4525 /** Persist all metadata about this file. 4526 * @param src The string representation of the path 4527 * @param fileId The inode ID that we're fsyncing. Older clients will pass 4528 * INodeId.GRANDFATHER_INODE_ID here. 4529 * @param clientName The string representation of the client 4530 * @param lastBlockLength The length of the last block 4531 * under construction reported from client. 4532 * @throws IOException if path does not exist 4533 */ 4534 void fsync(String src, long fileId, String clientName, long lastBlockLength) 4535 throws IOException, UnresolvedLinkException { 4536 NameNode.stateChangeLog.info("BLOCK* fsync: " + src + " for " + clientName); 4537 checkOperation(OperationCategory.WRITE); 4538 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 4539 4540 waitForLoadingFSImage(); 4541 writeLock(); 4542 try { 4543 checkOperation(OperationCategory.WRITE); 4544 checkNameNodeSafeMode("Cannot fsync file " + src); 4545 src = resolvePath(src, pathComponents); 4546 final INode inode; 4547 if (fileId == INodeId.GRANDFATHER_INODE_ID) { 4548 // Older clients may not have given us an inode ID to work with. 4549 // In this case, we have to try to resolve the path and hope it 4550 // hasn't changed or been deleted since the file was opened for write. 4551 inode = dir.getINode(src); 4552 } else { 4553 inode = dir.getInode(fileId); 4554 if (inode != null) src = inode.getFullPathName(); 4555 } 4556 final INodeFile pendingFile = checkLease(src, clientName, inode, fileId); 4557 if (lastBlockLength > 0) { 4558 pendingFile.getFileUnderConstructionFeature().updateLengthOfLastBlock( 4559 pendingFile, lastBlockLength); 4560 } 4561 persistBlocks(src, pendingFile, false); 4562 } finally { 4563 writeUnlock(); 4564 } 4565 getEditLog().logSync(); 4566 } 4567 4568 /** 4569 * Move a file that is being written to be immutable. 4570 * @param src The filename 4571 * @param lease The lease for the client creating the file 4572 * @param recoveryLeaseHolder reassign lease to this holder if the last block 4573 * needs recovery; keep current holder if null. 4574 * @throws AlreadyBeingCreatedException if file is waiting to achieve minimal 4575 * replication;<br> 4576 * RecoveryInProgressException if lease recovery is in progress.<br> 4577 * IOException in case of an error. 4578 * @return true if file has been successfully finalized and closed or 4579 * false if block recovery has been initiated. Since the lease owner 4580 * has been changed and logged, caller should call logSync(). 4581 */ 4582 boolean internalReleaseLease(Lease lease, String src, 4583 String recoveryLeaseHolder) throws AlreadyBeingCreatedException, 4584 IOException, UnresolvedLinkException { 4585 LOG.info("Recovering " + lease + ", src=" + src); 4586 assert !isInSafeMode(); 4587 assert hasWriteLock(); 4588 4589 final INodesInPath iip = dir.getLastINodeInPath(src); 4590 final INodeFile pendingFile = iip.getINode(0).asFile(); 4591 int nrBlocks = pendingFile.numBlocks(); 4592 BlockInfo[] blocks = pendingFile.getBlocks(); 4593 4594 int nrCompleteBlocks; 4595 BlockInfo curBlock = null; 4596 for(nrCompleteBlocks = 0; nrCompleteBlocks < nrBlocks; nrCompleteBlocks++) { 4597 curBlock = blocks[nrCompleteBlocks]; 4598 if(!curBlock.isComplete()) 4599 break; 4600 assert blockManager.checkMinReplication(curBlock) : 4601 "A COMPLETE block is not minimally replicated in " + src; 4602 } 4603 4604 // If there are no incomplete blocks associated with this file, 4605 // then reap lease immediately and close the file. 4606 if(nrCompleteBlocks == nrBlocks) { 4607 finalizeINodeFileUnderConstruction(src, pendingFile, 4608 iip.getLatestSnapshotId()); 4609 NameNode.stateChangeLog.warn("BLOCK*" 4610 + " internalReleaseLease: All existing blocks are COMPLETE," 4611 + " lease removed, file closed."); 4612 return true; // closed! 4613 } 4614 4615 // Only the last and the penultimate blocks may be in non COMPLETE state. 4616 // If the penultimate block is not COMPLETE, then it must be COMMITTED. 4617 if(nrCompleteBlocks < nrBlocks - 2 || 4618 nrCompleteBlocks == nrBlocks - 2 && 4619 curBlock != null && 4620 curBlock.getBlockUCState() != BlockUCState.COMMITTED) { 4621 final String message = "DIR* NameSystem.internalReleaseLease: " 4622 + "attempt to release a create lock on " 4623 + src + " but file is already closed."; 4624 NameNode.stateChangeLog.warn(message); 4625 throw new IOException(message); 4626 } 4627 4628 // The last block is not COMPLETE, and 4629 // that the penultimate block if exists is either COMPLETE or COMMITTED 4630 final BlockInfo lastBlock = pendingFile.getLastBlock(); 4631 BlockUCState lastBlockState = lastBlock.getBlockUCState(); 4632 BlockInfo penultimateBlock = pendingFile.getPenultimateBlock(); 4633 4634 // If penultimate block doesn't exist then its minReplication is met 4635 boolean penultimateBlockMinReplication = penultimateBlock == null ? true : 4636 blockManager.checkMinReplication(penultimateBlock); 4637 4638 switch(lastBlockState) { 4639 case COMPLETE: 4640 assert false : "Already checked that the last block is incomplete"; 4641 break; 4642 case COMMITTED: 4643 // Close file if committed blocks are minimally replicated 4644 if(penultimateBlockMinReplication && 4645 blockManager.checkMinReplication(lastBlock)) { 4646 finalizeINodeFileUnderConstruction(src, pendingFile, 4647 iip.getLatestSnapshotId()); 4648 NameNode.stateChangeLog.warn("BLOCK*" 4649 + " internalReleaseLease: Committed blocks are minimally replicated," 4650 + " lease removed, file closed."); 4651 return true; // closed! 4652 } 4653 // Cannot close file right now, since some blocks 4654 // are not yet minimally replicated. 4655 // This may potentially cause infinite loop in lease recovery 4656 // if there are no valid replicas on data-nodes. 4657 String message = "DIR* NameSystem.internalReleaseLease: " + 4658 "Failed to release lease for file " + src + 4659 ". Committed blocks are waiting to be minimally replicated." + 4660 " Try again later."; 4661 NameNode.stateChangeLog.warn(message); 4662 throw new AlreadyBeingCreatedException(message); 4663 case UNDER_CONSTRUCTION: 4664 case UNDER_RECOVERY: 4665 final BlockInfoUnderConstruction uc = (BlockInfoUnderConstruction)lastBlock; 4666 // setup the last block locations from the blockManager if not known 4667 if (uc.getNumExpectedLocations() == 0) { 4668 uc.setExpectedLocations(blockManager.getStorages(lastBlock)); 4669 } 4670 4671 if (uc.getNumExpectedLocations() == 0 && uc.getNumBytes() == 0) { 4672 // There is no datanode reported to this block. 4673 // may be client have crashed before writing data to pipeline. 4674 // This blocks doesn't need any recovery. 4675 // We can remove this block and close the file. 4676 pendingFile.removeLastBlock(lastBlock); 4677 finalizeINodeFileUnderConstruction(src, pendingFile, 4678 iip.getLatestSnapshotId()); 4679 NameNode.stateChangeLog.warn("BLOCK* internalReleaseLease: " 4680 + "Removed empty last block and closed file."); 4681 return true; 4682 } 4683 // start recovery of the last block for this file 4684 long blockRecoveryId = nextGenerationStamp(isLegacyBlock(uc)); 4685 lease = reassignLease(lease, src, recoveryLeaseHolder, pendingFile); 4686 uc.initializeBlockRecovery(blockRecoveryId); 4687 leaseManager.renewLease(lease); 4688 // Cannot close file right now, since the last block requires recovery. 4689 // This may potentially cause infinite loop in lease recovery 4690 // if there are no valid replicas on data-nodes. 4691 NameNode.stateChangeLog.warn( 4692 "DIR* NameSystem.internalReleaseLease: " + 4693 "File " + src + " has not been closed." + 4694 " Lease recovery is in progress. " + 4695 "RecoveryId = " + blockRecoveryId + " for block " + lastBlock); 4696 break; 4697 } 4698 return false; 4699 } 4700 4701 private Lease reassignLease(Lease lease, String src, String newHolder, 4702 INodeFile pendingFile) { 4703 assert hasWriteLock(); 4704 if(newHolder == null) 4705 return lease; 4706 // The following transaction is not synced. Make sure it's sync'ed later. 4707 logReassignLease(lease.getHolder(), src, newHolder); 4708 return reassignLeaseInternal(lease, src, newHolder, pendingFile); 4709 } 4710 4711 Lease reassignLeaseInternal(Lease lease, String src, String newHolder, 4712 INodeFile pendingFile) { 4713 assert hasWriteLock(); 4714 pendingFile.getFileUnderConstructionFeature().setClientName(newHolder); 4715 return leaseManager.reassignLease(lease, src, newHolder); 4716 } 4717 4718 private void commitOrCompleteLastBlock(final INodeFile fileINode, 4719 final Block commitBlock) throws IOException { 4720 assert hasWriteLock(); 4721 Preconditions.checkArgument(fileINode.isUnderConstruction()); 4722 if (!blockManager.commitOrCompleteLastBlock(fileINode, commitBlock)) { 4723 return; 4724 } 4725 4726 // Adjust disk space consumption if required 4727 final long diff = fileINode.getPreferredBlockSize() - commitBlock.getNumBytes(); 4728 if (diff > 0) { 4729 try { 4730 String path = fileINode.getFullPathName(); 4731 dir.updateSpaceConsumed(path, 0, -diff*fileINode.getFileReplication()); 4732 } catch (IOException e) { 4733 LOG.warn("Unexpected exception while updating disk space.", e); 4734 } 4735 } 4736 } 4737 4738 private void finalizeINodeFileUnderConstruction(String src, 4739 INodeFile pendingFile, int latestSnapshot) throws IOException, 4740 UnresolvedLinkException { 4741 assert hasWriteLock(); 4742 4743 FileUnderConstructionFeature uc = pendingFile.getFileUnderConstructionFeature(); 4744 if (uc == null) { 4745 throw new IOException("Cannot finalize file " + src 4746 + " because it is not under construction"); 4747 } 4748 leaseManager.removeLease(uc.getClientName(), src); 4749 4750 pendingFile.recordModification(latestSnapshot); 4751 4752 // The file is no longer pending. 4753 // Create permanent INode, update blocks. No need to replace the inode here 4754 // since we just remove the uc feature from pendingFile 4755 final INodeFile newFile = pendingFile.toCompleteFile(now()); 4756 4757 waitForLoadingFSImage(); 4758 // close file and persist block allocations for this file 4759 closeFile(src, newFile); 4760 4761 blockManager.checkReplication(newFile); 4762 } 4763 4764 @VisibleForTesting 4765 BlockInfo getStoredBlock(Block block) { 4766 return blockManager.getStoredBlock(block); 4767 } 4768 4769 @Override 4770 public boolean isInSnapshot(BlockInfoUnderConstruction blockUC) { 4771 assert hasReadLock(); 4772 final BlockCollection bc = blockUC.getBlockCollection(); 4773 if (bc == null || !(bc instanceof INodeFile) 4774 || !bc.isUnderConstruction()) { 4775 return false; 4776 } 4777 4778 INodeFile inodeUC = (INodeFile) bc; 4779 String fullName = inodeUC.getName(); 4780 try { 4781 if (fullName != null && fullName.startsWith(Path.SEPARATOR) 4782 && dir.getINode(fullName) == inodeUC) { 4783 // If file exists in normal path then no need to look in snapshot 4784 return false; 4785 } 4786 } catch (UnresolvedLinkException e) { 4787 LOG.error("Error while resolving the link : " + fullName, e); 4788 return false; 4789 } 4790 /* 4791 * 1. if bc is an instance of INodeFileUnderConstructionWithSnapshot, and 4792 * bc is not in the current fsdirectory tree, bc must represent a snapshot 4793 * file. 4794 * 2. if fullName is not an absolute path, bc cannot be existent in the 4795 * current fsdirectory tree. 4796 * 3. if bc is not the current node associated with fullName, bc must be a 4797 * snapshot inode. 4798 */ 4799 return true; 4800 } 4801 4802 void commitBlockSynchronization(ExtendedBlock lastblock, 4803 long newgenerationstamp, long newlength, 4804 boolean closeFile, boolean deleteblock, DatanodeID[] newtargets, 4805 String[] newtargetstorages) 4806 throws IOException, UnresolvedLinkException { 4807 LOG.info("commitBlockSynchronization(lastblock=" + lastblock 4808 + ", newgenerationstamp=" + newgenerationstamp 4809 + ", newlength=" + newlength 4810 + ", newtargets=" + Arrays.asList(newtargets) 4811 + ", closeFile=" + closeFile 4812 + ", deleteBlock=" + deleteblock 4813 + ")"); 4814 checkOperation(OperationCategory.WRITE); 4815 String src = ""; 4816 waitForLoadingFSImage(); 4817 writeLock(); 4818 try { 4819 checkOperation(OperationCategory.WRITE); 4820 // If a DN tries to commit to the standby, the recovery will 4821 // fail, and the next retry will succeed on the new NN. 4822 4823 checkNameNodeSafeMode( 4824 "Cannot commitBlockSynchronization while in safe mode"); 4825 final BlockInfo storedBlock = getStoredBlock( 4826 ExtendedBlock.getLocalBlock(lastblock)); 4827 if (storedBlock == null) { 4828 if (deleteblock) { 4829 // This may be a retry attempt so ignore the failure 4830 // to locate the block. 4831 if (LOG.isDebugEnabled()) { 4832 LOG.debug("Block (=" + lastblock + ") not found"); 4833 } 4834 return; 4835 } else { 4836 throw new IOException("Block (=" + lastblock + ") not found"); 4837 } 4838 } 4839 // 4840 // The implementation of delete operation (see @deleteInternal method) 4841 // first removes the file paths from namespace, and delays the removal 4842 // of blocks to later time for better performance. When 4843 // commitBlockSynchronization (this method) is called in between, the 4844 // blockCollection of storedBlock could have been assigned to null by 4845 // the delete operation, throw IOException here instead of NPE; if the 4846 // file path is already removed from namespace by the delete operation, 4847 // throw FileNotFoundException here, so not to proceed to the end of 4848 // this method to add a CloseOp to the edit log for an already deleted 4849 // file (See HDFS-6825). 4850 // 4851 BlockCollection blockCollection = storedBlock.getBlockCollection(); 4852 if (blockCollection == null) { 4853 throw new IOException("The blockCollection of " + storedBlock 4854 + " is null, likely because the file owning this block was" 4855 + " deleted and the block removal is delayed"); 4856 } 4857 INodeFile iFile = ((INode)blockCollection).asFile(); 4858 if (isFileDeleted(iFile)) { 4859 throw new FileNotFoundException("File not found: " 4860 + iFile.getFullPathName() + ", likely due to delayed block" 4861 + " removal"); 4862 } 4863 if (!iFile.isUnderConstruction() || storedBlock.isComplete()) { 4864 if (LOG.isDebugEnabled()) { 4865 LOG.debug("Unexpected block (=" + lastblock 4866 + ") since the file (=" + iFile.getLocalName() 4867 + ") is not under construction"); 4868 } 4869 return; 4870 } 4871 4872 long recoveryId = 4873 ((BlockInfoUnderConstruction)storedBlock).getBlockRecoveryId(); 4874 if(recoveryId != newgenerationstamp) { 4875 throw new IOException("The recovery id " + newgenerationstamp 4876 + " does not match current recovery id " 4877 + recoveryId + " for block " + lastblock); 4878 } 4879 4880 if (deleteblock) { 4881 Block blockToDel = ExtendedBlock.getLocalBlock(lastblock); 4882 boolean remove = iFile.removeLastBlock(blockToDel); 4883 if (remove) { 4884 blockManager.removeBlockFromMap(storedBlock); 4885 } 4886 } 4887 else { 4888 // update last block 4889 storedBlock.setGenerationStamp(newgenerationstamp); 4890 storedBlock.setNumBytes(newlength); 4891 4892 // find the DatanodeDescriptor objects 4893 // There should be no locations in the blockManager till now because the 4894 // file is underConstruction 4895 ArrayList<DatanodeDescriptor> trimmedTargets = 4896 new ArrayList<DatanodeDescriptor>(newtargets.length); 4897 ArrayList<String> trimmedStorages = 4898 new ArrayList<String>(newtargets.length); 4899 if (newtargets.length > 0) { 4900 for (int i = 0; i < newtargets.length; ++i) { 4901 // try to get targetNode 4902 DatanodeDescriptor targetNode = 4903 blockManager.getDatanodeManager().getDatanode(newtargets[i]); 4904 if (targetNode != null) { 4905 trimmedTargets.add(targetNode); 4906 trimmedStorages.add(newtargetstorages[i]); 4907 } else if (LOG.isDebugEnabled()) { 4908 LOG.debug("DatanodeDescriptor (=" + newtargets[i] + ") not found"); 4909 } 4910 } 4911 } 4912 if ((closeFile) && !trimmedTargets.isEmpty()) { 4913 // the file is getting closed. Insert block locations into blockManager. 4914 // Otherwise fsck will report these blocks as MISSING, especially if the 4915 // blocksReceived from Datanodes take a long time to arrive. 4916 for (int i = 0; i < trimmedTargets.size(); i++) { 4917 DatanodeStorageInfo storageInfo = 4918 trimmedTargets.get(i).getStorageInfo(trimmedStorages.get(i)); 4919 if (storageInfo != null) { 4920 storageInfo.addBlock(storedBlock); 4921 } 4922 } 4923 } 4924 4925 // add pipeline locations into the INodeUnderConstruction 4926 DatanodeStorageInfo[] trimmedStorageInfos = 4927 blockManager.getDatanodeManager().getDatanodeStorageInfos( 4928 trimmedTargets.toArray(new DatanodeID[trimmedTargets.size()]), 4929 trimmedStorages.toArray(new String[trimmedStorages.size()])); 4930 iFile.setLastBlock(storedBlock, trimmedStorageInfos); 4931 } 4932 4933 if (closeFile) { 4934 src = closeFileCommitBlocks(iFile, storedBlock); 4935 } else { 4936 // If this commit does not want to close the file, persist blocks 4937 src = iFile.getFullPathName(); 4938 persistBlocks(src, iFile, false); 4939 } 4940 } finally { 4941 writeUnlock(); 4942 } 4943 getEditLog().logSync(); 4944 if (closeFile) { 4945 LOG.info("commitBlockSynchronization(newblock=" + lastblock 4946 + ", file=" + src 4947 + ", newgenerationstamp=" + newgenerationstamp 4948 + ", newlength=" + newlength 4949 + ", newtargets=" + Arrays.asList(newtargets) + ") successful"); 4950 } else { 4951 LOG.info("commitBlockSynchronization(" + lastblock + ") successful"); 4952 } 4953 } 4954 4955 /** 4956 * @param pendingFile open file that needs to be closed 4957 * @param storedBlock last block 4958 * @return Path of the file that was closed. 4959 * @throws IOException on error 4960 */ 4961 @VisibleForTesting 4962 String closeFileCommitBlocks(INodeFile pendingFile, BlockInfo storedBlock) 4963 throws IOException { 4964 String src = pendingFile.getFullPathName(); 4965 4966 // commit the last block and complete it if it has minimum replicas 4967 commitOrCompleteLastBlock(pendingFile, storedBlock); 4968 4969 //remove lease, close file 4970 finalizeINodeFileUnderConstruction(src, pendingFile, 4971 Snapshot.findLatestSnapshot(pendingFile, Snapshot.CURRENT_STATE_ID)); 4972 4973 return src; 4974 } 4975 4976 /** 4977 * Renew the lease(s) held by the given client 4978 */ 4979 void renewLease(String holder) throws IOException { 4980 checkOperation(OperationCategory.WRITE); 4981 readLock(); 4982 try { 4983 checkOperation(OperationCategory.WRITE); 4984 checkNameNodeSafeMode("Cannot renew lease for " + holder); 4985 leaseManager.renewLease(holder); 4986 } finally { 4987 readUnlock(); 4988 } 4989 } 4990 4991 /** 4992 * Get a partial listing of the indicated directory 4993 * 4994 * @param src the directory name 4995 * @param startAfter the name to start after 4996 * @param needLocation if blockLocations need to be returned 4997 * @return a partial listing starting after startAfter 4998 * 4999 * @throws AccessControlException if access is denied 5000 * @throws UnresolvedLinkException if symbolic link is encountered 5001 * @throws IOException if other I/O error occurred 5002 */ 5003 DirectoryListing getListing(String src, byte[] startAfter, 5004 boolean needLocation) 5005 throws AccessControlException, UnresolvedLinkException, IOException { 5006 try { 5007 return getListingInt(src, startAfter, needLocation); 5008 } catch (AccessControlException e) { 5009 logAuditEvent(false, "listStatus", src); 5010 throw e; 5011 } 5012 } 5013 5014 private DirectoryListing getListingInt(final String srcArg, byte[] startAfter, 5015 boolean needLocation) 5016 throws AccessControlException, UnresolvedLinkException, IOException { 5017 String src = srcArg; 5018 DirectoryListing dl; 5019 FSPermissionChecker pc = getPermissionChecker(); 5020 checkOperation(OperationCategory.READ); 5021 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 5022 String startAfterString = new String(startAfter); 5023 readLock(); 5024 try { 5025 checkOperation(OperationCategory.READ); 5026 src = resolvePath(src, pathComponents); 5027 5028 // Get file name when startAfter is an INodePath 5029 if (FSDirectory.isReservedName(startAfterString)) { 5030 byte[][] startAfterComponents = FSDirectory 5031 .getPathComponentsForReservedPath(startAfterString); 5032 try { 5033 String tmp = FSDirectory.resolvePath(src, startAfterComponents, dir); 5034 byte[][] regularPath = INode.getPathComponents(tmp); 5035 startAfter = regularPath[regularPath.length - 1]; 5036 } catch (IOException e) { 5037 // Possibly the inode is deleted 5038 throw new DirectoryListingStartAfterNotFoundException( 5039 "Can't find startAfter " + startAfterString); 5040 } 5041 } 5042 5043 boolean isSuperUser = true; 5044 if (isPermissionEnabled) { 5045 if (dir.isDir(src)) { 5046 checkPathAccess(pc, src, FsAction.READ_EXECUTE); 5047 } else { 5048 checkTraverse(pc, src); 5049 } 5050 isSuperUser = pc.isSuperUser(); 5051 } 5052 logAuditEvent(true, "listStatus", srcArg); 5053 dl = dir.getListing(src, startAfter, needLocation, isSuperUser); 5054 } finally { 5055 readUnlock(); 5056 } 5057 return dl; 5058 } 5059 5060 ///////////////////////////////////////////////////////// 5061 // 5062 // These methods are called by datanodes 5063 // 5064 ///////////////////////////////////////////////////////// 5065 /** 5066 * Register Datanode. 5067 * <p> 5068 * The purpose of registration is to identify whether the new datanode 5069 * serves a new data storage, and will report new data block copies, 5070 * which the namenode was not aware of; or the datanode is a replacement 5071 * node for the data storage that was previously served by a different 5072 * or the same (in terms of host:port) datanode. 5073 * The data storages are distinguished by their storageIDs. When a new 5074 * data storage is reported the namenode issues a new unique storageID. 5075 * <p> 5076 * Finally, the namenode returns its namespaceID as the registrationID 5077 * for the datanodes. 5078 * namespaceID is a persistent attribute of the name space. 5079 * The registrationID is checked every time the datanode is communicating 5080 * with the namenode. 5081 * Datanodes with inappropriate registrationID are rejected. 5082 * If the namenode stops, and then restarts it can restore its 5083 * namespaceID and will continue serving the datanodes that has previously 5084 * registered with the namenode without restarting the whole cluster. 5085 * 5086 * @see org.apache.hadoop.hdfs.server.datanode.DataNode 5087 */ 5088 void registerDatanode(DatanodeRegistration nodeReg) throws IOException { 5089 writeLock(); 5090 try { 5091 getBlockManager().getDatanodeManager().registerDatanode(nodeReg); 5092 checkSafeMode(); 5093 } finally { 5094 writeUnlock(); 5095 } 5096 } 5097 5098 /** 5099 * Get registrationID for datanodes based on the namespaceID. 5100 * 5101 * @see #registerDatanode(DatanodeRegistration) 5102 * @return registration ID 5103 */ 5104 String getRegistrationID() { 5105 return Storage.getRegistrationID(getFSImage().getStorage()); 5106 } 5107 5108 /** 5109 * The given node has reported in. This method should: 5110 * 1) Record the heartbeat, so the datanode isn't timed out 5111 * 2) Adjust usage stats for future block allocation 5112 * 5113 * If a substantial amount of time passed since the last datanode 5114 * heartbeat then request an immediate block report. 5115 * 5116 * @return an array of datanode commands 5117 * @throws IOException 5118 */ 5119 HeartbeatResponse handleHeartbeat(DatanodeRegistration nodeReg, 5120 StorageReport[] reports, long cacheCapacity, long cacheUsed, 5121 int xceiverCount, int xmitsInProgress, int failedVolumes, 5122 VolumeFailureSummary volumeFailureSummary) throws IOException { 5123 readLock(); 5124 try { 5125 //get datanode commands 5126 final int maxTransfer = blockManager.getMaxReplicationStreams() 5127 - xmitsInProgress; 5128 DatanodeCommand[] cmds = blockManager.getDatanodeManager().handleHeartbeat( 5129 nodeReg, reports, blockPoolId, cacheCapacity, cacheUsed, 5130 xceiverCount, maxTransfer, failedVolumes, volumeFailureSummary); 5131 5132 //create ha status 5133 final NNHAStatusHeartbeat haState = new NNHAStatusHeartbeat( 5134 haContext.getState().getServiceState(), 5135 getFSImage().getLastAppliedOrWrittenTxId()); 5136 5137 return new HeartbeatResponse(cmds, haState, rollingUpgradeInfo); 5138 } finally { 5139 readUnlock(); 5140 } 5141 } 5142 5143 /** 5144 * Returns whether or not there were available resources at the last check of 5145 * resources. 5146 * 5147 * @return true if there were sufficient resources available, false otherwise. 5148 */ 5149 boolean nameNodeHasResourcesAvailable() { 5150 return hasResourcesAvailable; 5151 } 5152 5153 /** 5154 * Perform resource checks and cache the results. 5155 */ 5156 void checkAvailableResources() { 5157 Preconditions.checkState(nnResourceChecker != null, 5158 "nnResourceChecker not initialized"); 5159 hasResourcesAvailable = nnResourceChecker.hasAvailableDiskSpace(); 5160 } 5161 5162 /** 5163 * Persist the block list for the inode. 5164 * @param path 5165 * @param file 5166 * @param logRetryCache 5167 */ 5168 private void persistBlocks(String path, INodeFile file, 5169 boolean logRetryCache) { 5170 assert hasWriteLock(); 5171 Preconditions.checkArgument(file.isUnderConstruction()); 5172 getEditLog().logUpdateBlocks(path, file, logRetryCache); 5173 if(NameNode.stateChangeLog.isDebugEnabled()) { 5174 NameNode.stateChangeLog.debug("persistBlocks: " + path 5175 + " with " + file.getBlocks().length + " blocks is persisted to" + 5176 " the file system"); 5177 } 5178 } 5179 5180 void incrDeletedFileCount(long count) { 5181 NameNode.getNameNodeMetrics().incrFilesDeleted(count); 5182 } 5183 5184 /** 5185 * Close file. 5186 * @param path 5187 * @param file 5188 */ 5189 private void closeFile(String path, INodeFile file) { 5190 assert hasWriteLock(); 5191 waitForLoadingFSImage(); 5192 // file is closed 5193 getEditLog().logCloseFile(path, file); 5194 if (NameNode.stateChangeLog.isDebugEnabled()) { 5195 NameNode.stateChangeLog.debug("closeFile: " 5196 +path+" with "+ file.getBlocks().length 5197 +" blocks is persisted to the file system"); 5198 } 5199 } 5200 5201 /** 5202 * Add the given symbolic link to the fs. Record it in the edits log. 5203 */ 5204 private INodeSymlink addSymlink(String path, String target, 5205 PermissionStatus dirPerms, 5206 boolean createParent, boolean logRetryCache) 5207 throws UnresolvedLinkException, FileAlreadyExistsException, 5208 QuotaExceededException, SnapshotAccessControlException, AclException { 5209 waitForLoadingFSImage(); 5210 5211 final long modTime = now(); 5212 if (createParent) { 5213 final String parent = new Path(path).getParent().toString(); 5214 if (!mkdirsRecursively(parent, dirPerms, true, modTime)) { 5215 return null; 5216 } 5217 } 5218 final String userName = dirPerms.getUserName(); 5219 long id = allocateNewInodeId(); 5220 INodeSymlink newNode = dir.addSymlink(id, path, target, modTime, modTime, 5221 new PermissionStatus(userName, null, FsPermission.getDefault())); 5222 if (newNode == null) { 5223 NameNode.stateChangeLog.info("addSymlink: failed to add " + path); 5224 return null; 5225 } 5226 getEditLog().logSymlink(path, target, modTime, modTime, newNode, 5227 logRetryCache); 5228 5229 if(NameNode.stateChangeLog.isDebugEnabled()) { 5230 NameNode.stateChangeLog.debug("addSymlink: " + path + " is added"); 5231 } 5232 return newNode; 5233 } 5234 5235 /** 5236 * Periodically calls hasAvailableResources of NameNodeResourceChecker, and if 5237 * there are found to be insufficient resources available, causes the NN to 5238 * enter safe mode. If resources are later found to have returned to 5239 * acceptable levels, this daemon will cause the NN to exit safe mode. 5240 */ 5241 class NameNodeResourceMonitor implements Runnable { 5242 boolean shouldNNRmRun = true; 5243 @Override 5244 public void run () { 5245 try { 5246 while (fsRunning && shouldNNRmRun) { 5247 checkAvailableResources(); 5248 if(!nameNodeHasResourcesAvailable()) { 5249 String lowResourcesMsg = "NameNode low on available disk space. "; 5250 if (!isInSafeMode()) { 5251 FSNamesystem.LOG.warn(lowResourcesMsg + "Entering safe mode."); 5252 } else { 5253 FSNamesystem.LOG.warn(lowResourcesMsg + "Already in safe mode."); 5254 } 5255 enterSafeMode(true); 5256 } 5257 try { 5258 Thread.sleep(resourceRecheckInterval); 5259 } catch (InterruptedException ie) { 5260 // Deliberately ignore 5261 } 5262 } 5263 } catch (Exception e) { 5264 FSNamesystem.LOG.error("Exception in NameNodeResourceMonitor: ", e); 5265 } 5266 } 5267 5268 public void stopMonitor() { 5269 shouldNNRmRun = false; 5270 } 5271 } 5272 5273 class NameNodeEditLogRoller implements Runnable { 5274 5275 private boolean shouldRun = true; 5276 private final long rollThreshold; 5277 private final long sleepIntervalMs; 5278 5279 public NameNodeEditLogRoller(long rollThreshold, int sleepIntervalMs) { 5280 this.rollThreshold = rollThreshold; 5281 this.sleepIntervalMs = sleepIntervalMs; 5282 } 5283 5284 @Override 5285 public void run() { 5286 while (fsRunning && shouldRun) { 5287 try { 5288 FSEditLog editLog = getFSImage().getEditLog(); 5289 long numEdits = 5290 editLog.getLastWrittenTxId() - editLog.getCurSegmentTxId(); 5291 if (numEdits > rollThreshold) { 5292 FSNamesystem.LOG.info("NameNode rolling its own edit log because" 5293 + " number of edits in open segment exceeds threshold of " 5294 + rollThreshold); 5295 rollEditLog(); 5296 } 5297 Thread.sleep(sleepIntervalMs); 5298 } catch (InterruptedException e) { 5299 FSNamesystem.LOG.info(NameNodeEditLogRoller.class.getSimpleName() 5300 + " was interrupted, exiting"); 5301 break; 5302 } catch (Exception e) { 5303 FSNamesystem.LOG.error("Swallowing exception in " 5304 + NameNodeEditLogRoller.class.getSimpleName() + ":", e); 5305 } 5306 } 5307 } 5308 5309 public void stop() { 5310 shouldRun = false; 5311 } 5312 } 5313 5314 /** 5315 * Daemon to periodically scan the namespace for lazyPersist files 5316 * with missing blocks and unlink them. 5317 */ 5318 class LazyPersistFileScrubber implements Runnable { 5319 private volatile boolean shouldRun = true; 5320 final int scrubIntervalSec; 5321 public LazyPersistFileScrubber(final int scrubIntervalSec) { 5322 this.scrubIntervalSec = scrubIntervalSec; 5323 } 5324 5325 /** 5326 * Periodically go over the list of lazyPersist files with missing 5327 * blocks and unlink them from the namespace. 5328 */ 5329 private void clearCorruptLazyPersistFiles() 5330 throws SafeModeException, AccessControlException, 5331 UnresolvedLinkException, IOException { 5332 5333 BlockStoragePolicy lpPolicy = blockManager.getStoragePolicy("LAZY_PERSIST"); 5334 5335 List<BlockCollection> filesToDelete = new ArrayList<BlockCollection>(); 5336 5337 writeLock(); 5338 5339 try { 5340 final Iterator<Block> it = blockManager.getCorruptReplicaBlockIterator(); 5341 5342 while (it.hasNext()) { 5343 Block b = it.next(); 5344 BlockInfo blockInfo = blockManager.getStoredBlock(b); 5345 if (blockInfo.getBlockCollection().getStoragePolicyID() == lpPolicy.getId()) { 5346 filesToDelete.add(blockInfo.getBlockCollection()); 5347 } 5348 } 5349 5350 for (BlockCollection bc : filesToDelete) { 5351 LOG.warn("Removing lazyPersist file " + bc.getName() + " with no replicas."); 5352 deleteInternal(bc.getName(), false, false, false); 5353 } 5354 } finally { 5355 writeUnlock(); 5356 } 5357 } 5358 5359 @Override 5360 public void run() { 5361 while (fsRunning && shouldRun) { 5362 try { 5363 clearCorruptLazyPersistFiles(); 5364 Thread.sleep(scrubIntervalSec * 1000); 5365 } catch (InterruptedException e) { 5366 FSNamesystem.LOG.info( 5367 "LazyPersistFileScrubber was interrupted, exiting"); 5368 break; 5369 } catch (Exception e) { 5370 FSNamesystem.LOG.error( 5371 "Ignoring exception in LazyPersistFileScrubber:", e); 5372 } 5373 } 5374 } 5375 5376 public void stop() { 5377 shouldRun = false; 5378 } 5379 } 5380 5381 public FSImage getFSImage() { 5382 return fsImage; 5383 } 5384 5385 public FSEditLog getEditLog() { 5386 return getFSImage().getEditLog(); 5387 } 5388 5389 private void checkBlock(ExtendedBlock block) throws IOException { 5390 if (block != null && !this.blockPoolId.equals(block.getBlockPoolId())) { 5391 throw new IOException("Unexpected BlockPoolId " + block.getBlockPoolId() 5392 + " - expected " + blockPoolId); 5393 } 5394 } 5395 5396 @Metric({"MissingBlocks", "Number of missing blocks"}) 5397 public long getMissingBlocksCount() { 5398 // not locking 5399 return blockManager.getMissingBlocksCount(); 5400 } 5401 5402 @Metric({"MissingReplOneBlocks", "Number of missing blocks " + 5403 "with replication factor 1"}) 5404 public long getMissingReplOneBlocksCount() { 5405 // not locking 5406 return blockManager.getMissingReplOneBlocksCount(); 5407 } 5408 5409 @Metric({"ExpiredHeartbeats", "Number of expired heartbeats"}) 5410 public int getExpiredHeartbeats() { 5411 return datanodeStatistics.getExpiredHeartbeats(); 5412 } 5413 5414 @Metric({"TransactionsSinceLastCheckpoint", 5415 "Number of transactions since last checkpoint"}) 5416 public long getTransactionsSinceLastCheckpoint() { 5417 return getFSImage().getLastAppliedOrWrittenTxId() - 5418 getFSImage().getStorage().getMostRecentCheckpointTxId(); 5419 } 5420 5421 @Metric({"TransactionsSinceLastLogRoll", 5422 "Number of transactions since last edit log roll"}) 5423 public long getTransactionsSinceLastLogRoll() { 5424 if (isInStandbyState() || !getEditLog().isSegmentOpen()) { 5425 return 0; 5426 } else { 5427 return getEditLog().getLastWrittenTxId() - 5428 getEditLog().getCurSegmentTxId() + 1; 5429 } 5430 } 5431 5432 @Metric({"LastWrittenTransactionId", "Transaction ID written to the edit log"}) 5433 public long getLastWrittenTransactionId() { 5434 return getEditLog().getLastWrittenTxId(); 5435 } 5436 5437 @Metric({"LastCheckpointTime", 5438 "Time in milliseconds since the epoch of the last checkpoint"}) 5439 public long getLastCheckpointTime() { 5440 return getFSImage().getStorage().getMostRecentCheckpointTime(); 5441 } 5442 5443 /** @see ClientProtocol#getStats() */ 5444 long[] getStats() { 5445 final long[] stats = datanodeStatistics.getStats(); 5446 stats[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX] = getUnderReplicatedBlocks(); 5447 stats[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX] = getCorruptReplicaBlocks(); 5448 stats[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX] = getMissingBlocksCount(); 5449 stats[ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX] = 5450 getMissingReplOneBlocksCount(); 5451 return stats; 5452 } 5453 5454 @Override // FSNamesystemMBean 5455 @Metric({"CapacityTotal", 5456 "Total raw capacity of data nodes in bytes"}) 5457 public long getCapacityTotal() { 5458 return datanodeStatistics.getCapacityTotal(); 5459 } 5460 5461 @Metric({"CapacityTotalGB", 5462 "Total raw capacity of data nodes in GB"}) 5463 public float getCapacityTotalGB() { 5464 return DFSUtil.roundBytesToGB(getCapacityTotal()); 5465 } 5466 5467 @Override // FSNamesystemMBean 5468 @Metric({"CapacityUsed", 5469 "Total used capacity across all data nodes in bytes"}) 5470 public long getCapacityUsed() { 5471 return datanodeStatistics.getCapacityUsed(); 5472 } 5473 5474 @Metric({"CapacityUsedGB", 5475 "Total used capacity across all data nodes in GB"}) 5476 public float getCapacityUsedGB() { 5477 return DFSUtil.roundBytesToGB(getCapacityUsed()); 5478 } 5479 5480 @Override // FSNamesystemMBean 5481 @Metric({"CapacityRemaining", "Remaining capacity in bytes"}) 5482 public long getCapacityRemaining() { 5483 return datanodeStatistics.getCapacityRemaining(); 5484 } 5485 5486 @Metric({"CapacityRemainingGB", "Remaining capacity in GB"}) 5487 public float getCapacityRemainingGB() { 5488 return DFSUtil.roundBytesToGB(getCapacityRemaining()); 5489 } 5490 5491 @Metric({"CapacityUsedNonDFS", 5492 "Total space used by data nodes for non DFS purposes in bytes"}) 5493 public long getCapacityUsedNonDFS() { 5494 return datanodeStatistics.getCapacityUsedNonDFS(); 5495 } 5496 5497 /** 5498 * Total number of connections. 5499 */ 5500 @Override // FSNamesystemMBean 5501 @Metric 5502 public int getTotalLoad() { 5503 return datanodeStatistics.getXceiverCount(); 5504 } 5505 5506 @Metric({ "SnapshottableDirectories", "Number of snapshottable directories" }) 5507 public int getNumSnapshottableDirs() { 5508 return this.snapshotManager.getNumSnapshottableDirs(); 5509 } 5510 5511 @Metric({ "Snapshots", "The number of snapshots" }) 5512 public int getNumSnapshots() { 5513 return this.snapshotManager.getNumSnapshots(); 5514 } 5515 5516 @Override 5517 public String getSnapshotStats() { 5518 Map<String, Object> info = new HashMap<String, Object>(); 5519 info.put("SnapshottableDirectories", this.getNumSnapshottableDirs()); 5520 info.put("Snapshots", this.getNumSnapshots()); 5521 return JSON.toString(info); 5522 } 5523 5524 int getNumberOfDatanodes(DatanodeReportType type) { 5525 readLock(); 5526 try { 5527 return getBlockManager().getDatanodeManager().getDatanodeListForReport( 5528 type).size(); 5529 } finally { 5530 readUnlock(); 5531 } 5532 } 5533 5534 DatanodeInfo[] datanodeReport(final DatanodeReportType type 5535 ) throws AccessControlException, StandbyException { 5536 checkSuperuserPrivilege(); 5537 checkOperation(OperationCategory.UNCHECKED); 5538 readLock(); 5539 try { 5540 checkOperation(OperationCategory.UNCHECKED); 5541 final DatanodeManager dm = getBlockManager().getDatanodeManager(); 5542 final List<DatanodeDescriptor> results = dm.getDatanodeListForReport(type); 5543 5544 DatanodeInfo[] arr = new DatanodeInfo[results.size()]; 5545 for (int i=0; i<arr.length; i++) { 5546 arr[i] = new DatanodeInfo(results.get(i)); 5547 } 5548 return arr; 5549 } finally { 5550 readUnlock(); 5551 } 5552 } 5553 5554 DatanodeStorageReport[] getDatanodeStorageReport(final DatanodeReportType type 5555 ) throws AccessControlException, StandbyException { 5556 checkSuperuserPrivilege(); 5557 checkOperation(OperationCategory.UNCHECKED); 5558 readLock(); 5559 try { 5560 checkOperation(OperationCategory.UNCHECKED); 5561 final DatanodeManager dm = getBlockManager().getDatanodeManager(); 5562 final List<DatanodeDescriptor> datanodes = dm.getDatanodeListForReport(type); 5563 5564 DatanodeStorageReport[] reports = new DatanodeStorageReport[datanodes.size()]; 5565 for (int i = 0; i < reports.length; i++) { 5566 final DatanodeDescriptor d = datanodes.get(i); 5567 reports[i] = new DatanodeStorageReport(new DatanodeInfo(d), 5568 d.getStorageReports()); 5569 } 5570 return reports; 5571 } finally { 5572 readUnlock(); 5573 } 5574 } 5575 5576 /** 5577 * Save namespace image. 5578 * This will save current namespace into fsimage file and empty edits file. 5579 * Requires superuser privilege and safe mode. 5580 * 5581 * @throws AccessControlException if superuser privilege is violated. 5582 * @throws IOException if 5583 */ 5584 void saveNamespace() throws AccessControlException, IOException { 5585 checkOperation(OperationCategory.UNCHECKED); 5586 checkSuperuserPrivilege(); 5587 5588 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 5589 if (cacheEntry != null && cacheEntry.isSuccess()) { 5590 return; // Return previous response 5591 } 5592 boolean success = false; 5593 5594 cpLock(); // Block if a checkpointing is in progress on standby. 5595 readLock(); 5596 try { 5597 checkOperation(OperationCategory.UNCHECKED); 5598 5599 if (!isInSafeMode()) { 5600 throw new IOException("Safe mode should be turned ON " 5601 + "in order to create namespace image."); 5602 } 5603 getFSImage().saveNamespace(this); 5604 success = true; 5605 } finally { 5606 readUnlock(); 5607 cpUnlock(); 5608 RetryCache.setState(cacheEntry, success); 5609 } 5610 LOG.info("New namespace image has been created"); 5611 } 5612 5613 /** 5614 * Enables/Disables/Checks restoring failed storage replicas if the storage becomes available again. 5615 * Requires superuser privilege. 5616 * 5617 * @throws AccessControlException if superuser privilege is violated. 5618 */ 5619 boolean restoreFailedStorage(String arg) throws AccessControlException, 5620 StandbyException { 5621 checkSuperuserPrivilege(); 5622 checkOperation(OperationCategory.UNCHECKED); 5623 cpLock(); // Block if a checkpointing is in progress on standby. 5624 writeLock(); 5625 try { 5626 checkOperation(OperationCategory.UNCHECKED); 5627 5628 // if it is disabled - enable it and vice versa. 5629 if(arg.equals("check")) 5630 return getFSImage().getStorage().getRestoreFailedStorage(); 5631 5632 boolean val = arg.equals("true"); // false if not 5633 getFSImage().getStorage().setRestoreFailedStorage(val); 5634 5635 return val; 5636 } finally { 5637 writeUnlock(); 5638 cpUnlock(); 5639 } 5640 } 5641 5642 Date getStartTime() { 5643 return new Date(startTime); 5644 } 5645 5646 void finalizeUpgrade() throws IOException { 5647 checkSuperuserPrivilege(); 5648 checkOperation(OperationCategory.UNCHECKED); 5649 cpLock(); // Block if a checkpointing is in progress on standby. 5650 writeLock(); 5651 try { 5652 checkOperation(OperationCategory.UNCHECKED); 5653 getFSImage().finalizeUpgrade(this.isHaEnabled() && inActiveState()); 5654 } finally { 5655 writeUnlock(); 5656 cpUnlock(); 5657 } 5658 } 5659 5660 void refreshNodes() throws IOException { 5661 checkOperation(OperationCategory.UNCHECKED); 5662 checkSuperuserPrivilege(); 5663 getBlockManager().getDatanodeManager().refreshNodes(new HdfsConfiguration()); 5664 } 5665 5666 void setBalancerBandwidth(long bandwidth) throws IOException { 5667 checkOperation(OperationCategory.UNCHECKED); 5668 checkSuperuserPrivilege(); 5669 getBlockManager().getDatanodeManager().setBalancerBandwidth(bandwidth); 5670 } 5671 5672 /** 5673 * Persist the new block (the last block of the given file). 5674 * @param path 5675 * @param file 5676 */ 5677 private void persistNewBlock(String path, INodeFile file) { 5678 Preconditions.checkArgument(file.isUnderConstruction()); 5679 getEditLog().logAddBlock(path, file); 5680 if (NameNode.stateChangeLog.isDebugEnabled()) { 5681 NameNode.stateChangeLog.debug("persistNewBlock: " 5682 + path + " with new block " + file.getLastBlock().toString() 5683 + ", current total block count is " + file.getBlocks().length); 5684 } 5685 } 5686 5687 /** 5688 * SafeModeInfo contains information related to the safe mode. 5689 * <p> 5690 * An instance of {@link SafeModeInfo} is created when the name node 5691 * enters safe mode. 5692 * <p> 5693 * During name node startup {@link SafeModeInfo} counts the number of 5694 * <em>safe blocks</em>, those that have at least the minimal number of 5695 * replicas, and calculates the ratio of safe blocks to the total number 5696 * of blocks in the system, which is the size of blocks in 5697 * {@link FSNamesystem#blockManager}. When the ratio reaches the 5698 * {@link #threshold} it starts the SafeModeMonitor daemon in order 5699 * to monitor whether the safe mode {@link #extension} is passed. 5700 * Then it leaves safe mode and destroys itself. 5701 * <p> 5702 * If safe mode is turned on manually then the number of safe blocks is 5703 * not tracked because the name node is not intended to leave safe mode 5704 * automatically in the case. 5705 * 5706 * @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction, boolean) 5707 */ 5708 public class SafeModeInfo { 5709 // configuration fields 5710 /** Safe mode threshold condition %.*/ 5711 private final double threshold; 5712 /** Safe mode minimum number of datanodes alive */ 5713 private final int datanodeThreshold; 5714 /** 5715 * Safe mode extension after the threshold. 5716 * Make it volatile so that getSafeModeTip can read the latest value 5717 * without taking a lock. 5718 */ 5719 private volatile int extension; 5720 /** Min replication required by safe mode. */ 5721 private final int safeReplication; 5722 /** threshold for populating needed replication queues */ 5723 private final double replQueueThreshold; 5724 // internal fields 5725 /** Time when threshold was reached. 5726 * <br> -1 safe mode is off 5727 * <br> 0 safe mode is on, and threshold is not reached yet 5728 * <br> >0 safe mode is on, but we are in extension period 5729 */ 5730 private long reached = -1; 5731 /** Total number of blocks. */ 5732 int blockTotal; 5733 /** Number of safe blocks. */ 5734 int blockSafe; 5735 /** Number of blocks needed to satisfy safe mode threshold condition */ 5736 private int blockThreshold; 5737 /** Number of blocks needed before populating replication queues */ 5738 private int blockReplQueueThreshold; 5739 /** time of the last status printout */ 5740 private long lastStatusReport = 0; 5741 /** 5742 * Was safemode entered automatically because available resources were low. 5743 * Make it volatile so that getSafeModeTip can read the latest value 5744 * without taking a lock. 5745 */ 5746 private volatile boolean resourcesLow = false; 5747 /** Should safemode adjust its block totals as blocks come in */ 5748 private boolean shouldIncrementallyTrackBlocks = false; 5749 /** counter for tracking startup progress of reported blocks */ 5750 private Counter awaitingReportedBlocksCounter; 5751 5752 /** 5753 * Creates SafeModeInfo when the name node enters 5754 * automatic safe mode at startup. 5755 * 5756 * @param conf configuration 5757 */ 5758 private SafeModeInfo(Configuration conf) { 5759 this.threshold = conf.getFloat(DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, 5760 DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT); 5761 if(threshold > 1.0) { 5762 LOG.warn("The threshold value should't be greater than 1, threshold: " + threshold); 5763 } 5764 this.datanodeThreshold = conf.getInt( 5765 DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY, 5766 DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT); 5767 this.extension = conf.getInt(DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, 0); 5768 this.safeReplication = conf.getInt(DFS_NAMENODE_REPLICATION_MIN_KEY, 5769 DFS_NAMENODE_REPLICATION_MIN_DEFAULT); 5770 5771 LOG.info(DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY + " = " + threshold); 5772 LOG.info(DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY + " = " + datanodeThreshold); 5773 LOG.info(DFS_NAMENODE_SAFEMODE_EXTENSION_KEY + " = " + extension); 5774 5775 // default to safe mode threshold (i.e., don't populate queues before leaving safe mode) 5776 this.replQueueThreshold = 5777 conf.getFloat(DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY, 5778 (float) threshold); 5779 this.blockTotal = 0; 5780 this.blockSafe = 0; 5781 } 5782 5783 /** 5784 * In the HA case, the StandbyNode can be in safemode while the namespace 5785 * is modified by the edit log tailer. In this case, the number of total 5786 * blocks changes as edits are processed (eg blocks are added and deleted). 5787 * However, we don't want to do the incremental tracking during the 5788 * startup-time loading process -- only once the initial total has been 5789 * set after the image has been loaded. 5790 */ 5791 private boolean shouldIncrementallyTrackBlocks() { 5792 return shouldIncrementallyTrackBlocks; 5793 } 5794 5795 /** 5796 * Creates SafeModeInfo when safe mode is entered manually, or because 5797 * available resources are low. 5798 * 5799 * The {@link #threshold} is set to 1.5 so that it could never be reached. 5800 * {@link #blockTotal} is set to -1 to indicate that safe mode is manual. 5801 * 5802 * @see SafeModeInfo 5803 */ 5804 private SafeModeInfo(boolean resourcesLow) { 5805 this.threshold = 1.5f; // this threshold can never be reached 5806 this.datanodeThreshold = Integer.MAX_VALUE; 5807 this.extension = Integer.MAX_VALUE; 5808 this.safeReplication = Short.MAX_VALUE + 1; // more than maxReplication 5809 this.replQueueThreshold = 1.5f; // can never be reached 5810 this.blockTotal = -1; 5811 this.blockSafe = -1; 5812 this.resourcesLow = resourcesLow; 5813 enter(); 5814 reportStatus("STATE* Safe mode is ON.", true); 5815 } 5816 5817 /** 5818 * Check if safe mode is on. 5819 * @return true if in safe mode 5820 */ 5821 private synchronized boolean isOn() { 5822 doConsistencyCheck(); 5823 return this.reached >= 0; 5824 } 5825 5826 /** 5827 * Enter safe mode. 5828 */ 5829 private void enter() { 5830 this.reached = 0; 5831 } 5832 5833 /** 5834 * Leave safe mode. 5835 * <p> 5836 * Check for invalid, under- & over-replicated blocks in the end of startup. 5837 */ 5838 private synchronized void leave() { 5839 // if not done yet, initialize replication queues. 5840 // In the standby, do not populate repl queues 5841 if (!isPopulatingReplQueues() && shouldPopulateReplQueues()) { 5842 initializeReplQueues(); 5843 } 5844 long timeInSafemode = now() - startTime; 5845 NameNode.stateChangeLog.info("STATE* Leaving safe mode after " 5846 + timeInSafemode/1000 + " secs"); 5847 NameNode.getNameNodeMetrics().setSafeModeTime((int) timeInSafemode); 5848 5849 //Log the following only once (when transitioning from ON -> OFF) 5850 if (reached >= 0) { 5851 NameNode.stateChangeLog.info("STATE* Safe mode is OFF"); 5852 } 5853 reached = -1; 5854 safeMode = null; 5855 final NetworkTopology nt = blockManager.getDatanodeManager().getNetworkTopology(); 5856 NameNode.stateChangeLog.info("STATE* Network topology has " 5857 + nt.getNumOfRacks() + " racks and " 5858 + nt.getNumOfLeaves() + " datanodes"); 5859 NameNode.stateChangeLog.info("STATE* UnderReplicatedBlocks has " 5860 + blockManager.numOfUnderReplicatedBlocks() + " blocks"); 5861 5862 startSecretManagerIfNecessary(); 5863 5864 // If startup has not yet completed, end safemode phase. 5865 StartupProgress prog = NameNode.getStartupProgress(); 5866 if (prog.getStatus(Phase.SAFEMODE) != Status.COMPLETE) { 5867 prog.endStep(Phase.SAFEMODE, STEP_AWAITING_REPORTED_BLOCKS); 5868 prog.endPhase(Phase.SAFEMODE); 5869 } 5870 } 5871 5872 /** 5873 * Check whether we have reached the threshold for 5874 * initializing replication queues. 5875 */ 5876 private synchronized boolean canInitializeReplQueues() { 5877 return shouldPopulateReplQueues() 5878 && blockSafe >= blockReplQueueThreshold; 5879 } 5880 5881 /** 5882 * Safe mode can be turned off iff 5883 * the threshold is reached and 5884 * the extension time have passed. 5885 * @return true if can leave or false otherwise. 5886 */ 5887 private synchronized boolean canLeave() { 5888 if (reached == 0) { 5889 return false; 5890 } 5891 5892 if (now() - reached < extension) { 5893 reportStatus("STATE* Safe mode ON, in safe mode extension.", false); 5894 return false; 5895 } 5896 5897 if (needEnter()) { 5898 reportStatus("STATE* Safe mode ON, thresholds not met.", false); 5899 return false; 5900 } 5901 5902 return true; 5903 } 5904 5905 /** 5906 * There is no need to enter safe mode 5907 * if DFS is empty or {@link #threshold} == 0 5908 */ 5909 private boolean needEnter() { 5910 return (threshold != 0 && blockSafe < blockThreshold) || 5911 (datanodeThreshold != 0 && getNumLiveDataNodes() < datanodeThreshold) || 5912 (!nameNodeHasResourcesAvailable()); 5913 } 5914 5915 /** 5916 * Check and trigger safe mode if needed. 5917 */ 5918 private void checkMode() { 5919 // Have to have write-lock since leaving safemode initializes 5920 // repl queues, which requires write lock 5921 assert hasWriteLock(); 5922 if (inTransitionToActive()) { 5923 return; 5924 } 5925 // if smmthread is already running, the block threshold must have been 5926 // reached before, there is no need to enter the safe mode again 5927 if (smmthread == null && needEnter()) { 5928 enter(); 5929 // check if we are ready to initialize replication queues 5930 if (canInitializeReplQueues() && !isPopulatingReplQueues() 5931 && !haEnabled) { 5932 initializeReplQueues(); 5933 } 5934 reportStatus("STATE* Safe mode ON.", false); 5935 return; 5936 } 5937 // the threshold is reached or was reached before 5938 if (!isOn() || // safe mode is off 5939 extension <= 0 || threshold <= 0) { // don't need to wait 5940 this.leave(); // leave safe mode 5941 return; 5942 } 5943 if (reached > 0) { // threshold has already been reached before 5944 reportStatus("STATE* Safe mode ON.", false); 5945 return; 5946 } 5947 // start monitor 5948 reached = now(); 5949 if (smmthread == null) { 5950 smmthread = new Daemon(new SafeModeMonitor()); 5951 smmthread.start(); 5952 reportStatus("STATE* Safe mode extension entered.", true); 5953 } 5954 5955 // check if we are ready to initialize replication queues 5956 if (canInitializeReplQueues() && !isPopulatingReplQueues() && !haEnabled) { 5957 initializeReplQueues(); 5958 } 5959 } 5960 5961 /** 5962 * Set total number of blocks. 5963 */ 5964 private synchronized void setBlockTotal(int total) { 5965 this.blockTotal = total; 5966 this.blockThreshold = (int) (blockTotal * threshold); 5967 this.blockReplQueueThreshold = 5968 (int) (blockTotal * replQueueThreshold); 5969 if (haEnabled) { 5970 // After we initialize the block count, any further namespace 5971 // modifications done while in safe mode need to keep track 5972 // of the number of total blocks in the system. 5973 this.shouldIncrementallyTrackBlocks = true; 5974 } 5975 if(blockSafe < 0) 5976 this.blockSafe = 0; 5977 checkMode(); 5978 } 5979 5980 /** 5981 * Increment number of safe blocks if current block has 5982 * reached minimal replication. 5983 * @param replication current replication 5984 */ 5985 private synchronized void incrementSafeBlockCount(short replication) { 5986 if (replication == safeReplication) { 5987 this.blockSafe++; 5988 5989 // Report startup progress only if we haven't completed startup yet. 5990 StartupProgress prog = NameNode.getStartupProgress(); 5991 if (prog.getStatus(Phase.SAFEMODE) != Status.COMPLETE) { 5992 if (this.awaitingReportedBlocksCounter == null) { 5993 this.awaitingReportedBlocksCounter = prog.getCounter(Phase.SAFEMODE, 5994 STEP_AWAITING_REPORTED_BLOCKS); 5995 } 5996 this.awaitingReportedBlocksCounter.increment(); 5997 } 5998 5999 checkMode(); 6000 } 6001 } 6002 6003 /** 6004 * Decrement number of safe blocks if current block has 6005 * fallen below minimal replication. 6006 * @param replication current replication 6007 */ 6008 private synchronized void decrementSafeBlockCount(short replication) { 6009 if (replication == safeReplication-1) { 6010 this.blockSafe--; 6011 //blockSafe is set to -1 in manual / low resources safemode 6012 assert blockSafe >= 0 || isManual() || areResourcesLow(); 6013 checkMode(); 6014 } 6015 } 6016 6017 /** 6018 * Check if safe mode was entered manually 6019 */ 6020 private boolean isManual() { 6021 return extension == Integer.MAX_VALUE; 6022 } 6023 6024 /** 6025 * Set manual safe mode. 6026 */ 6027 private synchronized void setManual() { 6028 extension = Integer.MAX_VALUE; 6029 } 6030 6031 /** 6032 * Check if safe mode was entered due to resources being low. 6033 */ 6034 private boolean areResourcesLow() { 6035 return resourcesLow; 6036 } 6037 6038 /** 6039 * Set that resources are low for this instance of safe mode. 6040 */ 6041 private void setResourcesLow() { 6042 resourcesLow = true; 6043 } 6044 6045 /** 6046 * A tip on how safe mode is to be turned off: manually or automatically. 6047 */ 6048 String getTurnOffTip() { 6049 if(!isOn()) { 6050 return "Safe mode is OFF."; 6051 } 6052 6053 //Manual OR low-resource safemode. (Admin intervention required) 6054 String adminMsg = "It was turned on manually. "; 6055 if (areResourcesLow()) { 6056 adminMsg = "Resources are low on NN. Please add or free up more " 6057 + "resources then turn off safe mode manually. NOTE: If you turn off" 6058 + " safe mode before adding resources, " 6059 + "the NN will immediately return to safe mode. "; 6060 } 6061 if (isManual() || areResourcesLow()) { 6062 return adminMsg 6063 + "Use \"hdfs dfsadmin -safemode leave\" to turn safe mode off."; 6064 } 6065 6066 boolean thresholdsMet = true; 6067 int numLive = getNumLiveDataNodes(); 6068 String msg = ""; 6069 if (blockSafe < blockThreshold) { 6070 msg += String.format( 6071 "The reported blocks %d needs additional %d" 6072 + " blocks to reach the threshold %.4f of total blocks %d.%n", 6073 blockSafe, (blockThreshold - blockSafe) + 1, threshold, blockTotal); 6074 thresholdsMet = false; 6075 } else { 6076 msg += String.format("The reported blocks %d has reached the threshold" 6077 + " %.4f of total blocks %d. ", blockSafe, threshold, blockTotal); 6078 } 6079 if (numLive < datanodeThreshold) { 6080 msg += String.format( 6081 "The number of live datanodes %d needs an additional %d live " 6082 + "datanodes to reach the minimum number %d.%n", 6083 numLive, (datanodeThreshold - numLive), datanodeThreshold); 6084 thresholdsMet = false; 6085 } else { 6086 msg += String.format("The number of live datanodes %d has reached " 6087 + "the minimum number %d. ", 6088 numLive, datanodeThreshold); 6089 } 6090 msg += (reached > 0) ? "In safe mode extension. " : ""; 6091 msg += "Safe mode will be turned off automatically "; 6092 6093 if (!thresholdsMet) { 6094 msg += "once the thresholds have been reached."; 6095 } else if (reached + extension - now() > 0) { 6096 msg += ("in " + (reached + extension - now()) / 1000 + " seconds."); 6097 } else { 6098 msg += "soon."; 6099 } 6100 6101 return msg; 6102 } 6103 6104 /** 6105 * Print status every 20 seconds. 6106 */ 6107 private void reportStatus(String msg, boolean rightNow) { 6108 long curTime = now(); 6109 if(!rightNow && (curTime - lastStatusReport < 20 * 1000)) 6110 return; 6111 NameNode.stateChangeLog.info(msg + " \n" + getTurnOffTip()); 6112 lastStatusReport = curTime; 6113 } 6114 6115 @Override 6116 public String toString() { 6117 String resText = "Current safe blocks = " 6118 + blockSafe 6119 + ". Target blocks = " + blockThreshold + " for threshold = %" + threshold 6120 + ". Minimal replication = " + safeReplication + "."; 6121 if (reached > 0) 6122 resText += " Threshold was reached " + new Date(reached) + "."; 6123 return resText; 6124 } 6125 6126 /** 6127 * Checks consistency of the class state. 6128 * This is costly so only runs if asserts are enabled. 6129 */ 6130 private void doConsistencyCheck() { 6131 boolean assertsOn = false; 6132 assert assertsOn = true; // set to true if asserts are on 6133 if (!assertsOn) return; 6134 6135 if (blockTotal == -1 && blockSafe == -1) { 6136 return; // manual safe mode 6137 } 6138 int activeBlocks = blockManager.getActiveBlockCount(); 6139 if ((blockTotal != activeBlocks) && 6140 !(blockSafe >= 0 && blockSafe <= blockTotal)) { 6141 throw new AssertionError( 6142 " SafeMode: Inconsistent filesystem state: " 6143 + "SafeMode data: blockTotal=" + blockTotal 6144 + " blockSafe=" + blockSafe + "; " 6145 + "BlockManager data: active=" + activeBlocks); 6146 } 6147 } 6148 6149 private synchronized void adjustBlockTotals(int deltaSafe, int deltaTotal) { 6150 if (!shouldIncrementallyTrackBlocks) { 6151 return; 6152 } 6153 assert haEnabled; 6154 6155 if (LOG.isDebugEnabled()) { 6156 LOG.debug("Adjusting block totals from " + 6157 blockSafe + "/" + blockTotal + " to " + 6158 (blockSafe + deltaSafe) + "/" + (blockTotal + deltaTotal)); 6159 } 6160 assert blockSafe + deltaSafe >= 0 : "Can't reduce blockSafe " + 6161 blockSafe + " by " + deltaSafe + ": would be negative"; 6162 assert blockTotal + deltaTotal >= 0 : "Can't reduce blockTotal " + 6163 blockTotal + " by " + deltaTotal + ": would be negative"; 6164 6165 blockSafe += deltaSafe; 6166 setBlockTotal(blockTotal + deltaTotal); 6167 } 6168 } 6169 6170 /** 6171 * Periodically check whether it is time to leave safe mode. 6172 * This thread starts when the threshold level is reached. 6173 * 6174 */ 6175 class SafeModeMonitor implements Runnable { 6176 /** interval in msec for checking safe mode: {@value} */ 6177 private static final long recheckInterval = 1000; 6178 6179 /** 6180 */ 6181 @Override 6182 public void run() { 6183 while (fsRunning) { 6184 writeLock(); 6185 try { 6186 if (safeMode == null) { // Not in safe mode. 6187 break; 6188 } 6189 if (safeMode.canLeave()) { 6190 // Leave safe mode. 6191 safeMode.leave(); 6192 smmthread = null; 6193 break; 6194 } 6195 } finally { 6196 writeUnlock(); 6197 } 6198 6199 try { 6200 Thread.sleep(recheckInterval); 6201 } catch (InterruptedException ie) { 6202 // Ignored 6203 } 6204 } 6205 if (!fsRunning) { 6206 LOG.info("NameNode is being shutdown, exit SafeModeMonitor thread"); 6207 } 6208 } 6209 } 6210 6211 boolean setSafeMode(SafeModeAction action) throws IOException { 6212 if (action != SafeModeAction.SAFEMODE_GET) { 6213 checkSuperuserPrivilege(); 6214 switch(action) { 6215 case SAFEMODE_LEAVE: // leave safe mode 6216 leaveSafeMode(); 6217 break; 6218 case SAFEMODE_ENTER: // enter safe mode 6219 enterSafeMode(false); 6220 break; 6221 default: 6222 LOG.error("Unexpected safe mode action"); 6223 } 6224 } 6225 return isInSafeMode(); 6226 } 6227 6228 @Override 6229 public void checkSafeMode() { 6230 // safeMode is volatile, and may be set to null at any time 6231 SafeModeInfo safeMode = this.safeMode; 6232 if (safeMode != null) { 6233 safeMode.checkMode(); 6234 } 6235 } 6236 6237 @Override 6238 public boolean isInSafeMode() { 6239 // safeMode is volatile, and may be set to null at any time 6240 SafeModeInfo safeMode = this.safeMode; 6241 if (safeMode == null) 6242 return false; 6243 return safeMode.isOn(); 6244 } 6245 6246 @Override 6247 public boolean isInStartupSafeMode() { 6248 // safeMode is volatile, and may be set to null at any time 6249 SafeModeInfo safeMode = this.safeMode; 6250 if (safeMode == null) 6251 return false; 6252 // If the NN is in safemode, and not due to manual / low resources, we 6253 // assume it must be because of startup. If the NN had low resources during 6254 // startup, we assume it came out of startup safemode and it is now in low 6255 // resources safemode 6256 return !safeMode.isManual() && !safeMode.areResourcesLow() 6257 && safeMode.isOn(); 6258 } 6259 6260 /** 6261 * Check if replication queues are to be populated 6262 * @return true when node is HAState.Active and not in the very first safemode 6263 */ 6264 @Override 6265 public boolean isPopulatingReplQueues() { 6266 if (!shouldPopulateReplQueues()) { 6267 return false; 6268 } 6269 return initializedReplQueues; 6270 } 6271 6272 private boolean shouldPopulateReplQueues() { 6273 if(haContext == null || haContext.getState() == null) 6274 return false; 6275 return haContext.getState().shouldPopulateReplQueues(); 6276 } 6277 6278 @Override 6279 public void incrementSafeBlockCount(int replication) { 6280 // safeMode is volatile, and may be set to null at any time 6281 SafeModeInfo safeMode = this.safeMode; 6282 if (safeMode == null) 6283 return; 6284 safeMode.incrementSafeBlockCount((short)replication); 6285 } 6286 6287 @Override 6288 public void decrementSafeBlockCount(Block b) { 6289 // safeMode is volatile, and may be set to null at any time 6290 SafeModeInfo safeMode = this.safeMode; 6291 if (safeMode == null) // mostly true 6292 return; 6293 BlockInfo storedBlock = getStoredBlock(b); 6294 if (storedBlock.isComplete()) { 6295 safeMode.decrementSafeBlockCount((short)blockManager.countNodes(b).liveReplicas()); 6296 } 6297 } 6298 6299 /** 6300 * Adjust the total number of blocks safe and expected during safe mode. 6301 * If safe mode is not currently on, this is a no-op. 6302 * @param deltaSafe the change in number of safe blocks 6303 * @param deltaTotal the change i nnumber of total blocks expected 6304 */ 6305 @Override 6306 public void adjustSafeModeBlockTotals(int deltaSafe, int deltaTotal) { 6307 // safeMode is volatile, and may be set to null at any time 6308 SafeModeInfo safeMode = this.safeMode; 6309 if (safeMode == null) 6310 return; 6311 safeMode.adjustBlockTotals(deltaSafe, deltaTotal); 6312 } 6313 6314 /** 6315 * Set the total number of blocks in the system. 6316 */ 6317 public void setBlockTotal() { 6318 // safeMode is volatile, and may be set to null at any time 6319 SafeModeInfo safeMode = this.safeMode; 6320 if (safeMode == null) 6321 return; 6322 safeMode.setBlockTotal((int)getCompleteBlocksTotal()); 6323 } 6324 6325 /** 6326 * Get the total number of blocks in the system. 6327 */ 6328 @Override // FSNamesystemMBean 6329 @Metric 6330 public long getBlocksTotal() { 6331 return blockManager.getTotalBlocks(); 6332 } 6333 6334 /** 6335 * Get the total number of COMPLETE blocks in the system. 6336 * For safe mode only complete blocks are counted. 6337 */ 6338 private long getCompleteBlocksTotal() { 6339 // Calculate number of blocks under construction 6340 long numUCBlocks = 0; 6341 readLock(); 6342 numUCBlocks = leaseManager.getNumUnderConstructionBlocks(); 6343 try { 6344 return getBlocksTotal() - numUCBlocks; 6345 } finally { 6346 readUnlock(); 6347 } 6348 } 6349 6350 /** 6351 * Enter safe mode. If resourcesLow is false, then we assume it is manual 6352 * @throws IOException 6353 */ 6354 void enterSafeMode(boolean resourcesLow) throws IOException { 6355 writeLock(); 6356 try { 6357 // Stop the secret manager, since rolling the master key would 6358 // try to write to the edit log 6359 stopSecretManager(); 6360 6361 // Ensure that any concurrent operations have been fully synced 6362 // before entering safe mode. This ensures that the FSImage 6363 // is entirely stable on disk as soon as we're in safe mode. 6364 boolean isEditlogOpenForWrite = getEditLog().isOpenForWrite(); 6365 // Before Editlog is in OpenForWrite mode, editLogStream will be null. So, 6366 // logSyncAll call can be called only when Edlitlog is in OpenForWrite mode 6367 if (isEditlogOpenForWrite) { 6368 getEditLog().logSyncAll(); 6369 } 6370 if (!isInSafeMode()) { 6371 safeMode = new SafeModeInfo(resourcesLow); 6372 return; 6373 } 6374 if (resourcesLow) { 6375 safeMode.setResourcesLow(); 6376 } else { 6377 safeMode.setManual(); 6378 } 6379 if (isEditlogOpenForWrite) { 6380 getEditLog().logSyncAll(); 6381 } 6382 NameNode.stateChangeLog.info("STATE* Safe mode is ON" 6383 + safeMode.getTurnOffTip()); 6384 } finally { 6385 writeUnlock(); 6386 } 6387 } 6388 6389 /** 6390 * Leave safe mode. 6391 */ 6392 void leaveSafeMode() { 6393 writeLock(); 6394 try { 6395 if (!isInSafeMode()) { 6396 NameNode.stateChangeLog.info("STATE* Safe mode is already OFF"); 6397 return; 6398 } 6399 safeMode.leave(); 6400 } finally { 6401 writeUnlock(); 6402 } 6403 } 6404 6405 String getSafeModeTip() { 6406 // There is no need to take readLock. 6407 // Don't use isInSafeMode as this.safeMode might be set to null. 6408 // after isInSafeMode returns. 6409 boolean inSafeMode; 6410 SafeModeInfo safeMode = this.safeMode; 6411 if (safeMode == null) { 6412 inSafeMode = false; 6413 } else { 6414 inSafeMode = safeMode.isOn(); 6415 } 6416 6417 if (!inSafeMode) { 6418 return ""; 6419 } else { 6420 return safeMode.getTurnOffTip(); 6421 } 6422 } 6423 6424 CheckpointSignature rollEditLog() throws IOException { 6425 checkSuperuserPrivilege(); 6426 checkOperation(OperationCategory.JOURNAL); 6427 writeLock(); 6428 try { 6429 checkOperation(OperationCategory.JOURNAL); 6430 checkNameNodeSafeMode("Log not rolled"); 6431 if (Server.isRpcInvocation()) { 6432 LOG.info("Roll Edit Log from " + Server.getRemoteAddress()); 6433 } 6434 return getFSImage().rollEditLog(); 6435 } finally { 6436 writeUnlock(); 6437 } 6438 } 6439 6440 NamenodeCommand startCheckpoint(NamenodeRegistration backupNode, 6441 NamenodeRegistration activeNamenode) throws IOException { 6442 checkOperation(OperationCategory.CHECKPOINT); 6443 CacheEntryWithPayload cacheEntry = RetryCache.waitForCompletion(retryCache, 6444 null); 6445 if (cacheEntry != null && cacheEntry.isSuccess()) { 6446 return (NamenodeCommand) cacheEntry.getPayload(); 6447 } 6448 writeLock(); 6449 NamenodeCommand cmd = null; 6450 try { 6451 checkOperation(OperationCategory.CHECKPOINT); 6452 checkNameNodeSafeMode("Checkpoint not started"); 6453 6454 LOG.info("Start checkpoint for " + backupNode.getAddress()); 6455 cmd = getFSImage().startCheckpoint(backupNode, activeNamenode); 6456 getEditLog().logSync(); 6457 return cmd; 6458 } finally { 6459 writeUnlock(); 6460 RetryCache.setState(cacheEntry, cmd != null, cmd); 6461 } 6462 } 6463 6464 public void processIncrementalBlockReport(final DatanodeID nodeID, 6465 final StorageReceivedDeletedBlocks srdb) 6466 throws IOException { 6467 writeLock(); 6468 try { 6469 blockManager.processIncrementalBlockReport(nodeID, srdb); 6470 } finally { 6471 writeUnlock(); 6472 } 6473 } 6474 6475 void endCheckpoint(NamenodeRegistration registration, 6476 CheckpointSignature sig) throws IOException { 6477 checkOperation(OperationCategory.CHECKPOINT); 6478 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 6479 if (cacheEntry != null && cacheEntry.isSuccess()) { 6480 return; // Return previous response 6481 } 6482 boolean success = false; 6483 readLock(); 6484 try { 6485 checkOperation(OperationCategory.CHECKPOINT); 6486 6487 checkNameNodeSafeMode("Checkpoint not ended"); 6488 LOG.info("End checkpoint for " + registration.getAddress()); 6489 getFSImage().endCheckpoint(sig); 6490 success = true; 6491 } finally { 6492 readUnlock(); 6493 RetryCache.setState(cacheEntry, success); 6494 } 6495 } 6496 6497 PermissionStatus createFsOwnerPermissions(FsPermission permission) { 6498 return new PermissionStatus(fsOwner.getShortUserName(), supergroup, permission); 6499 } 6500 6501 private void checkOwner(FSPermissionChecker pc, String path) 6502 throws AccessControlException, UnresolvedLinkException { 6503 checkPermission(pc, path, true, null, null, null, null); 6504 } 6505 6506 private void checkPathAccess(FSPermissionChecker pc, 6507 String path, FsAction access) throws AccessControlException, 6508 UnresolvedLinkException { 6509 checkPermission(pc, path, false, null, null, access, null); 6510 } 6511 6512 private void checkUnreadableBySuperuser(FSPermissionChecker pc, 6513 INode inode, int snapshotId) 6514 throws IOException { 6515 if (pc.isSuperUser()) { 6516 for (XAttr xattr : dir.getXAttrs(inode, snapshotId)) { 6517 if (XAttrHelper.getPrefixName(xattr). 6518 equals(SECURITY_XATTR_UNREADABLE_BY_SUPERUSER)) { 6519 throw new AccessControlException("Access is denied for " + 6520 pc.getUser() + " since the superuser is not allowed to " + 6521 "perform this operation."); 6522 } 6523 } 6524 } 6525 } 6526 6527 private void checkParentAccess(FSPermissionChecker pc, 6528 String path, FsAction access) throws AccessControlException, 6529 UnresolvedLinkException { 6530 checkPermission(pc, path, false, null, access, null, null); 6531 } 6532 6533 private void checkAncestorAccess(FSPermissionChecker pc, 6534 String path, FsAction access) throws AccessControlException, 6535 UnresolvedLinkException { 6536 checkPermission(pc, path, false, access, null, null, null); 6537 } 6538 6539 private void checkTraverse(FSPermissionChecker pc, String path) 6540 throws AccessControlException, UnresolvedLinkException { 6541 checkPermission(pc, path, false, null, null, null, null); 6542 } 6543 6544 /** 6545 * This is a wrapper for FSDirectory.resolvePath(). If the path passed 6546 * is prefixed with /.reserved/raw, then it checks to ensure that the caller 6547 * has super user privs. 6548 * 6549 * @param path The path to resolve. 6550 * @param pathComponents path components corresponding to the path 6551 * @return if the path indicates an inode, return path after replacing up to 6552 * <inodeid> with the corresponding path of the inode, else the path 6553 * in {@code src} as is. If the path refers to a path in the "raw" 6554 * directory, return the non-raw pathname. 6555 * @throws FileNotFoundException 6556 * @throws AccessControlException 6557 */ 6558 private String resolvePath(String path, byte[][] pathComponents) 6559 throws FileNotFoundException, AccessControlException { 6560 if (FSDirectory.isReservedRawName(path)) { 6561 checkSuperuserPrivilege(); 6562 } 6563 return FSDirectory.resolvePath(path, pathComponents, dir); 6564 } 6565 6566 @Override 6567 public void checkSuperuserPrivilege() 6568 throws AccessControlException { 6569 if (isPermissionEnabled) { 6570 FSPermissionChecker pc = getPermissionChecker(); 6571 pc.checkSuperuserPrivilege(); 6572 } 6573 } 6574 6575 /** 6576 * Check whether current user have permissions to access the path. For more 6577 * details of the parameters, see 6578 * {@link FSPermissionChecker#checkPermission}. 6579 */ 6580 private void checkPermission(FSPermissionChecker pc, 6581 String path, boolean doCheckOwner, FsAction ancestorAccess, 6582 FsAction parentAccess, FsAction access, FsAction subAccess) 6583 throws AccessControlException, UnresolvedLinkException { 6584 checkPermission(pc, path, doCheckOwner, ancestorAccess, 6585 parentAccess, access, subAccess, false, true); 6586 } 6587 6588 /** 6589 * Check whether current user have permissions to access the path. For more 6590 * details of the parameters, see 6591 * {@link FSPermissionChecker#checkPermission}. 6592 */ 6593 private void checkPermission(FSPermissionChecker pc, 6594 String path, boolean doCheckOwner, FsAction ancestorAccess, 6595 FsAction parentAccess, FsAction access, FsAction subAccess, 6596 boolean ignoreEmptyDir, boolean resolveLink) 6597 throws AccessControlException, UnresolvedLinkException { 6598 if (!pc.isSuperUser()) { 6599 waitForLoadingFSImage(); 6600 readLock(); 6601 try { 6602 pc.checkPermission(path, dir, doCheckOwner, ancestorAccess, 6603 parentAccess, access, subAccess, ignoreEmptyDir, resolveLink); 6604 } finally { 6605 readUnlock(); 6606 } 6607 } 6608 } 6609 6610 /** 6611 * Check to see if we have exceeded the limit on the number 6612 * of inodes. 6613 */ 6614 void checkFsObjectLimit() throws IOException { 6615 if (maxFsObjects != 0 && 6616 maxFsObjects <= dir.totalInodes() + getBlocksTotal()) { 6617 throw new IOException("Exceeded the configured number of objects " + 6618 maxFsObjects + " in the filesystem."); 6619 } 6620 } 6621 6622 /** 6623 * Get the total number of objects in the system. 6624 */ 6625 @Override // FSNamesystemMBean 6626 public long getMaxObjects() { 6627 return maxFsObjects; 6628 } 6629 6630 @Override // FSNamesystemMBean 6631 @Metric 6632 public long getFilesTotal() { 6633 // There is no need to take fSNamesystem's lock as 6634 // FSDirectory has its own lock. 6635 return this.dir.totalInodes(); 6636 } 6637 6638 @Override // FSNamesystemMBean 6639 @Metric 6640 public long getPendingReplicationBlocks() { 6641 return blockManager.getPendingReplicationBlocksCount(); 6642 } 6643 6644 @Override // FSNamesystemMBean 6645 @Metric 6646 public long getUnderReplicatedBlocks() { 6647 return blockManager.getUnderReplicatedBlocksCount(); 6648 } 6649 6650 /** Returns number of blocks with corrupt replicas */ 6651 @Metric({"CorruptBlocks", "Number of blocks with corrupt replicas"}) 6652 public long getCorruptReplicaBlocks() { 6653 return blockManager.getCorruptReplicaBlocksCount(); 6654 } 6655 6656 @Override // FSNamesystemMBean 6657 @Metric 6658 public long getScheduledReplicationBlocks() { 6659 return blockManager.getScheduledReplicationBlocksCount(); 6660 } 6661 6662 @Override 6663 @Metric 6664 public long getPendingDeletionBlocks() { 6665 return blockManager.getPendingDeletionBlocksCount(); 6666 } 6667 6668 @Override 6669 public long getBlockDeletionStartTime() { 6670 return startTime + blockManager.getStartupDelayBlockDeletionInMs(); 6671 } 6672 6673 @Metric 6674 public long getExcessBlocks() { 6675 return blockManager.getExcessBlocksCount(); 6676 } 6677 6678 // HA-only metric 6679 @Metric 6680 public long getPostponedMisreplicatedBlocks() { 6681 return blockManager.getPostponedMisreplicatedBlocksCount(); 6682 } 6683 6684 // HA-only metric 6685 @Metric 6686 public int getPendingDataNodeMessageCount() { 6687 return blockManager.getPendingDataNodeMessageCount(); 6688 } 6689 6690 // HA-only metric 6691 @Metric 6692 public String getHAState() { 6693 return haContext.getState().toString(); 6694 } 6695 6696 // HA-only metric 6697 @Metric 6698 public long getMillisSinceLastLoadedEdits() { 6699 if (isInStandbyState() && editLogTailer != null) { 6700 return now() - editLogTailer.getLastLoadTimestamp(); 6701 } else { 6702 return 0; 6703 } 6704 } 6705 6706 @Metric 6707 public int getBlockCapacity() { 6708 return blockManager.getCapacity(); 6709 } 6710 6711 @Override // FSNamesystemMBean 6712 public String getFSState() { 6713 return isInSafeMode() ? "safeMode" : "Operational"; 6714 } 6715 6716 private ObjectName mbeanName; 6717 private ObjectName mxbeanName; 6718 6719 /** 6720 * Register the FSNamesystem MBean using the name 6721 * "hadoop:service=NameNode,name=FSNamesystemState" 6722 */ 6723 private void registerMBean() { 6724 // We can only implement one MXBean interface, so we keep the old one. 6725 try { 6726 StandardMBean bean = new StandardMBean(this, FSNamesystemMBean.class); 6727 mbeanName = MBeans.register("NameNode", "FSNamesystemState", bean); 6728 } catch (NotCompliantMBeanException e) { 6729 throw new RuntimeException("Bad MBean setup", e); 6730 } 6731 6732 LOG.info("Registered FSNamesystemState MBean"); 6733 } 6734 6735 /** 6736 * shutdown FSNamesystem 6737 */ 6738 void shutdown() { 6739 if (snapshotManager != null) { 6740 snapshotManager.shutdown(); 6741 } 6742 if (mbeanName != null) { 6743 MBeans.unregister(mbeanName); 6744 mbeanName = null; 6745 } 6746 if (mxbeanName != null) { 6747 MBeans.unregister(mxbeanName); 6748 mxbeanName = null; 6749 } 6750 if (dir != null) { 6751 dir.shutdown(); 6752 } 6753 if (blockManager != null) { 6754 blockManager.shutdown(); 6755 } 6756 } 6757 6758 @Override // FSNamesystemMBean 6759 public int getNumLiveDataNodes() { 6760 return getBlockManager().getDatanodeManager().getNumLiveDataNodes(); 6761 } 6762 6763 @Override // FSNamesystemMBean 6764 public int getNumDeadDataNodes() { 6765 return getBlockManager().getDatanodeManager().getNumDeadDataNodes(); 6766 } 6767 6768 @Override // FSNamesystemMBean 6769 public int getNumDecomLiveDataNodes() { 6770 final List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); 6771 getBlockManager().getDatanodeManager().fetchDatanodes(live, null, true); 6772 int liveDecommissioned = 0; 6773 for (DatanodeDescriptor node : live) { 6774 liveDecommissioned += node.isDecommissioned() ? 1 : 0; 6775 } 6776 return liveDecommissioned; 6777 } 6778 6779 @Override // FSNamesystemMBean 6780 public int getNumDecomDeadDataNodes() { 6781 final List<DatanodeDescriptor> dead = new ArrayList<DatanodeDescriptor>(); 6782 getBlockManager().getDatanodeManager().fetchDatanodes(null, dead, true); 6783 int deadDecommissioned = 0; 6784 for (DatanodeDescriptor node : dead) { 6785 deadDecommissioned += node.isDecommissioned() ? 1 : 0; 6786 } 6787 return deadDecommissioned; 6788 } 6789 6790 @Override // FSNamesystemMBean 6791 public int getVolumeFailuresTotal() { 6792 List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); 6793 getBlockManager().getDatanodeManager().fetchDatanodes(live, null, true); 6794 int volumeFailuresTotal = 0; 6795 for (DatanodeDescriptor node: live) { 6796 volumeFailuresTotal += node.getVolumeFailures(); 6797 } 6798 return volumeFailuresTotal; 6799 } 6800 6801 @Override // FSNamesystemMBean 6802 public long getEstimatedCapacityLostTotal() { 6803 List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); 6804 getBlockManager().getDatanodeManager().fetchDatanodes(live, null, true); 6805 long estimatedCapacityLostTotal = 0; 6806 for (DatanodeDescriptor node: live) { 6807 VolumeFailureSummary volumeFailureSummary = node.getVolumeFailureSummary(); 6808 if (volumeFailureSummary != null) { 6809 estimatedCapacityLostTotal += 6810 volumeFailureSummary.getEstimatedCapacityLostTotal(); 6811 } 6812 } 6813 return estimatedCapacityLostTotal; 6814 } 6815 6816 @Override // FSNamesystemMBean 6817 public int getNumDecommissioningDataNodes() { 6818 return getBlockManager().getDatanodeManager().getDecommissioningNodes() 6819 .size(); 6820 } 6821 6822 @Override // FSNamesystemMBean 6823 @Metric({"StaleDataNodes", 6824 "Number of datanodes marked stale due to delayed heartbeat"}) 6825 public int getNumStaleDataNodes() { 6826 return getBlockManager().getDatanodeManager().getNumStaleNodes(); 6827 } 6828 6829 /** 6830 * Storages are marked as "content stale" after NN restart or fails over and 6831 * before NN receives the first Heartbeat followed by the first Blockreport. 6832 */ 6833 @Override // FSNamesystemMBean 6834 public int getNumStaleStorages() { 6835 return getBlockManager().getDatanodeManager().getNumStaleStorages(); 6836 } 6837 6838 @Override // FSNamesystemMBean 6839 public String getTopUserOpCounts() { 6840 if (!topConf.isEnabled) { 6841 return null; 6842 } 6843 6844 Date now = new Date(); 6845 final List<RollingWindowManager.TopWindow> topWindows = 6846 topMetrics.getTopWindows(); 6847 Map<String, Object> topMap = new TreeMap<String, Object>(); 6848 topMap.put("windows", topWindows); 6849 topMap.put("timestamp", DFSUtil.dateToIso8601String(now)); 6850 ObjectMapper mapper = new ObjectMapper(); 6851 try { 6852 return mapper.writeValueAsString(topMap); 6853 } catch (IOException e) { 6854 LOG.warn("Failed to fetch TopUser metrics", e); 6855 } 6856 return null; 6857 } 6858 6859 /** 6860 * Sets the current generation stamp for legacy blocks 6861 */ 6862 void setGenerationStampV1(long stamp) { 6863 generationStampV1.setCurrentValue(stamp); 6864 } 6865 6866 /** 6867 * Gets the current generation stamp for legacy blocks 6868 */ 6869 long getGenerationStampV1() { 6870 return generationStampV1.getCurrentValue(); 6871 } 6872 6873 /** 6874 * Gets the current generation stamp for this filesystem 6875 */ 6876 void setGenerationStampV2(long stamp) { 6877 generationStampV2.setCurrentValue(stamp); 6878 } 6879 6880 /** 6881 * Gets the current generation stamp for this filesystem 6882 */ 6883 long getGenerationStampV2() { 6884 return generationStampV2.getCurrentValue(); 6885 } 6886 6887 /** 6888 * Upgrades the generation stamp for the filesystem 6889 * by reserving a sufficient range for all existing blocks. 6890 * Should be invoked only during the first upgrade to 6891 * sequential block IDs. 6892 */ 6893 long upgradeGenerationStampToV2() { 6894 Preconditions.checkState(generationStampV2.getCurrentValue() == 6895 GenerationStamp.LAST_RESERVED_STAMP); 6896 6897 generationStampV2.skipTo( 6898 generationStampV1.getCurrentValue() + 6899 HdfsConstants.RESERVED_GENERATION_STAMPS_V1); 6900 6901 generationStampV1Limit = generationStampV2.getCurrentValue(); 6902 return generationStampV2.getCurrentValue(); 6903 } 6904 6905 /** 6906 * Sets the generation stamp that delineates random and sequentially 6907 * allocated block IDs. 6908 * @param stamp set generation stamp limit to this value 6909 */ 6910 void setGenerationStampV1Limit(long stamp) { 6911 Preconditions.checkState(generationStampV1Limit == 6912 GenerationStamp.GRANDFATHER_GENERATION_STAMP); 6913 generationStampV1Limit = stamp; 6914 } 6915 6916 /** 6917 * Gets the value of the generation stamp that delineates sequential 6918 * and random block IDs. 6919 */ 6920 long getGenerationStampAtblockIdSwitch() { 6921 return generationStampV1Limit; 6922 } 6923 6924 @VisibleForTesting 6925 SequentialBlockIdGenerator getBlockIdGenerator() { 6926 return blockIdGenerator; 6927 } 6928 6929 /** 6930 * Sets the maximum allocated block ID for this filesystem. This is 6931 * the basis for allocating new block IDs. 6932 */ 6933 void setLastAllocatedBlockId(long blockId) { 6934 blockIdGenerator.skipTo(blockId); 6935 } 6936 6937 /** 6938 * Gets the maximum sequentially allocated block ID for this filesystem 6939 */ 6940 long getLastAllocatedBlockId() { 6941 return blockIdGenerator.getCurrentValue(); 6942 } 6943 6944 /** 6945 * Increments, logs and then returns the stamp 6946 */ 6947 long nextGenerationStamp(boolean legacyBlock) 6948 throws IOException, SafeModeException { 6949 assert hasWriteLock(); 6950 checkNameNodeSafeMode("Cannot get next generation stamp"); 6951 6952 long gs; 6953 if (legacyBlock) { 6954 gs = getNextGenerationStampV1(); 6955 getEditLog().logGenerationStampV1(gs); 6956 } else { 6957 gs = getNextGenerationStampV2(); 6958 getEditLog().logGenerationStampV2(gs); 6959 } 6960 6961 // NB: callers sync the log 6962 return gs; 6963 } 6964 6965 @VisibleForTesting 6966 long getNextGenerationStampV1() throws IOException { 6967 long genStampV1 = generationStampV1.nextValue(); 6968 6969 if (genStampV1 >= generationStampV1Limit) { 6970 // We ran out of generation stamps for legacy blocks. In practice, it 6971 // is extremely unlikely as we reserved 1T v1 generation stamps. The 6972 // result is that we can no longer append to the legacy blocks that 6973 // were created before the upgrade to sequential block IDs. 6974 throw new OutOfV1GenerationStampsException(); 6975 } 6976 6977 return genStampV1; 6978 } 6979 6980 @VisibleForTesting 6981 long getNextGenerationStampV2() { 6982 return generationStampV2.nextValue(); 6983 } 6984 6985 long getGenerationStampV1Limit() { 6986 return generationStampV1Limit; 6987 } 6988 6989 /** 6990 * Determine whether the block ID was randomly generated (legacy) or 6991 * sequentially generated. The generation stamp value is used to 6992 * make the distinction. 6993 * @return true if the block ID was randomly generated, false otherwise. 6994 */ 6995 boolean isLegacyBlock(Block block) { 6996 return block.getGenerationStamp() < getGenerationStampV1Limit(); 6997 } 6998 6999 /** 7000 * Increments, logs and then returns the block ID 7001 */ 7002 private long nextBlockId() throws IOException { 7003 assert hasWriteLock(); 7004 checkNameNodeSafeMode("Cannot get next block ID"); 7005 final long blockId = blockIdGenerator.nextValue(); 7006 getEditLog().logAllocateBlockId(blockId); 7007 // NB: callers sync the log 7008 return blockId; 7009 } 7010 7011 private boolean isFileDeleted(INodeFile file) { 7012 // Not in the inodeMap or in the snapshot but marked deleted. 7013 if (dir.getInode(file.getId()) == null) { 7014 return true; 7015 } 7016 7017 // look at the path hierarchy to see if one parent is deleted by recursive 7018 // deletion 7019 INode tmpChild = file; 7020 INodeDirectory tmpParent = file.getParent(); 7021 while (true) { 7022 if (tmpParent == null) { 7023 return true; 7024 } 7025 7026 INode childINode = tmpParent.getChild(tmpChild.getLocalNameBytes(), 7027 Snapshot.CURRENT_STATE_ID); 7028 if (childINode == null || !childINode.equals(tmpChild)) { 7029 // a newly created INode with the same name as an already deleted one 7030 // would be a different INode than the deleted one 7031 return true; 7032 } 7033 7034 if (tmpParent.isRoot()) { 7035 break; 7036 } 7037 7038 tmpChild = tmpParent; 7039 tmpParent = tmpParent.getParent(); 7040 } 7041 7042 if (file.isWithSnapshot() && 7043 file.getFileWithSnapshotFeature().isCurrentFileDeleted()) { 7044 return true; 7045 } 7046 return false; 7047 } 7048 7049 private INodeFile checkUCBlock(ExtendedBlock block, 7050 String clientName) throws IOException { 7051 assert hasWriteLock(); 7052 checkNameNodeSafeMode("Cannot get a new generation stamp and an " 7053 + "access token for block " + block); 7054 7055 // check stored block state 7056 BlockInfo storedBlock = getStoredBlock(ExtendedBlock.getLocalBlock(block)); 7057 if (storedBlock == null || 7058 storedBlock.getBlockUCState() != BlockUCState.UNDER_CONSTRUCTION) { 7059 throw new IOException(block + 7060 " does not exist or is not under Construction" + storedBlock); 7061 } 7062 7063 // check file inode 7064 final INodeFile file = ((INode)storedBlock.getBlockCollection()).asFile(); 7065 if (file == null || !file.isUnderConstruction() || isFileDeleted(file)) { 7066 throw new IOException("The file " + storedBlock + 7067 " belonged to does not exist or it is not under construction."); 7068 } 7069 7070 // check lease 7071 if (clientName == null 7072 || !clientName.equals(file.getFileUnderConstructionFeature() 7073 .getClientName())) { 7074 throw new LeaseExpiredException("Lease mismatch: " + block + 7075 " is accessed by a non lease holder " + clientName); 7076 } 7077 7078 return file; 7079 } 7080 7081 /** 7082 * Client is reporting some bad block locations. 7083 */ 7084 void reportBadBlocks(LocatedBlock[] blocks) throws IOException { 7085 checkOperation(OperationCategory.WRITE); 7086 NameNode.stateChangeLog.info("*DIR* reportBadBlocks"); 7087 writeLock(); 7088 try { 7089 checkOperation(OperationCategory.WRITE); 7090 for (int i = 0; i < blocks.length; i++) { 7091 ExtendedBlock blk = blocks[i].getBlock(); 7092 DatanodeInfo[] nodes = blocks[i].getLocations(); 7093 String[] storageIDs = blocks[i].getStorageIDs(); 7094 for (int j = 0; j < nodes.length; j++) { 7095 blockManager.findAndMarkBlockAsCorrupt(blk, nodes[j], 7096 storageIDs == null ? null: storageIDs[j], 7097 "client machine reported it"); 7098 } 7099 } 7100 } finally { 7101 writeUnlock(); 7102 } 7103 } 7104 7105 /** 7106 * Get a new generation stamp together with an access token for 7107 * a block under construction 7108 * 7109 * This method is called for recovering a failed pipeline or setting up 7110 * a pipeline to append to a block. 7111 * 7112 * @param block a block 7113 * @param clientName the name of a client 7114 * @return a located block with a new generation stamp and an access token 7115 * @throws IOException if any error occurs 7116 */ 7117 LocatedBlock updateBlockForPipeline(ExtendedBlock block, 7118 String clientName) throws IOException { 7119 LocatedBlock locatedBlock; 7120 checkOperation(OperationCategory.WRITE); 7121 writeLock(); 7122 try { 7123 checkOperation(OperationCategory.WRITE); 7124 7125 // check vadility of parameters 7126 checkUCBlock(block, clientName); 7127 7128 // get a new generation stamp and an access token 7129 block.setGenerationStamp( 7130 nextGenerationStamp(isLegacyBlock(block.getLocalBlock()))); 7131 locatedBlock = new LocatedBlock(block, new DatanodeInfo[0]); 7132 blockManager.setBlockToken(locatedBlock, AccessMode.WRITE); 7133 } finally { 7134 writeUnlock(); 7135 } 7136 // Ensure we record the new generation stamp 7137 getEditLog().logSync(); 7138 return locatedBlock; 7139 } 7140 7141 /** 7142 * Update a pipeline for a block under construction 7143 * 7144 * @param clientName the name of the client 7145 * @param oldBlock and old block 7146 * @param newBlock a new block with a new generation stamp and length 7147 * @param newNodes datanodes in the pipeline 7148 * @throws IOException if any error occurs 7149 */ 7150 void updatePipeline(String clientName, ExtendedBlock oldBlock, 7151 ExtendedBlock newBlock, DatanodeID[] newNodes, String[] newStorageIDs) 7152 throws IOException { 7153 checkOperation(OperationCategory.WRITE); 7154 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 7155 if (cacheEntry != null && cacheEntry.isSuccess()) { 7156 return; // Return previous response 7157 } 7158 LOG.info("updatePipeline(block=" + oldBlock 7159 + ", newGenerationStamp=" + newBlock.getGenerationStamp() 7160 + ", newLength=" + newBlock.getNumBytes() 7161 + ", newNodes=" + Arrays.asList(newNodes) 7162 + ", clientName=" + clientName 7163 + ")"); 7164 waitForLoadingFSImage(); 7165 writeLock(); 7166 boolean success = false; 7167 try { 7168 checkOperation(OperationCategory.WRITE); 7169 checkNameNodeSafeMode("Pipeline not updated"); 7170 assert newBlock.getBlockId()==oldBlock.getBlockId() : newBlock + " and " 7171 + oldBlock + " has different block identifier"; 7172 updatePipelineInternal(clientName, oldBlock, newBlock, newNodes, 7173 newStorageIDs, cacheEntry != null); 7174 success = true; 7175 } finally { 7176 writeUnlock(); 7177 RetryCache.setState(cacheEntry, success); 7178 } 7179 getEditLog().logSync(); 7180 LOG.info("updatePipeline(" + oldBlock + ") successfully to " + newBlock); 7181 } 7182 7183 /** 7184 * @see #updatePipeline(String, ExtendedBlock, ExtendedBlock, DatanodeID[], String[]) 7185 */ 7186 private void updatePipelineInternal(String clientName, ExtendedBlock oldBlock, 7187 ExtendedBlock newBlock, DatanodeID[] newNodes, String[] newStorageIDs, 7188 boolean logRetryCache) 7189 throws IOException { 7190 assert hasWriteLock(); 7191 // check the vadility of the block and lease holder name 7192 final INodeFile pendingFile = checkUCBlock(oldBlock, clientName); 7193 final BlockInfoUnderConstruction blockinfo 7194 = (BlockInfoUnderConstruction)pendingFile.getLastBlock(); 7195 7196 // check new GS & length: this is not expected 7197 if (newBlock.getGenerationStamp() <= blockinfo.getGenerationStamp() || 7198 newBlock.getNumBytes() < blockinfo.getNumBytes()) { 7199 String msg = "Update " + oldBlock + " (len = " + 7200 blockinfo.getNumBytes() + ") to an older state: " + newBlock + 7201 " (len = " + newBlock.getNumBytes() +")"; 7202 LOG.warn(msg); 7203 throw new IOException(msg); 7204 } 7205 7206 // Update old block with the new generation stamp and new length 7207 blockinfo.setNumBytes(newBlock.getNumBytes()); 7208 blockinfo.setGenerationStampAndVerifyReplicas(newBlock.getGenerationStamp()); 7209 7210 // find the DatanodeDescriptor objects 7211 final DatanodeStorageInfo[] storages = blockManager.getDatanodeManager() 7212 .getDatanodeStorageInfos(newNodes, newStorageIDs); 7213 blockinfo.setExpectedLocations(storages); 7214 7215 String src = pendingFile.getFullPathName(); 7216 persistBlocks(src, pendingFile, logRetryCache); 7217 } 7218 7219 // rename was successful. If any part of the renamed subtree had 7220 // files that were being written to, update with new filename. 7221 void unprotectedChangeLease(String src, String dst) { 7222 assert hasWriteLock(); 7223 leaseManager.changeLease(src, dst); 7224 } 7225 7226 /** 7227 * Serializes leases. 7228 */ 7229 void saveFilesUnderConstruction(DataOutputStream out, 7230 Map<Long, INodeFile> snapshotUCMap) throws IOException { 7231 // This is run by an inferior thread of saveNamespace, which holds a read 7232 // lock on our behalf. If we took the read lock here, we could block 7233 // for fairness if a writer is waiting on the lock. 7234 synchronized (leaseManager) { 7235 Map<String, INodeFile> nodes = leaseManager.getINodesUnderConstruction(); 7236 for (Map.Entry<String, INodeFile> entry : nodes.entrySet()) { 7237 // TODO: for HDFS-5428, because of rename operations, some 7238 // under-construction files that are 7239 // in the current fs directory can also be captured in the 7240 // snapshotUCMap. We should remove them from the snapshotUCMap. 7241 snapshotUCMap.remove(entry.getValue().getId()); 7242 } 7243 7244 out.writeInt(nodes.size() + snapshotUCMap.size()); // write the size 7245 for (Map.Entry<String, INodeFile> entry : nodes.entrySet()) { 7246 FSImageSerialization.writeINodeUnderConstruction( 7247 out, entry.getValue(), entry.getKey()); 7248 } 7249 for (Map.Entry<Long, INodeFile> entry : snapshotUCMap.entrySet()) { 7250 // for those snapshot INodeFileUC, we use "/.reserved/.inodes/<inodeid>" 7251 // as their paths 7252 StringBuilder b = new StringBuilder(); 7253 b.append(FSDirectory.DOT_RESERVED_PATH_PREFIX) 7254 .append(Path.SEPARATOR).append(FSDirectory.DOT_INODES_STRING) 7255 .append(Path.SEPARATOR).append(entry.getValue().getId()); 7256 FSImageSerialization.writeINodeUnderConstruction( 7257 out, entry.getValue(), b.toString()); 7258 } 7259 } 7260 } 7261 7262 /** 7263 * @return all the under-construction files in the lease map 7264 */ 7265 Map<String, INodeFile> getFilesUnderConstruction() { 7266 synchronized (leaseManager) { 7267 return leaseManager.getINodesUnderConstruction(); 7268 } 7269 } 7270 7271 /** 7272 * Register a Backup name-node, verifying that it belongs 7273 * to the correct namespace, and adding it to the set of 7274 * active journals if necessary. 7275 * 7276 * @param bnReg registration of the new BackupNode 7277 * @param nnReg registration of this NameNode 7278 * @throws IOException if the namespace IDs do not match 7279 */ 7280 void registerBackupNode(NamenodeRegistration bnReg, 7281 NamenodeRegistration nnReg) throws IOException { 7282 writeLock(); 7283 try { 7284 if(getFSImage().getStorage().getNamespaceID() 7285 != bnReg.getNamespaceID()) 7286 throw new IOException("Incompatible namespaceIDs: " 7287 + " Namenode namespaceID = " 7288 + getFSImage().getStorage().getNamespaceID() + "; " 7289 + bnReg.getRole() + 7290 " node namespaceID = " + bnReg.getNamespaceID()); 7291 if (bnReg.getRole() == NamenodeRole.BACKUP) { 7292 getFSImage().getEditLog().registerBackupNode( 7293 bnReg, nnReg); 7294 } 7295 } finally { 7296 writeUnlock(); 7297 } 7298 } 7299 7300 /** 7301 * Release (unregister) backup node. 7302 * <p> 7303 * Find and remove the backup stream corresponding to the node. 7304 * @throws IOException 7305 */ 7306 void releaseBackupNode(NamenodeRegistration registration) 7307 throws IOException { 7308 checkOperation(OperationCategory.WRITE); 7309 writeLock(); 7310 try { 7311 checkOperation(OperationCategory.WRITE); 7312 if(getFSImage().getStorage().getNamespaceID() 7313 != registration.getNamespaceID()) 7314 throw new IOException("Incompatible namespaceIDs: " 7315 + " Namenode namespaceID = " 7316 + getFSImage().getStorage().getNamespaceID() + "; " 7317 + registration.getRole() + 7318 " node namespaceID = " + registration.getNamespaceID()); 7319 getEditLog().releaseBackupStream(registration); 7320 } finally { 7321 writeUnlock(); 7322 } 7323 } 7324 7325 static class CorruptFileBlockInfo { 7326 final String path; 7327 final Block block; 7328 7329 public CorruptFileBlockInfo(String p, Block b) { 7330 path = p; 7331 block = b; 7332 } 7333 7334 @Override 7335 public String toString() { 7336 return block.getBlockName() + "\t" + path; 7337 } 7338 } 7339 /** 7340 * @param path Restrict corrupt files to this portion of namespace. 7341 * @param cookieTab Support for continuation; cookieTab tells where 7342 * to start from 7343 * @return a list in which each entry describes a corrupt file/block 7344 * @throws IOException 7345 */ 7346 Collection<CorruptFileBlockInfo> listCorruptFileBlocks(String path, 7347 String[] cookieTab) throws IOException { 7348 checkSuperuserPrivilege(); 7349 checkOperation(OperationCategory.READ); 7350 7351 int count = 0; 7352 ArrayList<CorruptFileBlockInfo> corruptFiles = 7353 new ArrayList<CorruptFileBlockInfo>(); 7354 if (cookieTab == null) { 7355 cookieTab = new String[] { null }; 7356 } 7357 7358 // Do a quick check if there are any corrupt files without taking the lock 7359 if (blockManager.getMissingBlocksCount() == 0) { 7360 if (cookieTab[0] == null) { 7361 cookieTab[0] = String.valueOf(getIntCookie(cookieTab[0])); 7362 } 7363 LOG.info("there are no corrupt file blocks."); 7364 return corruptFiles; 7365 } 7366 7367 readLock(); 7368 try { 7369 checkOperation(OperationCategory.READ); 7370 if (!isPopulatingReplQueues()) { 7371 throw new IOException("Cannot run listCorruptFileBlocks because " + 7372 "replication queues have not been initialized."); 7373 } 7374 // print a limited # of corrupt files per call 7375 7376 final Iterator<Block> blkIterator = blockManager.getCorruptReplicaBlockIterator(); 7377 7378 int skip = getIntCookie(cookieTab[0]); 7379 for (int i = 0; i < skip && blkIterator.hasNext(); i++) { 7380 blkIterator.next(); 7381 } 7382 7383 while (blkIterator.hasNext()) { 7384 Block blk = blkIterator.next(); 7385 final INode inode = (INode)blockManager.getBlockCollection(blk); 7386 skip++; 7387 if (inode != null && blockManager.countNodes(blk).liveReplicas() == 0) { 7388 String src = FSDirectory.getFullPathName(inode); 7389 if (src.startsWith(path)){ 7390 corruptFiles.add(new CorruptFileBlockInfo(src, blk)); 7391 count++; 7392 if (count >= DEFAULT_MAX_CORRUPT_FILEBLOCKS_RETURNED) 7393 break; 7394 } 7395 } 7396 } 7397 cookieTab[0] = String.valueOf(skip); 7398 LOG.info("list corrupt file blocks returned: " + count); 7399 return corruptFiles; 7400 } finally { 7401 readUnlock(); 7402 } 7403 } 7404 7405 /** 7406 * Convert string cookie to integer. 7407 */ 7408 private static int getIntCookie(String cookie){ 7409 int c; 7410 if(cookie == null){ 7411 c = 0; 7412 } else { 7413 try{ 7414 c = Integer.parseInt(cookie); 7415 }catch (NumberFormatException e) { 7416 c = 0; 7417 } 7418 } 7419 c = Math.max(0, c); 7420 return c; 7421 } 7422 7423 /** 7424 * Create delegation token secret manager 7425 */ 7426 private DelegationTokenSecretManager createDelegationTokenSecretManager( 7427 Configuration conf) { 7428 return new DelegationTokenSecretManager(conf.getLong( 7429 DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_KEY, 7430 DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT), 7431 conf.getLong(DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_KEY, 7432 DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT), 7433 conf.getLong(DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY, 7434 DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT), 7435 DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL, 7436 conf.getBoolean(DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_KEY, 7437 DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_DEFAULT), 7438 this); 7439 } 7440 7441 /** 7442 * Returns the DelegationTokenSecretManager instance in the namesystem. 7443 * @return delegation token secret manager object 7444 */ 7445 DelegationTokenSecretManager getDelegationTokenSecretManager() { 7446 return dtSecretManager; 7447 } 7448 7449 /** 7450 * @param renewer Renewer information 7451 * @return delegation toek 7452 * @throws IOException on error 7453 */ 7454 Token<DelegationTokenIdentifier> getDelegationToken(Text renewer) 7455 throws IOException { 7456 Token<DelegationTokenIdentifier> token; 7457 checkOperation(OperationCategory.WRITE); 7458 writeLock(); 7459 try { 7460 checkOperation(OperationCategory.WRITE); 7461 checkNameNodeSafeMode("Cannot issue delegation token"); 7462 if (!isAllowedDelegationTokenOp()) { 7463 throw new IOException( 7464 "Delegation Token can be issued only with kerberos or web authentication"); 7465 } 7466 if (dtSecretManager == null || !dtSecretManager.isRunning()) { 7467 LOG.warn("trying to get DT with no secret manager running"); 7468 return null; 7469 } 7470 7471 UserGroupInformation ugi = getRemoteUser(); 7472 String user = ugi.getUserName(); 7473 Text owner = new Text(user); 7474 Text realUser = null; 7475 if (ugi.getRealUser() != null) { 7476 realUser = new Text(ugi.getRealUser().getUserName()); 7477 } 7478 DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(owner, 7479 renewer, realUser); 7480 token = new Token<DelegationTokenIdentifier>( 7481 dtId, dtSecretManager); 7482 long expiryTime = dtSecretManager.getTokenExpiryTime(dtId); 7483 getEditLog().logGetDelegationToken(dtId, expiryTime); 7484 } finally { 7485 writeUnlock(); 7486 } 7487 getEditLog().logSync(); 7488 return token; 7489 } 7490 7491 /** 7492 * 7493 * @param token token to renew 7494 * @return new expiryTime of the token 7495 * @throws InvalidToken if {@code token} is invalid 7496 * @throws IOException on other errors 7497 */ 7498 long renewDelegationToken(Token<DelegationTokenIdentifier> token) 7499 throws InvalidToken, IOException { 7500 long expiryTime; 7501 checkOperation(OperationCategory.WRITE); 7502 writeLock(); 7503 try { 7504 checkOperation(OperationCategory.WRITE); 7505 7506 checkNameNodeSafeMode("Cannot renew delegation token"); 7507 if (!isAllowedDelegationTokenOp()) { 7508 throw new IOException( 7509 "Delegation Token can be renewed only with kerberos or web authentication"); 7510 } 7511 String renewer = getRemoteUser().getShortUserName(); 7512 expiryTime = dtSecretManager.renewToken(token, renewer); 7513 DelegationTokenIdentifier id = new DelegationTokenIdentifier(); 7514 ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier()); 7515 DataInputStream in = new DataInputStream(buf); 7516 id.readFields(in); 7517 getEditLog().logRenewDelegationToken(id, expiryTime); 7518 } finally { 7519 writeUnlock(); 7520 } 7521 getEditLog().logSync(); 7522 return expiryTime; 7523 } 7524 7525 /** 7526 * 7527 * @param token token to cancel 7528 * @throws IOException on error 7529 */ 7530 void cancelDelegationToken(Token<DelegationTokenIdentifier> token) 7531 throws IOException { 7532 checkOperation(OperationCategory.WRITE); 7533 writeLock(); 7534 try { 7535 checkOperation(OperationCategory.WRITE); 7536 7537 checkNameNodeSafeMode("Cannot cancel delegation token"); 7538 String canceller = getRemoteUser().getUserName(); 7539 DelegationTokenIdentifier id = dtSecretManager 7540 .cancelToken(token, canceller); 7541 getEditLog().logCancelDelegationToken(id); 7542 } finally { 7543 writeUnlock(); 7544 } 7545 getEditLog().logSync(); 7546 } 7547 7548 /** 7549 * @param out save state of the secret manager 7550 * @param sdPath String storage directory path 7551 */ 7552 void saveSecretManagerStateCompat(DataOutputStream out, String sdPath) 7553 throws IOException { 7554 dtSecretManager.saveSecretManagerStateCompat(out, sdPath); 7555 } 7556 7557 SecretManagerState saveSecretManagerState() { 7558 return dtSecretManager.saveSecretManagerState(); 7559 } 7560 7561 /** 7562 * @param in load the state of secret manager from input stream 7563 */ 7564 void loadSecretManagerStateCompat(DataInput in) throws IOException { 7565 dtSecretManager.loadSecretManagerStateCompat(in); 7566 } 7567 7568 void loadSecretManagerState(SecretManagerSection s, 7569 List<SecretManagerSection.DelegationKey> keys, 7570 List<SecretManagerSection.PersistToken> tokens) throws IOException { 7571 dtSecretManager.loadSecretManagerState(new SecretManagerState(s, keys, tokens)); 7572 } 7573 7574 /** 7575 * Log the updateMasterKey operation to edit logs 7576 * 7577 * @param key new delegation key. 7578 */ 7579 public void logUpdateMasterKey(DelegationKey key) { 7580 7581 assert !isInSafeMode() : 7582 "this should never be called while in safemode, since we stop " + 7583 "the DT manager before entering safemode!"; 7584 // No need to hold FSN lock since we don't access any internal 7585 // structures, and this is stopped before the FSN shuts itself 7586 // down, etc. 7587 getEditLog().logUpdateMasterKey(key); 7588 getEditLog().logSync(); 7589 } 7590 7591 /** 7592 * Log the cancellation of expired tokens to edit logs 7593 * 7594 * @param id token identifier to cancel 7595 */ 7596 public void logExpireDelegationToken(DelegationTokenIdentifier id) { 7597 assert !isInSafeMode() : 7598 "this should never be called while in safemode, since we stop " + 7599 "the DT manager before entering safemode!"; 7600 // No need to hold FSN lock since we don't access any internal 7601 // structures, and this is stopped before the FSN shuts itself 7602 // down, etc. 7603 getEditLog().logCancelDelegationToken(id); 7604 } 7605 7606 private void logReassignLease(String leaseHolder, String src, 7607 String newHolder) { 7608 assert hasWriteLock(); 7609 getEditLog().logReassignLease(leaseHolder, src, newHolder); 7610 } 7611 7612 /** 7613 * 7614 * @return true if delegation token operation is allowed 7615 */ 7616 private boolean isAllowedDelegationTokenOp() throws IOException { 7617 AuthenticationMethod authMethod = getConnectionAuthenticationMethod(); 7618 if (UserGroupInformation.isSecurityEnabled() 7619 && (authMethod != AuthenticationMethod.KERBEROS) 7620 && (authMethod != AuthenticationMethod.KERBEROS_SSL) 7621 && (authMethod != AuthenticationMethod.CERTIFICATE)) { 7622 return false; 7623 } 7624 return true; 7625 } 7626 7627 /** 7628 * Returns authentication method used to establish the connection 7629 * @return AuthenticationMethod used to establish connection 7630 * @throws IOException 7631 */ 7632 private AuthenticationMethod getConnectionAuthenticationMethod() 7633 throws IOException { 7634 UserGroupInformation ugi = getRemoteUser(); 7635 AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); 7636 if (authMethod == AuthenticationMethod.PROXY) { 7637 authMethod = ugi.getRealUser().getAuthenticationMethod(); 7638 } 7639 return authMethod; 7640 } 7641 7642 /** 7643 * Client invoked methods are invoked over RPC and will be in 7644 * RPC call context even if the client exits. 7645 */ 7646 private boolean isExternalInvocation() { 7647 return Server.isRpcInvocation() || NamenodeWebHdfsMethods.isWebHdfsInvocation(); 7648 } 7649 7650 private static InetAddress getRemoteIp() { 7651 InetAddress ip = Server.getRemoteIp(); 7652 if (ip != null) { 7653 return ip; 7654 } 7655 return NamenodeWebHdfsMethods.getRemoteIp(); 7656 } 7657 7658 // optimize ugi lookup for RPC operations to avoid a trip through 7659 // UGI.getCurrentUser which is synch'ed 7660 private static UserGroupInformation getRemoteUser() throws IOException { 7661 return NameNode.getRemoteUser(); 7662 } 7663 7664 /** 7665 * Log fsck event in the audit log 7666 */ 7667 void logFsckEvent(String src, InetAddress remoteAddress) throws IOException { 7668 if (isAuditEnabled()) { 7669 logAuditEvent(true, getRemoteUser(), 7670 remoteAddress, 7671 "fsck", src, null, null); 7672 } 7673 } 7674 /** 7675 * Register NameNodeMXBean 7676 */ 7677 private void registerMXBean() { 7678 mxbeanName = MBeans.register("NameNode", "NameNodeInfo", this); 7679 } 7680 7681 /** 7682 * Class representing Namenode information for JMX interfaces 7683 */ 7684 @Override // NameNodeMXBean 7685 public String getVersion() { 7686 return VersionInfo.getVersion() + ", r" + VersionInfo.getRevision(); 7687 } 7688 7689 @Override // NameNodeMXBean 7690 public long getUsed() { 7691 return this.getCapacityUsed(); 7692 } 7693 7694 @Override // NameNodeMXBean 7695 public long getFree() { 7696 return this.getCapacityRemaining(); 7697 } 7698 7699 @Override // NameNodeMXBean 7700 public long getTotal() { 7701 return this.getCapacityTotal(); 7702 } 7703 7704 @Override // NameNodeMXBean 7705 public String getSafemode() { 7706 if (!this.isInSafeMode()) 7707 return ""; 7708 return "Safe mode is ON. " + this.getSafeModeTip(); 7709 } 7710 7711 @Override // NameNodeMXBean 7712 public boolean isUpgradeFinalized() { 7713 return this.getFSImage().isUpgradeFinalized(); 7714 } 7715 7716 @Override // NameNodeMXBean 7717 public long getNonDfsUsedSpace() { 7718 return datanodeStatistics.getCapacityUsedNonDFS(); 7719 } 7720 7721 @Override // NameNodeMXBean 7722 public float getPercentUsed() { 7723 return datanodeStatistics.getCapacityUsedPercent(); 7724 } 7725 7726 @Override // NameNodeMXBean 7727 public long getBlockPoolUsedSpace() { 7728 return datanodeStatistics.getBlockPoolUsed(); 7729 } 7730 7731 @Override // NameNodeMXBean 7732 public float getPercentBlockPoolUsed() { 7733 return datanodeStatistics.getPercentBlockPoolUsed(); 7734 } 7735 7736 @Override // NameNodeMXBean 7737 public float getPercentRemaining() { 7738 return datanodeStatistics.getCapacityRemainingPercent(); 7739 } 7740 7741 @Override // NameNodeMXBean 7742 public long getCacheCapacity() { 7743 return datanodeStatistics.getCacheCapacity(); 7744 } 7745 7746 @Override // NameNodeMXBean 7747 public long getCacheUsed() { 7748 return datanodeStatistics.getCacheUsed(); 7749 } 7750 7751 @Override // NameNodeMXBean 7752 public long getTotalBlocks() { 7753 return getBlocksTotal(); 7754 } 7755 7756 @Override // NameNodeMXBean 7757 @Metric 7758 public long getTotalFiles() { 7759 return getFilesTotal(); 7760 } 7761 7762 @Override // NameNodeMXBean 7763 public long getNumberOfMissingBlocks() { 7764 return getMissingBlocksCount(); 7765 } 7766 7767 @Override // NameNodeMXBean 7768 public long getNumberOfMissingBlocksWithReplicationFactorOne() { 7769 return getMissingReplOneBlocksCount(); 7770 } 7771 7772 @Override // NameNodeMXBean 7773 public int getThreads() { 7774 return ManagementFactory.getThreadMXBean().getThreadCount(); 7775 } 7776 7777 /** 7778 * Returned information is a JSON representation of map with host name as the 7779 * key and value is a map of live node attribute keys to its values 7780 */ 7781 @Override // NameNodeMXBean 7782 public String getLiveNodes() { 7783 final Map<String, Map<String,Object>> info = 7784 new HashMap<String, Map<String,Object>>(); 7785 final List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); 7786 blockManager.getDatanodeManager().fetchDatanodes(live, null, true); 7787 for (DatanodeDescriptor node : live) { 7788 ImmutableMap.Builder<String, Object> innerinfo = 7789 ImmutableMap.<String,Object>builder(); 7790 innerinfo 7791 .put("infoAddr", node.getInfoAddr()) 7792 .put("infoSecureAddr", node.getInfoSecureAddr()) 7793 .put("xferaddr", node.getXferAddr()) 7794 .put("lastContact", getLastContact(node)) 7795 .put("usedSpace", getDfsUsed(node)) 7796 .put("adminState", node.getAdminState().toString()) 7797 .put("nonDfsUsedSpace", node.getNonDfsUsed()) 7798 .put("capacity", node.getCapacity()) 7799 .put("numBlocks", node.numBlocks()) 7800 .put("version", node.getSoftwareVersion()) 7801 .put("used", node.getDfsUsed()) 7802 .put("remaining", node.getRemaining()) 7803 .put("blockScheduled", node.getBlocksScheduled()) 7804 .put("blockPoolUsed", node.getBlockPoolUsed()) 7805 .put("blockPoolUsedPercent", node.getBlockPoolUsedPercent()) 7806 .put("volfails", node.getVolumeFailures()); 7807 VolumeFailureSummary volumeFailureSummary = node.getVolumeFailureSummary(); 7808 if (volumeFailureSummary != null) { 7809 innerinfo 7810 .put("failedStorageLocations", 7811 volumeFailureSummary.getFailedStorageLocations()) 7812 .put("lastVolumeFailureDate", 7813 volumeFailureSummary.getLastVolumeFailureDate()) 7814 .put("estimatedCapacityLostTotal", 7815 volumeFailureSummary.getEstimatedCapacityLostTotal()); 7816 } 7817 // CLOUDERA-BUILD: revert JMX output changes in HDFS-7604 7818 info.put(node.getHostName(), innerinfo.build()); 7819 } 7820 return JSON.toString(info); 7821 } 7822 7823 /** 7824 * Returned information is a JSON representation of map with host name as the 7825 * key and value is a map of dead node attribute keys to its values 7826 */ 7827 @Override // NameNodeMXBean 7828 public String getDeadNodes() { 7829 final Map<String, Map<String, Object>> info = 7830 new HashMap<String, Map<String, Object>>(); 7831 final List<DatanodeDescriptor> dead = new ArrayList<DatanodeDescriptor>(); 7832 blockManager.getDatanodeManager().fetchDatanodes(null, dead, true); 7833 for (DatanodeDescriptor node : dead) { 7834 Map<String, Object> innerinfo = ImmutableMap.<String, Object>builder() 7835 .put("lastContact", getLastContact(node)) 7836 .put("decommissioned", node.isDecommissioned()) 7837 .put("xferaddr", node.getXferAddr()) 7838 .build(); 7839 info.put(node.getHostName(), innerinfo); 7840 } 7841 return JSON.toString(info); 7842 } 7843 7844 /** 7845 * Returned information is a JSON representation of map with host name as the 7846 * key and value is a map of decommissioning node attribute keys to its 7847 * values 7848 */ 7849 @Override // NameNodeMXBean 7850 public String getDecomNodes() { 7851 final Map<String, Map<String, Object>> info = 7852 new HashMap<String, Map<String, Object>>(); 7853 final List<DatanodeDescriptor> decomNodeList = blockManager.getDatanodeManager( 7854 ).getDecommissioningNodes(); 7855 for (DatanodeDescriptor node : decomNodeList) { 7856 Map<String, Object> innerinfo = ImmutableMap 7857 .<String, Object> builder() 7858 .put("xferaddr", node.getXferAddr()) 7859 .put("underReplicatedBlocks", 7860 node.decommissioningStatus.getUnderReplicatedBlocks()) 7861 .put("decommissionOnlyReplicas", 7862 node.decommissioningStatus.getDecommissionOnlyReplicas()) 7863 .put("underReplicateInOpenFiles", 7864 node.decommissioningStatus.getUnderReplicatedInOpenFiles()) 7865 .build(); 7866 info.put(node.getHostName(), innerinfo); 7867 } 7868 return JSON.toString(info); 7869 } 7870 7871 private long getLastContact(DatanodeDescriptor alivenode) { 7872 return (Time.now() - alivenode.getLastUpdate())/1000; 7873 } 7874 7875 private long getDfsUsed(DatanodeDescriptor alivenode) { 7876 return alivenode.getDfsUsed(); 7877 } 7878 7879 @Override // NameNodeMXBean 7880 public String getClusterId() { 7881 return getFSImage().getStorage().getClusterID(); 7882 } 7883 7884 @Override // NameNodeMXBean 7885 public String getBlockPoolId() { 7886 return blockPoolId; 7887 } 7888 7889 @Override // NameNodeMXBean 7890 public String getNameDirStatuses() { 7891 Map<String, Map<File, StorageDirType>> statusMap = 7892 new HashMap<String, Map<File, StorageDirType>>(); 7893 7894 Map<File, StorageDirType> activeDirs = new HashMap<File, StorageDirType>(); 7895 for (Iterator<StorageDirectory> it 7896 = getFSImage().getStorage().dirIterator(); it.hasNext();) { 7897 StorageDirectory st = it.next(); 7898 activeDirs.put(st.getRoot(), st.getStorageDirType()); 7899 } 7900 statusMap.put("active", activeDirs); 7901 7902 List<Storage.StorageDirectory> removedStorageDirs 7903 = getFSImage().getStorage().getRemovedStorageDirs(); 7904 Map<File, StorageDirType> failedDirs = new HashMap<File, StorageDirType>(); 7905 for (StorageDirectory st : removedStorageDirs) { 7906 failedDirs.put(st.getRoot(), st.getStorageDirType()); 7907 } 7908 statusMap.put("failed", failedDirs); 7909 7910 return JSON.toString(statusMap); 7911 } 7912 7913 @Override // NameNodeMXBean 7914 public String getNodeUsage() { 7915 float median = 0; 7916 float max = 0; 7917 float min = 0; 7918 float dev = 0; 7919 7920 final Map<String, Map<String,Object>> info = 7921 new HashMap<String, Map<String,Object>>(); 7922 final List<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); 7923 blockManager.getDatanodeManager().fetchDatanodes(live, null, true); 7924 7925 if (live.size() > 0) { 7926 float totalDfsUsed = 0; 7927 float[] usages = new float[live.size()]; 7928 int i = 0; 7929 for (DatanodeDescriptor dn : live) { 7930 usages[i++] = dn.getDfsUsedPercent(); 7931 totalDfsUsed += dn.getDfsUsedPercent(); 7932 } 7933 totalDfsUsed /= live.size(); 7934 Arrays.sort(usages); 7935 median = usages[usages.length / 2]; 7936 max = usages[usages.length - 1]; 7937 min = usages[0]; 7938 7939 for (i = 0; i < usages.length; i++) { 7940 dev += (usages[i] - totalDfsUsed) * (usages[i] - totalDfsUsed); 7941 } 7942 dev = (float) Math.sqrt(dev / usages.length); 7943 } 7944 7945 final Map<String, Object> innerInfo = new HashMap<String, Object>(); 7946 innerInfo.put("min", StringUtils.format("%.2f%%", min)); 7947 innerInfo.put("median", StringUtils.format("%.2f%%", median)); 7948 innerInfo.put("max", StringUtils.format("%.2f%%", max)); 7949 innerInfo.put("stdDev", StringUtils.format("%.2f%%", dev)); 7950 info.put("nodeUsage", innerInfo); 7951 7952 return JSON.toString(info); 7953 } 7954 7955 @Override // NameNodeMXBean 7956 public String getNameJournalStatus() { 7957 List<Map<String, String>> jasList = new ArrayList<Map<String, String>>(); 7958 FSEditLog log = getFSImage().getEditLog(); 7959 if (log != null) { 7960 boolean openForWrite = log.isOpenForWrite(); 7961 for (JournalAndStream jas : log.getJournals()) { 7962 final Map<String, String> jasMap = new HashMap<String, String>(); 7963 String manager = jas.getManager().toString(); 7964 7965 jasMap.put("required", String.valueOf(jas.isRequired())); 7966 jasMap.put("disabled", String.valueOf(jas.isDisabled())); 7967 jasMap.put("manager", manager); 7968 7969 if (jas.isDisabled()) { 7970 jasMap.put("stream", "Failed"); 7971 } else if (openForWrite) { 7972 EditLogOutputStream elos = jas.getCurrentStream(); 7973 if (elos != null) { 7974 jasMap.put("stream", elos.generateReport()); 7975 } else { 7976 jasMap.put("stream", "not currently writing"); 7977 } 7978 } else { 7979 jasMap.put("stream", "open for read"); 7980 } 7981 jasList.add(jasMap); 7982 } 7983 } 7984 return JSON.toString(jasList); 7985 } 7986 7987 @Override // NameNodeMxBean 7988 public String getJournalTransactionInfo() { 7989 Map<String, String> txnIdMap = new HashMap<String, String>(); 7990 txnIdMap.put("LastAppliedOrWrittenTxId", 7991 Long.toString(this.getFSImage().getLastAppliedOrWrittenTxId())); 7992 txnIdMap.put("MostRecentCheckpointTxId", 7993 Long.toString(this.getFSImage().getMostRecentCheckpointTxId())); 7994 return JSON.toString(txnIdMap); 7995 } 7996 7997 @Override // NameNodeMXBean 7998 public String getNNStarted() { 7999 return getStartTime().toString(); 8000 } 8001 8002 @Override // NameNodeMXBean 8003 public String getCompileInfo() { 8004 return VersionInfo.getDate() + " by " + VersionInfo.getUser() + 8005 " from " + VersionInfo.getBranch(); 8006 } 8007 8008 /** @return the block manager. */ 8009 public BlockManager getBlockManager() { 8010 return blockManager; 8011 } 8012 /** @return the FSDirectory. */ 8013 public FSDirectory getFSDirectory() { 8014 return dir; 8015 } 8016 /** Set the FSDirectory. */ 8017 @VisibleForTesting 8018 public void setFSDirectory(FSDirectory dir) { 8019 this.dir = dir; 8020 } 8021 /** @return the cache manager. */ 8022 public CacheManager getCacheManager() { 8023 return cacheManager; 8024 } 8025 8026 @Override // NameNodeMXBean 8027 public String getCorruptFiles() { 8028 List<String> list = new ArrayList<String>(); 8029 Collection<FSNamesystem.CorruptFileBlockInfo> corruptFileBlocks; 8030 try { 8031 corruptFileBlocks = listCorruptFileBlocks("/", null); 8032 int corruptFileCount = corruptFileBlocks.size(); 8033 if (corruptFileCount != 0) { 8034 for (FSNamesystem.CorruptFileBlockInfo c : corruptFileBlocks) { 8035 list.add(c.toString()); 8036 } 8037 } 8038 } catch (IOException e) { 8039 LOG.warn("Get corrupt file blocks returned error: " + e.getMessage()); 8040 } 8041 return JSON.toString(list); 8042 } 8043 8044 @Override //NameNodeMXBean 8045 public int getDistinctVersionCount() { 8046 return blockManager.getDatanodeManager().getDatanodesSoftwareVersions() 8047 .size(); 8048 } 8049 8050 @Override //NameNodeMXBean 8051 public Map<String, Integer> getDistinctVersions() { 8052 return blockManager.getDatanodeManager().getDatanodesSoftwareVersions(); 8053 } 8054 8055 @Override //NameNodeMXBean 8056 public String getSoftwareVersion() { 8057 return VersionInfo.getVersion(); 8058 } 8059 8060 /** 8061 * Verifies that the given identifier and password are valid and match. 8062 * @param identifier Token identifier. 8063 * @param password Password in the token. 8064 */ 8065 public synchronized void verifyToken(DelegationTokenIdentifier identifier, 8066 byte[] password) throws InvalidToken, RetriableException { 8067 try { 8068 getDelegationTokenSecretManager().verifyToken(identifier, password); 8069 } catch (InvalidToken it) { 8070 if (inTransitionToActive()) { 8071 throw new RetriableException(it); 8072 } 8073 throw it; 8074 } 8075 } 8076 8077 @Override 8078 public boolean isGenStampInFuture(Block block) { 8079 if (isLegacyBlock(block)) { 8080 return block.getGenerationStamp() > getGenerationStampV1(); 8081 } else { 8082 return block.getGenerationStamp() > getGenerationStampV2(); 8083 } 8084 } 8085 8086 @VisibleForTesting 8087 public EditLogTailer getEditLogTailer() { 8088 return editLogTailer; 8089 } 8090 8091 @VisibleForTesting 8092 public void setEditLogTailerForTests(EditLogTailer tailer) { 8093 this.editLogTailer = tailer; 8094 } 8095 8096 @VisibleForTesting 8097 void setFsLockForTests(ReentrantReadWriteLock lock) { 8098 this.fsLock.coarseLock = lock; 8099 } 8100 8101 @VisibleForTesting 8102 public ReentrantReadWriteLock getFsLockForTests() { 8103 return fsLock.coarseLock; 8104 } 8105 8106 @VisibleForTesting 8107 public ReentrantLock getCpLockForTests() { 8108 return cpLock; 8109 } 8110 8111 @VisibleForTesting 8112 public SafeModeInfo getSafeModeInfoForTests() { 8113 return safeMode; 8114 } 8115 8116 @VisibleForTesting 8117 public void setNNResourceChecker(NameNodeResourceChecker nnResourceChecker) { 8118 this.nnResourceChecker = nnResourceChecker; 8119 } 8120 8121 @Override 8122 public boolean isAvoidingStaleDataNodesForWrite() { 8123 return this.blockManager.getDatanodeManager() 8124 .shouldAvoidStaleDataNodesForWrite(); 8125 } 8126 8127 @Override // FSClusterStats 8128 public int getNumDatanodesInService() { 8129 return datanodeStatistics.getNumDatanodesInService(); 8130 } 8131 8132 @Override // for block placement strategy 8133 public double getInServiceXceiverAverage() { 8134 double avgLoad = 0; 8135 final int nodes = getNumDatanodesInService(); 8136 if (nodes != 0) { 8137 final int xceivers = datanodeStatistics.getInServiceXceiverCount(); 8138 avgLoad = (double)xceivers/nodes; 8139 } 8140 return avgLoad; 8141 } 8142 8143 public SnapshotManager getSnapshotManager() { 8144 return snapshotManager; 8145 } 8146 8147 /** Allow snapshot on a directory. */ 8148 void allowSnapshot(String path) throws SafeModeException, IOException { 8149 checkOperation(OperationCategory.WRITE); 8150 writeLock(); 8151 try { 8152 checkOperation(OperationCategory.WRITE); 8153 checkNameNodeSafeMode("Cannot allow snapshot for " + path); 8154 checkSuperuserPrivilege(); 8155 8156 dir.writeLock(); 8157 try { 8158 snapshotManager.setSnapshottable(path, true); 8159 } finally { 8160 dir.writeUnlock(); 8161 } 8162 getEditLog().logAllowSnapshot(path); 8163 } finally { 8164 writeUnlock(); 8165 } 8166 getEditLog().logSync(); 8167 8168 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8169 logAuditEvent(true, "allowSnapshot", path, null, null); 8170 } 8171 } 8172 8173 /** Disallow snapshot on a directory. */ 8174 void disallowSnapshot(String path) throws SafeModeException, IOException { 8175 checkOperation(OperationCategory.WRITE); 8176 writeLock(); 8177 try { 8178 checkOperation(OperationCategory.WRITE); 8179 checkNameNodeSafeMode("Cannot disallow snapshot for " + path); 8180 checkSuperuserPrivilege(); 8181 8182 dir.writeLock(); 8183 try { 8184 snapshotManager.resetSnapshottable(path); 8185 } finally { 8186 dir.writeUnlock(); 8187 } 8188 getEditLog().logDisallowSnapshot(path); 8189 } finally { 8190 writeUnlock(); 8191 } 8192 getEditLog().logSync(); 8193 8194 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8195 logAuditEvent(true, "disallowSnapshot", path, null, null); 8196 } 8197 } 8198 8199 /** 8200 * Create a snapshot 8201 * @param snapshotRoot The directory path where the snapshot is taken 8202 * @param snapshotName The name of the snapshot 8203 */ 8204 String createSnapshot(String snapshotRoot, String snapshotName) 8205 throws SafeModeException, IOException { 8206 checkOperation(OperationCategory.WRITE); 8207 final FSPermissionChecker pc = getPermissionChecker(); 8208 CacheEntryWithPayload cacheEntry = RetryCache.waitForCompletion(retryCache, 8209 null); 8210 if (cacheEntry != null && cacheEntry.isSuccess()) { 8211 return (String) cacheEntry.getPayload(); 8212 } 8213 String snapshotPath = null; 8214 writeLock(); 8215 try { 8216 checkOperation(OperationCategory.WRITE); 8217 checkNameNodeSafeMode("Cannot create snapshot for " + snapshotRoot); 8218 if (isPermissionEnabled) { 8219 checkOwner(pc, snapshotRoot); 8220 } 8221 8222 if (snapshotName == null || snapshotName.isEmpty()) { 8223 snapshotName = Snapshot.generateDefaultSnapshotName(); 8224 } 8225 if(snapshotName != null){ 8226 if (!DFSUtil.isValidNameForComponent(snapshotName)) { 8227 throw new InvalidPathException("Invalid snapshot name: " 8228 + snapshotName); 8229 } 8230 } 8231 dir.verifySnapshotName(snapshotName, snapshotRoot); 8232 dir.writeLock(); 8233 try { 8234 snapshotPath = snapshotManager.createSnapshot(snapshotRoot, snapshotName); 8235 } finally { 8236 dir.writeUnlock(); 8237 } 8238 getEditLog().logCreateSnapshot(snapshotRoot, snapshotName, 8239 cacheEntry != null); 8240 } finally { 8241 writeUnlock(); 8242 RetryCache.setState(cacheEntry, snapshotPath != null, snapshotPath); 8243 } 8244 getEditLog().logSync(); 8245 8246 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8247 logAuditEvent(true, "createSnapshot", snapshotRoot, snapshotPath, null); 8248 } 8249 return snapshotPath; 8250 } 8251 8252 /** 8253 * Rename a snapshot 8254 * @param path The directory path where the snapshot was taken 8255 * @param snapshotOldName Old snapshot name 8256 * @param snapshotNewName New snapshot name 8257 * @throws SafeModeException 8258 * @throws IOException 8259 */ 8260 void renameSnapshot(String path, String snapshotOldName, 8261 String snapshotNewName) throws SafeModeException, IOException { 8262 checkOperation(OperationCategory.WRITE); 8263 final FSPermissionChecker pc = getPermissionChecker(); 8264 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8265 if (cacheEntry != null && cacheEntry.isSuccess()) { 8266 return; // Return previous response 8267 } 8268 writeLock(); 8269 boolean success = false; 8270 try { 8271 checkOperation(OperationCategory.WRITE); 8272 checkNameNodeSafeMode("Cannot rename snapshot for " + path); 8273 if (isPermissionEnabled) { 8274 checkOwner(pc, path); 8275 } 8276 dir.verifySnapshotName(snapshotNewName, path); 8277 8278 snapshotManager.renameSnapshot(path, snapshotOldName, snapshotNewName); 8279 getEditLog().logRenameSnapshot(path, snapshotOldName, snapshotNewName, 8280 cacheEntry != null); 8281 success = true; 8282 } finally { 8283 writeUnlock(); 8284 RetryCache.setState(cacheEntry, success); 8285 } 8286 getEditLog().logSync(); 8287 8288 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8289 String oldSnapshotRoot = Snapshot.getSnapshotPath(path, snapshotOldName); 8290 String newSnapshotRoot = Snapshot.getSnapshotPath(path, snapshotNewName); 8291 logAuditEvent(true, "renameSnapshot", oldSnapshotRoot, newSnapshotRoot, null); 8292 } 8293 } 8294 8295 /** 8296 * Get the list of snapshottable directories that are owned 8297 * by the current user. Return all the snapshottable directories if the 8298 * current user is a super user. 8299 * @return The list of all the current snapshottable directories 8300 * @throws IOException 8301 */ 8302 public SnapshottableDirectoryStatus[] getSnapshottableDirListing() 8303 throws IOException { 8304 SnapshottableDirectoryStatus[] status = null; 8305 checkOperation(OperationCategory.READ); 8306 final FSPermissionChecker checker = getPermissionChecker(); 8307 readLock(); 8308 try { 8309 checkOperation(OperationCategory.READ); 8310 final String user = checker.isSuperUser()? null : checker.getUser(); 8311 status = snapshotManager.getSnapshottableDirListing(user); 8312 } finally { 8313 readUnlock(); 8314 } 8315 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8316 logAuditEvent(true, "listSnapshottableDirectory", null, null, null); 8317 } 8318 return status; 8319 } 8320 8321 /** 8322 * Get the difference between two snapshots (or between a snapshot and the 8323 * current status) of a snapshottable directory. 8324 * 8325 * @param path The full path of the snapshottable directory. 8326 * @param fromSnapshot Name of the snapshot to calculate the diff from. Null 8327 * or empty string indicates the current tree. 8328 * @param toSnapshot Name of the snapshot to calculated the diff to. Null or 8329 * empty string indicates the current tree. 8330 * @return A report about the difference between {@code fromSnapshot} and 8331 * {@code toSnapshot}. Modified/deleted/created/renamed files and 8332 * directories belonging to the snapshottable directories are listed 8333 * and labeled as M/-/+/R respectively. 8334 * @throws IOException 8335 */ 8336 SnapshotDiffReport getSnapshotDiffReport(String path, 8337 String fromSnapshot, String toSnapshot) throws IOException { 8338 SnapshotDiffReport diffs; 8339 checkOperation(OperationCategory.READ); 8340 final FSPermissionChecker pc = getPermissionChecker(); 8341 readLock(); 8342 try { 8343 checkOperation(OperationCategory.READ); 8344 if (isPermissionEnabled) { 8345 checkSubtreeReadPermission(pc, path, fromSnapshot); 8346 checkSubtreeReadPermission(pc, path, toSnapshot); 8347 } 8348 diffs = snapshotManager.diff(path, fromSnapshot, toSnapshot); 8349 } finally { 8350 readUnlock(); 8351 } 8352 8353 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8354 logAuditEvent(true, "computeSnapshotDiff", null, null, null); 8355 } 8356 return diffs; 8357 } 8358 8359 private void checkSubtreeReadPermission(final FSPermissionChecker pc, 8360 final String snapshottablePath, final String snapshot) 8361 throws AccessControlException, UnresolvedLinkException { 8362 final String fromPath = snapshot == null? 8363 snapshottablePath: Snapshot.getSnapshotPath(snapshottablePath, snapshot); 8364 checkPermission(pc, fromPath, false, null, null, FsAction.READ, FsAction.READ); 8365 } 8366 8367 /** 8368 * Delete a snapshot of a snapshottable directory 8369 * @param snapshotRoot The snapshottable directory 8370 * @param snapshotName The name of the to-be-deleted snapshot 8371 * @throws SafeModeException 8372 * @throws IOException 8373 */ 8374 void deleteSnapshot(String snapshotRoot, String snapshotName) 8375 throws SafeModeException, IOException { 8376 checkOperation(OperationCategory.WRITE); 8377 final FSPermissionChecker pc = getPermissionChecker(); 8378 8379 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8380 if (cacheEntry != null && cacheEntry.isSuccess()) { 8381 return; // Return previous response 8382 } 8383 boolean success = false; 8384 BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo(); 8385 writeLock(); 8386 try { 8387 checkOperation(OperationCategory.WRITE); 8388 checkNameNodeSafeMode("Cannot delete snapshot for " + snapshotRoot); 8389 if (isPermissionEnabled) { 8390 checkOwner(pc, snapshotRoot); 8391 } 8392 8393 List<INode> removedINodes = new ChunkedArrayList<INode>(); 8394 dir.writeLock(); 8395 try { 8396 snapshotManager.deleteSnapshot(snapshotRoot, snapshotName, 8397 collectedBlocks, removedINodes); 8398 dir.removeFromInodeMap(removedINodes); 8399 } finally { 8400 dir.writeUnlock(); 8401 } 8402 removedINodes.clear(); 8403 getEditLog().logDeleteSnapshot(snapshotRoot, snapshotName, 8404 cacheEntry != null); 8405 success = true; 8406 } finally { 8407 writeUnlock(); 8408 RetryCache.setState(cacheEntry, success); 8409 } 8410 getEditLog().logSync(); 8411 8412 removeBlocks(collectedBlocks); 8413 collectedBlocks.clear(); 8414 8415 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8416 String rootPath = Snapshot.getSnapshotPath(snapshotRoot, snapshotName); 8417 logAuditEvent(true, "deleteSnapshot", rootPath, null, null); 8418 } 8419 } 8420 8421 /** 8422 * Remove a list of INodeDirectorySnapshottable from the SnapshotManager 8423 * @param toRemove the list of INodeDirectorySnapshottable to be removed 8424 */ 8425 void removeSnapshottableDirs(List<INodeDirectory> toRemove) { 8426 if (snapshotManager != null) { 8427 snapshotManager.removeSnapshottable(toRemove); 8428 } 8429 } 8430 8431 RollingUpgradeInfo queryRollingUpgrade() throws IOException { 8432 checkSuperuserPrivilege(); 8433 checkOperation(OperationCategory.READ); 8434 readLock(); 8435 try { 8436 if (!isRollingUpgrade()) { 8437 return null; 8438 } 8439 Preconditions.checkNotNull(rollingUpgradeInfo); 8440 boolean hasRollbackImage = this.getFSImage().hasRollbackFSImage(); 8441 rollingUpgradeInfo.setCreatedRollbackImages(hasRollbackImage); 8442 return rollingUpgradeInfo; 8443 } finally { 8444 readUnlock(); 8445 } 8446 } 8447 8448 RollingUpgradeInfo startRollingUpgrade() throws IOException { 8449 checkSuperuserPrivilege(); 8450 checkOperation(OperationCategory.WRITE); 8451 writeLock(); 8452 try { 8453 checkOperation(OperationCategory.WRITE); 8454 if (isRollingUpgrade()) { 8455 return rollingUpgradeInfo; 8456 } 8457 long startTime = now(); 8458 if (!haEnabled) { // for non-HA, we require NN to be in safemode 8459 startRollingUpgradeInternalForNonHA(startTime); 8460 } else { // for HA, NN cannot be in safemode 8461 checkNameNodeSafeMode("Failed to start rolling upgrade"); 8462 startRollingUpgradeInternal(startTime); 8463 } 8464 8465 getEditLog().logStartRollingUpgrade(rollingUpgradeInfo.getStartTime()); 8466 if (haEnabled) { 8467 // roll the edit log to make sure the standby NameNode can tail 8468 getFSImage().rollEditLog(); 8469 } 8470 } finally { 8471 writeUnlock(); 8472 } 8473 8474 getEditLog().logSync(); 8475 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8476 logAuditEvent(true, "startRollingUpgrade", null, null, null); 8477 } 8478 return rollingUpgradeInfo; 8479 } 8480 8481 /** 8482 * Update internal state to indicate that a rolling upgrade is in progress. 8483 * @param startTime rolling upgrade start time 8484 */ 8485 void startRollingUpgradeInternal(long startTime) 8486 throws IOException { 8487 checkRollingUpgrade("start rolling upgrade"); 8488 getFSImage().checkUpgrade(); 8489 setRollingUpgradeInfo(false, startTime); 8490 } 8491 8492 /** 8493 * Update internal state to indicate that a rolling upgrade is in progress for 8494 * non-HA setup. This requires the namesystem is in SafeMode and after doing a 8495 * checkpoint for rollback the namesystem will quit the safemode automatically 8496 */ 8497 private void startRollingUpgradeInternalForNonHA(long startTime) 8498 throws IOException { 8499 Preconditions.checkState(!haEnabled); 8500 if (!isInSafeMode()) { 8501 throw new IOException("Safe mode should be turned ON " 8502 + "in order to create namespace image."); 8503 } 8504 checkRollingUpgrade("start rolling upgrade"); 8505 getFSImage().checkUpgrade(); 8506 // in non-HA setup, we do an extra checkpoint to generate a rollback image 8507 getFSImage().saveNamespace(this, NameNodeFile.IMAGE_ROLLBACK, null); 8508 LOG.info("Successfully saved namespace for preparing rolling upgrade."); 8509 8510 // leave SafeMode automatically 8511 setSafeMode(SafeModeAction.SAFEMODE_LEAVE); 8512 setRollingUpgradeInfo(true, startTime); 8513 } 8514 8515 void setRollingUpgradeInfo(boolean createdRollbackImages, long startTime) { 8516 rollingUpgradeInfo = new RollingUpgradeInfo(blockPoolId, 8517 createdRollbackImages, startTime, 0L); 8518 } 8519 8520 public void setCreatedRollbackImages(boolean created) { 8521 if (rollingUpgradeInfo != null) { 8522 rollingUpgradeInfo.setCreatedRollbackImages(created); 8523 } 8524 } 8525 8526 public RollingUpgradeInfo getRollingUpgradeInfo() { 8527 return rollingUpgradeInfo; 8528 } 8529 8530 public boolean isNeedRollbackFsImage() { 8531 return needRollbackFsImage; 8532 } 8533 8534 public void setNeedRollbackFsImage(boolean needRollbackFsImage) { 8535 this.needRollbackFsImage = needRollbackFsImage; 8536 } 8537 8538 @Override // NameNodeMXBean 8539 public RollingUpgradeInfo.Bean getRollingUpgradeStatus() { 8540 if (!isRollingUpgrade()) { 8541 return null; 8542 } 8543 RollingUpgradeInfo upgradeInfo = getRollingUpgradeInfo(); 8544 if (upgradeInfo.createdRollbackImages()) { 8545 return new RollingUpgradeInfo.Bean(upgradeInfo); 8546 } 8547 readLock(); 8548 try { 8549 // check again after acquiring the read lock. 8550 upgradeInfo = getRollingUpgradeInfo(); 8551 if (upgradeInfo == null) { 8552 return null; 8553 } 8554 if (!upgradeInfo.createdRollbackImages()) { 8555 boolean hasRollbackImage = this.getFSImage().hasRollbackFSImage(); 8556 upgradeInfo.setCreatedRollbackImages(hasRollbackImage); 8557 } 8558 } catch (IOException ioe) { 8559 LOG.warn("Encountered exception setting Rollback Image", ioe); 8560 } finally { 8561 readUnlock(); 8562 } 8563 return new RollingUpgradeInfo.Bean(upgradeInfo); 8564 } 8565 8566 /** Is rolling upgrade in progress? */ 8567 public boolean isRollingUpgrade() { 8568 return rollingUpgradeInfo != null && !rollingUpgradeInfo.isFinalized(); 8569 } 8570 8571 void checkRollingUpgrade(String action) throws RollingUpgradeException { 8572 if (isRollingUpgrade()) { 8573 throw new RollingUpgradeException("Failed to " + action 8574 + " since a rolling upgrade is already in progress." 8575 + " Existing rolling upgrade info:\n" + rollingUpgradeInfo); 8576 } 8577 } 8578 8579 RollingUpgradeInfo finalizeRollingUpgrade() throws IOException { 8580 checkSuperuserPrivilege(); 8581 checkOperation(OperationCategory.WRITE); 8582 writeLock(); 8583 try { 8584 checkOperation(OperationCategory.WRITE); 8585 if (!isRollingUpgrade()) { 8586 return null; 8587 } 8588 checkNameNodeSafeMode("Failed to finalize rolling upgrade"); 8589 8590 finalizeRollingUpgradeInternal(now()); 8591 getEditLog().logFinalizeRollingUpgrade(rollingUpgradeInfo.getFinalizeTime()); 8592 if (haEnabled) { 8593 // roll the edit log to make sure the standby NameNode can tail 8594 getFSImage().rollEditLog(); 8595 } 8596 getFSImage().updateStorageVersion(); 8597 getFSImage().renameCheckpoint(NameNodeFile.IMAGE_ROLLBACK, 8598 NameNodeFile.IMAGE); 8599 } finally { 8600 writeUnlock(); 8601 } 8602 8603 if (!haEnabled) { 8604 // Sync not needed for ha since the edit was rolled after logging. 8605 getEditLog().logSync(); 8606 } 8607 8608 if (auditLog.isInfoEnabled() && isExternalInvocation()) { 8609 logAuditEvent(true, "finalizeRollingUpgrade", null, null, null); 8610 } 8611 return rollingUpgradeInfo; 8612 } 8613 8614 void finalizeRollingUpgradeInternal(long finalizeTime) { 8615 // Set the finalize time 8616 rollingUpgradeInfo.finalize(finalizeTime); 8617 } 8618 8619 long addCacheDirective(CacheDirectiveInfo directive, EnumSet<CacheFlag> flags) 8620 throws IOException { 8621 checkOperation(OperationCategory.WRITE); 8622 final FSPermissionChecker pc = isPermissionEnabled ? 8623 getPermissionChecker() : null; 8624 CacheEntryWithPayload cacheEntry = 8625 RetryCache.waitForCompletion(retryCache, null); 8626 if (cacheEntry != null && cacheEntry.isSuccess()) { 8627 return (Long) cacheEntry.getPayload(); 8628 } 8629 boolean success = false; 8630 if (!flags.contains(CacheFlag.FORCE)) { 8631 cacheManager.waitForRescanIfNeeded(); 8632 } 8633 writeLock(); 8634 String effectiveDirectiveStr = null; 8635 Long result = null; 8636 try { 8637 checkOperation(OperationCategory.WRITE); 8638 if (isInSafeMode()) { 8639 throw new SafeModeException( 8640 "Cannot add cache directive", safeMode); 8641 } 8642 if (directive.getId() != null) { 8643 throw new IOException("addDirective: you cannot specify an ID " + 8644 "for this operation."); 8645 } 8646 CacheDirectiveInfo effectiveDirective = 8647 cacheManager.addDirective(directive, pc, flags); 8648 getEditLog().logAddCacheDirectiveInfo(effectiveDirective, 8649 cacheEntry != null); 8650 result = effectiveDirective.getId(); 8651 effectiveDirectiveStr = effectiveDirective.toString(); 8652 success = true; 8653 } finally { 8654 writeUnlock(); 8655 if (success) { 8656 getEditLog().logSync(); 8657 } 8658 if (isAuditEnabled() && isExternalInvocation()) { 8659 logAuditEvent(success, "addCacheDirective", effectiveDirectiveStr, null, null); 8660 } 8661 RetryCache.setState(cacheEntry, success, result); 8662 } 8663 return result; 8664 } 8665 8666 void modifyCacheDirective(CacheDirectiveInfo directive, 8667 EnumSet<CacheFlag> flags) throws IOException { 8668 checkOperation(OperationCategory.WRITE); 8669 final FSPermissionChecker pc = isPermissionEnabled ? 8670 getPermissionChecker() : null; 8671 boolean success = false; 8672 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8673 if (cacheEntry != null && cacheEntry.isSuccess()) { 8674 return; 8675 } 8676 if (!flags.contains(CacheFlag.FORCE)) { 8677 cacheManager.waitForRescanIfNeeded(); 8678 } 8679 writeLock(); 8680 try { 8681 checkOperation(OperationCategory.WRITE); 8682 if (isInSafeMode()) { 8683 throw new SafeModeException( 8684 "Cannot add cache directive", safeMode); 8685 } 8686 cacheManager.modifyDirective(directive, pc, flags); 8687 getEditLog().logModifyCacheDirectiveInfo(directive, 8688 cacheEntry != null); 8689 success = true; 8690 } finally { 8691 writeUnlock(); 8692 if (success) { 8693 getEditLog().logSync(); 8694 } 8695 if (isAuditEnabled() && isExternalInvocation()) { 8696 String idStr = "{id: " + directive.getId().toString() + "}"; 8697 logAuditEvent(success, "modifyCacheDirective", idStr, directive.toString(), null); 8698 } 8699 RetryCache.setState(cacheEntry, success); 8700 } 8701 } 8702 8703 void removeCacheDirective(Long id) throws IOException { 8704 checkOperation(OperationCategory.WRITE); 8705 final FSPermissionChecker pc = isPermissionEnabled ? 8706 getPermissionChecker() : null; 8707 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8708 if (cacheEntry != null && cacheEntry.isSuccess()) { 8709 return; 8710 } 8711 boolean success = false; 8712 writeLock(); 8713 try { 8714 checkOperation(OperationCategory.WRITE); 8715 if (isInSafeMode()) { 8716 throw new SafeModeException( 8717 "Cannot remove cache directives", safeMode); 8718 } 8719 cacheManager.removeDirective(id, pc); 8720 getEditLog().logRemoveCacheDirectiveInfo(id, cacheEntry != null); 8721 success = true; 8722 } finally { 8723 writeUnlock(); 8724 if (isAuditEnabled() && isExternalInvocation()) { 8725 String idStr = "{id: " + id.toString() + "}"; 8726 logAuditEvent(success, "removeCacheDirective", idStr, null, 8727 null); 8728 } 8729 RetryCache.setState(cacheEntry, success); 8730 } 8731 getEditLog().logSync(); 8732 } 8733 8734 BatchedListEntries<CacheDirectiveEntry> listCacheDirectives( 8735 long startId, CacheDirectiveInfo filter) throws IOException { 8736 checkOperation(OperationCategory.READ); 8737 final FSPermissionChecker pc = isPermissionEnabled ? 8738 getPermissionChecker() : null; 8739 BatchedListEntries<CacheDirectiveEntry> results; 8740 cacheManager.waitForRescanIfNeeded(); 8741 readLock(); 8742 boolean success = false; 8743 try { 8744 checkOperation(OperationCategory.READ); 8745 results = 8746 cacheManager.listCacheDirectives(startId, filter, pc); 8747 success = true; 8748 } finally { 8749 readUnlock(); 8750 if (isAuditEnabled() && isExternalInvocation()) { 8751 logAuditEvent(success, "listCacheDirectives", filter.toString(), null, 8752 null); 8753 } 8754 } 8755 return results; 8756 } 8757 8758 public void addCachePool(CachePoolInfo req) throws IOException { 8759 checkOperation(OperationCategory.WRITE); 8760 final FSPermissionChecker pc = isPermissionEnabled ? 8761 getPermissionChecker() : null; 8762 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8763 if (cacheEntry != null && cacheEntry.isSuccess()) { 8764 return; // Return previous response 8765 } 8766 writeLock(); 8767 boolean success = false; 8768 String poolInfoStr = null; 8769 try { 8770 checkOperation(OperationCategory.WRITE); 8771 if (isInSafeMode()) { 8772 throw new SafeModeException( 8773 "Cannot add cache pool " + req.getPoolName(), safeMode); 8774 } 8775 if (pc != null) { 8776 pc.checkSuperuserPrivilege(); 8777 } 8778 CachePoolInfo info = cacheManager.addCachePool(req); 8779 poolInfoStr = info.toString(); 8780 getEditLog().logAddCachePool(info, cacheEntry != null); 8781 success = true; 8782 } finally { 8783 writeUnlock(); 8784 if (isAuditEnabled() && isExternalInvocation()) { 8785 logAuditEvent(success, "addCachePool", poolInfoStr, null, null); 8786 } 8787 RetryCache.setState(cacheEntry, success); 8788 } 8789 8790 getEditLog().logSync(); 8791 } 8792 8793 public void modifyCachePool(CachePoolInfo req) throws IOException { 8794 checkOperation(OperationCategory.WRITE); 8795 final FSPermissionChecker pc = 8796 isPermissionEnabled ? getPermissionChecker() : null; 8797 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8798 if (cacheEntry != null && cacheEntry.isSuccess()) { 8799 return; // Return previous response 8800 } 8801 writeLock(); 8802 boolean success = false; 8803 try { 8804 checkOperation(OperationCategory.WRITE); 8805 if (isInSafeMode()) { 8806 throw new SafeModeException( 8807 "Cannot modify cache pool " + req.getPoolName(), safeMode); 8808 } 8809 if (pc != null) { 8810 pc.checkSuperuserPrivilege(); 8811 } 8812 cacheManager.modifyCachePool(req); 8813 getEditLog().logModifyCachePool(req, cacheEntry != null); 8814 success = true; 8815 } finally { 8816 writeUnlock(); 8817 if (isAuditEnabled() && isExternalInvocation()) { 8818 String poolNameStr = "{poolName: " + req.getPoolName() + "}"; 8819 logAuditEvent(success, "modifyCachePool", poolNameStr, req.toString(), null); 8820 } 8821 RetryCache.setState(cacheEntry, success); 8822 } 8823 8824 getEditLog().logSync(); 8825 } 8826 8827 public void removeCachePool(String cachePoolName) throws IOException { 8828 checkOperation(OperationCategory.WRITE); 8829 final FSPermissionChecker pc = 8830 isPermissionEnabled ? getPermissionChecker() : null; 8831 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 8832 if (cacheEntry != null && cacheEntry.isSuccess()) { 8833 return; // Return previous response 8834 } 8835 writeLock(); 8836 boolean success = false; 8837 try { 8838 checkOperation(OperationCategory.WRITE); 8839 if (isInSafeMode()) { 8840 throw new SafeModeException( 8841 "Cannot remove cache pool " + cachePoolName, safeMode); 8842 } 8843 if (pc != null) { 8844 pc.checkSuperuserPrivilege(); 8845 } 8846 cacheManager.removeCachePool(cachePoolName); 8847 getEditLog().logRemoveCachePool(cachePoolName, cacheEntry != null); 8848 success = true; 8849 } finally { 8850 writeUnlock(); 8851 if (isAuditEnabled() && isExternalInvocation()) { 8852 String poolNameStr = "{poolName: " + cachePoolName + "}"; 8853 logAuditEvent(success, "removeCachePool", poolNameStr, null, null); 8854 } 8855 RetryCache.setState(cacheEntry, success); 8856 } 8857 8858 getEditLog().logSync(); 8859 } 8860 8861 public BatchedListEntries<CachePoolEntry> listCachePools(String prevKey) 8862 throws IOException { 8863 final FSPermissionChecker pc = 8864 isPermissionEnabled ? getPermissionChecker() : null; 8865 BatchedListEntries<CachePoolEntry> results; 8866 checkOperation(OperationCategory.READ); 8867 boolean success = false; 8868 cacheManager.waitForRescanIfNeeded(); 8869 readLock(); 8870 try { 8871 checkOperation(OperationCategory.READ); 8872 results = cacheManager.listCachePools(pc, prevKey); 8873 success = true; 8874 } finally { 8875 readUnlock(); 8876 if (isAuditEnabled() && isExternalInvocation()) { 8877 logAuditEvent(success, "listCachePools", null, null, null); 8878 } 8879 } 8880 return results; 8881 } 8882 8883 void modifyAclEntries(final String srcArg, List<AclEntry> aclSpec) 8884 throws IOException { 8885 String src = srcArg; 8886 nnConf.checkAclsConfigFlag(); 8887 HdfsFileStatus resultingStat = null; 8888 FSPermissionChecker pc = getPermissionChecker(); 8889 checkOperation(OperationCategory.WRITE); 8890 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 8891 writeLock(); 8892 try { 8893 checkOperation(OperationCategory.WRITE); 8894 checkNameNodeSafeMode("Cannot modify ACL entries on " + src); 8895 src = resolvePath(src, pathComponents); 8896 checkOwner(pc, src); 8897 List<AclEntry> newAcl = dir.modifyAclEntries(src, aclSpec); 8898 getEditLog().logSetAcl(src, newAcl); 8899 resultingStat = getAuditFileInfo(src, false); 8900 } catch (AccessControlException e) { 8901 logAuditEvent(false, "modifyAclEntries", srcArg); 8902 throw e; 8903 } finally { 8904 writeUnlock(); 8905 } 8906 getEditLog().logSync(); 8907 logAuditEvent(true, "modifyAclEntries", srcArg, null, resultingStat); 8908 } 8909 8910 void removeAclEntries(final String srcArg, List<AclEntry> aclSpec) 8911 throws IOException { 8912 String src = srcArg; 8913 nnConf.checkAclsConfigFlag(); 8914 HdfsFileStatus resultingStat = null; 8915 FSPermissionChecker pc = getPermissionChecker(); 8916 checkOperation(OperationCategory.WRITE); 8917 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 8918 writeLock(); 8919 try { 8920 checkOperation(OperationCategory.WRITE); 8921 checkNameNodeSafeMode("Cannot remove ACL entries on " + src); 8922 src = resolvePath(src, pathComponents); 8923 checkOwner(pc, src); 8924 List<AclEntry> newAcl = dir.removeAclEntries(src, aclSpec); 8925 getEditLog().logSetAcl(src, newAcl); 8926 resultingStat = getAuditFileInfo(src, false); 8927 } catch (AccessControlException e) { 8928 logAuditEvent(false, "removeAclEntries", srcArg); 8929 throw e; 8930 } finally { 8931 writeUnlock(); 8932 } 8933 getEditLog().logSync(); 8934 logAuditEvent(true, "removeAclEntries", srcArg, null, resultingStat); 8935 } 8936 8937 void removeDefaultAcl(final String srcArg) throws IOException { 8938 String src = srcArg; 8939 nnConf.checkAclsConfigFlag(); 8940 HdfsFileStatus resultingStat = null; 8941 FSPermissionChecker pc = getPermissionChecker(); 8942 checkOperation(OperationCategory.WRITE); 8943 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 8944 writeLock(); 8945 try { 8946 checkOperation(OperationCategory.WRITE); 8947 checkNameNodeSafeMode("Cannot remove default ACL entries on " + src); 8948 src = resolvePath(src, pathComponents); 8949 checkOwner(pc, src); 8950 List<AclEntry> newAcl = dir.removeDefaultAcl(src); 8951 getEditLog().logSetAcl(src, newAcl); 8952 resultingStat = getAuditFileInfo(src, false); 8953 } catch (AccessControlException e) { 8954 logAuditEvent(false, "removeDefaultAcl", srcArg); 8955 throw e; 8956 } finally { 8957 writeUnlock(); 8958 } 8959 getEditLog().logSync(); 8960 logAuditEvent(true, "removeDefaultAcl", srcArg, null, resultingStat); 8961 } 8962 8963 void removeAcl(final String srcArg) throws IOException { 8964 String src = srcArg; 8965 nnConf.checkAclsConfigFlag(); 8966 HdfsFileStatus resultingStat = null; 8967 FSPermissionChecker pc = getPermissionChecker(); 8968 checkOperation(OperationCategory.WRITE); 8969 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 8970 writeLock(); 8971 try { 8972 checkOperation(OperationCategory.WRITE); 8973 checkNameNodeSafeMode("Cannot remove ACL on " + src); 8974 src = resolvePath(src, pathComponents); 8975 checkOwner(pc, src); 8976 dir.removeAcl(src); 8977 getEditLog().logSetAcl(src, AclFeature.EMPTY_ENTRY_LIST); 8978 resultingStat = getAuditFileInfo(src, false); 8979 } catch (AccessControlException e) { 8980 logAuditEvent(false, "removeAcl", srcArg); 8981 throw e; 8982 } finally { 8983 writeUnlock(); 8984 } 8985 getEditLog().logSync(); 8986 logAuditEvent(true, "removeAcl", srcArg, null, resultingStat); 8987 } 8988 8989 void setAcl(final String srcArg, List<AclEntry> aclSpec) throws IOException { 8990 String src = srcArg; 8991 nnConf.checkAclsConfigFlag(); 8992 HdfsFileStatus resultingStat = null; 8993 FSPermissionChecker pc = getPermissionChecker(); 8994 checkOperation(OperationCategory.WRITE); 8995 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 8996 writeLock(); 8997 try { 8998 checkOperation(OperationCategory.WRITE); 8999 checkNameNodeSafeMode("Cannot set ACL on " + src); 9000 src = resolvePath(src, pathComponents); 9001 checkOwner(pc, src); 9002 List<AclEntry> newAcl = dir.setAcl(src, aclSpec); 9003 getEditLog().logSetAcl(src, newAcl); 9004 resultingStat = getAuditFileInfo(src, false); 9005 } catch (AccessControlException e) { 9006 logAuditEvent(false, "setAcl", srcArg); 9007 throw e; 9008 } finally { 9009 writeUnlock(); 9010 } 9011 getEditLog().logSync(); 9012 logAuditEvent(true, "setAcl", srcArg, null, resultingStat); 9013 } 9014 9015 AclStatus getAclStatus(String src) throws IOException { 9016 nnConf.checkAclsConfigFlag(); 9017 FSPermissionChecker pc = getPermissionChecker(); 9018 checkOperation(OperationCategory.READ); 9019 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9020 boolean success = false; 9021 readLock(); 9022 try { 9023 checkOperation(OperationCategory.READ); 9024 src = resolvePath(src, pathComponents); 9025 if (isPermissionEnabled) { 9026 checkPermission(pc, src, false, null, null, null, null); 9027 } 9028 final AclStatus ret = dir.getAclStatus(src); 9029 success = true; 9030 return ret; 9031 } finally { 9032 readUnlock(); 9033 logAuditEvent(success, "getAclStatus", src); 9034 } 9035 } 9036 9037 /** 9038 * Create an encryption zone on directory src using the specified key. 9039 * 9040 * @param src the path of a directory which will be the root of the 9041 * encryption zone. The directory must be empty. 9042 * @param keyName name of a key which must be present in the configured 9043 * KeyProvider. 9044 * @throws AccessControlException if the caller is not the superuser. 9045 * @throws UnresolvedLinkException if the path can't be resolved. 9046 * @throws SafeModeException if the Namenode is in safe mode. 9047 */ 9048 void createEncryptionZone(final String src, final String keyName) 9049 throws IOException, UnresolvedLinkException, 9050 SafeModeException, AccessControlException { 9051 final CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 9052 if (cacheEntry != null && cacheEntry.isSuccess()) { 9053 return; // Return previous response 9054 } 9055 9056 boolean success = false; 9057 try { 9058 if (provider == null) { 9059 throw new IOException( 9060 "Can't create an encryption zone for " + src + 9061 " since no key provider is available."); 9062 } 9063 if (keyName == null || keyName.isEmpty()) { 9064 throw new IOException("Must specify a key name when creating an " + 9065 "encryption zone"); 9066 } 9067 KeyProvider.Metadata metadata = provider.getMetadata(keyName); 9068 if (metadata == null) { 9069 /* 9070 * It would be nice if we threw something more specific than 9071 * IOException when the key is not found, but the KeyProvider API 9072 * doesn't provide for that. If that API is ever changed to throw 9073 * something more specific (e.g. UnknownKeyException) then we can 9074 * update this to match it, or better yet, just rethrow the 9075 * KeyProvider's exception. 9076 */ 9077 throw new IOException("Key " + keyName + " doesn't exist."); 9078 } 9079 // If the provider supports pool for EDEKs, this will fill in the pool 9080 generateEncryptedDataEncryptionKey(keyName); 9081 createEncryptionZoneInt(src, metadata.getCipher(), 9082 keyName, cacheEntry != null); 9083 success = true; 9084 } catch (AccessControlException e) { 9085 logAuditEvent(false, "createEncryptionZone", src); 9086 throw e; 9087 } finally { 9088 RetryCache.setState(cacheEntry, success); 9089 } 9090 } 9091 9092 private void createEncryptionZoneInt(final String srcArg, String cipher, 9093 String keyName, final boolean logRetryCache) throws IOException { 9094 String src = srcArg; 9095 HdfsFileStatus resultingStat = null; 9096 checkSuperuserPrivilege(); 9097 checkOperation(OperationCategory.WRITE); 9098 final byte[][] pathComponents = 9099 FSDirectory.getPathComponentsForReservedPath(src); 9100 writeLock(); 9101 try { 9102 checkSuperuserPrivilege(); 9103 checkOperation(OperationCategory.WRITE); 9104 checkNameNodeSafeMode("Cannot create encryption zone on " + src); 9105 src = resolvePath(src, pathComponents); 9106 9107 final CipherSuite suite = CipherSuite.convert(cipher); 9108 // For now this is hardcoded, as we only support one method. 9109 final CryptoProtocolVersion version = 9110 CryptoProtocolVersion.ENCRYPTION_ZONES; 9111 final XAttr ezXAttr = dir.createEncryptionZone(src, suite, 9112 version, keyName); 9113 List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1); 9114 xAttrs.add(ezXAttr); 9115 getEditLog().logSetXAttrs(src, xAttrs, logRetryCache); 9116 resultingStat = getAuditFileInfo(src, false); 9117 } finally { 9118 writeUnlock(); 9119 } 9120 getEditLog().logSync(); 9121 logAuditEvent(true, "createEncryptionZone", srcArg, null, resultingStat); 9122 } 9123 9124 /** 9125 * Get the encryption zone for the specified path. 9126 * 9127 * @param srcArg the path of a file or directory to get the EZ for. 9128 * @return the EZ of the of the path or null if none. 9129 * @throws AccessControlException if the caller is not the superuser. 9130 * @throws UnresolvedLinkException if the path can't be resolved. 9131 */ 9132 EncryptionZone getEZForPath(final String srcArg) 9133 throws AccessControlException, UnresolvedLinkException, IOException { 9134 String src = srcArg; 9135 HdfsFileStatus resultingStat = null; 9136 final byte[][] pathComponents = 9137 FSDirectory.getPathComponentsForReservedPath(src); 9138 boolean success = false; 9139 final FSPermissionChecker pc = getPermissionChecker(); 9140 checkOperation(OperationCategory.READ); 9141 readLock(); 9142 try { 9143 if (isPermissionEnabled) { 9144 checkPathAccess(pc, src, FsAction.READ); 9145 } 9146 checkOperation(OperationCategory.READ); 9147 src = resolvePath(src, pathComponents); 9148 final INodesInPath iip = dir.getINodesInPath(src, true); 9149 final EncryptionZone ret = dir.getEZForPath(iip); 9150 resultingStat = getAuditFileInfo(src, false); 9151 success = true; 9152 return ret; 9153 } finally { 9154 readUnlock(); 9155 logAuditEvent(success, "getEZForPath", srcArg, null, resultingStat); 9156 } 9157 } 9158 9159 BatchedListEntries<EncryptionZone> listEncryptionZones(long prevId) 9160 throws IOException { 9161 boolean success = false; 9162 checkSuperuserPrivilege(); 9163 checkOperation(OperationCategory.READ); 9164 readLock(); 9165 try { 9166 checkSuperuserPrivilege(); 9167 checkOperation(OperationCategory.READ); 9168 final BatchedListEntries<EncryptionZone> ret = 9169 dir.listEncryptionZones(prevId); 9170 success = true; 9171 return ret; 9172 } finally { 9173 readUnlock(); 9174 logAuditEvent(success, "listEncryptionZones", null); 9175 } 9176 } 9177 9178 /** 9179 * Set xattr for a file or directory. 9180 * 9181 * @param src 9182 * - path on which it sets the xattr 9183 * @param xAttr 9184 * - xAttr details to set 9185 * @param flag 9186 * - xAttrs flags 9187 * @throws AccessControlException 9188 * @throws SafeModeException 9189 * @throws UnresolvedLinkException 9190 * @throws IOException 9191 */ 9192 void setXAttr(String src, XAttr xAttr, EnumSet<XAttrSetFlag> flag) 9193 throws AccessControlException, SafeModeException, 9194 UnresolvedLinkException, IOException { 9195 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 9196 if (cacheEntry != null && cacheEntry.isSuccess()) { 9197 return; // Return previous response 9198 } 9199 boolean success = false; 9200 try { 9201 setXAttrInt(src, xAttr, flag, cacheEntry != null); 9202 success = true; 9203 } catch (AccessControlException e) { 9204 logAuditEvent(false, "setXAttr", src); 9205 throw e; 9206 } finally { 9207 RetryCache.setState(cacheEntry, success); 9208 } 9209 } 9210 9211 private void setXAttrInt(final String srcArg, XAttr xAttr, 9212 EnumSet<XAttrSetFlag> flag, boolean logRetryCache) throws IOException { 9213 String src = srcArg; 9214 nnConf.checkXAttrsConfigFlag(); 9215 checkXAttrSize(xAttr); 9216 HdfsFileStatus resultingStat = null; 9217 FSPermissionChecker pc = getPermissionChecker(); 9218 XAttrPermissionFilter.checkPermissionForApi(pc, xAttr, 9219 FSDirectory.isReservedRawName(src)); 9220 checkOperation(OperationCategory.WRITE); 9221 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9222 writeLock(); 9223 try { 9224 checkOperation(OperationCategory.WRITE); 9225 checkNameNodeSafeMode("Cannot set XAttr on " + src); 9226 src = resolvePath(src, pathComponents); 9227 checkXAttrChangeAccess(src, xAttr, pc); 9228 List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1); 9229 xAttrs.add(xAttr); 9230 dir.setXAttrs(src, xAttrs, flag); 9231 getEditLog().logSetXAttrs(src, xAttrs, logRetryCache); 9232 resultingStat = getAuditFileInfo(src, false); 9233 } finally { 9234 writeUnlock(); 9235 } 9236 getEditLog().logSync(); 9237 logAuditEvent(true, "setXAttr", srcArg, null, resultingStat); 9238 } 9239 9240 /** 9241 * Verifies that the combined size of the name and value of an xattr is within 9242 * the configured limit. Setting a limit of zero disables this check. 9243 */ 9244 private void checkXAttrSize(XAttr xAttr) { 9245 if (nnConf.xattrMaxSize == 0) { 9246 return; 9247 } 9248 int size = xAttr.getName().getBytes(Charsets.UTF_8).length; 9249 if (xAttr.getValue() != null) { 9250 size += xAttr.getValue().length; 9251 } 9252 if (size > nnConf.xattrMaxSize) { 9253 throw new HadoopIllegalArgumentException( 9254 "The XAttr is too big. The maximum combined size of the" 9255 + " name and value is " + nnConf.xattrMaxSize 9256 + ", but the total size is " + size); 9257 } 9258 } 9259 9260 List<XAttr> getXAttrs(final String srcArg, List<XAttr> xAttrs) 9261 throws IOException { 9262 String src = srcArg; 9263 nnConf.checkXAttrsConfigFlag(); 9264 FSPermissionChecker pc = getPermissionChecker(); 9265 final boolean isRawPath = FSDirectory.isReservedRawName(src); 9266 boolean getAll = xAttrs == null || xAttrs.isEmpty(); 9267 if (!getAll) { 9268 try { 9269 XAttrPermissionFilter.checkPermissionForApi(pc, xAttrs, isRawPath); 9270 } catch (AccessControlException e) { 9271 logAuditEvent(false, "getXAttrs", srcArg); 9272 throw e; 9273 } 9274 } 9275 checkOperation(OperationCategory.READ); 9276 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9277 readLock(); 9278 try { 9279 src = resolvePath(src, pathComponents); 9280 checkOperation(OperationCategory.READ); 9281 if (isPermissionEnabled) { 9282 checkPathAccess(pc, src, FsAction.READ); 9283 } 9284 List<XAttr> all = dir.getXAttrs(src); 9285 List<XAttr> filteredAll = XAttrPermissionFilter. 9286 filterXAttrsForApi(pc, all, isRawPath); 9287 if (getAll) { 9288 return filteredAll; 9289 } else { 9290 if (filteredAll == null || filteredAll.isEmpty()) { 9291 return null; 9292 } 9293 List<XAttr> toGet = Lists.newArrayListWithCapacity(xAttrs.size()); 9294 for (XAttr xAttr : xAttrs) { 9295 boolean foundIt = false; 9296 for (XAttr a : filteredAll) { 9297 if (xAttr.getNameSpace() == a.getNameSpace() 9298 && xAttr.getName().equals(a.getName())) { 9299 toGet.add(a); 9300 foundIt = true; 9301 break; 9302 } 9303 } 9304 if (!foundIt) { 9305 throw new IOException( 9306 "At least one of the attributes provided was not found."); 9307 } 9308 } 9309 return toGet; 9310 } 9311 } catch (AccessControlException e) { 9312 logAuditEvent(false, "getXAttrs", srcArg); 9313 throw e; 9314 } finally { 9315 readUnlock(); 9316 } 9317 } 9318 9319 List<XAttr> listXAttrs(String src) throws IOException { 9320 nnConf.checkXAttrsConfigFlag(); 9321 final FSPermissionChecker pc = getPermissionChecker(); 9322 final boolean isRawPath = FSDirectory.isReservedRawName(src); 9323 checkOperation(OperationCategory.READ); 9324 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9325 readLock(); 9326 try { 9327 src = resolvePath(src, pathComponents); 9328 checkOperation(OperationCategory.READ); 9329 if (isPermissionEnabled) { 9330 /* To access xattr names, you need EXECUTE in the owning directory. */ 9331 checkParentAccess(pc, src, FsAction.EXECUTE); 9332 } 9333 final List<XAttr> all = dir.getXAttrs(src); 9334 final List<XAttr> filteredAll = XAttrPermissionFilter. 9335 filterXAttrsForApi(pc, all, isRawPath); 9336 return filteredAll; 9337 } catch (AccessControlException e) { 9338 logAuditEvent(false, "listXAttrs", src); 9339 throw e; 9340 } finally { 9341 readUnlock(); 9342 } 9343 } 9344 9345 /** 9346 * Remove an xattr for a file or directory. 9347 * 9348 * @param src 9349 * - path to remove the xattr from 9350 * @param xAttr 9351 * - xAttr to remove 9352 * @throws AccessControlException 9353 * @throws SafeModeException 9354 * @throws UnresolvedLinkException 9355 * @throws IOException 9356 */ 9357 void removeXAttr(String src, XAttr xAttr) throws IOException { 9358 CacheEntry cacheEntry = RetryCache.waitForCompletion(retryCache); 9359 if (cacheEntry != null && cacheEntry.isSuccess()) { 9360 return; // Return previous response 9361 } 9362 boolean success = false; 9363 try { 9364 removeXAttrInt(src, xAttr, cacheEntry != null); 9365 success = true; 9366 } catch (AccessControlException e) { 9367 logAuditEvent(false, "removeXAttr", src); 9368 throw e; 9369 } finally { 9370 RetryCache.setState(cacheEntry, success); 9371 } 9372 } 9373 9374 void removeXAttrInt(final String srcArg, XAttr xAttr, boolean logRetryCache) 9375 throws IOException { 9376 String src = srcArg; 9377 nnConf.checkXAttrsConfigFlag(); 9378 HdfsFileStatus resultingStat = null; 9379 FSPermissionChecker pc = getPermissionChecker(); 9380 XAttrPermissionFilter.checkPermissionForApi(pc, xAttr, 9381 FSDirectory.isReservedRawName(src)); 9382 checkOperation(OperationCategory.WRITE); 9383 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9384 writeLock(); 9385 try { 9386 checkOperation(OperationCategory.WRITE); 9387 checkNameNodeSafeMode("Cannot remove XAttr entry on " + src); 9388 src = resolvePath(src, pathComponents); 9389 checkXAttrChangeAccess(src, xAttr, pc); 9390 9391 List<XAttr> xAttrs = Lists.newArrayListWithCapacity(1); 9392 xAttrs.add(xAttr); 9393 List<XAttr> removedXAttrs = dir.removeXAttrs(src, xAttrs); 9394 if (removedXAttrs != null && !removedXAttrs.isEmpty()) { 9395 getEditLog().logRemoveXAttrs(src, removedXAttrs, logRetryCache); 9396 } else { 9397 throw new IOException( 9398 "No matching attributes found for remove operation"); 9399 } 9400 resultingStat = getAuditFileInfo(src, false); 9401 } finally { 9402 writeUnlock(); 9403 } 9404 getEditLog().logSync(); 9405 logAuditEvent(true, "removeXAttr", srcArg, null, resultingStat); 9406 } 9407 9408 private void checkXAttrChangeAccess(String src, XAttr xAttr, 9409 FSPermissionChecker pc) throws UnresolvedLinkException, 9410 AccessControlException { 9411 if (isPermissionEnabled && xAttr.getNameSpace() == XAttr.NameSpace.USER) { 9412 final INode inode = dir.getINode(src); 9413 if (inode != null && 9414 inode.isDirectory() && 9415 inode.getFsPermission().getStickyBit()) { 9416 if (!pc.isSuperUser()) { 9417 checkOwner(pc, src); 9418 } 9419 } else { 9420 checkPathAccess(pc, src, FsAction.WRITE); 9421 } 9422 } 9423 } 9424 9425 void checkAccess(String src, FsAction mode) throws AccessControlException, 9426 FileNotFoundException, UnresolvedLinkException, IOException { 9427 checkOperation(OperationCategory.READ); 9428 byte[][] pathComponents = FSDirectory.getPathComponentsForReservedPath(src); 9429 readLock(); 9430 try { 9431 checkOperation(OperationCategory.READ); 9432 src = FSDirectory.resolvePath(src, pathComponents, dir); 9433 if (dir.getINode(src) == null) { 9434 throw new FileNotFoundException("Path not found"); 9435 } 9436 if (isPermissionEnabled) { 9437 FSPermissionChecker pc = getPermissionChecker(); 9438 checkPathAccess(pc, src, mode); 9439 } 9440 } catch (AccessControlException e) { 9441 logAuditEvent(false, "checkAccess", src); 9442 throw e; 9443 } finally { 9444 readUnlock(); 9445 } 9446 } 9447 9448 /** 9449 * Default AuditLogger implementation; used when no access logger is 9450 * defined in the config file. It can also be explicitly listed in the 9451 * config file. 9452 */ 9453 private static class DefaultAuditLogger extends HdfsAuditLogger { 9454 9455 private boolean logTokenTrackingId; 9456 9457 @Override 9458 public void initialize(Configuration conf) { 9459 logTokenTrackingId = conf.getBoolean( 9460 DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_KEY, 9461 DFSConfigKeys.DFS_NAMENODE_AUDIT_LOG_TOKEN_TRACKING_ID_DEFAULT); 9462 } 9463 9464 @Override 9465 public void logAuditEvent(boolean succeeded, String userName, 9466 InetAddress addr, String cmd, String src, String dst, 9467 FileStatus status, UserGroupInformation ugi, 9468 DelegationTokenSecretManager dtSecretManager) { 9469 if (auditLog.isInfoEnabled()) { 9470 final StringBuilder sb = auditBuffer.get(); 9471 sb.setLength(0); 9472 sb.append("allowed=").append(succeeded).append("\t"); 9473 sb.append("ugi=").append(userName).append("\t"); 9474 sb.append("ip=").append(addr).append("\t"); 9475 sb.append("cmd=").append(cmd).append("\t"); 9476 sb.append("src=").append(src).append("\t"); 9477 sb.append("dst=").append(dst).append("\t"); 9478 if (null == status) { 9479 sb.append("perm=null"); 9480 } else { 9481 sb.append("perm="); 9482 sb.append(status.getOwner()).append(":"); 9483 sb.append(status.getGroup()).append(":"); 9484 sb.append(status.getPermission()); 9485 } 9486 if (logTokenTrackingId) { 9487 sb.append("\t").append("trackingId="); 9488 String trackingId = null; 9489 if (ugi != null && dtSecretManager != null 9490 && ugi.getAuthenticationMethod() == AuthenticationMethod.TOKEN) { 9491 for (TokenIdentifier tid: ugi.getTokenIdentifiers()) { 9492 if (tid instanceof DelegationTokenIdentifier) { 9493 DelegationTokenIdentifier dtid = 9494 (DelegationTokenIdentifier)tid; 9495 trackingId = dtSecretManager.getTokenTrackingId(dtid); 9496 break; 9497 } 9498 } 9499 } 9500 sb.append(trackingId); 9501 } 9502 sb.append("\t").append("proto="); 9503 sb.append(NamenodeWebHdfsMethods.isWebHdfsInvocation() ? "webhdfs" : "rpc"); 9504 logAuditMessage(sb.toString()); 9505 } 9506 } 9507 9508 public void logAuditMessage(String message) { 9509 auditLog.info(message); 9510 } 9511 } 9512 9513 private static void enableAsyncAuditLog() { 9514 if (!(auditLog instanceof Log4JLogger)) { 9515 LOG.warn("Log4j is required to enable async auditlog"); 9516 return; 9517 } 9518 Logger logger = ((Log4JLogger)auditLog).getLogger(); 9519 @SuppressWarnings("unchecked") 9520 List<Appender> appenders = Collections.list(logger.getAllAppenders()); 9521 // failsafe against trying to async it more than once 9522 if (!appenders.isEmpty() && !(appenders.get(0) instanceof AsyncAppender)) { 9523 AsyncAppender asyncAppender = new AsyncAppender(); 9524 // change logger to have an async appender containing all the 9525 // previously configured appenders 9526 for (Appender appender : appenders) { 9527 logger.removeAppender(appender); 9528 asyncAppender.addAppender(appender); 9529 } 9530 logger.addAppender(asyncAppender); 9531 } 9532 } 9533} 9534