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.protocolPB; 019 020import static com.google.common.base.Preconditions.checkNotNull; 021import static org.apache.hadoop.hdfs.protocol.proto.EncryptionZonesProtos 022 .EncryptionZoneProto; 023import static org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CipherSuiteProto; 024import static org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CryptoProtocolVersionProto; 025 026import java.io.EOFException; 027import java.io.IOException; 028import java.io.InputStream; 029import java.util.ArrayList; 030import java.util.Arrays; 031import java.util.EnumSet; 032import java.util.List; 033 034import org.apache.hadoop.fs.CacheFlag; 035import org.apache.hadoop.fs.ContentSummary; 036import org.apache.hadoop.fs.CreateFlag; 037import org.apache.hadoop.fs.FsServerDefaults; 038import org.apache.hadoop.fs.Path; 039import org.apache.hadoop.fs.StorageType; 040import org.apache.hadoop.fs.XAttr; 041import org.apache.hadoop.fs.XAttrSetFlag; 042import org.apache.hadoop.fs.permission.AclEntry; 043import org.apache.hadoop.fs.permission.AclEntryScope; 044import org.apache.hadoop.fs.permission.AclEntryType; 045import org.apache.hadoop.fs.permission.AclStatus; 046import org.apache.hadoop.fs.permission.FsAction; 047import org.apache.hadoop.fs.permission.FsPermission; 048import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; 049import org.apache.hadoop.ha.proto.HAServiceProtocolProtos; 050import org.apache.hadoop.hdfs.inotify.EventBatch; 051import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy; 052import org.apache.hadoop.hdfs.DFSUtil; 053import org.apache.hadoop.hdfs.inotify.Event; 054import org.apache.hadoop.hdfs.inotify.EventBatchList; 055import org.apache.hadoop.hdfs.protocol.Block; 056import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry; 057import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo; 058import org.apache.hadoop.hdfs.protocol.CacheDirectiveStats; 059import org.apache.hadoop.hdfs.protocol.CachePoolEntry; 060import org.apache.hadoop.hdfs.protocol.CachePoolInfo; 061import org.apache.hadoop.hdfs.protocol.CachePoolStats; 062import org.apache.hadoop.crypto.CipherOption; 063import org.apache.hadoop.crypto.CipherSuite; 064import org.apache.hadoop.hdfs.protocol.ClientProtocol; 065import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks; 066import org.apache.hadoop.crypto.CryptoProtocolVersion; 067import org.apache.hadoop.hdfs.protocol.DatanodeID; 068import org.apache.hadoop.hdfs.protocol.DatanodeInfo; 069import org.apache.hadoop.hdfs.protocol.DatanodeInfo.AdminStates; 070import org.apache.hadoop.hdfs.protocol.DatanodeLocalInfo; 071import org.apache.hadoop.hdfs.protocol.DirectoryListing; 072import org.apache.hadoop.hdfs.protocol.EncryptionZone; 073import org.apache.hadoop.hdfs.protocol.ExtendedBlock; 074import org.apache.hadoop.fs.FileEncryptionInfo; 075import org.apache.hadoop.hdfs.protocol.FsPermissionExtension; 076import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType; 077import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction; 078import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction; 079import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; 080import org.apache.hadoop.hdfs.protocol.HdfsLocatedFileStatus; 081import org.apache.hadoop.hdfs.protocol.LocatedBlock; 082import org.apache.hadoop.hdfs.protocol.LocatedBlocks; 083import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo; 084import org.apache.hadoop.hdfs.protocol.RollingUpgradeStatus; 085import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport; 086import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry; 087import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType; 088import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus; 089import org.apache.hadoop.hdfs.protocol.proto.AclProtos.AclEntryProto; 090import org.apache.hadoop.hdfs.protocol.proto.AclProtos.AclEntryProto.AclEntryScopeProto; 091import org.apache.hadoop.hdfs.protocol.proto.AclProtos.AclEntryProto.AclEntryTypeProto; 092import org.apache.hadoop.hdfs.protocol.proto.AclProtos.AclEntryProto.FsActionProto; 093import org.apache.hadoop.hdfs.protocol.proto.AclProtos.AclStatusProto; 094import org.apache.hadoop.hdfs.protocol.proto.AclProtos.GetAclStatusResponseProto; 095import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos; 096import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveEntryProto; 097import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveInfoExpirationProto; 098import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveInfoProto; 099import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveStatsProto; 100import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheFlagProto; 101import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolEntryProto; 102import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolInfoProto; 103import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolStatsProto; 104import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CreateFlagProto; 105import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DatanodeReportTypeProto; 106import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.DatanodeStorageReportProto; 107import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetEditsFromTxidResponseProto; 108import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetFsStatsResponseProto; 109import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeActionProto; 110import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.RollingUpgradeInfoProto; 111import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.SafeModeActionProto; 112import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ShortCircuitShmIdProto; 113import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ShortCircuitShmSlotProto; 114import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos; 115import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BalancerBandwidthCommandProto; 116import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockCommandProto; 117import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockIdCommandProto; 118import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockRecoveryCommandProto; 119import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.DatanodeCommandProto; 120import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.DatanodeRegistrationProto; 121import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.FinalizeCommandProto; 122import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.KeyUpdateCommandProto; 123import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.NNHAStatusHeartbeatProto; 124import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ReceivedDeletedBlockInfoProto; 125import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.RegisterCommandProto; 126import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.VolumeFailureSummaryProto; 127import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockReportContextProto; 128import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos; 129import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockKeyProto; 130import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockProto; 131import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockStoragePolicyProto; 132import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockWithLocationsProto; 133import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlocksWithLocationsProto; 134import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CheckpointCommandProto; 135import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CheckpointSignatureProto; 136import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CipherOptionProto; 137import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ContentSummaryProto; 138import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.CorruptFileBlocksProto; 139import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DataEncryptionKeyProto; 140import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeIDProto; 141import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeInfoProto; 142import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeInfoProto.AdminState; 143import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeInfosProto; 144import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeLocalInfoProto; 145import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeStorageProto; 146import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeStorageProto.StorageState; 147import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DirectoryListingProto; 148import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ExportedBlockKeysProto; 149import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ExtendedBlockProto; 150import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.FsPermissionProto; 151import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.FsServerDefaultsProto; 152import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.HdfsFileStatusProto; 153import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.HdfsFileStatusProto.FileType; 154import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.LocatedBlockProto; 155import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.LocatedBlockProto.Builder; 156import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.LocatedBlocksProto; 157import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.NamenodeCommandProto; 158import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.NamenodeRegistrationProto; 159import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.NamenodeRegistrationProto.NamenodeRoleProto; 160import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.NamespaceInfoProto; 161import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.RecoveringBlockProto; 162import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.RemoteEditLogManifestProto; 163import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.RemoteEditLogProto; 164import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ReplicaStateProto; 165import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.RollingUpgradeStatusProto; 166import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.SnapshotDiffReportEntryProto; 167import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.SnapshotDiffReportProto; 168import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.SnapshottableDirectoryListingProto; 169import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.SnapshottableDirectoryStatusProto; 170import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.StorageInfoProto; 171import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.StorageReportProto; 172import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.StorageTypeProto; 173import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.StorageTypesProto; 174import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.StorageUuidsProto; 175import org.apache.hadoop.hdfs.protocol.proto.InotifyProtos; 176import org.apache.hadoop.hdfs.protocol.proto.JournalProtocolProtos.JournalInfoProto; 177import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.GetXAttrsResponseProto; 178import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.ListXAttrsResponseProto; 179import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.XAttrProto; 180import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.XAttrProto.XAttrNamespaceProto; 181import org.apache.hadoop.hdfs.protocol.proto.XAttrProtos.XAttrSetFlagProto; 182import org.apache.hadoop.hdfs.security.token.block.BlockKey; 183import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; 184import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey; 185import org.apache.hadoop.hdfs.security.token.block.ExportedBlockKeys; 186import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; 187import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite; 188import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NamenodeRole; 189import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType; 190import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState; 191import org.apache.hadoop.hdfs.server.common.Storage; 192import org.apache.hadoop.hdfs.server.common.StorageInfo; 193import org.apache.hadoop.hdfs.server.namenode.CheckpointSignature; 194import org.apache.hadoop.hdfs.server.namenode.INodeId; 195import org.apache.hadoop.hdfs.server.protocol.BalancerBandwidthCommand; 196import org.apache.hadoop.hdfs.server.protocol.BlockCommand; 197import org.apache.hadoop.hdfs.server.protocol.BlockIdCommand; 198import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand; 199import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlock; 200import org.apache.hadoop.hdfs.server.protocol.BlockReportContext; 201import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations; 202import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations.BlockWithLocations; 203import org.apache.hadoop.hdfs.server.protocol.CheckpointCommand; 204import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand; 205import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol; 206import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; 207import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage; 208import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage.State; 209import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport; 210import org.apache.hadoop.hdfs.server.protocol.FinalizeCommand; 211import org.apache.hadoop.hdfs.server.protocol.JournalInfo; 212import org.apache.hadoop.hdfs.server.protocol.KeyUpdateCommand; 213import org.apache.hadoop.hdfs.server.protocol.NNHAStatusHeartbeat; 214import org.apache.hadoop.hdfs.server.protocol.NamenodeCommand; 215import org.apache.hadoop.hdfs.server.protocol.NamenodeRegistration; 216import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; 217import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo; 218import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo.BlockStatus; 219import org.apache.hadoop.hdfs.server.protocol.RegisterCommand; 220import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog; 221import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest; 222import org.apache.hadoop.hdfs.server.protocol.StorageReport; 223import org.apache.hadoop.hdfs.server.protocol.VolumeFailureSummary; 224import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.ShmId; 225import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.SlotId; 226import org.apache.hadoop.hdfs.util.ExactSizeInputStream; 227import org.apache.hadoop.io.EnumSetWritable; 228import org.apache.hadoop.io.Text; 229import org.apache.hadoop.security.proto.SecurityProtos.TokenProto; 230import org.apache.hadoop.security.token.Token; 231import org.apache.hadoop.util.DataChecksum; 232 233import com.google.common.base.Preconditions; 234import com.google.common.collect.Lists; 235import com.google.common.primitives.Shorts; 236import com.google.protobuf.ByteString; 237import com.google.protobuf.CodedInputStream; 238 239/** 240 * Utilities for converting protobuf classes to and from implementation classes 241 * and other helper utilities to help in dealing with protobuf. 242 * 243 * Note that when converting from an internal type to protobuf type, the 244 * converter never return null for protobuf type. The check for internal type 245 * being null must be done before calling the convert() method. 246 */ 247public class PBHelper { 248 private static final RegisterCommandProto REG_CMD_PROTO = 249 RegisterCommandProto.newBuilder().build(); 250 private static final RegisterCommand REG_CMD = new RegisterCommand(); 251 252 private static final AclEntryScope[] ACL_ENTRY_SCOPE_VALUES = 253 AclEntryScope.values(); 254 private static final AclEntryType[] ACL_ENTRY_TYPE_VALUES = 255 AclEntryType.values(); 256 private static final FsAction[] FSACTION_VALUES = 257 FsAction.values(); 258 private static final XAttr.NameSpace[] XATTR_NAMESPACE_VALUES = 259 XAttr.NameSpace.values(); 260 261 private PBHelper() { 262 /** Hidden constructor */ 263 } 264 265 public static ByteString getByteString(byte[] bytes) { 266 return ByteString.copyFrom(bytes); 267 } 268 269 private static <T extends Enum<T>, U extends Enum<U>> U castEnum(T from, U[] to) { 270 return to[from.ordinal()]; 271 } 272 273 public static NamenodeRole convert(NamenodeRoleProto role) { 274 switch (role) { 275 case NAMENODE: 276 return NamenodeRole.NAMENODE; 277 case BACKUP: 278 return NamenodeRole.BACKUP; 279 case CHECKPOINT: 280 return NamenodeRole.CHECKPOINT; 281 } 282 return null; 283 } 284 285 public static NamenodeRoleProto convert(NamenodeRole role) { 286 switch (role) { 287 case NAMENODE: 288 return NamenodeRoleProto.NAMENODE; 289 case BACKUP: 290 return NamenodeRoleProto.BACKUP; 291 case CHECKPOINT: 292 return NamenodeRoleProto.CHECKPOINT; 293 } 294 return null; 295 } 296 297 public static BlockStoragePolicy[] convertStoragePolicies( 298 List<BlockStoragePolicyProto> policyProtos) { 299 if (policyProtos == null || policyProtos.size() == 0) { 300 return new BlockStoragePolicy[0]; 301 } 302 BlockStoragePolicy[] policies = new BlockStoragePolicy[policyProtos.size()]; 303 int i = 0; 304 for (BlockStoragePolicyProto proto : policyProtos) { 305 policies[i++] = convert(proto); 306 } 307 return policies; 308 } 309 310 public static BlockStoragePolicy convert(BlockStoragePolicyProto proto) { 311 List<StorageTypeProto> cList = proto.getCreationPolicy() 312 .getStorageTypesList(); 313 StorageType[] creationTypes = convertStorageTypes(cList, cList.size()); 314 List<StorageTypeProto> cfList = proto.hasCreationFallbackPolicy() ? proto 315 .getCreationFallbackPolicy().getStorageTypesList() : null; 316 StorageType[] creationFallbackTypes = cfList == null ? StorageType 317 .EMPTY_ARRAY : convertStorageTypes(cfList, cfList.size()); 318 List<StorageTypeProto> rfList = proto.hasReplicationFallbackPolicy() ? 319 proto.getReplicationFallbackPolicy().getStorageTypesList() : null; 320 StorageType[] replicationFallbackTypes = rfList == null ? StorageType 321 .EMPTY_ARRAY : convertStorageTypes(rfList, rfList.size()); 322 return new BlockStoragePolicy((byte) proto.getPolicyId(), proto.getName(), 323 creationTypes, creationFallbackTypes, replicationFallbackTypes); 324 } 325 326 public static BlockStoragePolicyProto convert(BlockStoragePolicy policy) { 327 BlockStoragePolicyProto.Builder builder = BlockStoragePolicyProto 328 .newBuilder().setPolicyId(policy.getId()).setName(policy.getName()); 329 // creation storage types 330 StorageTypesProto creationProto = convert(policy.getStorageTypes()); 331 Preconditions.checkArgument(creationProto != null); 332 builder.setCreationPolicy(creationProto); 333 // creation fallback 334 StorageTypesProto creationFallbackProto = convert( 335 policy.getCreationFallbacks()); 336 if (creationFallbackProto != null) { 337 builder.setCreationFallbackPolicy(creationFallbackProto); 338 } 339 // replication fallback 340 StorageTypesProto replicationFallbackProto = convert( 341 policy.getReplicationFallbacks()); 342 if (replicationFallbackProto != null) { 343 builder.setReplicationFallbackPolicy(replicationFallbackProto); 344 } 345 return builder.build(); 346 } 347 348 public static StorageTypesProto convert(StorageType[] types) { 349 if (types == null || types.length == 0) { 350 return null; 351 } 352 List<StorageTypeProto> list = convertStorageTypes(types); 353 return StorageTypesProto.newBuilder().addAllStorageTypes(list).build(); 354 } 355 356 public static StorageInfoProto convert(StorageInfo info) { 357 return StorageInfoProto.newBuilder().setClusterID(info.getClusterID()) 358 .setCTime(info.getCTime()).setLayoutVersion(info.getLayoutVersion()) 359 .setNamespceID(info.getNamespaceID()).build(); 360 } 361 362 public static StorageInfo convert(StorageInfoProto info, NodeType type) { 363 return new StorageInfo(info.getLayoutVersion(), info.getNamespceID(), 364 info.getClusterID(), info.getCTime(), type); 365 } 366 367 public static NamenodeRegistrationProto convert(NamenodeRegistration reg) { 368 return NamenodeRegistrationProto.newBuilder() 369 .setHttpAddress(reg.getHttpAddress()).setRole(convert(reg.getRole())) 370 .setRpcAddress(reg.getAddress()) 371 .setStorageInfo(convert((StorageInfo) reg)).build(); 372 } 373 374 public static NamenodeRegistration convert(NamenodeRegistrationProto reg) { 375 StorageInfo si = convert(reg.getStorageInfo(), NodeType.NAME_NODE); 376 return new NamenodeRegistration(reg.getRpcAddress(), reg.getHttpAddress(), 377 si, convert(reg.getRole())); 378 } 379 380 // DatanodeId 381 public static DatanodeID convert(DatanodeIDProto dn) { 382 return new DatanodeID(dn.getIpAddr(), dn.getHostName(), dn.getDatanodeUuid(), 383 dn.getXferPort(), dn.getInfoPort(), dn.hasInfoSecurePort() ? dn 384 .getInfoSecurePort() : 0, dn.getIpcPort()); 385 } 386 387 public static DatanodeIDProto convert(DatanodeID dn) { 388 // For wire compatibility with older versions we transmit the StorageID 389 // which is the same as the DatanodeUuid. Since StorageID is a required 390 // field we pass the empty string if the DatanodeUuid is not yet known. 391 return DatanodeIDProto.newBuilder() 392 .setIpAddr(dn.getIpAddr()) 393 .setHostName(dn.getHostName()) 394 .setXferPort(dn.getXferPort()) 395 .setDatanodeUuid(dn.getDatanodeUuid() != null ? dn.getDatanodeUuid() : "") 396 .setInfoPort(dn.getInfoPort()) 397 .setInfoSecurePort(dn.getInfoSecurePort()) 398 .setIpcPort(dn.getIpcPort()).build(); 399 } 400 401 // Arrays of DatanodeId 402 public static DatanodeIDProto[] convert(DatanodeID[] did) { 403 if (did == null) 404 return null; 405 final int len = did.length; 406 DatanodeIDProto[] result = new DatanodeIDProto[len]; 407 for (int i = 0; i < len; ++i) { 408 result[i] = convert(did[i]); 409 } 410 return result; 411 } 412 413 public static DatanodeID[] convert(DatanodeIDProto[] did) { 414 if (did == null) return null; 415 final int len = did.length; 416 DatanodeID[] result = new DatanodeID[len]; 417 for (int i = 0; i < len; ++i) { 418 result[i] = convert(did[i]); 419 } 420 return result; 421 } 422 423 // Block 424 public static BlockProto convert(Block b) { 425 return BlockProto.newBuilder().setBlockId(b.getBlockId()) 426 .setGenStamp(b.getGenerationStamp()).setNumBytes(b.getNumBytes()) 427 .build(); 428 } 429 430 public static Block convert(BlockProto b) { 431 return new Block(b.getBlockId(), b.getNumBytes(), b.getGenStamp()); 432 } 433 434 public static BlockWithLocationsProto convert(BlockWithLocations blk) { 435 return BlockWithLocationsProto.newBuilder() 436 .setBlock(convert(blk.getBlock())) 437 .addAllDatanodeUuids(Arrays.asList(blk.getDatanodeUuids())) 438 .addAllStorageUuids(Arrays.asList(blk.getStorageIDs())) 439 .addAllStorageTypes(convertStorageTypes(blk.getStorageTypes())) 440 .build(); 441 } 442 443 public static BlockWithLocations convert(BlockWithLocationsProto b) { 444 final List<String> datanodeUuids = b.getDatanodeUuidsList(); 445 final List<String> storageUuids = b.getStorageUuidsList(); 446 final List<StorageTypeProto> storageTypes = b.getStorageTypesList(); 447 return new BlockWithLocations(convert(b.getBlock()), 448 datanodeUuids.toArray(new String[datanodeUuids.size()]), 449 storageUuids.toArray(new String[storageUuids.size()]), 450 convertStorageTypes(storageTypes, storageUuids.size())); 451 } 452 453 public static BlocksWithLocationsProto convert(BlocksWithLocations blks) { 454 BlocksWithLocationsProto.Builder builder = BlocksWithLocationsProto 455 .newBuilder(); 456 for (BlockWithLocations b : blks.getBlocks()) { 457 builder.addBlocks(convert(b)); 458 } 459 return builder.build(); 460 } 461 462 public static BlocksWithLocations convert(BlocksWithLocationsProto blocks) { 463 List<BlockWithLocationsProto> b = blocks.getBlocksList(); 464 BlockWithLocations[] ret = new BlockWithLocations[b.size()]; 465 int i = 0; 466 for (BlockWithLocationsProto entry : b) { 467 ret[i++] = convert(entry); 468 } 469 return new BlocksWithLocations(ret); 470 } 471 472 public static BlockKeyProto convert(BlockKey key) { 473 byte[] encodedKey = key.getEncodedKey(); 474 ByteString keyBytes = ByteString.copyFrom(encodedKey == null ? 475 DFSUtil.EMPTY_BYTES : encodedKey); 476 return BlockKeyProto.newBuilder().setKeyId(key.getKeyId()) 477 .setKeyBytes(keyBytes).setExpiryDate(key.getExpiryDate()).build(); 478 } 479 480 public static BlockKey convert(BlockKeyProto k) { 481 return new BlockKey(k.getKeyId(), k.getExpiryDate(), k.getKeyBytes() 482 .toByteArray()); 483 } 484 485 public static ExportedBlockKeysProto convert(ExportedBlockKeys keys) { 486 ExportedBlockKeysProto.Builder builder = ExportedBlockKeysProto 487 .newBuilder(); 488 builder.setIsBlockTokenEnabled(keys.isBlockTokenEnabled()) 489 .setKeyUpdateInterval(keys.getKeyUpdateInterval()) 490 .setTokenLifeTime(keys.getTokenLifetime()) 491 .setCurrentKey(convert(keys.getCurrentKey())); 492 for (BlockKey k : keys.getAllKeys()) { 493 builder.addAllKeys(convert(k)); 494 } 495 return builder.build(); 496 } 497 498 public static ExportedBlockKeys convert(ExportedBlockKeysProto keys) { 499 return new ExportedBlockKeys(keys.getIsBlockTokenEnabled(), 500 keys.getKeyUpdateInterval(), keys.getTokenLifeTime(), 501 convert(keys.getCurrentKey()), convertBlockKeys(keys.getAllKeysList())); 502 } 503 504 public static CheckpointSignatureProto convert(CheckpointSignature s) { 505 return CheckpointSignatureProto.newBuilder() 506 .setBlockPoolId(s.getBlockpoolID()) 507 .setCurSegmentTxId(s.getCurSegmentTxId()) 508 .setMostRecentCheckpointTxId(s.getMostRecentCheckpointTxId()) 509 .setStorageInfo(PBHelper.convert((StorageInfo) s)).build(); 510 } 511 512 public static CheckpointSignature convert(CheckpointSignatureProto s) { 513 StorageInfo si = PBHelper.convert(s.getStorageInfo(), NodeType.NAME_NODE); 514 return new CheckpointSignature(si, s.getBlockPoolId(), 515 s.getMostRecentCheckpointTxId(), s.getCurSegmentTxId()); 516 } 517 518 public static RemoteEditLogProto convert(RemoteEditLog log) { 519 return RemoteEditLogProto.newBuilder() 520 .setStartTxId(log.getStartTxId()) 521 .setEndTxId(log.getEndTxId()) 522 .setIsInProgress(log.isInProgress()).build(); 523 } 524 525 public static RemoteEditLog convert(RemoteEditLogProto l) { 526 return new RemoteEditLog(l.getStartTxId(), l.getEndTxId(), 527 l.getIsInProgress()); 528 } 529 530 public static RemoteEditLogManifestProto convert( 531 RemoteEditLogManifest manifest) { 532 RemoteEditLogManifestProto.Builder builder = RemoteEditLogManifestProto 533 .newBuilder(); 534 for (RemoteEditLog log : manifest.getLogs()) { 535 builder.addLogs(convert(log)); 536 } 537 return builder.build(); 538 } 539 540 public static RemoteEditLogManifest convert( 541 RemoteEditLogManifestProto manifest) { 542 List<RemoteEditLog> logs = new ArrayList<RemoteEditLog>(manifest 543 .getLogsList().size()); 544 for (RemoteEditLogProto l : manifest.getLogsList()) { 545 logs.add(convert(l)); 546 } 547 return new RemoteEditLogManifest(logs); 548 } 549 550 public static CheckpointCommandProto convert(CheckpointCommand cmd) { 551 return CheckpointCommandProto.newBuilder() 552 .setSignature(convert(cmd.getSignature())) 553 .setNeedToReturnImage(cmd.needToReturnImage()).build(); 554 } 555 556 public static NamenodeCommandProto convert(NamenodeCommand cmd) { 557 if (cmd instanceof CheckpointCommand) { 558 return NamenodeCommandProto.newBuilder().setAction(cmd.getAction()) 559 .setType(NamenodeCommandProto.Type.CheckPointCommand) 560 .setCheckpointCmd(convert((CheckpointCommand) cmd)).build(); 561 } 562 return NamenodeCommandProto.newBuilder() 563 .setType(NamenodeCommandProto.Type.NamenodeCommand) 564 .setAction(cmd.getAction()).build(); 565 } 566 567 public static BlockKey[] convertBlockKeys(List<BlockKeyProto> list) { 568 BlockKey[] ret = new BlockKey[list.size()]; 569 int i = 0; 570 for (BlockKeyProto k : list) { 571 ret[i++] = convert(k); 572 } 573 return ret; 574 } 575 576 public static NamespaceInfo convert(NamespaceInfoProto info) { 577 StorageInfoProto storage = info.getStorageInfo(); 578 return new NamespaceInfo(storage.getNamespceID(), storage.getClusterID(), 579 info.getBlockPoolID(), storage.getCTime(), info.getBuildVersion(), 580 info.getSoftwareVersion(), info.getCapabilities()); 581 } 582 583 public static NamenodeCommand convert(NamenodeCommandProto cmd) { 584 if (cmd == null) return null; 585 switch (cmd.getType()) { 586 case CheckPointCommand: 587 CheckpointCommandProto chkPt = cmd.getCheckpointCmd(); 588 return new CheckpointCommand(PBHelper.convert(chkPt.getSignature()), 589 chkPt.getNeedToReturnImage()); 590 default: 591 return new NamenodeCommand(cmd.getAction()); 592 } 593 } 594 595 public static ExtendedBlock convert(ExtendedBlockProto eb) { 596 if (eb == null) return null; 597 return new ExtendedBlock( eb.getPoolId(), eb.getBlockId(), eb.getNumBytes(), 598 eb.getGenerationStamp()); 599 } 600 601 public static ExtendedBlockProto convert(final ExtendedBlock b) { 602 if (b == null) return null; 603 return ExtendedBlockProto.newBuilder(). 604 setPoolId(b.getBlockPoolId()). 605 setBlockId(b.getBlockId()). 606 setNumBytes(b.getNumBytes()). 607 setGenerationStamp(b.getGenerationStamp()). 608 build(); 609 } 610 611 public static RecoveringBlockProto convert(RecoveringBlock b) { 612 if (b == null) { 613 return null; 614 } 615 LocatedBlockProto lb = PBHelper.convert((LocatedBlock)b); 616 RecoveringBlockProto.Builder builder = RecoveringBlockProto.newBuilder(); 617 builder.setBlock(lb).setNewGenStamp(b.getNewGenerationStamp()); 618 if(b.getNewBlock() != null) 619 builder.setTruncateBlock(PBHelper.convert(b.getNewBlock())); 620 return builder.build(); 621 } 622 623 public static RecoveringBlock convert(RecoveringBlockProto b) { 624 ExtendedBlock block = convert(b.getBlock().getB()); 625 DatanodeInfo[] locs = convert(b.getBlock().getLocsList()); 626 return (b.hasTruncateBlock()) ? 627 new RecoveringBlock(block, locs, PBHelper.convert(b.getTruncateBlock())) : 628 new RecoveringBlock(block, locs, b.getNewGenStamp()); 629 } 630 631 public static DatanodeInfoProto.AdminState convert( 632 final DatanodeInfo.AdminStates inAs) { 633 switch (inAs) { 634 case NORMAL: return DatanodeInfoProto.AdminState.NORMAL; 635 case DECOMMISSION_INPROGRESS: 636 return DatanodeInfoProto.AdminState.DECOMMISSION_INPROGRESS; 637 case DECOMMISSIONED: return DatanodeInfoProto.AdminState.DECOMMISSIONED; 638 default: return DatanodeInfoProto.AdminState.NORMAL; 639 } 640 } 641 642 static public DatanodeInfo convert(DatanodeInfoProto di) { 643 if (di == null) return null; 644 return new DatanodeInfo( 645 PBHelper.convert(di.getId()), 646 di.hasLocation() ? di.getLocation() : null , 647 di.getCapacity(), di.getDfsUsed(), di.getRemaining(), 648 di.getBlockPoolUsed(), di.getCacheCapacity(), di.getCacheUsed(), 649 di.getLastUpdate(), di.getLastUpdateMonotonic(), 650 di.getXceiverCount(), PBHelper.convert(di.getAdminState())); 651 } 652 653 static public DatanodeInfoProto convertDatanodeInfo(DatanodeInfo di) { 654 if (di == null) return null; 655 return convert(di); 656 } 657 658 659 static public DatanodeInfo[] convert(DatanodeInfoProto di[]) { 660 if (di == null) return null; 661 DatanodeInfo[] result = new DatanodeInfo[di.length]; 662 for (int i = 0; i < di.length; i++) { 663 result[i] = convert(di[i]); 664 } 665 return result; 666 } 667 668 public static List<? extends HdfsProtos.DatanodeInfoProto> convert( 669 DatanodeInfo[] dnInfos) { 670 return convert(dnInfos, 0); 671 } 672 673 /** 674 * Copy from {@code dnInfos} to a target of list of same size starting at 675 * {@code startIdx}. 676 */ 677 public static List<? extends HdfsProtos.DatanodeInfoProto> convert( 678 DatanodeInfo[] dnInfos, int startIdx) { 679 if (dnInfos == null) 680 return null; 681 ArrayList<HdfsProtos.DatanodeInfoProto> protos = Lists 682 .newArrayListWithCapacity(dnInfos.length); 683 for (int i = startIdx; i < dnInfos.length; i++) { 684 protos.add(convert(dnInfos[i])); 685 } 686 return protos; 687 } 688 689 public static DatanodeInfo[] convert(List<DatanodeInfoProto> list) { 690 DatanodeInfo[] info = new DatanodeInfo[list.size()]; 691 for (int i = 0; i < info.length; i++) { 692 info[i] = convert(list.get(i)); 693 } 694 return info; 695 } 696 697 public static DatanodeInfoProto convert(DatanodeInfo info) { 698 DatanodeInfoProto.Builder builder = DatanodeInfoProto.newBuilder(); 699 if (info.getNetworkLocation() != null) { 700 builder.setLocation(info.getNetworkLocation()); 701 } 702 builder 703 .setId(PBHelper.convert((DatanodeID)info)) 704 .setCapacity(info.getCapacity()) 705 .setDfsUsed(info.getDfsUsed()) 706 .setRemaining(info.getRemaining()) 707 .setBlockPoolUsed(info.getBlockPoolUsed()) 708 .setCacheCapacity(info.getCacheCapacity()) 709 .setCacheUsed(info.getCacheUsed()) 710 .setLastUpdate(info.getLastUpdate()) 711 .setLastUpdateMonotonic(info.getLastUpdateMonotonic()) 712 .setXceiverCount(info.getXceiverCount()) 713 .setAdminState(PBHelper.convert(info.getAdminState())) 714 .build(); 715 return builder.build(); 716 } 717 718 public static DatanodeStorageReportProto convertDatanodeStorageReport( 719 DatanodeStorageReport report) { 720 return DatanodeStorageReportProto.newBuilder() 721 .setDatanodeInfo(convert(report.getDatanodeInfo())) 722 .addAllStorageReports(convertStorageReports(report.getStorageReports())) 723 .build(); 724 } 725 726 public static List<DatanodeStorageReportProto> convertDatanodeStorageReports( 727 DatanodeStorageReport[] reports) { 728 final List<DatanodeStorageReportProto> protos 729 = new ArrayList<DatanodeStorageReportProto>(reports.length); 730 for(int i = 0; i < reports.length; i++) { 731 protos.add(convertDatanodeStorageReport(reports[i])); 732 } 733 return protos; 734 } 735 736 public static DatanodeStorageReport convertDatanodeStorageReport( 737 DatanodeStorageReportProto proto) { 738 return new DatanodeStorageReport( 739 convert(proto.getDatanodeInfo()), 740 convertStorageReports(proto.getStorageReportsList())); 741 } 742 743 public static DatanodeStorageReport[] convertDatanodeStorageReports( 744 List<DatanodeStorageReportProto> protos) { 745 final DatanodeStorageReport[] reports 746 = new DatanodeStorageReport[protos.size()]; 747 for(int i = 0; i < reports.length; i++) { 748 reports[i] = convertDatanodeStorageReport(protos.get(i)); 749 } 750 return reports; 751 } 752 753 public static AdminStates convert(AdminState adminState) { 754 switch(adminState) { 755 case DECOMMISSION_INPROGRESS: 756 return AdminStates.DECOMMISSION_INPROGRESS; 757 case DECOMMISSIONED: 758 return AdminStates.DECOMMISSIONED; 759 case NORMAL: 760 default: 761 return AdminStates.NORMAL; 762 } 763 } 764 765 public static LocatedBlockProto convert(LocatedBlock b) { 766 if (b == null) return null; 767 Builder builder = LocatedBlockProto.newBuilder(); 768 DatanodeInfo[] locs = b.getLocations(); 769 List<DatanodeInfo> cachedLocs = 770 Lists.newLinkedList(Arrays.asList(b.getCachedLocations())); 771 for (int i = 0; i < locs.length; i++) { 772 DatanodeInfo loc = locs[i]; 773 builder.addLocs(i, PBHelper.convert(loc)); 774 boolean locIsCached = cachedLocs.contains(loc); 775 builder.addIsCached(locIsCached); 776 if (locIsCached) { 777 cachedLocs.remove(loc); 778 } 779 } 780 Preconditions.checkArgument(cachedLocs.size() == 0, 781 "Found additional cached replica locations that are not in the set of" 782 + " storage-backed locations!"); 783 784 StorageType[] storageTypes = b.getStorageTypes(); 785 if (storageTypes != null) { 786 for (int i = 0; i < storageTypes.length; ++i) { 787 builder.addStorageTypes(PBHelper.convertStorageType(storageTypes[i])); 788 } 789 } 790 final String[] storageIDs = b.getStorageIDs(); 791 if (storageIDs != null) { 792 builder.addAllStorageIDs(Arrays.asList(storageIDs)); 793 } 794 795 return builder.setB(PBHelper.convert(b.getBlock())) 796 .setBlockToken(PBHelper.convert(b.getBlockToken())) 797 .setCorrupt(b.isCorrupt()).setOffset(b.getStartOffset()).build(); 798 } 799 800 public static LocatedBlock convert(LocatedBlockProto proto) { 801 if (proto == null) return null; 802 List<DatanodeInfoProto> locs = proto.getLocsList(); 803 DatanodeInfo[] targets = new DatanodeInfo[locs.size()]; 804 for (int i = 0; i < locs.size(); i++) { 805 targets[i] = PBHelper.convert(locs.get(i)); 806 } 807 808 final StorageType[] storageTypes = convertStorageTypes( 809 proto.getStorageTypesList(), locs.size()); 810 811 final int storageIDsCount = proto.getStorageIDsCount(); 812 final String[] storageIDs; 813 if (storageIDsCount == 0) { 814 storageIDs = null; 815 } else { 816 Preconditions.checkState(storageIDsCount == locs.size()); 817 storageIDs = proto.getStorageIDsList().toArray(new String[storageIDsCount]); 818 } 819 820 // Set values from the isCached list, re-using references from loc 821 List<DatanodeInfo> cachedLocs = new ArrayList<DatanodeInfo>(locs.size()); 822 List<Boolean> isCachedList = proto.getIsCachedList(); 823 for (int i=0; i<isCachedList.size(); i++) { 824 if (isCachedList.get(i)) { 825 cachedLocs.add(targets[i]); 826 } 827 } 828 829 LocatedBlock lb = new LocatedBlock(PBHelper.convert(proto.getB()), targets, 830 storageIDs, storageTypes, proto.getOffset(), proto.getCorrupt(), 831 cachedLocs.toArray(new DatanodeInfo[0])); 832 lb.setBlockToken(PBHelper.convert(proto.getBlockToken())); 833 834 return lb; 835 } 836 837 public static TokenProto convert(Token<?> tok) { 838 return TokenProto.newBuilder(). 839 setIdentifier(ByteString.copyFrom(tok.getIdentifier())). 840 setPassword(ByteString.copyFrom(tok.getPassword())). 841 setKind(tok.getKind().toString()). 842 setService(tok.getService().toString()).build(); 843 } 844 845 public static Token<BlockTokenIdentifier> convert( 846 TokenProto blockToken) { 847 return new Token<BlockTokenIdentifier>(blockToken.getIdentifier() 848 .toByteArray(), blockToken.getPassword().toByteArray(), new Text( 849 blockToken.getKind()), new Text(blockToken.getService())); 850 } 851 852 853 public static Token<DelegationTokenIdentifier> convertDelegationToken( 854 TokenProto blockToken) { 855 return new Token<DelegationTokenIdentifier>(blockToken.getIdentifier() 856 .toByteArray(), blockToken.getPassword().toByteArray(), new Text( 857 blockToken.getKind()), new Text(blockToken.getService())); 858 } 859 860 public static ReplicaState convert(ReplicaStateProto state) { 861 switch (state) { 862 case RBW: 863 return ReplicaState.RBW; 864 case RUR: 865 return ReplicaState.RUR; 866 case RWR: 867 return ReplicaState.RWR; 868 case TEMPORARY: 869 return ReplicaState.TEMPORARY; 870 case FINALIZED: 871 default: 872 return ReplicaState.FINALIZED; 873 } 874 } 875 876 public static ReplicaStateProto convert(ReplicaState state) { 877 switch (state) { 878 case RBW: 879 return ReplicaStateProto.RBW; 880 case RUR: 881 return ReplicaStateProto.RUR; 882 case RWR: 883 return ReplicaStateProto.RWR; 884 case TEMPORARY: 885 return ReplicaStateProto.TEMPORARY; 886 case FINALIZED: 887 default: 888 return ReplicaStateProto.FINALIZED; 889 } 890 } 891 892 public static DatanodeRegistrationProto convert( 893 DatanodeRegistration registration) { 894 DatanodeRegistrationProto.Builder builder = DatanodeRegistrationProto 895 .newBuilder(); 896 return builder.setDatanodeID(PBHelper.convert((DatanodeID) registration)) 897 .setStorageInfo(PBHelper.convert(registration.getStorageInfo())) 898 .setKeys(PBHelper.convert(registration.getExportedKeys())) 899 .setSoftwareVersion(registration.getSoftwareVersion()).build(); 900 } 901 902 public static DatanodeRegistration convert(DatanodeRegistrationProto proto) { 903 StorageInfo si = convert(proto.getStorageInfo(), NodeType.DATA_NODE); 904 return new DatanodeRegistration(PBHelper.convert(proto.getDatanodeID()), 905 si, PBHelper.convert(proto.getKeys()), proto.getSoftwareVersion()); 906 } 907 908 public static DatanodeCommand convert(DatanodeCommandProto proto) { 909 switch (proto.getCmdType()) { 910 case BalancerBandwidthCommand: 911 return PBHelper.convert(proto.getBalancerCmd()); 912 case BlockCommand: 913 return PBHelper.convert(proto.getBlkCmd()); 914 case BlockRecoveryCommand: 915 return PBHelper.convert(proto.getRecoveryCmd()); 916 case FinalizeCommand: 917 return PBHelper.convert(proto.getFinalizeCmd()); 918 case KeyUpdateCommand: 919 return PBHelper.convert(proto.getKeyUpdateCmd()); 920 case RegisterCommand: 921 return REG_CMD; 922 case BlockIdCommand: 923 return PBHelper.convert(proto.getBlkIdCmd()); 924 default: 925 return null; 926 } 927 } 928 929 public static BalancerBandwidthCommandProto convert( 930 BalancerBandwidthCommand bbCmd) { 931 return BalancerBandwidthCommandProto.newBuilder() 932 .setBandwidth(bbCmd.getBalancerBandwidthValue()).build(); 933 } 934 935 public static KeyUpdateCommandProto convert(KeyUpdateCommand cmd) { 936 return KeyUpdateCommandProto.newBuilder() 937 .setKeys(PBHelper.convert(cmd.getExportedKeys())).build(); 938 } 939 940 public static BlockRecoveryCommandProto convert(BlockRecoveryCommand cmd) { 941 BlockRecoveryCommandProto.Builder builder = BlockRecoveryCommandProto 942 .newBuilder(); 943 for (RecoveringBlock b : cmd.getRecoveringBlocks()) { 944 builder.addBlocks(PBHelper.convert(b)); 945 } 946 return builder.build(); 947 } 948 949 public static FinalizeCommandProto convert(FinalizeCommand cmd) { 950 return FinalizeCommandProto.newBuilder() 951 .setBlockPoolId(cmd.getBlockPoolId()).build(); 952 } 953 954 public static BlockCommandProto convert(BlockCommand cmd) { 955 BlockCommandProto.Builder builder = BlockCommandProto.newBuilder() 956 .setBlockPoolId(cmd.getBlockPoolId()); 957 switch (cmd.getAction()) { 958 case DatanodeProtocol.DNA_TRANSFER: 959 builder.setAction(BlockCommandProto.Action.TRANSFER); 960 break; 961 case DatanodeProtocol.DNA_INVALIDATE: 962 builder.setAction(BlockCommandProto.Action.INVALIDATE); 963 break; 964 case DatanodeProtocol.DNA_SHUTDOWN: 965 builder.setAction(BlockCommandProto.Action.SHUTDOWN); 966 break; 967 default: 968 throw new AssertionError("Invalid action"); 969 } 970 Block[] blocks = cmd.getBlocks(); 971 for (int i = 0; i < blocks.length; i++) { 972 builder.addBlocks(PBHelper.convert(blocks[i])); 973 } 974 builder.addAllTargets(convert(cmd.getTargets())) 975 .addAllTargetStorageUuids(convert(cmd.getTargetStorageIDs())); 976 StorageType[][] types = cmd.getTargetStorageTypes(); 977 if (types != null) { 978 builder.addAllTargetStorageTypes(convert(types)); 979 } 980 return builder.build(); 981 } 982 983 private static List<StorageTypesProto> convert(StorageType[][] types) { 984 List<StorageTypesProto> list = Lists.newArrayList(); 985 if (types != null) { 986 for (StorageType[] ts : types) { 987 StorageTypesProto.Builder builder = StorageTypesProto.newBuilder(); 988 builder.addAllStorageTypes(convertStorageTypes(ts)); 989 list.add(builder.build()); 990 } 991 } 992 return list; 993 } 994 995 public static BlockIdCommandProto convert(BlockIdCommand cmd) { 996 BlockIdCommandProto.Builder builder = BlockIdCommandProto.newBuilder() 997 .setBlockPoolId(cmd.getBlockPoolId()); 998 switch (cmd.getAction()) { 999 case DatanodeProtocol.DNA_CACHE: 1000 builder.setAction(BlockIdCommandProto.Action.CACHE); 1001 break; 1002 case DatanodeProtocol.DNA_UNCACHE: 1003 builder.setAction(BlockIdCommandProto.Action.UNCACHE); 1004 break; 1005 default: 1006 throw new AssertionError("Invalid action"); 1007 } 1008 long[] blockIds = cmd.getBlockIds(); 1009 for (int i = 0; i < blockIds.length; i++) { 1010 builder.addBlockIds(blockIds[i]); 1011 } 1012 return builder.build(); 1013 } 1014 1015 private static List<DatanodeInfosProto> convert(DatanodeInfo[][] targets) { 1016 DatanodeInfosProto[] ret = new DatanodeInfosProto[targets.length]; 1017 for (int i = 0; i < targets.length; i++) { 1018 ret[i] = DatanodeInfosProto.newBuilder() 1019 .addAllDatanodes(PBHelper.convert(targets[i])).build(); 1020 } 1021 return Arrays.asList(ret); 1022 } 1023 1024 private static List<StorageUuidsProto> convert(String[][] targetStorageUuids) { 1025 StorageUuidsProto[] ret = new StorageUuidsProto[targetStorageUuids.length]; 1026 for (int i = 0; i < targetStorageUuids.length; i++) { 1027 ret[i] = StorageUuidsProto.newBuilder() 1028 .addAllStorageUuids(Arrays.asList(targetStorageUuids[i])).build(); 1029 } 1030 return Arrays.asList(ret); 1031 } 1032 1033 public static DatanodeCommandProto convert(DatanodeCommand datanodeCommand) { 1034 DatanodeCommandProto.Builder builder = DatanodeCommandProto.newBuilder(); 1035 if (datanodeCommand == null) { 1036 return builder.setCmdType(DatanodeCommandProto.Type.NullDatanodeCommand) 1037 .build(); 1038 } 1039 switch (datanodeCommand.getAction()) { 1040 case DatanodeProtocol.DNA_BALANCERBANDWIDTHUPDATE: 1041 builder.setCmdType(DatanodeCommandProto.Type.BalancerBandwidthCommand) 1042 .setBalancerCmd( 1043 PBHelper.convert((BalancerBandwidthCommand) datanodeCommand)); 1044 break; 1045 case DatanodeProtocol.DNA_ACCESSKEYUPDATE: 1046 builder 1047 .setCmdType(DatanodeCommandProto.Type.KeyUpdateCommand) 1048 .setKeyUpdateCmd(PBHelper.convert((KeyUpdateCommand) datanodeCommand)); 1049 break; 1050 case DatanodeProtocol.DNA_RECOVERBLOCK: 1051 builder.setCmdType(DatanodeCommandProto.Type.BlockRecoveryCommand) 1052 .setRecoveryCmd( 1053 PBHelper.convert((BlockRecoveryCommand) datanodeCommand)); 1054 break; 1055 case DatanodeProtocol.DNA_FINALIZE: 1056 builder.setCmdType(DatanodeCommandProto.Type.FinalizeCommand) 1057 .setFinalizeCmd(PBHelper.convert((FinalizeCommand) datanodeCommand)); 1058 break; 1059 case DatanodeProtocol.DNA_REGISTER: 1060 builder.setCmdType(DatanodeCommandProto.Type.RegisterCommand) 1061 .setRegisterCmd(REG_CMD_PROTO); 1062 break; 1063 case DatanodeProtocol.DNA_TRANSFER: 1064 case DatanodeProtocol.DNA_INVALIDATE: 1065 case DatanodeProtocol.DNA_SHUTDOWN: 1066 builder.setCmdType(DatanodeCommandProto.Type.BlockCommand). 1067 setBlkCmd(PBHelper.convert((BlockCommand) datanodeCommand)); 1068 break; 1069 case DatanodeProtocol.DNA_CACHE: 1070 case DatanodeProtocol.DNA_UNCACHE: 1071 builder.setCmdType(DatanodeCommandProto.Type.BlockIdCommand). 1072 setBlkIdCmd(PBHelper.convert((BlockIdCommand) datanodeCommand)); 1073 break; 1074 case DatanodeProtocol.DNA_UNKNOWN: //Not expected 1075 default: 1076 builder.setCmdType(DatanodeCommandProto.Type.NullDatanodeCommand); 1077 } 1078 return builder.build(); 1079 } 1080 1081 public static KeyUpdateCommand convert(KeyUpdateCommandProto keyUpdateCmd) { 1082 return new KeyUpdateCommand(PBHelper.convert(keyUpdateCmd.getKeys())); 1083 } 1084 1085 public static FinalizeCommand convert(FinalizeCommandProto finalizeCmd) { 1086 return new FinalizeCommand(finalizeCmd.getBlockPoolId()); 1087 } 1088 1089 public static BlockRecoveryCommand convert( 1090 BlockRecoveryCommandProto recoveryCmd) { 1091 List<RecoveringBlockProto> list = recoveryCmd.getBlocksList(); 1092 List<RecoveringBlock> recoveringBlocks = new ArrayList<RecoveringBlock>( 1093 list.size()); 1094 1095 for (RecoveringBlockProto rbp : list) { 1096 recoveringBlocks.add(PBHelper.convert(rbp)); 1097 } 1098 return new BlockRecoveryCommand(recoveringBlocks); 1099 } 1100 1101 public static BlockCommand convert(BlockCommandProto blkCmd) { 1102 List<BlockProto> blockProtoList = blkCmd.getBlocksList(); 1103 Block[] blocks = new Block[blockProtoList.size()]; 1104 for (int i = 0; i < blockProtoList.size(); i++) { 1105 blocks[i] = PBHelper.convert(blockProtoList.get(i)); 1106 } 1107 List<DatanodeInfosProto> targetList = blkCmd.getTargetsList(); 1108 DatanodeInfo[][] targets = new DatanodeInfo[targetList.size()][]; 1109 for (int i = 0; i < targetList.size(); i++) { 1110 targets[i] = PBHelper.convert(targetList.get(i)); 1111 } 1112 1113 StorageType[][] targetStorageTypes = new StorageType[targetList.size()][]; 1114 List<StorageTypesProto> targetStorageTypesList = blkCmd.getTargetStorageTypesList(); 1115 if (targetStorageTypesList.isEmpty()) { // missing storage types 1116 for(int i = 0; i < targetStorageTypes.length; i++) { 1117 targetStorageTypes[i] = new StorageType[targets[i].length]; 1118 Arrays.fill(targetStorageTypes[i], StorageType.DEFAULT); 1119 } 1120 } else { 1121 for(int i = 0; i < targetStorageTypes.length; i++) { 1122 List<StorageTypeProto> p = targetStorageTypesList.get(i).getStorageTypesList(); 1123 targetStorageTypes[i] = convertStorageTypes(p, targets[i].length); 1124 } 1125 } 1126 1127 List<StorageUuidsProto> targetStorageUuidsList = blkCmd.getTargetStorageUuidsList(); 1128 String[][] targetStorageIDs = new String[targetStorageUuidsList.size()][]; 1129 for(int i = 0; i < targetStorageIDs.length; i++) { 1130 List<String> storageIDs = targetStorageUuidsList.get(i).getStorageUuidsList(); 1131 targetStorageIDs[i] = storageIDs.toArray(new String[storageIDs.size()]); 1132 } 1133 1134 int action = DatanodeProtocol.DNA_UNKNOWN; 1135 switch (blkCmd.getAction()) { 1136 case TRANSFER: 1137 action = DatanodeProtocol.DNA_TRANSFER; 1138 break; 1139 case INVALIDATE: 1140 action = DatanodeProtocol.DNA_INVALIDATE; 1141 break; 1142 case SHUTDOWN: 1143 action = DatanodeProtocol.DNA_SHUTDOWN; 1144 break; 1145 default: 1146 throw new AssertionError("Unknown action type: " + blkCmd.getAction()); 1147 } 1148 return new BlockCommand(action, blkCmd.getBlockPoolId(), blocks, targets, 1149 targetStorageTypes, targetStorageIDs); 1150 } 1151 1152 public static BlockIdCommand convert(BlockIdCommandProto blkIdCmd) { 1153 int numBlockIds = blkIdCmd.getBlockIdsCount(); 1154 long blockIds[] = new long[numBlockIds]; 1155 for (int i = 0; i < numBlockIds; i++) { 1156 blockIds[i] = blkIdCmd.getBlockIds(i); 1157 } 1158 int action = DatanodeProtocol.DNA_UNKNOWN; 1159 switch (blkIdCmd.getAction()) { 1160 case CACHE: 1161 action = DatanodeProtocol.DNA_CACHE; 1162 break; 1163 case UNCACHE: 1164 action = DatanodeProtocol.DNA_UNCACHE; 1165 break; 1166 default: 1167 throw new AssertionError("Unknown action type: " + blkIdCmd.getAction()); 1168 } 1169 return new BlockIdCommand(action, blkIdCmd.getBlockPoolId(), blockIds); 1170 } 1171 1172 public static DatanodeInfo[] convert(DatanodeInfosProto datanodeInfosProto) { 1173 List<DatanodeInfoProto> proto = datanodeInfosProto.getDatanodesList(); 1174 DatanodeInfo[] infos = new DatanodeInfo[proto.size()]; 1175 for (int i = 0; i < infos.length; i++) { 1176 infos[i] = PBHelper.convert(proto.get(i)); 1177 } 1178 return infos; 1179 } 1180 1181 public static BalancerBandwidthCommand convert( 1182 BalancerBandwidthCommandProto balancerCmd) { 1183 return new BalancerBandwidthCommand(balancerCmd.getBandwidth()); 1184 } 1185 1186 public static ReceivedDeletedBlockInfoProto convert( 1187 ReceivedDeletedBlockInfo receivedDeletedBlockInfo) { 1188 ReceivedDeletedBlockInfoProto.Builder builder = 1189 ReceivedDeletedBlockInfoProto.newBuilder(); 1190 1191 ReceivedDeletedBlockInfoProto.BlockStatus status; 1192 switch (receivedDeletedBlockInfo.getStatus()) { 1193 case RECEIVING_BLOCK: 1194 status = ReceivedDeletedBlockInfoProto.BlockStatus.RECEIVING; 1195 break; 1196 case RECEIVED_BLOCK: 1197 status = ReceivedDeletedBlockInfoProto.BlockStatus.RECEIVED; 1198 break; 1199 case DELETED_BLOCK: 1200 status = ReceivedDeletedBlockInfoProto.BlockStatus.DELETED; 1201 break; 1202 default: 1203 throw new IllegalArgumentException("Bad status: " + 1204 receivedDeletedBlockInfo.getStatus()); 1205 } 1206 builder.setStatus(status); 1207 1208 if (receivedDeletedBlockInfo.getDelHints() != null) { 1209 builder.setDeleteHint(receivedDeletedBlockInfo.getDelHints()); 1210 } 1211 return builder.setBlock(PBHelper.convert(receivedDeletedBlockInfo.getBlock())) 1212 .build(); 1213 } 1214 1215 public static ReceivedDeletedBlockInfo convert( 1216 ReceivedDeletedBlockInfoProto proto) { 1217 ReceivedDeletedBlockInfo.BlockStatus status = null; 1218 switch (proto.getStatus()) { 1219 case RECEIVING: 1220 status = BlockStatus.RECEIVING_BLOCK; 1221 break; 1222 case RECEIVED: 1223 status = BlockStatus.RECEIVED_BLOCK; 1224 break; 1225 case DELETED: 1226 status = BlockStatus.DELETED_BLOCK; 1227 break; 1228 } 1229 return new ReceivedDeletedBlockInfo( 1230 PBHelper.convert(proto.getBlock()), 1231 status, 1232 proto.hasDeleteHint() ? proto.getDeleteHint() : null); 1233 } 1234 1235 public static NamespaceInfoProto convert(NamespaceInfo info) { 1236 return NamespaceInfoProto.newBuilder() 1237 .setBlockPoolID(info.getBlockPoolID()) 1238 .setBuildVersion(info.getBuildVersion()) 1239 .setUnused(0) 1240 .setStorageInfo(PBHelper.convert((StorageInfo)info)) 1241 .setSoftwareVersion(info.getSoftwareVersion()) 1242 .setCapabilities(info.getCapabilities()) 1243 .build(); 1244 } 1245 1246 // Located Block Arrays and Lists 1247 public static LocatedBlockProto[] convertLocatedBlock(LocatedBlock[] lb) { 1248 if (lb == null) return null; 1249 return convertLocatedBlock2(Arrays.asList(lb)).toArray( 1250 new LocatedBlockProto[lb.length]); 1251 } 1252 1253 public static LocatedBlock[] convertLocatedBlock(LocatedBlockProto[] lb) { 1254 if (lb == null) return null; 1255 return convertLocatedBlock(Arrays.asList(lb)).toArray( 1256 new LocatedBlock[lb.length]); 1257 } 1258 1259 public static List<LocatedBlock> convertLocatedBlock( 1260 List<LocatedBlockProto> lb) { 1261 if (lb == null) return null; 1262 final int len = lb.size(); 1263 List<LocatedBlock> result = 1264 new ArrayList<LocatedBlock>(len); 1265 for (int i = 0; i < len; ++i) { 1266 result.add(PBHelper.convert(lb.get(i))); 1267 } 1268 return result; 1269 } 1270 1271 public static List<LocatedBlockProto> convertLocatedBlock2(List<LocatedBlock> lb) { 1272 if (lb == null) return null; 1273 final int len = lb.size(); 1274 List<LocatedBlockProto> result = new ArrayList<LocatedBlockProto>(len); 1275 for (int i = 0; i < len; ++i) { 1276 result.add(PBHelper.convert(lb.get(i))); 1277 } 1278 return result; 1279 } 1280 1281 1282 // LocatedBlocks 1283 public static LocatedBlocks convert(LocatedBlocksProto lb) { 1284 return new LocatedBlocks( 1285 lb.getFileLength(), lb.getUnderConstruction(), 1286 PBHelper.convertLocatedBlock(lb.getBlocksList()), 1287 lb.hasLastBlock() ? PBHelper.convert(lb.getLastBlock()) : null, 1288 lb.getIsLastBlockComplete(), 1289 lb.hasFileEncryptionInfo() ? convert(lb.getFileEncryptionInfo()) : 1290 null); 1291 } 1292 1293 public static LocatedBlocksProto convert(LocatedBlocks lb) { 1294 if (lb == null) { 1295 return null; 1296 } 1297 LocatedBlocksProto.Builder builder = 1298 LocatedBlocksProto.newBuilder(); 1299 if (lb.getLastLocatedBlock() != null) { 1300 builder.setLastBlock(PBHelper.convert(lb.getLastLocatedBlock())); 1301 } 1302 if (lb.getFileEncryptionInfo() != null) { 1303 builder.setFileEncryptionInfo(convert(lb.getFileEncryptionInfo())); 1304 } 1305 return builder.setFileLength(lb.getFileLength()) 1306 .setUnderConstruction(lb.isUnderConstruction()) 1307 .addAllBlocks(PBHelper.convertLocatedBlock2(lb.getLocatedBlocks())) 1308 .setIsLastBlockComplete(lb.isLastBlockComplete()).build(); 1309 } 1310 1311 // DataEncryptionKey 1312 public static DataEncryptionKey convert(DataEncryptionKeyProto bet) { 1313 String encryptionAlgorithm = bet.getEncryptionAlgorithm(); 1314 return new DataEncryptionKey(bet.getKeyId(), 1315 bet.getBlockPoolId(), 1316 bet.getNonce().toByteArray(), 1317 bet.getEncryptionKey().toByteArray(), 1318 bet.getExpiryDate(), 1319 encryptionAlgorithm.isEmpty() ? null : encryptionAlgorithm); 1320 } 1321 1322 public static DataEncryptionKeyProto convert(DataEncryptionKey bet) { 1323 DataEncryptionKeyProto.Builder b = DataEncryptionKeyProto.newBuilder() 1324 .setKeyId(bet.keyId) 1325 .setBlockPoolId(bet.blockPoolId) 1326 .setNonce(ByteString.copyFrom(bet.nonce)) 1327 .setEncryptionKey(ByteString.copyFrom(bet.encryptionKey)) 1328 .setExpiryDate(bet.expiryDate); 1329 if (bet.encryptionAlgorithm != null) { 1330 b.setEncryptionAlgorithm(bet.encryptionAlgorithm); 1331 } 1332 return b.build(); 1333 } 1334 1335 public static FsServerDefaults convert(FsServerDefaultsProto fs) { 1336 if (fs == null) return null; 1337 return new FsServerDefaults( 1338 fs.getBlockSize(), fs.getBytesPerChecksum(), 1339 fs.getWritePacketSize(), (short) fs.getReplication(), 1340 fs.getFileBufferSize(), 1341 fs.getEncryptDataTransfer(), 1342 fs.getTrashInterval(), 1343 PBHelper.convert(fs.getChecksumType())); 1344 } 1345 1346 public static FsServerDefaultsProto convert(FsServerDefaults fs) { 1347 if (fs == null) return null; 1348 return FsServerDefaultsProto.newBuilder(). 1349 setBlockSize(fs.getBlockSize()). 1350 setBytesPerChecksum(fs.getBytesPerChecksum()). 1351 setWritePacketSize(fs.getWritePacketSize()) 1352 .setReplication(fs.getReplication()) 1353 .setFileBufferSize(fs.getFileBufferSize()) 1354 .setEncryptDataTransfer(fs.getEncryptDataTransfer()) 1355 .setTrashInterval(fs.getTrashInterval()) 1356 .setChecksumType(PBHelper.convert(fs.getChecksumType())) 1357 .build(); 1358 } 1359 1360 public static FsPermissionProto convert(FsPermission p) { 1361 return FsPermissionProto.newBuilder().setPerm(p.toExtendedShort()).build(); 1362 } 1363 1364 public static FsPermission convert(FsPermissionProto p) { 1365 return new FsPermissionExtension((short)p.getPerm()); 1366 } 1367 1368 1369 // The creatFlag field in PB is a bitmask whose values are the same a the 1370 // emum values of CreateFlag 1371 public static int convertCreateFlag(EnumSetWritable<CreateFlag> flag) { 1372 int value = 0; 1373 if (flag.contains(CreateFlag.APPEND)) { 1374 value |= CreateFlagProto.APPEND.getNumber(); 1375 } 1376 if (flag.contains(CreateFlag.CREATE)) { 1377 value |= CreateFlagProto.CREATE.getNumber(); 1378 } 1379 if (flag.contains(CreateFlag.OVERWRITE)) { 1380 value |= CreateFlagProto.OVERWRITE.getNumber(); 1381 } 1382 if (flag.contains(CreateFlag.LAZY_PERSIST)) { 1383 value |= CreateFlagProto.LAZY_PERSIST.getNumber(); 1384 } 1385 if (flag.contains(CreateFlag.NEW_BLOCK)) { 1386 value |= CreateFlagProto.NEW_BLOCK.getNumber(); 1387 } 1388 return value; 1389 } 1390 1391 public static EnumSetWritable<CreateFlag> convertCreateFlag(int flag) { 1392 EnumSet<CreateFlag> result = 1393 EnumSet.noneOf(CreateFlag.class); 1394 if ((flag & CreateFlagProto.APPEND_VALUE) == CreateFlagProto.APPEND_VALUE) { 1395 result.add(CreateFlag.APPEND); 1396 } 1397 if ((flag & CreateFlagProto.CREATE_VALUE) == CreateFlagProto.CREATE_VALUE) { 1398 result.add(CreateFlag.CREATE); 1399 } 1400 if ((flag & CreateFlagProto.OVERWRITE_VALUE) 1401 == CreateFlagProto.OVERWRITE_VALUE) { 1402 result.add(CreateFlag.OVERWRITE); 1403 } 1404 if ((flag & CreateFlagProto.LAZY_PERSIST_VALUE) 1405 == CreateFlagProto.LAZY_PERSIST_VALUE) { 1406 result.add(CreateFlag.LAZY_PERSIST); 1407 } 1408 if ((flag & CreateFlagProto.NEW_BLOCK_VALUE) 1409 == CreateFlagProto.NEW_BLOCK_VALUE) { 1410 result.add(CreateFlag.NEW_BLOCK); 1411 } 1412 return new EnumSetWritable<CreateFlag>(result, CreateFlag.class); 1413 } 1414 1415 public static int convertCacheFlags(EnumSet<CacheFlag> flags) { 1416 int value = 0; 1417 if (flags.contains(CacheFlag.FORCE)) { 1418 value |= CacheFlagProto.FORCE.getNumber(); 1419 } 1420 return value; 1421 } 1422 1423 public static EnumSet<CacheFlag> convertCacheFlags(int flags) { 1424 EnumSet<CacheFlag> result = EnumSet.noneOf(CacheFlag.class); 1425 if ((flags & CacheFlagProto.FORCE_VALUE) == CacheFlagProto.FORCE_VALUE) { 1426 result.add(CacheFlag.FORCE); 1427 } 1428 return result; 1429 } 1430 1431 public static HdfsFileStatus convert(HdfsFileStatusProto fs) { 1432 if (fs == null) 1433 return null; 1434 return new HdfsLocatedFileStatus( 1435 fs.getLength(), fs.getFileType().equals(FileType.IS_DIR), 1436 fs.getBlockReplication(), fs.getBlocksize(), 1437 fs.getModificationTime(), fs.getAccessTime(), 1438 PBHelper.convert(fs.getPermission()), fs.getOwner(), fs.getGroup(), 1439 fs.getFileType().equals(FileType.IS_SYMLINK) ? 1440 fs.getSymlink().toByteArray() : null, 1441 fs.getPath().toByteArray(), 1442 fs.hasFileId()? fs.getFileId(): INodeId.GRANDFATHER_INODE_ID, 1443 fs.hasLocations() ? PBHelper.convert(fs.getLocations()) : null, 1444 fs.hasChildrenNum() ? fs.getChildrenNum() : -1, 1445 fs.hasFileEncryptionInfo() ? convert(fs.getFileEncryptionInfo()) : null, 1446 fs.hasStoragePolicy() ? (byte) fs.getStoragePolicy() 1447 : BlockStoragePolicySuite.ID_UNSPECIFIED); 1448 } 1449 1450 public static SnapshottableDirectoryStatus convert( 1451 SnapshottableDirectoryStatusProto sdirStatusProto) { 1452 if (sdirStatusProto == null) { 1453 return null; 1454 } 1455 final HdfsFileStatusProto status = sdirStatusProto.getDirStatus(); 1456 return new SnapshottableDirectoryStatus( 1457 status.getModificationTime(), 1458 status.getAccessTime(), 1459 PBHelper.convert(status.getPermission()), 1460 status.getOwner(), 1461 status.getGroup(), 1462 status.getPath().toByteArray(), 1463 status.getFileId(), 1464 status.getChildrenNum(), 1465 sdirStatusProto.getSnapshotNumber(), 1466 sdirStatusProto.getSnapshotQuota(), 1467 sdirStatusProto.getParentFullpath().toByteArray()); 1468 } 1469 1470 public static HdfsFileStatusProto convert(HdfsFileStatus fs) { 1471 if (fs == null) 1472 return null; 1473 FileType fType = FileType.IS_FILE; 1474 if (fs.isDir()) { 1475 fType = FileType.IS_DIR; 1476 } else if (fs.isSymlink()) { 1477 fType = FileType.IS_SYMLINK; 1478 } 1479 1480 HdfsFileStatusProto.Builder builder = 1481 HdfsFileStatusProto.newBuilder(). 1482 setLength(fs.getLen()). 1483 setFileType(fType). 1484 setBlockReplication(fs.getReplication()). 1485 setBlocksize(fs.getBlockSize()). 1486 setModificationTime(fs.getModificationTime()). 1487 setAccessTime(fs.getAccessTime()). 1488 setPermission(PBHelper.convert(fs.getPermission())). 1489 setOwner(fs.getOwner()). 1490 setGroup(fs.getGroup()). 1491 setFileId(fs.getFileId()). 1492 setChildrenNum(fs.getChildrenNum()). 1493 setPath(ByteString.copyFrom(fs.getLocalNameInBytes())). 1494 setStoragePolicy(fs.getStoragePolicy()); 1495 if (fs.isSymlink()) { 1496 builder.setSymlink(ByteString.copyFrom(fs.getSymlinkInBytes())); 1497 } 1498 if (fs.getFileEncryptionInfo() != null) { 1499 builder.setFileEncryptionInfo(convert(fs.getFileEncryptionInfo())); 1500 } 1501 if (fs instanceof HdfsLocatedFileStatus) { 1502 final HdfsLocatedFileStatus lfs = (HdfsLocatedFileStatus) fs; 1503 LocatedBlocks locations = lfs.getBlockLocations(); 1504 if (locations != null) { 1505 builder.setLocations(PBHelper.convert(locations)); 1506 } 1507 } 1508 return builder.build(); 1509 } 1510 1511 public static SnapshottableDirectoryStatusProto convert( 1512 SnapshottableDirectoryStatus status) { 1513 if (status == null) { 1514 return null; 1515 } 1516 int snapshotNumber = status.getSnapshotNumber(); 1517 int snapshotQuota = status.getSnapshotQuota(); 1518 byte[] parentFullPath = status.getParentFullPath(); 1519 ByteString parentFullPathBytes = ByteString.copyFrom( 1520 parentFullPath == null ? DFSUtil.EMPTY_BYTES : parentFullPath); 1521 HdfsFileStatusProto fs = convert(status.getDirStatus()); 1522 SnapshottableDirectoryStatusProto.Builder builder = 1523 SnapshottableDirectoryStatusProto 1524 .newBuilder().setSnapshotNumber(snapshotNumber) 1525 .setSnapshotQuota(snapshotQuota).setParentFullpath(parentFullPathBytes) 1526 .setDirStatus(fs); 1527 return builder.build(); 1528 } 1529 1530 public static HdfsFileStatusProto[] convert(HdfsFileStatus[] fs) { 1531 if (fs == null) return null; 1532 final int len = fs.length; 1533 HdfsFileStatusProto[] result = new HdfsFileStatusProto[len]; 1534 for (int i = 0; i < len; ++i) { 1535 result[i] = PBHelper.convert(fs[i]); 1536 } 1537 return result; 1538 } 1539 1540 public static HdfsFileStatus[] convert(HdfsFileStatusProto[] fs) { 1541 if (fs == null) return null; 1542 final int len = fs.length; 1543 HdfsFileStatus[] result = new HdfsFileStatus[len]; 1544 for (int i = 0; i < len; ++i) { 1545 result[i] = PBHelper.convert(fs[i]); 1546 } 1547 return result; 1548 } 1549 1550 public static DirectoryListing convert(DirectoryListingProto dl) { 1551 if (dl == null) 1552 return null; 1553 List<HdfsFileStatusProto> partList = dl.getPartialListingList(); 1554 return new DirectoryListing( 1555 partList.isEmpty() ? new HdfsLocatedFileStatus[0] 1556 : PBHelper.convert( 1557 partList.toArray(new HdfsFileStatusProto[partList.size()])), 1558 dl.getRemainingEntries()); 1559 } 1560 1561 public static DirectoryListingProto convert(DirectoryListing d) { 1562 if (d == null) 1563 return null; 1564 return DirectoryListingProto.newBuilder(). 1565 addAllPartialListing(Arrays.asList( 1566 PBHelper.convert(d.getPartialListing()))). 1567 setRemainingEntries(d.getRemainingEntries()). 1568 build(); 1569 } 1570 1571 public static long[] convert(GetFsStatsResponseProto res) { 1572 long[] result = new long[7]; 1573 result[ClientProtocol.GET_STATS_CAPACITY_IDX] = res.getCapacity(); 1574 result[ClientProtocol.GET_STATS_USED_IDX] = res.getUsed(); 1575 result[ClientProtocol.GET_STATS_REMAINING_IDX] = res.getRemaining(); 1576 result[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX] = res.getUnderReplicated(); 1577 result[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX] = res.getCorruptBlocks(); 1578 result[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX] = res.getMissingBlocks(); 1579 result[ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX] = 1580 res.getMissingReplOneBlocks(); 1581 return result; 1582 } 1583 1584 public static GetFsStatsResponseProto convert(long[] fsStats) { 1585 GetFsStatsResponseProto.Builder result = GetFsStatsResponseProto 1586 .newBuilder(); 1587 if (fsStats.length >= ClientProtocol.GET_STATS_CAPACITY_IDX + 1) 1588 result.setCapacity(fsStats[ClientProtocol.GET_STATS_CAPACITY_IDX]); 1589 if (fsStats.length >= ClientProtocol.GET_STATS_USED_IDX + 1) 1590 result.setUsed(fsStats[ClientProtocol.GET_STATS_USED_IDX]); 1591 if (fsStats.length >= ClientProtocol.GET_STATS_REMAINING_IDX + 1) 1592 result.setRemaining(fsStats[ClientProtocol.GET_STATS_REMAINING_IDX]); 1593 if (fsStats.length >= ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX + 1) 1594 result.setUnderReplicated( 1595 fsStats[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX]); 1596 if (fsStats.length >= ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX + 1) 1597 result.setCorruptBlocks( 1598 fsStats[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX]); 1599 if (fsStats.length >= ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX + 1) 1600 result.setMissingBlocks( 1601 fsStats[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX]); 1602 if (fsStats.length >= ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX + 1) 1603 result.setMissingReplOneBlocks( 1604 fsStats[ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX]); 1605 return result.build(); 1606 } 1607 1608 public static DatanodeReportTypeProto 1609 convert(DatanodeReportType t) { 1610 switch (t) { 1611 case ALL: return DatanodeReportTypeProto.ALL; 1612 case LIVE: return DatanodeReportTypeProto.LIVE; 1613 case DEAD: return DatanodeReportTypeProto.DEAD; 1614 case DECOMMISSIONING: return DatanodeReportTypeProto.DECOMMISSIONING; 1615 default: 1616 throw new IllegalArgumentException("Unexpected data type report:" + t); 1617 } 1618 } 1619 1620 public static DatanodeReportType 1621 convert(DatanodeReportTypeProto t) { 1622 switch (t) { 1623 case ALL: return DatanodeReportType.ALL; 1624 case LIVE: return DatanodeReportType.LIVE; 1625 case DEAD: return DatanodeReportType.DEAD; 1626 case DECOMMISSIONING: return DatanodeReportType.DECOMMISSIONING; 1627 default: 1628 throw new IllegalArgumentException("Unexpected data type report:" + t); 1629 } 1630 } 1631 1632 public static SafeModeActionProto convert( 1633 SafeModeAction a) { 1634 switch (a) { 1635 case SAFEMODE_LEAVE: 1636 return SafeModeActionProto.SAFEMODE_LEAVE; 1637 case SAFEMODE_ENTER: 1638 return SafeModeActionProto.SAFEMODE_ENTER; 1639 case SAFEMODE_GET: 1640 return SafeModeActionProto.SAFEMODE_GET; 1641 default: 1642 throw new IllegalArgumentException("Unexpected SafeModeAction :" + a); 1643 } 1644 } 1645 1646 public static SafeModeAction convert( 1647 ClientNamenodeProtocolProtos.SafeModeActionProto a) { 1648 switch (a) { 1649 case SAFEMODE_LEAVE: 1650 return SafeModeAction.SAFEMODE_LEAVE; 1651 case SAFEMODE_ENTER: 1652 return SafeModeAction.SAFEMODE_ENTER; 1653 case SAFEMODE_GET: 1654 return SafeModeAction.SAFEMODE_GET; 1655 default: 1656 throw new IllegalArgumentException("Unexpected SafeModeAction :" + a); 1657 } 1658 } 1659 1660 public static RollingUpgradeActionProto convert(RollingUpgradeAction a) { 1661 switch (a) { 1662 case QUERY: 1663 return RollingUpgradeActionProto.QUERY; 1664 case PREPARE: 1665 return RollingUpgradeActionProto.START; 1666 case FINALIZE: 1667 return RollingUpgradeActionProto.FINALIZE; 1668 default: 1669 throw new IllegalArgumentException("Unexpected value: " + a); 1670 } 1671 } 1672 1673 public static RollingUpgradeAction convert(RollingUpgradeActionProto a) { 1674 switch (a) { 1675 case QUERY: 1676 return RollingUpgradeAction.QUERY; 1677 case START: 1678 return RollingUpgradeAction.PREPARE; 1679 case FINALIZE: 1680 return RollingUpgradeAction.FINALIZE; 1681 default: 1682 throw new IllegalArgumentException("Unexpected value: " + a); 1683 } 1684 } 1685 1686 public static RollingUpgradeStatusProto convertRollingUpgradeStatus( 1687 RollingUpgradeStatus status) { 1688 return RollingUpgradeStatusProto.newBuilder() 1689 .setBlockPoolId(status.getBlockPoolId()) 1690 .build(); 1691 } 1692 1693 public static RollingUpgradeStatus convert(RollingUpgradeStatusProto proto) { 1694 return new RollingUpgradeStatus(proto.getBlockPoolId()); 1695 } 1696 1697 public static RollingUpgradeInfoProto convert(RollingUpgradeInfo info) { 1698 return RollingUpgradeInfoProto.newBuilder() 1699 .setStatus(convertRollingUpgradeStatus(info)) 1700 .setCreatedRollbackImages(info.createdRollbackImages()) 1701 .setStartTime(info.getStartTime()) 1702 .setFinalizeTime(info.getFinalizeTime()) 1703 .build(); 1704 } 1705 1706 public static RollingUpgradeInfo convert(RollingUpgradeInfoProto proto) { 1707 RollingUpgradeStatusProto status = proto.getStatus(); 1708 return new RollingUpgradeInfo(status.getBlockPoolId(), 1709 proto.getCreatedRollbackImages(), 1710 proto.getStartTime(), proto.getFinalizeTime()); 1711 } 1712 1713 public static CorruptFileBlocks convert(CorruptFileBlocksProto c) { 1714 if (c == null) 1715 return null; 1716 List<String> fileList = c.getFilesList(); 1717 return new CorruptFileBlocks(fileList.toArray(new String[fileList.size()]), 1718 c.getCookie()); 1719 } 1720 1721 public static CorruptFileBlocksProto convert(CorruptFileBlocks c) { 1722 if (c == null) 1723 return null; 1724 return CorruptFileBlocksProto.newBuilder(). 1725 addAllFiles(Arrays.asList(c.getFiles())). 1726 setCookie(c.getCookie()). 1727 build(); 1728 } 1729 1730 public static ContentSummary convert(ContentSummaryProto cs) { 1731 if (cs == null) return null; 1732 ContentSummary.Builder builder = new ContentSummary.Builder(); 1733 builder.length(cs.getLength()). 1734 fileCount(cs.getFileCount()). 1735 directoryCount(cs.getDirectoryCount()). 1736 quota(cs.getQuota()). 1737 spaceConsumed(cs.getSpaceConsumed()). 1738 spaceQuota(cs.getSpaceQuota()); 1739 if (cs.hasTypeQuotaInfos()) { 1740 for (HdfsProtos.StorageTypeQuotaInfoProto info : 1741 cs.getTypeQuotaInfos().getTypeQuotaInfoList()) { 1742 StorageType type = PBHelper.convertStorageType(info.getType()); 1743 builder.typeConsumed(type, info.getConsumed()); 1744 builder.typeQuota(type, info.getQuota()); 1745 } 1746 } 1747 return builder.build(); 1748 } 1749 1750 public static ContentSummaryProto convert(ContentSummary cs) { 1751 if (cs == null) return null; 1752 ContentSummaryProto.Builder builder = ContentSummaryProto.newBuilder(); 1753 builder.setLength(cs.getLength()). 1754 setFileCount(cs.getFileCount()). 1755 setDirectoryCount(cs.getDirectoryCount()). 1756 setQuota(cs.getQuota()). 1757 setSpaceConsumed(cs.getSpaceConsumed()). 1758 setSpaceQuota(cs.getSpaceQuota()); 1759 1760 if (cs.isTypeQuotaSet() || cs.isTypeConsumedAvailable()) { 1761 HdfsProtos.StorageTypeQuotaInfosProto.Builder isb = 1762 HdfsProtos.StorageTypeQuotaInfosProto.newBuilder(); 1763 for (StorageType t: StorageType.getTypesSupportingQuota()) { 1764 HdfsProtos.StorageTypeQuotaInfoProto info = 1765 HdfsProtos.StorageTypeQuotaInfoProto.newBuilder(). 1766 setType(convertStorageType(t)). 1767 setConsumed(cs.getTypeConsumed(t)). 1768 setQuota(cs.getTypeQuota(t)). 1769 build(); 1770 isb.addTypeQuotaInfo(info); 1771 } 1772 builder.setTypeQuotaInfos(isb); 1773 } 1774 return builder.build(); 1775 } 1776 1777 public static NNHAStatusHeartbeat convert(NNHAStatusHeartbeatProto s) { 1778 if (s == null) return null; 1779 switch (s.getState()) { 1780 case ACTIVE: 1781 return new NNHAStatusHeartbeat(HAServiceState.ACTIVE, s.getTxid()); 1782 case STANDBY: 1783 return new NNHAStatusHeartbeat(HAServiceState.STANDBY, s.getTxid()); 1784 default: 1785 throw new IllegalArgumentException("Unexpected NNHAStatusHeartbeat.State:" + s.getState()); 1786 } 1787 } 1788 1789 public static NNHAStatusHeartbeatProto convert(NNHAStatusHeartbeat hb) { 1790 if (hb == null) return null; 1791 NNHAStatusHeartbeatProto.Builder builder = 1792 NNHAStatusHeartbeatProto.newBuilder(); 1793 switch (hb.getState()) { 1794 case ACTIVE: 1795 builder.setState(NNHAStatusHeartbeatProto.State.ACTIVE); 1796 break; 1797 case STANDBY: 1798 builder.setState(NNHAStatusHeartbeatProto.State.STANDBY); 1799 break; 1800 default: 1801 throw new IllegalArgumentException("Unexpected NNHAStatusHeartbeat.State:" + 1802 hb.getState()); 1803 } 1804 builder.setTxid(hb.getTxId()); 1805 return builder.build(); 1806 } 1807 1808 public static DatanodeStorageProto convert(DatanodeStorage s) { 1809 return DatanodeStorageProto.newBuilder() 1810 .setState(PBHelper.convertState(s.getState())) 1811 .setStorageType(PBHelper.convertStorageType(s.getStorageType())) 1812 .setStorageUuid(s.getStorageID()).build(); 1813 } 1814 1815 private static StorageState convertState(State state) { 1816 switch(state) { 1817 case READ_ONLY_SHARED: 1818 return StorageState.READ_ONLY_SHARED; 1819 case NORMAL: 1820 default: 1821 return StorageState.NORMAL; 1822 } 1823 } 1824 1825 public static List<StorageTypeProto> convertStorageTypes( 1826 StorageType[] types) { 1827 return convertStorageTypes(types, 0); 1828 } 1829 1830 public static List<StorageTypeProto> convertStorageTypes( 1831 StorageType[] types, int startIdx) { 1832 if (types == null) { 1833 return null; 1834 } 1835 final List<StorageTypeProto> protos = new ArrayList<StorageTypeProto>( 1836 types.length); 1837 for (int i = startIdx; i < types.length; ++i) { 1838 protos.add(convertStorageType(types[i])); 1839 } 1840 return protos; 1841 } 1842 1843 public static StorageTypeProto convertStorageType(StorageType type) { 1844 switch(type) { 1845 case DISK: 1846 return StorageTypeProto.DISK; 1847 case SSD: 1848 return StorageTypeProto.SSD; 1849 case ARCHIVE: 1850 return StorageTypeProto.ARCHIVE; 1851 case RAM_DISK: 1852 return StorageTypeProto.RAM_DISK; 1853 default: 1854 throw new IllegalStateException( 1855 "BUG: StorageType not found, type=" + type); 1856 } 1857 } 1858 1859 public static DatanodeStorage convert(DatanodeStorageProto s) { 1860 return new DatanodeStorage(s.getStorageUuid(), 1861 PBHelper.convertState(s.getState()), 1862 PBHelper.convertStorageType(s.getStorageType())); 1863 } 1864 1865 private static State convertState(StorageState state) { 1866 switch(state) { 1867 case READ_ONLY_SHARED: 1868 return DatanodeStorage.State.READ_ONLY_SHARED; 1869 case NORMAL: 1870 default: 1871 return DatanodeStorage.State.NORMAL; 1872 } 1873 } 1874 1875 public static StorageType convertStorageType(StorageTypeProto type) { 1876 switch(type) { 1877 case DISK: 1878 return StorageType.DISK; 1879 case SSD: 1880 return StorageType.SSD; 1881 case ARCHIVE: 1882 return StorageType.ARCHIVE; 1883 case RAM_DISK: 1884 return StorageType.RAM_DISK; 1885 default: 1886 throw new IllegalStateException( 1887 "BUG: StorageTypeProto not found, type=" + type); 1888 } 1889 } 1890 1891 public static StorageType[] convertStorageTypes( 1892 List<StorageTypeProto> storageTypesList, int expectedSize) { 1893 final StorageType[] storageTypes = new StorageType[expectedSize]; 1894 if (storageTypesList.size() != expectedSize) { // missing storage types 1895 Preconditions.checkState(storageTypesList.isEmpty()); 1896 Arrays.fill(storageTypes, StorageType.DEFAULT); 1897 } else { 1898 for (int i = 0; i < storageTypes.length; ++i) { 1899 storageTypes[i] = convertStorageType(storageTypesList.get(i)); 1900 } 1901 } 1902 return storageTypes; 1903 } 1904 1905 public static StorageReportProto convert(StorageReport r) { 1906 StorageReportProto.Builder builder = StorageReportProto.newBuilder() 1907 .setBlockPoolUsed(r.getBlockPoolUsed()).setCapacity(r.getCapacity()) 1908 .setDfsUsed(r.getDfsUsed()).setRemaining(r.getRemaining()) 1909 .setStorageUuid(r.getStorage().getStorageID()) 1910 .setStorage(convert(r.getStorage())); 1911 return builder.build(); 1912 } 1913 1914 public static StorageReport convert(StorageReportProto p) { 1915 return new StorageReport( 1916 p.hasStorage() ? 1917 convert(p.getStorage()) : 1918 new DatanodeStorage(p.getStorageUuid()), 1919 p.getFailed(), p.getCapacity(), p.getDfsUsed(), p.getRemaining(), 1920 p.getBlockPoolUsed()); 1921 } 1922 1923 public static StorageReport[] convertStorageReports( 1924 List<StorageReportProto> list) { 1925 final StorageReport[] report = new StorageReport[list.size()]; 1926 for (int i = 0; i < report.length; i++) { 1927 report[i] = convert(list.get(i)); 1928 } 1929 return report; 1930 } 1931 1932 public static List<StorageReportProto> convertStorageReports(StorageReport[] storages) { 1933 final List<StorageReportProto> protos = new ArrayList<StorageReportProto>( 1934 storages.length); 1935 for(int i = 0; i < storages.length; i++) { 1936 protos.add(convert(storages[i])); 1937 } 1938 return protos; 1939 } 1940 1941 public static VolumeFailureSummary convertVolumeFailureSummary( 1942 VolumeFailureSummaryProto proto) { 1943 List<String> failedStorageLocations = proto.getFailedStorageLocationsList(); 1944 return new VolumeFailureSummary( 1945 failedStorageLocations.toArray(new String[failedStorageLocations.size()]), 1946 proto.getLastVolumeFailureDate(), proto.getEstimatedCapacityLostTotal()); 1947 } 1948 1949 public static VolumeFailureSummaryProto convertVolumeFailureSummary( 1950 VolumeFailureSummary volumeFailureSummary) { 1951 VolumeFailureSummaryProto.Builder builder = 1952 VolumeFailureSummaryProto.newBuilder(); 1953 for (String failedStorageLocation: 1954 volumeFailureSummary.getFailedStorageLocations()) { 1955 builder.addFailedStorageLocations(failedStorageLocation); 1956 } 1957 builder.setLastVolumeFailureDate( 1958 volumeFailureSummary.getLastVolumeFailureDate()); 1959 builder.setEstimatedCapacityLostTotal( 1960 volumeFailureSummary.getEstimatedCapacityLostTotal()); 1961 return builder.build(); 1962 } 1963 1964 public static JournalInfo convert(JournalInfoProto info) { 1965 int lv = info.hasLayoutVersion() ? info.getLayoutVersion() : 0; 1966 int nsID = info.hasNamespaceID() ? info.getNamespaceID() : 0; 1967 return new JournalInfo(lv, info.getClusterID(), nsID); 1968 } 1969 1970 /** 1971 * Method used for converting {@link JournalInfoProto} sent from Namenode 1972 * to Journal receivers to {@link NamenodeRegistration}. 1973 */ 1974 public static JournalInfoProto convert(JournalInfo j) { 1975 return JournalInfoProto.newBuilder().setClusterID(j.getClusterId()) 1976 .setLayoutVersion(j.getLayoutVersion()) 1977 .setNamespaceID(j.getNamespaceId()).build(); 1978 } 1979 1980 public static SnapshottableDirectoryStatus[] convert( 1981 SnapshottableDirectoryListingProto sdlp) { 1982 if (sdlp == null) 1983 return null; 1984 List<SnapshottableDirectoryStatusProto> list = sdlp 1985 .getSnapshottableDirListingList(); 1986 if (list.isEmpty()) { 1987 return new SnapshottableDirectoryStatus[0]; 1988 } else { 1989 SnapshottableDirectoryStatus[] result = 1990 new SnapshottableDirectoryStatus[list.size()]; 1991 for (int i = 0; i < list.size(); i++) { 1992 result[i] = PBHelper.convert(list.get(i)); 1993 } 1994 return result; 1995 } 1996 } 1997 1998 public static SnapshottableDirectoryListingProto convert( 1999 SnapshottableDirectoryStatus[] status) { 2000 if (status == null) 2001 return null; 2002 SnapshottableDirectoryStatusProto[] protos = 2003 new SnapshottableDirectoryStatusProto[status.length]; 2004 for (int i = 0; i < status.length; i++) { 2005 protos[i] = PBHelper.convert(status[i]); 2006 } 2007 List<SnapshottableDirectoryStatusProto> protoList = Arrays.asList(protos); 2008 return SnapshottableDirectoryListingProto.newBuilder() 2009 .addAllSnapshottableDirListing(protoList).build(); 2010 } 2011 2012 public static DiffReportEntry convert(SnapshotDiffReportEntryProto entry) { 2013 if (entry == null) { 2014 return null; 2015 } 2016 DiffType type = DiffType.getTypeFromLabel(entry 2017 .getModificationLabel()); 2018 return type == null ? null : new DiffReportEntry(type, entry.getFullpath() 2019 .toByteArray(), entry.hasTargetPath() ? entry.getTargetPath() 2020 .toByteArray() : null); 2021 } 2022 2023 public static SnapshotDiffReportEntryProto convert(DiffReportEntry entry) { 2024 if (entry == null) { 2025 return null; 2026 } 2027 ByteString sourcePath = ByteString 2028 .copyFrom(entry.getSourcePath() == null ? DFSUtil.EMPTY_BYTES : entry 2029 .getSourcePath()); 2030 String modification = entry.getType().getLabel(); 2031 SnapshotDiffReportEntryProto.Builder builder = SnapshotDiffReportEntryProto 2032 .newBuilder().setFullpath(sourcePath) 2033 .setModificationLabel(modification); 2034 if (entry.getType() == DiffType.RENAME) { 2035 ByteString targetPath = ByteString 2036 .copyFrom(entry.getTargetPath() == null ? DFSUtil.EMPTY_BYTES : entry 2037 .getTargetPath()); 2038 builder.setTargetPath(targetPath); 2039 } 2040 return builder.build(); 2041 } 2042 2043 public static SnapshotDiffReport convert(SnapshotDiffReportProto reportProto) { 2044 if (reportProto == null) { 2045 return null; 2046 } 2047 String snapshotDir = reportProto.getSnapshotRoot(); 2048 String fromSnapshot = reportProto.getFromSnapshot(); 2049 String toSnapshot = reportProto.getToSnapshot(); 2050 List<SnapshotDiffReportEntryProto> list = reportProto 2051 .getDiffReportEntriesList(); 2052 List<DiffReportEntry> entries = new ArrayList<DiffReportEntry>(); 2053 for (SnapshotDiffReportEntryProto entryProto : list) { 2054 DiffReportEntry entry = convert(entryProto); 2055 if (entry != null) 2056 entries.add(entry); 2057 } 2058 return new SnapshotDiffReport(snapshotDir, fromSnapshot, toSnapshot, 2059 entries); 2060 } 2061 2062 public static SnapshotDiffReportProto convert(SnapshotDiffReport report) { 2063 if (report == null) { 2064 return null; 2065 } 2066 List<DiffReportEntry> entries = report.getDiffList(); 2067 List<SnapshotDiffReportEntryProto> entryProtos = 2068 new ArrayList<SnapshotDiffReportEntryProto>(); 2069 for (DiffReportEntry entry : entries) { 2070 SnapshotDiffReportEntryProto entryProto = convert(entry); 2071 if (entryProto != null) 2072 entryProtos.add(entryProto); 2073 } 2074 2075 SnapshotDiffReportProto reportProto = SnapshotDiffReportProto.newBuilder() 2076 .setSnapshotRoot(report.getSnapshotRoot()) 2077 .setFromSnapshot(report.getFromSnapshot()) 2078 .setToSnapshot(report.getLaterSnapshotName()) 2079 .addAllDiffReportEntries(entryProtos).build(); 2080 return reportProto; 2081 } 2082 2083 public static DataChecksum.Type convert(HdfsProtos.ChecksumTypeProto type) { 2084 return DataChecksum.Type.valueOf(type.getNumber()); 2085 } 2086 2087 public static CacheDirectiveInfoProto convert 2088 (CacheDirectiveInfo info) { 2089 CacheDirectiveInfoProto.Builder builder = 2090 CacheDirectiveInfoProto.newBuilder(); 2091 if (info.getId() != null) { 2092 builder.setId(info.getId()); 2093 } 2094 if (info.getPath() != null) { 2095 builder.setPath(info.getPath().toUri().getPath()); 2096 } 2097 if (info.getReplication() != null) { 2098 builder.setReplication(info.getReplication()); 2099 } 2100 if (info.getPool() != null) { 2101 builder.setPool(info.getPool()); 2102 } 2103 if (info.getExpiration() != null) { 2104 builder.setExpiration(convert(info.getExpiration())); 2105 } 2106 return builder.build(); 2107 } 2108 2109 public static CacheDirectiveInfo convert 2110 (CacheDirectiveInfoProto proto) { 2111 CacheDirectiveInfo.Builder builder = 2112 new CacheDirectiveInfo.Builder(); 2113 if (proto.hasId()) { 2114 builder.setId(proto.getId()); 2115 } 2116 if (proto.hasPath()) { 2117 builder.setPath(new Path(proto.getPath())); 2118 } 2119 if (proto.hasReplication()) { 2120 builder.setReplication(Shorts.checkedCast( 2121 proto.getReplication())); 2122 } 2123 if (proto.hasPool()) { 2124 builder.setPool(proto.getPool()); 2125 } 2126 if (proto.hasExpiration()) { 2127 builder.setExpiration(convert(proto.getExpiration())); 2128 } 2129 return builder.build(); 2130 } 2131 2132 public static CacheDirectiveInfoExpirationProto convert( 2133 CacheDirectiveInfo.Expiration expiration) { 2134 return CacheDirectiveInfoExpirationProto.newBuilder() 2135 .setIsRelative(expiration.isRelative()) 2136 .setMillis(expiration.getMillis()) 2137 .build(); 2138 } 2139 2140 public static CacheDirectiveInfo.Expiration convert( 2141 CacheDirectiveInfoExpirationProto proto) { 2142 if (proto.getIsRelative()) { 2143 return CacheDirectiveInfo.Expiration.newRelative(proto.getMillis()); 2144 } 2145 return CacheDirectiveInfo.Expiration.newAbsolute(proto.getMillis()); 2146 } 2147 2148 public static CacheDirectiveStatsProto convert(CacheDirectiveStats stats) { 2149 CacheDirectiveStatsProto.Builder builder = 2150 CacheDirectiveStatsProto.newBuilder(); 2151 builder.setBytesNeeded(stats.getBytesNeeded()); 2152 builder.setBytesCached(stats.getBytesCached()); 2153 builder.setFilesNeeded(stats.getFilesNeeded()); 2154 builder.setFilesCached(stats.getFilesCached()); 2155 builder.setHasExpired(stats.hasExpired()); 2156 return builder.build(); 2157 } 2158 2159 public static CacheDirectiveStats convert(CacheDirectiveStatsProto proto) { 2160 CacheDirectiveStats.Builder builder = new CacheDirectiveStats.Builder(); 2161 builder.setBytesNeeded(proto.getBytesNeeded()); 2162 builder.setBytesCached(proto.getBytesCached()); 2163 builder.setFilesNeeded(proto.getFilesNeeded()); 2164 builder.setFilesCached(proto.getFilesCached()); 2165 builder.setHasExpired(proto.getHasExpired()); 2166 return builder.build(); 2167 } 2168 2169 public static CacheDirectiveEntryProto convert(CacheDirectiveEntry entry) { 2170 CacheDirectiveEntryProto.Builder builder = 2171 CacheDirectiveEntryProto.newBuilder(); 2172 builder.setInfo(PBHelper.convert(entry.getInfo())); 2173 builder.setStats(PBHelper.convert(entry.getStats())); 2174 return builder.build(); 2175 } 2176 2177 public static CacheDirectiveEntry convert(CacheDirectiveEntryProto proto) { 2178 CacheDirectiveInfo info = PBHelper.convert(proto.getInfo()); 2179 CacheDirectiveStats stats = PBHelper.convert(proto.getStats()); 2180 return new CacheDirectiveEntry(info, stats); 2181 } 2182 2183 public static CachePoolInfoProto convert(CachePoolInfo info) { 2184 CachePoolInfoProto.Builder builder = CachePoolInfoProto.newBuilder(); 2185 builder.setPoolName(info.getPoolName()); 2186 if (info.getOwnerName() != null) { 2187 builder.setOwnerName(info.getOwnerName()); 2188 } 2189 if (info.getGroupName() != null) { 2190 builder.setGroupName(info.getGroupName()); 2191 } 2192 if (info.getMode() != null) { 2193 builder.setMode(info.getMode().toShort()); 2194 } 2195 if (info.getLimit() != null) { 2196 builder.setLimit(info.getLimit()); 2197 } 2198 if (info.getMaxRelativeExpiryMs() != null) { 2199 builder.setMaxRelativeExpiry(info.getMaxRelativeExpiryMs()); 2200 } 2201 return builder.build(); 2202 } 2203 2204 public static CachePoolInfo convert (CachePoolInfoProto proto) { 2205 // Pool name is a required field, the rest are optional 2206 String poolName = checkNotNull(proto.getPoolName()); 2207 CachePoolInfo info = new CachePoolInfo(poolName); 2208 if (proto.hasOwnerName()) { 2209 info.setOwnerName(proto.getOwnerName()); 2210 } 2211 if (proto.hasGroupName()) { 2212 info.setGroupName(proto.getGroupName()); 2213 } 2214 if (proto.hasMode()) { 2215 info.setMode(new FsPermission((short)proto.getMode())); 2216 } 2217 if (proto.hasLimit()) { 2218 info.setLimit(proto.getLimit()); 2219 } 2220 if (proto.hasMaxRelativeExpiry()) { 2221 info.setMaxRelativeExpiryMs(proto.getMaxRelativeExpiry()); 2222 } 2223 return info; 2224 } 2225 2226 public static CachePoolStatsProto convert(CachePoolStats stats) { 2227 CachePoolStatsProto.Builder builder = CachePoolStatsProto.newBuilder(); 2228 builder.setBytesNeeded(stats.getBytesNeeded()); 2229 builder.setBytesCached(stats.getBytesCached()); 2230 builder.setBytesOverlimit(stats.getBytesOverlimit()); 2231 builder.setFilesNeeded(stats.getFilesNeeded()); 2232 builder.setFilesCached(stats.getFilesCached()); 2233 return builder.build(); 2234 } 2235 2236 public static CachePoolStats convert (CachePoolStatsProto proto) { 2237 CachePoolStats.Builder builder = new CachePoolStats.Builder(); 2238 builder.setBytesNeeded(proto.getBytesNeeded()); 2239 builder.setBytesCached(proto.getBytesCached()); 2240 builder.setBytesOverlimit(proto.getBytesOverlimit()); 2241 builder.setFilesNeeded(proto.getFilesNeeded()); 2242 builder.setFilesCached(proto.getFilesCached()); 2243 return builder.build(); 2244 } 2245 2246 public static CachePoolEntryProto convert(CachePoolEntry entry) { 2247 CachePoolEntryProto.Builder builder = CachePoolEntryProto.newBuilder(); 2248 builder.setInfo(PBHelper.convert(entry.getInfo())); 2249 builder.setStats(PBHelper.convert(entry.getStats())); 2250 return builder.build(); 2251 } 2252 2253 public static CachePoolEntry convert (CachePoolEntryProto proto) { 2254 CachePoolInfo info = PBHelper.convert(proto.getInfo()); 2255 CachePoolStats stats = PBHelper.convert(proto.getStats()); 2256 return new CachePoolEntry(info, stats); 2257 } 2258 2259 public static HdfsProtos.ChecksumTypeProto convert(DataChecksum.Type type) { 2260 return HdfsProtos.ChecksumTypeProto.valueOf(type.id); 2261 } 2262 2263 public static DatanodeLocalInfoProto convert(DatanodeLocalInfo info) { 2264 DatanodeLocalInfoProto.Builder builder = DatanodeLocalInfoProto.newBuilder(); 2265 builder.setSoftwareVersion(info.getSoftwareVersion()); 2266 builder.setConfigVersion(info.getConfigVersion()); 2267 builder.setUptime(info.getUptime()); 2268 return builder.build(); 2269 } 2270 2271 public static DatanodeLocalInfo convert(DatanodeLocalInfoProto proto) { 2272 return new DatanodeLocalInfo(proto.getSoftwareVersion(), 2273 proto.getConfigVersion(), proto.getUptime()); 2274 } 2275 2276 public static InputStream vintPrefixed(final InputStream input) 2277 throws IOException { 2278 final int firstByte = input.read(); 2279 if (firstByte == -1) { 2280 throw new EOFException("Premature EOF: no length prefix available"); 2281 } 2282 2283 int size = CodedInputStream.readRawVarint32(firstByte, input); 2284 assert size >= 0; 2285 return new ExactSizeInputStream(input, size); 2286 } 2287 2288 private static AclEntryScopeProto convert(AclEntryScope v) { 2289 return AclEntryScopeProto.valueOf(v.ordinal()); 2290 } 2291 2292 private static AclEntryScope convert(AclEntryScopeProto v) { 2293 return castEnum(v, ACL_ENTRY_SCOPE_VALUES); 2294 } 2295 2296 private static AclEntryTypeProto convert(AclEntryType e) { 2297 return AclEntryTypeProto.valueOf(e.ordinal()); 2298 } 2299 2300 private static AclEntryType convert(AclEntryTypeProto v) { 2301 return castEnum(v, ACL_ENTRY_TYPE_VALUES); 2302 } 2303 2304 private static XAttrNamespaceProto convert(XAttr.NameSpace v) { 2305 return XAttrNamespaceProto.valueOf(v.ordinal()); 2306 } 2307 2308 private static XAttr.NameSpace convert(XAttrNamespaceProto v) { 2309 return castEnum(v, XATTR_NAMESPACE_VALUES); 2310 } 2311 2312 public static FsActionProto convert(FsAction v) { 2313 return FsActionProto.valueOf(v != null ? v.ordinal() : 0); 2314 } 2315 2316 public static FsAction convert(FsActionProto v) { 2317 return castEnum(v, FSACTION_VALUES); 2318 } 2319 2320 public static List<AclEntryProto> convertAclEntryProto( 2321 List<AclEntry> aclSpec) { 2322 ArrayList<AclEntryProto> r = Lists.newArrayListWithCapacity(aclSpec.size()); 2323 for (AclEntry e : aclSpec) { 2324 AclEntryProto.Builder builder = AclEntryProto.newBuilder(); 2325 builder.setType(convert(e.getType())); 2326 builder.setScope(convert(e.getScope())); 2327 builder.setPermissions(convert(e.getPermission())); 2328 if (e.getName() != null) { 2329 builder.setName(e.getName()); 2330 } 2331 r.add(builder.build()); 2332 } 2333 return r; 2334 } 2335 2336 public static List<AclEntry> convertAclEntry(List<AclEntryProto> aclSpec) { 2337 ArrayList<AclEntry> r = Lists.newArrayListWithCapacity(aclSpec.size()); 2338 for (AclEntryProto e : aclSpec) { 2339 AclEntry.Builder builder = new AclEntry.Builder(); 2340 builder.setType(convert(e.getType())); 2341 builder.setScope(convert(e.getScope())); 2342 builder.setPermission(convert(e.getPermissions())); 2343 if (e.hasName()) { 2344 builder.setName(e.getName()); 2345 } 2346 r.add(builder.build()); 2347 } 2348 return r; 2349 } 2350 2351 public static AclStatus convert(GetAclStatusResponseProto e) { 2352 AclStatusProto r = e.getResult(); 2353 AclStatus.Builder builder = new AclStatus.Builder(); 2354 builder.owner(r.getOwner()).group(r.getGroup()).stickyBit(r.getSticky()) 2355 .addEntries(convertAclEntry(r.getEntriesList())); 2356 if (r.hasPermission()) { 2357 builder.setPermission(convert(r.getPermission())); 2358 } 2359 return builder.build(); 2360 } 2361 2362 public static GetAclStatusResponseProto convert(AclStatus e) { 2363 AclStatusProto.Builder builder = AclStatusProto.newBuilder(); 2364 builder.setOwner(e.getOwner()) 2365 .setGroup(e.getGroup()).setSticky(e.isStickyBit()) 2366 .addAllEntries(convertAclEntryProto(e.getEntries())); 2367 if (e.getPermission() != null) { 2368 builder.setPermission(convert(e.getPermission())); 2369 } 2370 AclStatusProto r = builder.build(); 2371 return GetAclStatusResponseProto.newBuilder().setResult(r).build(); 2372 } 2373 2374 public static XAttrProto convertXAttrProto(XAttr a) { 2375 XAttrProto.Builder builder = XAttrProto.newBuilder(); 2376 builder.setNamespace(convert(a.getNameSpace())); 2377 if (a.getName() != null) { 2378 builder.setName(a.getName()); 2379 } 2380 if (a.getValue() != null) { 2381 builder.setValue(getByteString(a.getValue())); 2382 } 2383 return builder.build(); 2384 } 2385 2386 public static List<XAttrProto> convertXAttrProto( 2387 List<XAttr> xAttrSpec) { 2388 if (xAttrSpec == null) { 2389 return Lists.newArrayListWithCapacity(0); 2390 } 2391 ArrayList<XAttrProto> xAttrs = Lists.newArrayListWithCapacity( 2392 xAttrSpec.size()); 2393 for (XAttr a : xAttrSpec) { 2394 XAttrProto.Builder builder = XAttrProto.newBuilder(); 2395 builder.setNamespace(convert(a.getNameSpace())); 2396 if (a.getName() != null) { 2397 builder.setName(a.getName()); 2398 } 2399 if (a.getValue() != null) { 2400 builder.setValue(getByteString(a.getValue())); 2401 } 2402 xAttrs.add(builder.build()); 2403 } 2404 return xAttrs; 2405 } 2406 2407 /** 2408 * The flag field in PB is a bitmask whose values are the same a the 2409 * emum values of XAttrSetFlag 2410 */ 2411 public static int convert(EnumSet<XAttrSetFlag> flag) { 2412 int value = 0; 2413 if (flag.contains(XAttrSetFlag.CREATE)) { 2414 value |= XAttrSetFlagProto.XATTR_CREATE.getNumber(); 2415 } 2416 if (flag.contains(XAttrSetFlag.REPLACE)) { 2417 value |= XAttrSetFlagProto.XATTR_REPLACE.getNumber(); 2418 } 2419 return value; 2420 } 2421 2422 public static EnumSet<XAttrSetFlag> convert(int flag) { 2423 EnumSet<XAttrSetFlag> result = 2424 EnumSet.noneOf(XAttrSetFlag.class); 2425 if ((flag & XAttrSetFlagProto.XATTR_CREATE_VALUE) == 2426 XAttrSetFlagProto.XATTR_CREATE_VALUE) { 2427 result.add(XAttrSetFlag.CREATE); 2428 } 2429 if ((flag & XAttrSetFlagProto.XATTR_REPLACE_VALUE) == 2430 XAttrSetFlagProto.XATTR_REPLACE_VALUE) { 2431 result.add(XAttrSetFlag.REPLACE); 2432 } 2433 return result; 2434 } 2435 2436 public static XAttr convertXAttr(XAttrProto a) { 2437 XAttr.Builder builder = new XAttr.Builder(); 2438 builder.setNameSpace(convert(a.getNamespace())); 2439 if (a.hasName()) { 2440 builder.setName(a.getName()); 2441 } 2442 if (a.hasValue()) { 2443 builder.setValue(a.getValue().toByteArray()); 2444 } 2445 return builder.build(); 2446 } 2447 2448 public static List<XAttr> convertXAttrs(List<XAttrProto> xAttrSpec) { 2449 ArrayList<XAttr> xAttrs = Lists.newArrayListWithCapacity(xAttrSpec.size()); 2450 for (XAttrProto a : xAttrSpec) { 2451 XAttr.Builder builder = new XAttr.Builder(); 2452 builder.setNameSpace(convert(a.getNamespace())); 2453 if (a.hasName()) { 2454 builder.setName(a.getName()); 2455 } 2456 if (a.hasValue()) { 2457 builder.setValue(a.getValue().toByteArray()); 2458 } 2459 xAttrs.add(builder.build()); 2460 } 2461 return xAttrs; 2462 } 2463 2464 public static List<XAttr> convert(GetXAttrsResponseProto a) { 2465 List<XAttrProto> xAttrs = a.getXAttrsList(); 2466 return convertXAttrs(xAttrs); 2467 } 2468 2469 public static GetXAttrsResponseProto convertXAttrsResponse( 2470 List<XAttr> xAttrs) { 2471 GetXAttrsResponseProto.Builder builder = GetXAttrsResponseProto 2472 .newBuilder(); 2473 if (xAttrs != null) { 2474 builder.addAllXAttrs(convertXAttrProto(xAttrs)); 2475 } 2476 return builder.build(); 2477 } 2478 2479 public static List<XAttr> convert(ListXAttrsResponseProto a) { 2480 final List<XAttrProto> xAttrs = a.getXAttrsList(); 2481 return convertXAttrs(xAttrs); 2482 } 2483 2484 public static ListXAttrsResponseProto convertListXAttrsResponse( 2485 List<XAttr> names) { 2486 ListXAttrsResponseProto.Builder builder = 2487 ListXAttrsResponseProto.newBuilder(); 2488 if (names != null) { 2489 builder.addAllXAttrs(convertXAttrProto(names)); 2490 } 2491 return builder.build(); 2492 } 2493 2494 public static EncryptionZoneProto convert(EncryptionZone zone) { 2495 return EncryptionZoneProto.newBuilder() 2496 .setId(zone.getId()) 2497 .setPath(zone.getPath()) 2498 .setSuite(convert(zone.getSuite())) 2499 .setCryptoProtocolVersion(convert(zone.getVersion())) 2500 .setKeyName(zone.getKeyName()) 2501 .build(); 2502 } 2503 2504 public static EncryptionZone convert(EncryptionZoneProto proto) { 2505 return new EncryptionZone(proto.getId(), proto.getPath(), 2506 convert(proto.getSuite()), convert(proto.getCryptoProtocolVersion()), 2507 proto.getKeyName()); 2508 } 2509 2510 public static ShortCircuitShmSlotProto convert(SlotId slotId) { 2511 return ShortCircuitShmSlotProto.newBuilder(). 2512 setShmId(convert(slotId.getShmId())). 2513 setSlotIdx(slotId.getSlotIdx()). 2514 build(); 2515 } 2516 2517 public static ShortCircuitShmIdProto convert(ShmId shmId) { 2518 return ShortCircuitShmIdProto.newBuilder(). 2519 setHi(shmId.getHi()). 2520 setLo(shmId.getLo()). 2521 build(); 2522 2523 } 2524 2525 public static SlotId convert(ShortCircuitShmSlotProto slotId) { 2526 return new SlotId(PBHelper.convert(slotId.getShmId()), 2527 slotId.getSlotIdx()); 2528 } 2529 2530 public static ShmId convert(ShortCircuitShmIdProto shmId) { 2531 return new ShmId(shmId.getHi(), shmId.getLo()); 2532 } 2533 2534 private static Event.CreateEvent.INodeType createTypeConvert(InotifyProtos.INodeType 2535 type) { 2536 switch (type) { 2537 case I_TYPE_DIRECTORY: 2538 return Event.CreateEvent.INodeType.DIRECTORY; 2539 case I_TYPE_FILE: 2540 return Event.CreateEvent.INodeType.FILE; 2541 case I_TYPE_SYMLINK: 2542 return Event.CreateEvent.INodeType.SYMLINK; 2543 default: 2544 return null; 2545 } 2546 } 2547 2548 private static InotifyProtos.MetadataUpdateType metadataUpdateTypeConvert( 2549 Event.MetadataUpdateEvent.MetadataType type) { 2550 switch (type) { 2551 case TIMES: 2552 return InotifyProtos.MetadataUpdateType.META_TYPE_TIMES; 2553 case REPLICATION: 2554 return InotifyProtos.MetadataUpdateType.META_TYPE_REPLICATION; 2555 case OWNER: 2556 return InotifyProtos.MetadataUpdateType.META_TYPE_OWNER; 2557 case PERMS: 2558 return InotifyProtos.MetadataUpdateType.META_TYPE_PERMS; 2559 case ACLS: 2560 return InotifyProtos.MetadataUpdateType.META_TYPE_ACLS; 2561 case XATTRS: 2562 return InotifyProtos.MetadataUpdateType.META_TYPE_XATTRS; 2563 default: 2564 return null; 2565 } 2566 } 2567 2568 private static Event.MetadataUpdateEvent.MetadataType metadataUpdateTypeConvert( 2569 InotifyProtos.MetadataUpdateType type) { 2570 switch (type) { 2571 case META_TYPE_TIMES: 2572 return Event.MetadataUpdateEvent.MetadataType.TIMES; 2573 case META_TYPE_REPLICATION: 2574 return Event.MetadataUpdateEvent.MetadataType.REPLICATION; 2575 case META_TYPE_OWNER: 2576 return Event.MetadataUpdateEvent.MetadataType.OWNER; 2577 case META_TYPE_PERMS: 2578 return Event.MetadataUpdateEvent.MetadataType.PERMS; 2579 case META_TYPE_ACLS: 2580 return Event.MetadataUpdateEvent.MetadataType.ACLS; 2581 case META_TYPE_XATTRS: 2582 return Event.MetadataUpdateEvent.MetadataType.XATTRS; 2583 default: 2584 return null; 2585 } 2586 } 2587 2588 private static InotifyProtos.INodeType createTypeConvert(Event.CreateEvent.INodeType 2589 type) { 2590 switch (type) { 2591 case DIRECTORY: 2592 return InotifyProtos.INodeType.I_TYPE_DIRECTORY; 2593 case FILE: 2594 return InotifyProtos.INodeType.I_TYPE_FILE; 2595 case SYMLINK: 2596 return InotifyProtos.INodeType.I_TYPE_SYMLINK; 2597 default: 2598 return null; 2599 } 2600 } 2601 2602 public static EventBatchList convert(GetEditsFromTxidResponseProto resp) throws 2603 IOException { 2604 final InotifyProtos.EventsListProto list = resp.getEventsList(); 2605 final long firstTxid = list.getFirstTxid(); 2606 final long lastTxid = list.getLastTxid(); 2607 2608 List<EventBatch> batches = Lists.newArrayList(); 2609 if (list.getEventsList().size() > 0) { 2610 throw new IOException("Can't handle old inotify server response."); 2611 } 2612 for (InotifyProtos.EventBatchProto bp : list.getBatchList()) { 2613 long txid = bp.getTxid(); 2614 if ((txid != -1) && ((txid < firstTxid) || (txid > lastTxid))) { 2615 throw new IOException("Error converting TxidResponseProto: got a " + 2616 "transaction id " + txid + " that was outside the range of [" + 2617 firstTxid + ", " + lastTxid + "]."); 2618 } 2619 List<Event> events = Lists.newArrayList(); 2620 for (InotifyProtos.EventProto p : bp.getEventsList()) { 2621 switch (p.getType()) { 2622 case EVENT_CLOSE: 2623 InotifyProtos.CloseEventProto close = 2624 InotifyProtos.CloseEventProto.parseFrom(p.getContents()); 2625 events.add(new Event.CloseEvent(close.getPath(), 2626 close.getFileSize(), close.getTimestamp())); 2627 break; 2628 case EVENT_CREATE: 2629 InotifyProtos.CreateEventProto create = 2630 InotifyProtos.CreateEventProto.parseFrom(p.getContents()); 2631 events.add(new Event.CreateEvent.Builder() 2632 .iNodeType(createTypeConvert(create.getType())) 2633 .path(create.getPath()) 2634 .ctime(create.getCtime()) 2635 .ownerName(create.getOwnerName()) 2636 .groupName(create.getGroupName()) 2637 .perms(convert(create.getPerms())) 2638 .replication(create.getReplication()) 2639 .symlinkTarget(create.getSymlinkTarget().isEmpty() ? null : 2640 create.getSymlinkTarget()) 2641 .defaultBlockSize(create.getDefaultBlockSize()) 2642 .overwrite(create.getOverwrite()).build()); 2643 break; 2644 case EVENT_METADATA: 2645 InotifyProtos.MetadataUpdateEventProto meta = 2646 InotifyProtos.MetadataUpdateEventProto.parseFrom(p.getContents()); 2647 events.add(new Event.MetadataUpdateEvent.Builder() 2648 .path(meta.getPath()) 2649 .metadataType(metadataUpdateTypeConvert(meta.getType())) 2650 .mtime(meta.getMtime()) 2651 .atime(meta.getAtime()) 2652 .replication(meta.getReplication()) 2653 .ownerName( 2654 meta.getOwnerName().isEmpty() ? null : meta.getOwnerName()) 2655 .groupName( 2656 meta.getGroupName().isEmpty() ? null : meta.getGroupName()) 2657 .perms(meta.hasPerms() ? convert(meta.getPerms()) : null) 2658 .acls(meta.getAclsList().isEmpty() ? null : convertAclEntry( 2659 meta.getAclsList())) 2660 .xAttrs(meta.getXAttrsList().isEmpty() ? null : convertXAttrs( 2661 meta.getXAttrsList())) 2662 .xAttrsRemoved(meta.getXAttrsRemoved()) 2663 .build()); 2664 break; 2665 case EVENT_RENAME: 2666 InotifyProtos.RenameEventProto rename = 2667 InotifyProtos.RenameEventProto.parseFrom(p.getContents()); 2668 events.add(new Event.RenameEvent.Builder() 2669 .srcPath(rename.getSrcPath()) 2670 .dstPath(rename.getDestPath()) 2671 .timestamp(rename.getTimestamp()) 2672 .build()); 2673 break; 2674 case EVENT_APPEND: 2675 InotifyProtos.AppendEventProto append = 2676 InotifyProtos.AppendEventProto.parseFrom(p.getContents()); 2677 events.add(new Event.AppendEvent.Builder().path(append.getPath()) 2678 .newBlock(append.hasNewBlock() && append.getNewBlock()) 2679 .build()); 2680 break; 2681 case EVENT_UNLINK: 2682 InotifyProtos.UnlinkEventProto unlink = 2683 InotifyProtos.UnlinkEventProto.parseFrom(p.getContents()); 2684 events.add(new Event.UnlinkEvent.Builder() 2685 .path(unlink.getPath()) 2686 .timestamp(unlink.getTimestamp()) 2687 .build()); 2688 break; 2689 default: 2690 throw new RuntimeException("Unexpected inotify event type: " + 2691 p.getType()); 2692 } 2693 } 2694 batches.add(new EventBatch(txid, events.toArray(new Event[0]))); 2695 } 2696 return new EventBatchList(batches, resp.getEventsList().getFirstTxid(), 2697 resp.getEventsList().getLastTxid(), resp.getEventsList().getSyncTxid()); 2698 } 2699 2700 public static GetEditsFromTxidResponseProto convertEditsResponse(EventBatchList el) { 2701 InotifyProtos.EventsListProto.Builder builder = 2702 InotifyProtos.EventsListProto.newBuilder(); 2703 for (EventBatch b : el.getBatches()) { 2704 List<InotifyProtos.EventProto> events = Lists.newArrayList(); 2705 for (Event e : b.getEvents()) { 2706 switch (e.getEventType()) { 2707 case CLOSE: 2708 Event.CloseEvent ce = (Event.CloseEvent) e; 2709 events.add(InotifyProtos.EventProto.newBuilder() 2710 .setType(InotifyProtos.EventType.EVENT_CLOSE) 2711 .setContents( 2712 InotifyProtos.CloseEventProto.newBuilder() 2713 .setPath(ce.getPath()) 2714 .setFileSize(ce.getFileSize()) 2715 .setTimestamp(ce.getTimestamp()).build().toByteString() 2716 ).build()); 2717 break; 2718 case CREATE: 2719 Event.CreateEvent ce2 = (Event.CreateEvent) e; 2720 events.add(InotifyProtos.EventProto.newBuilder() 2721 .setType(InotifyProtos.EventType.EVENT_CREATE) 2722 .setContents( 2723 InotifyProtos.CreateEventProto.newBuilder() 2724 .setType(createTypeConvert(ce2.getiNodeType())) 2725 .setPath(ce2.getPath()) 2726 .setCtime(ce2.getCtime()) 2727 .setOwnerName(ce2.getOwnerName()) 2728 .setGroupName(ce2.getGroupName()) 2729 .setPerms(convert(ce2.getPerms())) 2730 .setReplication(ce2.getReplication()) 2731 .setSymlinkTarget(ce2.getSymlinkTarget() == null ? 2732 "" : ce2.getSymlinkTarget()) 2733 .setDefaultBlockSize(ce2.getDefaultBlockSize()) 2734 .setOverwrite(ce2.getOverwrite()).build().toByteString() 2735 ).build()); 2736 break; 2737 case METADATA: 2738 Event.MetadataUpdateEvent me = (Event.MetadataUpdateEvent) e; 2739 InotifyProtos.MetadataUpdateEventProto.Builder metaB = 2740 InotifyProtos.MetadataUpdateEventProto.newBuilder() 2741 .setPath(me.getPath()) 2742 .setType(metadataUpdateTypeConvert(me.getMetadataType())) 2743 .setMtime(me.getMtime()) 2744 .setAtime(me.getAtime()) 2745 .setReplication(me.getReplication()) 2746 .setOwnerName(me.getOwnerName() == null ? "" : 2747 me.getOwnerName()) 2748 .setGroupName(me.getGroupName() == null ? "" : 2749 me.getGroupName()) 2750 .addAllAcls(me.getAcls() == null ? 2751 Lists.<AclEntryProto>newArrayList() : 2752 convertAclEntryProto(me.getAcls())) 2753 .addAllXAttrs(me.getxAttrs() == null ? 2754 Lists.<XAttrProto>newArrayList() : 2755 convertXAttrProto(me.getxAttrs())) 2756 .setXAttrsRemoved(me.isxAttrsRemoved()); 2757 if (me.getPerms() != null) { 2758 metaB.setPerms(convert(me.getPerms())); 2759 } 2760 events.add(InotifyProtos.EventProto.newBuilder() 2761 .setType(InotifyProtos.EventType.EVENT_METADATA) 2762 .setContents(metaB.build().toByteString()) 2763 .build()); 2764 break; 2765 case RENAME: 2766 Event.RenameEvent re = (Event.RenameEvent) e; 2767 events.add(InotifyProtos.EventProto.newBuilder() 2768 .setType(InotifyProtos.EventType.EVENT_RENAME) 2769 .setContents( 2770 InotifyProtos.RenameEventProto.newBuilder() 2771 .setSrcPath(re.getSrcPath()) 2772 .setDestPath(re.getDstPath()) 2773 .setTimestamp(re.getTimestamp()).build().toByteString() 2774 ).build()); 2775 break; 2776 case APPEND: 2777 Event.AppendEvent re2 = (Event.AppendEvent) e; 2778 events.add(InotifyProtos.EventProto.newBuilder() 2779 .setType(InotifyProtos.EventType.EVENT_APPEND) 2780 .setContents(InotifyProtos.AppendEventProto.newBuilder() 2781 .setPath(re2.getPath()) 2782 .setNewBlock(re2.toNewBlock()).build().toByteString()) 2783 .build()); 2784 break; 2785 case UNLINK: 2786 Event.UnlinkEvent ue = (Event.UnlinkEvent) e; 2787 events.add(InotifyProtos.EventProto.newBuilder() 2788 .setType(InotifyProtos.EventType.EVENT_UNLINK) 2789 .setContents( 2790 InotifyProtos.UnlinkEventProto.newBuilder() 2791 .setPath(ue.getPath()) 2792 .setTimestamp(ue.getTimestamp()).build().toByteString() 2793 ).build()); 2794 break; 2795 default: 2796 throw new RuntimeException("Unexpected inotify event: " + e); 2797 } 2798 } 2799 builder.addBatch(InotifyProtos.EventBatchProto.newBuilder(). 2800 setTxid(b.getTxid()). 2801 addAllEvents(events)); 2802 } 2803 builder.setFirstTxid(el.getFirstTxid()); 2804 builder.setLastTxid(el.getLastTxid()); 2805 builder.setSyncTxid(el.getSyncTxid()); 2806 return GetEditsFromTxidResponseProto.newBuilder().setEventsList( 2807 builder.build()).build(); 2808 } 2809 2810 public static CipherOptionProto convert(CipherOption option) { 2811 if (option != null) { 2812 CipherOptionProto.Builder builder = CipherOptionProto. 2813 newBuilder(); 2814 if (option.getCipherSuite() != null) { 2815 builder.setSuite(convert(option.getCipherSuite())); 2816 } 2817 if (option.getInKey() != null) { 2818 builder.setInKey(ByteString.copyFrom(option.getInKey())); 2819 } 2820 if (option.getInIv() != null) { 2821 builder.setInIv(ByteString.copyFrom(option.getInIv())); 2822 } 2823 if (option.getOutKey() != null) { 2824 builder.setOutKey(ByteString.copyFrom(option.getOutKey())); 2825 } 2826 if (option.getOutIv() != null) { 2827 builder.setOutIv(ByteString.copyFrom(option.getOutIv())); 2828 } 2829 return builder.build(); 2830 } 2831 return null; 2832 } 2833 2834 public static CipherOption convert(CipherOptionProto proto) { 2835 if (proto != null) { 2836 CipherSuite suite = null; 2837 if (proto.getSuite() != null) { 2838 suite = convert(proto.getSuite()); 2839 } 2840 byte[] inKey = null; 2841 if (proto.getInKey() != null) { 2842 inKey = proto.getInKey().toByteArray(); 2843 } 2844 byte[] inIv = null; 2845 if (proto.getInIv() != null) { 2846 inIv = proto.getInIv().toByteArray(); 2847 } 2848 byte[] outKey = null; 2849 if (proto.getOutKey() != null) { 2850 outKey = proto.getOutKey().toByteArray(); 2851 } 2852 byte[] outIv = null; 2853 if (proto.getOutIv() != null) { 2854 outIv = proto.getOutIv().toByteArray(); 2855 } 2856 return new CipherOption(suite, inKey, inIv, outKey, outIv); 2857 } 2858 return null; 2859 } 2860 2861 public static List<CipherOptionProto> convertCipherOptions( 2862 List<CipherOption> options) { 2863 if (options != null) { 2864 List<CipherOptionProto> protos = 2865 Lists.newArrayListWithCapacity(options.size()); 2866 for (CipherOption option : options) { 2867 protos.add(convert(option)); 2868 } 2869 return protos; 2870 } 2871 return null; 2872 } 2873 2874 public static List<CipherOption> convertCipherOptionProtos( 2875 List<CipherOptionProto> protos) { 2876 if (protos != null) { 2877 List<CipherOption> options = 2878 Lists.newArrayListWithCapacity(protos.size()); 2879 for (CipherOptionProto proto : protos) { 2880 options.add(convert(proto)); 2881 } 2882 return options; 2883 } 2884 return null; 2885 } 2886 2887 public static CipherSuiteProto convert(CipherSuite suite) { 2888 switch (suite) { 2889 case UNKNOWN: 2890 return CipherSuiteProto.UNKNOWN; 2891 case AES_CTR_NOPADDING: 2892 return CipherSuiteProto.AES_CTR_NOPADDING; 2893 default: 2894 return null; 2895 } 2896 } 2897 2898 public static CipherSuite convert(CipherSuiteProto proto) { 2899 switch (proto) { 2900 case AES_CTR_NOPADDING: 2901 return CipherSuite.AES_CTR_NOPADDING; 2902 default: 2903 // Set to UNKNOWN and stash the unknown enum value 2904 CipherSuite suite = CipherSuite.UNKNOWN; 2905 suite.setUnknownValue(proto.getNumber()); 2906 return suite; 2907 } 2908 } 2909 2910 public static List<CryptoProtocolVersionProto> convert( 2911 CryptoProtocolVersion[] versions) { 2912 List<CryptoProtocolVersionProto> protos = 2913 Lists.newArrayListWithCapacity(versions.length); 2914 for (CryptoProtocolVersion v: versions) { 2915 protos.add(convert(v)); 2916 } 2917 return protos; 2918 } 2919 2920 public static CryptoProtocolVersion[] convertCryptoProtocolVersions( 2921 List<CryptoProtocolVersionProto> protos) { 2922 List<CryptoProtocolVersion> versions = 2923 Lists.newArrayListWithCapacity(protos.size()); 2924 for (CryptoProtocolVersionProto p: protos) { 2925 versions.add(convert(p)); 2926 } 2927 return versions.toArray(new CryptoProtocolVersion[] {}); 2928 } 2929 2930 public static CryptoProtocolVersion convert(CryptoProtocolVersionProto 2931 proto) { 2932 switch(proto) { 2933 case ENCRYPTION_ZONES: 2934 return CryptoProtocolVersion.ENCRYPTION_ZONES; 2935 default: 2936 // Set to UNKNOWN and stash the unknown enum value 2937 CryptoProtocolVersion version = CryptoProtocolVersion.UNKNOWN; 2938 version.setUnknownValue(proto.getNumber()); 2939 return version; 2940 } 2941 } 2942 2943 public static CryptoProtocolVersionProto convert(CryptoProtocolVersion 2944 version) { 2945 switch(version) { 2946 case UNKNOWN: 2947 return CryptoProtocolVersionProto.UNKNOWN_PROTOCOL_VERSION; 2948 case ENCRYPTION_ZONES: 2949 return CryptoProtocolVersionProto.ENCRYPTION_ZONES; 2950 default: 2951 return null; 2952 } 2953 } 2954 2955 public static HdfsProtos.FileEncryptionInfoProto convert( 2956 FileEncryptionInfo info) { 2957 if (info == null) { 2958 return null; 2959 } 2960 return HdfsProtos.FileEncryptionInfoProto.newBuilder() 2961 .setSuite(convert(info.getCipherSuite())) 2962 .setCryptoProtocolVersion(convert(info.getCryptoProtocolVersion())) 2963 .setKey(getByteString(info.getEncryptedDataEncryptionKey())) 2964 .setIv(getByteString(info.getIV())) 2965 .setEzKeyVersionName(info.getEzKeyVersionName()) 2966 .setKeyName(info.getKeyName()) 2967 .build(); 2968 } 2969 2970 public static HdfsProtos.PerFileEncryptionInfoProto convertPerFileEncInfo( 2971 FileEncryptionInfo info) { 2972 if (info == null) { 2973 return null; 2974 } 2975 return HdfsProtos.PerFileEncryptionInfoProto.newBuilder() 2976 .setKey(getByteString(info.getEncryptedDataEncryptionKey())) 2977 .setIv(getByteString(info.getIV())) 2978 .setEzKeyVersionName(info.getEzKeyVersionName()) 2979 .build(); 2980 } 2981 2982 public static HdfsProtos.ZoneEncryptionInfoProto convert( 2983 CipherSuite suite, CryptoProtocolVersion version, String keyName) { 2984 if (suite == null || version == null || keyName == null) { 2985 return null; 2986 } 2987 return HdfsProtos.ZoneEncryptionInfoProto.newBuilder() 2988 .setSuite(convert(suite)) 2989 .setCryptoProtocolVersion(convert(version)) 2990 .setKeyName(keyName) 2991 .build(); 2992 } 2993 2994 public static FileEncryptionInfo convert( 2995 HdfsProtos.FileEncryptionInfoProto proto) { 2996 if (proto == null) { 2997 return null; 2998 } 2999 CipherSuite suite = convert(proto.getSuite()); 3000 CryptoProtocolVersion version = convert(proto.getCryptoProtocolVersion()); 3001 byte[] key = proto.getKey().toByteArray(); 3002 byte[] iv = proto.getIv().toByteArray(); 3003 String ezKeyVersionName = proto.getEzKeyVersionName(); 3004 String keyName = proto.getKeyName(); 3005 return new FileEncryptionInfo(suite, version, key, iv, keyName, 3006 ezKeyVersionName); 3007 } 3008 3009 public static FileEncryptionInfo convert( 3010 HdfsProtos.PerFileEncryptionInfoProto fileProto, 3011 CipherSuite suite, CryptoProtocolVersion version, String keyName) { 3012 if (fileProto == null || suite == null || version == null || 3013 keyName == null) { 3014 return null; 3015 } 3016 byte[] key = fileProto.getKey().toByteArray(); 3017 byte[] iv = fileProto.getIv().toByteArray(); 3018 String ezKeyVersionName = fileProto.getEzKeyVersionName(); 3019 return new FileEncryptionInfo(suite, version, key, iv, keyName, 3020 ezKeyVersionName); 3021 } 3022 3023 public static List<Boolean> convert(boolean[] targetPinnings, int idx) { 3024 List<Boolean> pinnings = new ArrayList<Boolean>(); 3025 if (targetPinnings == null) { 3026 pinnings.add(Boolean.FALSE); 3027 } else { 3028 for (; idx < targetPinnings.length; ++idx) { 3029 pinnings.add(Boolean.valueOf(targetPinnings[idx])); 3030 } 3031 } 3032 return pinnings; 3033 } 3034 3035 public static boolean[] convertBooleanList( 3036 List<Boolean> targetPinningsList) { 3037 final boolean[] targetPinnings = new boolean[targetPinningsList.size()]; 3038 for (int i = 0; i < targetPinningsList.size(); i++) { 3039 targetPinnings[i] = targetPinningsList.get(i); 3040 } 3041 return targetPinnings; 3042 } 3043 3044 public static BlockReportContext convert(BlockReportContextProto proto) { 3045 return new BlockReportContext(proto.getTotalRpcs(), 3046 proto.getCurRpc(), proto.getId()); 3047 } 3048 3049 public static BlockReportContextProto convert(BlockReportContext context) { 3050 return BlockReportContextProto.newBuilder(). 3051 setTotalRpcs(context.getTotalRpcs()). 3052 setCurRpc(context.getCurRpc()). 3053 setId(context.getReportId()). 3054 build(); 3055 } 3056}