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.XAttr; 040import org.apache.hadoop.fs.XAttrSetFlag; 041import org.apache.hadoop.fs.permission.AclEntry; 042import org.apache.hadoop.fs.permission.AclEntryScope; 043import org.apache.hadoop.fs.permission.AclEntryType; 044import org.apache.hadoop.fs.permission.AclStatus; 045import org.apache.hadoop.fs.permission.FsAction; 046import org.apache.hadoop.fs.permission.FsPermission; 047import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; 048import org.apache.hadoop.ha.proto.HAServiceProtocolProtos; 049import org.apache.hadoop.hdfs.inotify.EventBatch; 050import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy; 051import org.apache.hadoop.hdfs.DFSUtil; 052import org.apache.hadoop.hdfs.StorageType; 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.BlockReportContextProto; 127import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.VolumeFailureSummaryProto; 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()); 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 return RecoveringBlockProto.newBuilder().setBlock(lb) 617 .setNewGenStamp(b.getNewGenerationStamp()).build(); 618 } 619 620 public static RecoveringBlock convert(RecoveringBlockProto b) { 621 ExtendedBlock block = convert(b.getBlock().getB()); 622 DatanodeInfo[] locs = convert(b.getBlock().getLocsList()); 623 return new RecoveringBlock(block, locs, b.getNewGenStamp()); 624 } 625 626 public static DatanodeInfoProto.AdminState convert( 627 final DatanodeInfo.AdminStates inAs) { 628 switch (inAs) { 629 case NORMAL: return DatanodeInfoProto.AdminState.NORMAL; 630 case DECOMMISSION_INPROGRESS: 631 return DatanodeInfoProto.AdminState.DECOMMISSION_INPROGRESS; 632 case DECOMMISSIONED: return DatanodeInfoProto.AdminState.DECOMMISSIONED; 633 default: return DatanodeInfoProto.AdminState.NORMAL; 634 } 635 } 636 637 static public DatanodeInfo convert(DatanodeInfoProto di) { 638 if (di == null) return null; 639 return new DatanodeInfo( 640 PBHelper.convert(di.getId()), 641 di.hasLocation() ? di.getLocation() : null , 642 di.getCapacity(), di.getDfsUsed(), di.getRemaining(), 643 di.getBlockPoolUsed(), di.getCacheCapacity(), di.getCacheUsed(), 644 di.getLastUpdate(), di.getXceiverCount(), 645 PBHelper.convert(di.getAdminState())); 646 } 647 648 static public DatanodeInfoProto convertDatanodeInfo(DatanodeInfo di) { 649 if (di == null) return null; 650 return convert(di); 651 } 652 653 654 static public DatanodeInfo[] convert(DatanodeInfoProto di[]) { 655 if (di == null) return null; 656 DatanodeInfo[] result = new DatanodeInfo[di.length]; 657 for (int i = 0; i < di.length; i++) { 658 result[i] = convert(di[i]); 659 } 660 return result; 661 } 662 663 public static List<? extends HdfsProtos.DatanodeInfoProto> convert( 664 DatanodeInfo[] dnInfos) { 665 return convert(dnInfos, 0); 666 } 667 668 /** 669 * Copy from {@code dnInfos} to a target of list of same size starting at 670 * {@code startIdx}. 671 */ 672 public static List<? extends HdfsProtos.DatanodeInfoProto> convert( 673 DatanodeInfo[] dnInfos, int startIdx) { 674 if (dnInfos == null) 675 return null; 676 ArrayList<HdfsProtos.DatanodeInfoProto> protos = Lists 677 .newArrayListWithCapacity(dnInfos.length); 678 for (int i = startIdx; i < dnInfos.length; i++) { 679 protos.add(convert(dnInfos[i])); 680 } 681 return protos; 682 } 683 684 public static DatanodeInfo[] convert(List<DatanodeInfoProto> list) { 685 DatanodeInfo[] info = new DatanodeInfo[list.size()]; 686 for (int i = 0; i < info.length; i++) { 687 info[i] = convert(list.get(i)); 688 } 689 return info; 690 } 691 692 public static DatanodeInfoProto convert(DatanodeInfo info) { 693 DatanodeInfoProto.Builder builder = DatanodeInfoProto.newBuilder(); 694 if (info.getNetworkLocation() != null) { 695 builder.setLocation(info.getNetworkLocation()); 696 } 697 builder 698 .setId(PBHelper.convert((DatanodeID)info)) 699 .setCapacity(info.getCapacity()) 700 .setDfsUsed(info.getDfsUsed()) 701 .setRemaining(info.getRemaining()) 702 .setBlockPoolUsed(info.getBlockPoolUsed()) 703 .setCacheCapacity(info.getCacheCapacity()) 704 .setCacheUsed(info.getCacheUsed()) 705 .setLastUpdate(info.getLastUpdate()) 706 .setXceiverCount(info.getXceiverCount()) 707 .setAdminState(PBHelper.convert(info.getAdminState())) 708 .build(); 709 return builder.build(); 710 } 711 712 public static DatanodeStorageReportProto convertDatanodeStorageReport( 713 DatanodeStorageReport report) { 714 return DatanodeStorageReportProto.newBuilder() 715 .setDatanodeInfo(convert(report.getDatanodeInfo())) 716 .addAllStorageReports(convertStorageReports(report.getStorageReports())) 717 .build(); 718 } 719 720 public static List<DatanodeStorageReportProto> convertDatanodeStorageReports( 721 DatanodeStorageReport[] reports) { 722 final List<DatanodeStorageReportProto> protos 723 = new ArrayList<DatanodeStorageReportProto>(reports.length); 724 for(int i = 0; i < reports.length; i++) { 725 protos.add(convertDatanodeStorageReport(reports[i])); 726 } 727 return protos; 728 } 729 730 public static DatanodeStorageReport convertDatanodeStorageReport( 731 DatanodeStorageReportProto proto) { 732 return new DatanodeStorageReport( 733 convert(proto.getDatanodeInfo()), 734 convertStorageReports(proto.getStorageReportsList())); 735 } 736 737 public static DatanodeStorageReport[] convertDatanodeStorageReports( 738 List<DatanodeStorageReportProto> protos) { 739 final DatanodeStorageReport[] reports 740 = new DatanodeStorageReport[protos.size()]; 741 for(int i = 0; i < reports.length; i++) { 742 reports[i] = convertDatanodeStorageReport(protos.get(i)); 743 } 744 return reports; 745 } 746 747 public static AdminStates convert(AdminState adminState) { 748 switch(adminState) { 749 case DECOMMISSION_INPROGRESS: 750 return AdminStates.DECOMMISSION_INPROGRESS; 751 case DECOMMISSIONED: 752 return AdminStates.DECOMMISSIONED; 753 case NORMAL: 754 default: 755 return AdminStates.NORMAL; 756 } 757 } 758 759 public static LocatedBlockProto convert(LocatedBlock b) { 760 if (b == null) return null; 761 Builder builder = LocatedBlockProto.newBuilder(); 762 DatanodeInfo[] locs = b.getLocations(); 763 List<DatanodeInfo> cachedLocs = 764 Lists.newLinkedList(Arrays.asList(b.getCachedLocations())); 765 for (int i = 0; i < locs.length; i++) { 766 DatanodeInfo loc = locs[i]; 767 builder.addLocs(i, PBHelper.convert(loc)); 768 boolean locIsCached = cachedLocs.contains(loc); 769 builder.addIsCached(locIsCached); 770 if (locIsCached) { 771 cachedLocs.remove(loc); 772 } 773 } 774 Preconditions.checkArgument(cachedLocs.size() == 0, 775 "Found additional cached replica locations that are not in the set of" 776 + " storage-backed locations!"); 777 778 StorageType[] storageTypes = b.getStorageTypes(); 779 if (storageTypes != null) { 780 for (int i = 0; i < storageTypes.length; ++i) { 781 builder.addStorageTypes(PBHelper.convertStorageType(storageTypes[i])); 782 } 783 } 784 final String[] storageIDs = b.getStorageIDs(); 785 if (storageIDs != null) { 786 builder.addAllStorageIDs(Arrays.asList(storageIDs)); 787 } 788 789 return builder.setB(PBHelper.convert(b.getBlock())) 790 .setBlockToken(PBHelper.convert(b.getBlockToken())) 791 .setCorrupt(b.isCorrupt()).setOffset(b.getStartOffset()).build(); 792 } 793 794 public static LocatedBlock convert(LocatedBlockProto proto) { 795 if (proto == null) return null; 796 List<DatanodeInfoProto> locs = proto.getLocsList(); 797 DatanodeInfo[] targets = new DatanodeInfo[locs.size()]; 798 for (int i = 0; i < locs.size(); i++) { 799 targets[i] = PBHelper.convert(locs.get(i)); 800 } 801 802 final StorageType[] storageTypes = convertStorageTypes( 803 proto.getStorageTypesList(), locs.size()); 804 805 final int storageIDsCount = proto.getStorageIDsCount(); 806 final String[] storageIDs; 807 if (storageIDsCount == 0) { 808 storageIDs = null; 809 } else { 810 Preconditions.checkState(storageIDsCount == locs.size()); 811 storageIDs = proto.getStorageIDsList().toArray(new String[storageIDsCount]); 812 } 813 814 // Set values from the isCached list, re-using references from loc 815 List<DatanodeInfo> cachedLocs = new ArrayList<DatanodeInfo>(locs.size()); 816 List<Boolean> isCachedList = proto.getIsCachedList(); 817 for (int i=0; i<isCachedList.size(); i++) { 818 if (isCachedList.get(i)) { 819 cachedLocs.add(targets[i]); 820 } 821 } 822 823 LocatedBlock lb = new LocatedBlock(PBHelper.convert(proto.getB()), targets, 824 storageIDs, storageTypes, proto.getOffset(), proto.getCorrupt(), 825 cachedLocs.toArray(new DatanodeInfo[0])); 826 lb.setBlockToken(PBHelper.convert(proto.getBlockToken())); 827 828 return lb; 829 } 830 831 public static TokenProto convert(Token<?> tok) { 832 return TokenProto.newBuilder(). 833 setIdentifier(ByteString.copyFrom(tok.getIdentifier())). 834 setPassword(ByteString.copyFrom(tok.getPassword())). 835 setKind(tok.getKind().toString()). 836 setService(tok.getService().toString()).build(); 837 } 838 839 public static Token<BlockTokenIdentifier> convert( 840 TokenProto blockToken) { 841 return new Token<BlockTokenIdentifier>(blockToken.getIdentifier() 842 .toByteArray(), blockToken.getPassword().toByteArray(), new Text( 843 blockToken.getKind()), new Text(blockToken.getService())); 844 } 845 846 847 public static Token<DelegationTokenIdentifier> convertDelegationToken( 848 TokenProto blockToken) { 849 return new Token<DelegationTokenIdentifier>(blockToken.getIdentifier() 850 .toByteArray(), blockToken.getPassword().toByteArray(), new Text( 851 blockToken.getKind()), new Text(blockToken.getService())); 852 } 853 854 public static ReplicaState convert(ReplicaStateProto state) { 855 switch (state) { 856 case RBW: 857 return ReplicaState.RBW; 858 case RUR: 859 return ReplicaState.RUR; 860 case RWR: 861 return ReplicaState.RWR; 862 case TEMPORARY: 863 return ReplicaState.TEMPORARY; 864 case FINALIZED: 865 default: 866 return ReplicaState.FINALIZED; 867 } 868 } 869 870 public static ReplicaStateProto convert(ReplicaState state) { 871 switch (state) { 872 case RBW: 873 return ReplicaStateProto.RBW; 874 case RUR: 875 return ReplicaStateProto.RUR; 876 case RWR: 877 return ReplicaStateProto.RWR; 878 case TEMPORARY: 879 return ReplicaStateProto.TEMPORARY; 880 case FINALIZED: 881 default: 882 return ReplicaStateProto.FINALIZED; 883 } 884 } 885 886 public static DatanodeRegistrationProto convert( 887 DatanodeRegistration registration) { 888 DatanodeRegistrationProto.Builder builder = DatanodeRegistrationProto 889 .newBuilder(); 890 return builder.setDatanodeID(PBHelper.convert((DatanodeID) registration)) 891 .setStorageInfo(PBHelper.convert(registration.getStorageInfo())) 892 .setKeys(PBHelper.convert(registration.getExportedKeys())) 893 .setSoftwareVersion(registration.getSoftwareVersion()).build(); 894 } 895 896 public static DatanodeRegistration convert(DatanodeRegistrationProto proto) { 897 StorageInfo si = convert(proto.getStorageInfo(), NodeType.DATA_NODE); 898 return new DatanodeRegistration(PBHelper.convert(proto.getDatanodeID()), 899 si, PBHelper.convert(proto.getKeys()), proto.getSoftwareVersion()); 900 } 901 902 public static DatanodeCommand convert(DatanodeCommandProto proto) { 903 switch (proto.getCmdType()) { 904 case BalancerBandwidthCommand: 905 return PBHelper.convert(proto.getBalancerCmd()); 906 case BlockCommand: 907 return PBHelper.convert(proto.getBlkCmd()); 908 case BlockRecoveryCommand: 909 return PBHelper.convert(proto.getRecoveryCmd()); 910 case FinalizeCommand: 911 return PBHelper.convert(proto.getFinalizeCmd()); 912 case KeyUpdateCommand: 913 return PBHelper.convert(proto.getKeyUpdateCmd()); 914 case RegisterCommand: 915 return REG_CMD; 916 case BlockIdCommand: 917 return PBHelper.convert(proto.getBlkIdCmd()); 918 default: 919 return null; 920 } 921 } 922 923 public static BalancerBandwidthCommandProto convert( 924 BalancerBandwidthCommand bbCmd) { 925 return BalancerBandwidthCommandProto.newBuilder() 926 .setBandwidth(bbCmd.getBalancerBandwidthValue()).build(); 927 } 928 929 public static KeyUpdateCommandProto convert(KeyUpdateCommand cmd) { 930 return KeyUpdateCommandProto.newBuilder() 931 .setKeys(PBHelper.convert(cmd.getExportedKeys())).build(); 932 } 933 934 public static BlockRecoveryCommandProto convert(BlockRecoveryCommand cmd) { 935 BlockRecoveryCommandProto.Builder builder = BlockRecoveryCommandProto 936 .newBuilder(); 937 for (RecoveringBlock b : cmd.getRecoveringBlocks()) { 938 builder.addBlocks(PBHelper.convert(b)); 939 } 940 return builder.build(); 941 } 942 943 public static FinalizeCommandProto convert(FinalizeCommand cmd) { 944 return FinalizeCommandProto.newBuilder() 945 .setBlockPoolId(cmd.getBlockPoolId()).build(); 946 } 947 948 public static BlockCommandProto convert(BlockCommand cmd) { 949 BlockCommandProto.Builder builder = BlockCommandProto.newBuilder() 950 .setBlockPoolId(cmd.getBlockPoolId()); 951 switch (cmd.getAction()) { 952 case DatanodeProtocol.DNA_TRANSFER: 953 builder.setAction(BlockCommandProto.Action.TRANSFER); 954 break; 955 case DatanodeProtocol.DNA_INVALIDATE: 956 builder.setAction(BlockCommandProto.Action.INVALIDATE); 957 break; 958 case DatanodeProtocol.DNA_SHUTDOWN: 959 builder.setAction(BlockCommandProto.Action.SHUTDOWN); 960 break; 961 default: 962 throw new AssertionError("Invalid action"); 963 } 964 Block[] blocks = cmd.getBlocks(); 965 for (int i = 0; i < blocks.length; i++) { 966 builder.addBlocks(PBHelper.convert(blocks[i])); 967 } 968 builder.addAllTargets(convert(cmd.getTargets())) 969 .addAllTargetStorageUuids(convert(cmd.getTargetStorageIDs())); 970 StorageType[][] types = cmd.getTargetStorageTypes(); 971 if (types != null) { 972 builder.addAllTargetStorageTypes(convert(types)); 973 } 974 return builder.build(); 975 } 976 977 private static List<StorageTypesProto> convert(StorageType[][] types) { 978 List<StorageTypesProto> list = Lists.newArrayList(); 979 if (types != null) { 980 for (StorageType[] ts : types) { 981 StorageTypesProto.Builder builder = StorageTypesProto.newBuilder(); 982 builder.addAllStorageTypes(convertStorageTypes(ts)); 983 list.add(builder.build()); 984 } 985 } 986 return list; 987 } 988 989 public static BlockIdCommandProto convert(BlockIdCommand cmd) { 990 BlockIdCommandProto.Builder builder = BlockIdCommandProto.newBuilder() 991 .setBlockPoolId(cmd.getBlockPoolId()); 992 switch (cmd.getAction()) { 993 case DatanodeProtocol.DNA_CACHE: 994 builder.setAction(BlockIdCommandProto.Action.CACHE); 995 break; 996 case DatanodeProtocol.DNA_UNCACHE: 997 builder.setAction(BlockIdCommandProto.Action.UNCACHE); 998 break; 999 default: 1000 throw new AssertionError("Invalid action"); 1001 } 1002 long[] blockIds = cmd.getBlockIds(); 1003 for (int i = 0; i < blockIds.length; i++) { 1004 builder.addBlockIds(blockIds[i]); 1005 } 1006 return builder.build(); 1007 } 1008 1009 private static List<DatanodeInfosProto> convert(DatanodeInfo[][] targets) { 1010 DatanodeInfosProto[] ret = new DatanodeInfosProto[targets.length]; 1011 for (int i = 0; i < targets.length; i++) { 1012 ret[i] = DatanodeInfosProto.newBuilder() 1013 .addAllDatanodes(PBHelper.convert(targets[i])).build(); 1014 } 1015 return Arrays.asList(ret); 1016 } 1017 1018 private static List<StorageUuidsProto> convert(String[][] targetStorageUuids) { 1019 StorageUuidsProto[] ret = new StorageUuidsProto[targetStorageUuids.length]; 1020 for (int i = 0; i < targetStorageUuids.length; i++) { 1021 ret[i] = StorageUuidsProto.newBuilder() 1022 .addAllStorageUuids(Arrays.asList(targetStorageUuids[i])).build(); 1023 } 1024 return Arrays.asList(ret); 1025 } 1026 1027 public static DatanodeCommandProto convert(DatanodeCommand datanodeCommand) { 1028 DatanodeCommandProto.Builder builder = DatanodeCommandProto.newBuilder(); 1029 if (datanodeCommand == null) { 1030 return builder.setCmdType(DatanodeCommandProto.Type.NullDatanodeCommand) 1031 .build(); 1032 } 1033 switch (datanodeCommand.getAction()) { 1034 case DatanodeProtocol.DNA_BALANCERBANDWIDTHUPDATE: 1035 builder.setCmdType(DatanodeCommandProto.Type.BalancerBandwidthCommand) 1036 .setBalancerCmd( 1037 PBHelper.convert((BalancerBandwidthCommand) datanodeCommand)); 1038 break; 1039 case DatanodeProtocol.DNA_ACCESSKEYUPDATE: 1040 builder 1041 .setCmdType(DatanodeCommandProto.Type.KeyUpdateCommand) 1042 .setKeyUpdateCmd(PBHelper.convert((KeyUpdateCommand) datanodeCommand)); 1043 break; 1044 case DatanodeProtocol.DNA_RECOVERBLOCK: 1045 builder.setCmdType(DatanodeCommandProto.Type.BlockRecoveryCommand) 1046 .setRecoveryCmd( 1047 PBHelper.convert((BlockRecoveryCommand) datanodeCommand)); 1048 break; 1049 case DatanodeProtocol.DNA_FINALIZE: 1050 builder.setCmdType(DatanodeCommandProto.Type.FinalizeCommand) 1051 .setFinalizeCmd(PBHelper.convert((FinalizeCommand) datanodeCommand)); 1052 break; 1053 case DatanodeProtocol.DNA_REGISTER: 1054 builder.setCmdType(DatanodeCommandProto.Type.RegisterCommand) 1055 .setRegisterCmd(REG_CMD_PROTO); 1056 break; 1057 case DatanodeProtocol.DNA_TRANSFER: 1058 case DatanodeProtocol.DNA_INVALIDATE: 1059 case DatanodeProtocol.DNA_SHUTDOWN: 1060 builder.setCmdType(DatanodeCommandProto.Type.BlockCommand). 1061 setBlkCmd(PBHelper.convert((BlockCommand) datanodeCommand)); 1062 break; 1063 case DatanodeProtocol.DNA_CACHE: 1064 case DatanodeProtocol.DNA_UNCACHE: 1065 builder.setCmdType(DatanodeCommandProto.Type.BlockIdCommand). 1066 setBlkIdCmd(PBHelper.convert((BlockIdCommand) datanodeCommand)); 1067 break; 1068 case DatanodeProtocol.DNA_UNKNOWN: //Not expected 1069 default: 1070 builder.setCmdType(DatanodeCommandProto.Type.NullDatanodeCommand); 1071 } 1072 return builder.build(); 1073 } 1074 1075 public static KeyUpdateCommand convert(KeyUpdateCommandProto keyUpdateCmd) { 1076 return new KeyUpdateCommand(PBHelper.convert(keyUpdateCmd.getKeys())); 1077 } 1078 1079 public static FinalizeCommand convert(FinalizeCommandProto finalizeCmd) { 1080 return new FinalizeCommand(finalizeCmd.getBlockPoolId()); 1081 } 1082 1083 public static BlockRecoveryCommand convert( 1084 BlockRecoveryCommandProto recoveryCmd) { 1085 List<RecoveringBlockProto> list = recoveryCmd.getBlocksList(); 1086 List<RecoveringBlock> recoveringBlocks = new ArrayList<RecoveringBlock>( 1087 list.size()); 1088 1089 for (RecoveringBlockProto rbp : list) { 1090 recoveringBlocks.add(PBHelper.convert(rbp)); 1091 } 1092 return new BlockRecoveryCommand(recoveringBlocks); 1093 } 1094 1095 public static BlockCommand convert(BlockCommandProto blkCmd) { 1096 List<BlockProto> blockProtoList = blkCmd.getBlocksList(); 1097 Block[] blocks = new Block[blockProtoList.size()]; 1098 for (int i = 0; i < blockProtoList.size(); i++) { 1099 blocks[i] = PBHelper.convert(blockProtoList.get(i)); 1100 } 1101 List<DatanodeInfosProto> targetList = blkCmd.getTargetsList(); 1102 DatanodeInfo[][] targets = new DatanodeInfo[targetList.size()][]; 1103 for (int i = 0; i < targetList.size(); i++) { 1104 targets[i] = PBHelper.convert(targetList.get(i)); 1105 } 1106 1107 StorageType[][] targetStorageTypes = new StorageType[targetList.size()][]; 1108 List<StorageTypesProto> targetStorageTypesList = blkCmd.getTargetStorageTypesList(); 1109 if (targetStorageTypesList.isEmpty()) { // missing storage types 1110 for(int i = 0; i < targetStorageTypes.length; i++) { 1111 targetStorageTypes[i] = new StorageType[targets[i].length]; 1112 Arrays.fill(targetStorageTypes[i], StorageType.DEFAULT); 1113 } 1114 } else { 1115 for(int i = 0; i < targetStorageTypes.length; i++) { 1116 List<StorageTypeProto> p = targetStorageTypesList.get(i).getStorageTypesList(); 1117 targetStorageTypes[i] = convertStorageTypes(p, targets[i].length); 1118 } 1119 } 1120 1121 List<StorageUuidsProto> targetStorageUuidsList = blkCmd.getTargetStorageUuidsList(); 1122 String[][] targetStorageIDs = new String[targetStorageUuidsList.size()][]; 1123 for(int i = 0; i < targetStorageIDs.length; i++) { 1124 List<String> storageIDs = targetStorageUuidsList.get(i).getStorageUuidsList(); 1125 targetStorageIDs[i] = storageIDs.toArray(new String[storageIDs.size()]); 1126 } 1127 1128 int action = DatanodeProtocol.DNA_UNKNOWN; 1129 switch (blkCmd.getAction()) { 1130 case TRANSFER: 1131 action = DatanodeProtocol.DNA_TRANSFER; 1132 break; 1133 case INVALIDATE: 1134 action = DatanodeProtocol.DNA_INVALIDATE; 1135 break; 1136 case SHUTDOWN: 1137 action = DatanodeProtocol.DNA_SHUTDOWN; 1138 break; 1139 default: 1140 throw new AssertionError("Unknown action type: " + blkCmd.getAction()); 1141 } 1142 return new BlockCommand(action, blkCmd.getBlockPoolId(), blocks, targets, 1143 targetStorageTypes, targetStorageIDs); 1144 } 1145 1146 public static BlockIdCommand convert(BlockIdCommandProto blkIdCmd) { 1147 int numBlockIds = blkIdCmd.getBlockIdsCount(); 1148 long blockIds[] = new long[numBlockIds]; 1149 for (int i = 0; i < numBlockIds; i++) { 1150 blockIds[i] = blkIdCmd.getBlockIds(i); 1151 } 1152 int action = DatanodeProtocol.DNA_UNKNOWN; 1153 switch (blkIdCmd.getAction()) { 1154 case CACHE: 1155 action = DatanodeProtocol.DNA_CACHE; 1156 break; 1157 case UNCACHE: 1158 action = DatanodeProtocol.DNA_UNCACHE; 1159 break; 1160 default: 1161 throw new AssertionError("Unknown action type: " + blkIdCmd.getAction()); 1162 } 1163 return new BlockIdCommand(action, blkIdCmd.getBlockPoolId(), blockIds); 1164 } 1165 1166 public static DatanodeInfo[] convert(DatanodeInfosProto datanodeInfosProto) { 1167 List<DatanodeInfoProto> proto = datanodeInfosProto.getDatanodesList(); 1168 DatanodeInfo[] infos = new DatanodeInfo[proto.size()]; 1169 for (int i = 0; i < infos.length; i++) { 1170 infos[i] = PBHelper.convert(proto.get(i)); 1171 } 1172 return infos; 1173 } 1174 1175 public static BalancerBandwidthCommand convert( 1176 BalancerBandwidthCommandProto balancerCmd) { 1177 return new BalancerBandwidthCommand(balancerCmd.getBandwidth()); 1178 } 1179 1180 public static ReceivedDeletedBlockInfoProto convert( 1181 ReceivedDeletedBlockInfo receivedDeletedBlockInfo) { 1182 ReceivedDeletedBlockInfoProto.Builder builder = 1183 ReceivedDeletedBlockInfoProto.newBuilder(); 1184 1185 ReceivedDeletedBlockInfoProto.BlockStatus status; 1186 switch (receivedDeletedBlockInfo.getStatus()) { 1187 case RECEIVING_BLOCK: 1188 status = ReceivedDeletedBlockInfoProto.BlockStatus.RECEIVING; 1189 break; 1190 case RECEIVED_BLOCK: 1191 status = ReceivedDeletedBlockInfoProto.BlockStatus.RECEIVED; 1192 break; 1193 case DELETED_BLOCK: 1194 status = ReceivedDeletedBlockInfoProto.BlockStatus.DELETED; 1195 break; 1196 default: 1197 throw new IllegalArgumentException("Bad status: " + 1198 receivedDeletedBlockInfo.getStatus()); 1199 } 1200 builder.setStatus(status); 1201 1202 if (receivedDeletedBlockInfo.getDelHints() != null) { 1203 builder.setDeleteHint(receivedDeletedBlockInfo.getDelHints()); 1204 } 1205 return builder.setBlock(PBHelper.convert(receivedDeletedBlockInfo.getBlock())) 1206 .build(); 1207 } 1208 1209 public static ReceivedDeletedBlockInfo convert( 1210 ReceivedDeletedBlockInfoProto proto) { 1211 ReceivedDeletedBlockInfo.BlockStatus status = null; 1212 switch (proto.getStatus()) { 1213 case RECEIVING: 1214 status = BlockStatus.RECEIVING_BLOCK; 1215 break; 1216 case RECEIVED: 1217 status = BlockStatus.RECEIVED_BLOCK; 1218 break; 1219 case DELETED: 1220 status = BlockStatus.DELETED_BLOCK; 1221 break; 1222 } 1223 return new ReceivedDeletedBlockInfo( 1224 PBHelper.convert(proto.getBlock()), 1225 status, 1226 proto.hasDeleteHint() ? proto.getDeleteHint() : null); 1227 } 1228 1229 public static NamespaceInfoProto convert(NamespaceInfo info) { 1230 return NamespaceInfoProto.newBuilder() 1231 .setBlockPoolID(info.getBlockPoolID()) 1232 .setBuildVersion(info.getBuildVersion()) 1233 .setUnused(0) 1234 .setStorageInfo(PBHelper.convert((StorageInfo)info)) 1235 .setSoftwareVersion(info.getSoftwareVersion()).build(); 1236 } 1237 1238 // Located Block Arrays and Lists 1239 public static LocatedBlockProto[] convertLocatedBlock(LocatedBlock[] lb) { 1240 if (lb == null) return null; 1241 return convertLocatedBlock2(Arrays.asList(lb)).toArray( 1242 new LocatedBlockProto[lb.length]); 1243 } 1244 1245 public static LocatedBlock[] convertLocatedBlock(LocatedBlockProto[] lb) { 1246 if (lb == null) return null; 1247 return convertLocatedBlock(Arrays.asList(lb)).toArray( 1248 new LocatedBlock[lb.length]); 1249 } 1250 1251 public static List<LocatedBlock> convertLocatedBlock( 1252 List<LocatedBlockProto> lb) { 1253 if (lb == null) return null; 1254 final int len = lb.size(); 1255 List<LocatedBlock> result = 1256 new ArrayList<LocatedBlock>(len); 1257 for (int i = 0; i < len; ++i) { 1258 result.add(PBHelper.convert(lb.get(i))); 1259 } 1260 return result; 1261 } 1262 1263 public static List<LocatedBlockProto> convertLocatedBlock2(List<LocatedBlock> lb) { 1264 if (lb == null) return null; 1265 final int len = lb.size(); 1266 List<LocatedBlockProto> result = new ArrayList<LocatedBlockProto>(len); 1267 for (int i = 0; i < len; ++i) { 1268 result.add(PBHelper.convert(lb.get(i))); 1269 } 1270 return result; 1271 } 1272 1273 1274 // LocatedBlocks 1275 public static LocatedBlocks convert(LocatedBlocksProto lb) { 1276 return new LocatedBlocks( 1277 lb.getFileLength(), lb.getUnderConstruction(), 1278 PBHelper.convertLocatedBlock(lb.getBlocksList()), 1279 lb.hasLastBlock() ? PBHelper.convert(lb.getLastBlock()) : null, 1280 lb.getIsLastBlockComplete(), 1281 lb.hasFileEncryptionInfo() ? convert(lb.getFileEncryptionInfo()) : 1282 null); 1283 } 1284 1285 public static LocatedBlocksProto convert(LocatedBlocks lb) { 1286 if (lb == null) { 1287 return null; 1288 } 1289 LocatedBlocksProto.Builder builder = 1290 LocatedBlocksProto.newBuilder(); 1291 if (lb.getLastLocatedBlock() != null) { 1292 builder.setLastBlock(PBHelper.convert(lb.getLastLocatedBlock())); 1293 } 1294 if (lb.getFileEncryptionInfo() != null) { 1295 builder.setFileEncryptionInfo(convert(lb.getFileEncryptionInfo())); 1296 } 1297 return builder.setFileLength(lb.getFileLength()) 1298 .setUnderConstruction(lb.isUnderConstruction()) 1299 .addAllBlocks(PBHelper.convertLocatedBlock2(lb.getLocatedBlocks())) 1300 .setIsLastBlockComplete(lb.isLastBlockComplete()).build(); 1301 } 1302 1303 // DataEncryptionKey 1304 public static DataEncryptionKey convert(DataEncryptionKeyProto bet) { 1305 String encryptionAlgorithm = bet.getEncryptionAlgorithm(); 1306 return new DataEncryptionKey(bet.getKeyId(), 1307 bet.getBlockPoolId(), 1308 bet.getNonce().toByteArray(), 1309 bet.getEncryptionKey().toByteArray(), 1310 bet.getExpiryDate(), 1311 encryptionAlgorithm.isEmpty() ? null : encryptionAlgorithm); 1312 } 1313 1314 public static DataEncryptionKeyProto convert(DataEncryptionKey bet) { 1315 DataEncryptionKeyProto.Builder b = DataEncryptionKeyProto.newBuilder() 1316 .setKeyId(bet.keyId) 1317 .setBlockPoolId(bet.blockPoolId) 1318 .setNonce(ByteString.copyFrom(bet.nonce)) 1319 .setEncryptionKey(ByteString.copyFrom(bet.encryptionKey)) 1320 .setExpiryDate(bet.expiryDate); 1321 if (bet.encryptionAlgorithm != null) { 1322 b.setEncryptionAlgorithm(bet.encryptionAlgorithm); 1323 } 1324 return b.build(); 1325 } 1326 1327 public static FsServerDefaults convert(FsServerDefaultsProto fs) { 1328 if (fs == null) return null; 1329 return new FsServerDefaults( 1330 fs.getBlockSize(), fs.getBytesPerChecksum(), 1331 fs.getWritePacketSize(), (short) fs.getReplication(), 1332 fs.getFileBufferSize(), 1333 fs.getEncryptDataTransfer(), 1334 fs.getTrashInterval(), 1335 PBHelper.convert(fs.getChecksumType())); 1336 } 1337 1338 public static FsServerDefaultsProto convert(FsServerDefaults fs) { 1339 if (fs == null) return null; 1340 return FsServerDefaultsProto.newBuilder(). 1341 setBlockSize(fs.getBlockSize()). 1342 setBytesPerChecksum(fs.getBytesPerChecksum()). 1343 setWritePacketSize(fs.getWritePacketSize()) 1344 .setReplication(fs.getReplication()) 1345 .setFileBufferSize(fs.getFileBufferSize()) 1346 .setEncryptDataTransfer(fs.getEncryptDataTransfer()) 1347 .setTrashInterval(fs.getTrashInterval()) 1348 .setChecksumType(PBHelper.convert(fs.getChecksumType())) 1349 .build(); 1350 } 1351 1352 public static FsPermissionProto convert(FsPermission p) { 1353 return FsPermissionProto.newBuilder().setPerm(p.toExtendedShort()).build(); 1354 } 1355 1356 public static FsPermission convert(FsPermissionProto p) { 1357 return new FsPermissionExtension((short)p.getPerm()); 1358 } 1359 1360 1361 // The creatFlag field in PB is a bitmask whose values are the same a the 1362 // emum values of CreateFlag 1363 public static int convertCreateFlag(EnumSetWritable<CreateFlag> flag) { 1364 int value = 0; 1365 if (flag.contains(CreateFlag.APPEND)) { 1366 value |= CreateFlagProto.APPEND.getNumber(); 1367 } 1368 if (flag.contains(CreateFlag.CREATE)) { 1369 value |= CreateFlagProto.CREATE.getNumber(); 1370 } 1371 if (flag.contains(CreateFlag.OVERWRITE)) { 1372 value |= CreateFlagProto.OVERWRITE.getNumber(); 1373 } 1374 if (flag.contains(CreateFlag.LAZY_PERSIST)) { 1375 value |= CreateFlagProto.LAZY_PERSIST.getNumber(); 1376 } 1377 return value; 1378 } 1379 1380 public static EnumSetWritable<CreateFlag> convertCreateFlag(int flag) { 1381 EnumSet<CreateFlag> result = 1382 EnumSet.noneOf(CreateFlag.class); 1383 if ((flag & CreateFlagProto.APPEND_VALUE) == CreateFlagProto.APPEND_VALUE) { 1384 result.add(CreateFlag.APPEND); 1385 } 1386 if ((flag & CreateFlagProto.CREATE_VALUE) == CreateFlagProto.CREATE_VALUE) { 1387 result.add(CreateFlag.CREATE); 1388 } 1389 if ((flag & CreateFlagProto.OVERWRITE_VALUE) 1390 == CreateFlagProto.OVERWRITE_VALUE) { 1391 result.add(CreateFlag.OVERWRITE); 1392 } 1393 if ((flag & CreateFlagProto.LAZY_PERSIST_VALUE) 1394 == CreateFlagProto.LAZY_PERSIST_VALUE) { 1395 result.add(CreateFlag.LAZY_PERSIST); 1396 } 1397 return new EnumSetWritable<CreateFlag>(result); 1398 } 1399 1400 public static int convertCacheFlags(EnumSet<CacheFlag> flags) { 1401 int value = 0; 1402 if (flags.contains(CacheFlag.FORCE)) { 1403 value |= CacheFlagProto.FORCE.getNumber(); 1404 } 1405 return value; 1406 } 1407 1408 public static EnumSet<CacheFlag> convertCacheFlags(int flags) { 1409 EnumSet<CacheFlag> result = EnumSet.noneOf(CacheFlag.class); 1410 if ((flags & CacheFlagProto.FORCE_VALUE) == CacheFlagProto.FORCE_VALUE) { 1411 result.add(CacheFlag.FORCE); 1412 } 1413 return result; 1414 } 1415 1416 public static HdfsFileStatus convert(HdfsFileStatusProto fs) { 1417 if (fs == null) 1418 return null; 1419 return new HdfsLocatedFileStatus( 1420 fs.getLength(), fs.getFileType().equals(FileType.IS_DIR), 1421 fs.getBlockReplication(), fs.getBlocksize(), 1422 fs.getModificationTime(), fs.getAccessTime(), 1423 PBHelper.convert(fs.getPermission()), fs.getOwner(), fs.getGroup(), 1424 fs.getFileType().equals(FileType.IS_SYMLINK) ? 1425 fs.getSymlink().toByteArray() : null, 1426 fs.getPath().toByteArray(), 1427 fs.hasFileId()? fs.getFileId(): INodeId.GRANDFATHER_INODE_ID, 1428 fs.hasLocations() ? PBHelper.convert(fs.getLocations()) : null, 1429 fs.hasChildrenNum() ? fs.getChildrenNum() : -1, 1430 fs.hasFileEncryptionInfo() ? convert(fs.getFileEncryptionInfo()) : null, 1431 fs.hasStoragePolicy() ? (byte) fs.getStoragePolicy() 1432 : BlockStoragePolicySuite.ID_UNSPECIFIED); 1433 } 1434 1435 public static SnapshottableDirectoryStatus convert( 1436 SnapshottableDirectoryStatusProto sdirStatusProto) { 1437 if (sdirStatusProto == null) { 1438 return null; 1439 } 1440 final HdfsFileStatusProto status = sdirStatusProto.getDirStatus(); 1441 return new SnapshottableDirectoryStatus( 1442 status.getModificationTime(), 1443 status.getAccessTime(), 1444 PBHelper.convert(status.getPermission()), 1445 status.getOwner(), 1446 status.getGroup(), 1447 status.getPath().toByteArray(), 1448 status.getFileId(), 1449 status.getChildrenNum(), 1450 sdirStatusProto.getSnapshotNumber(), 1451 sdirStatusProto.getSnapshotQuota(), 1452 sdirStatusProto.getParentFullpath().toByteArray()); 1453 } 1454 1455 public static HdfsFileStatusProto convert(HdfsFileStatus fs) { 1456 if (fs == null) 1457 return null; 1458 FileType fType = FileType.IS_FILE; 1459 if (fs.isDir()) { 1460 fType = FileType.IS_DIR; 1461 } else if (fs.isSymlink()) { 1462 fType = FileType.IS_SYMLINK; 1463 } 1464 1465 HdfsFileStatusProto.Builder builder = 1466 HdfsFileStatusProto.newBuilder(). 1467 setLength(fs.getLen()). 1468 setFileType(fType). 1469 setBlockReplication(fs.getReplication()). 1470 setBlocksize(fs.getBlockSize()). 1471 setModificationTime(fs.getModificationTime()). 1472 setAccessTime(fs.getAccessTime()). 1473 setPermission(PBHelper.convert(fs.getPermission())). 1474 setOwner(fs.getOwner()). 1475 setGroup(fs.getGroup()). 1476 setFileId(fs.getFileId()). 1477 setChildrenNum(fs.getChildrenNum()). 1478 setPath(ByteString.copyFrom(fs.getLocalNameInBytes())). 1479 setStoragePolicy(fs.getStoragePolicy()); 1480 if (fs.isSymlink()) { 1481 builder.setSymlink(ByteString.copyFrom(fs.getSymlinkInBytes())); 1482 } 1483 if (fs.getFileEncryptionInfo() != null) { 1484 builder.setFileEncryptionInfo(convert(fs.getFileEncryptionInfo())); 1485 } 1486 if (fs instanceof HdfsLocatedFileStatus) { 1487 final HdfsLocatedFileStatus lfs = (HdfsLocatedFileStatus) fs; 1488 LocatedBlocks locations = lfs.getBlockLocations(); 1489 if (locations != null) { 1490 builder.setLocations(PBHelper.convert(locations)); 1491 } 1492 } 1493 return builder.build(); 1494 } 1495 1496 public static SnapshottableDirectoryStatusProto convert( 1497 SnapshottableDirectoryStatus status) { 1498 if (status == null) { 1499 return null; 1500 } 1501 int snapshotNumber = status.getSnapshotNumber(); 1502 int snapshotQuota = status.getSnapshotQuota(); 1503 byte[] parentFullPath = status.getParentFullPath(); 1504 ByteString parentFullPathBytes = ByteString.copyFrom( 1505 parentFullPath == null ? DFSUtil.EMPTY_BYTES : parentFullPath); 1506 HdfsFileStatusProto fs = convert(status.getDirStatus()); 1507 SnapshottableDirectoryStatusProto.Builder builder = 1508 SnapshottableDirectoryStatusProto 1509 .newBuilder().setSnapshotNumber(snapshotNumber) 1510 .setSnapshotQuota(snapshotQuota).setParentFullpath(parentFullPathBytes) 1511 .setDirStatus(fs); 1512 return builder.build(); 1513 } 1514 1515 public static HdfsFileStatusProto[] convert(HdfsFileStatus[] fs) { 1516 if (fs == null) return null; 1517 final int len = fs.length; 1518 HdfsFileStatusProto[] result = new HdfsFileStatusProto[len]; 1519 for (int i = 0; i < len; ++i) { 1520 result[i] = PBHelper.convert(fs[i]); 1521 } 1522 return result; 1523 } 1524 1525 public static HdfsFileStatus[] convert(HdfsFileStatusProto[] fs) { 1526 if (fs == null) return null; 1527 final int len = fs.length; 1528 HdfsFileStatus[] result = new HdfsFileStatus[len]; 1529 for (int i = 0; i < len; ++i) { 1530 result[i] = PBHelper.convert(fs[i]); 1531 } 1532 return result; 1533 } 1534 1535 public static DirectoryListing convert(DirectoryListingProto dl) { 1536 if (dl == null) 1537 return null; 1538 List<HdfsFileStatusProto> partList = dl.getPartialListingList(); 1539 return new DirectoryListing( 1540 partList.isEmpty() ? new HdfsLocatedFileStatus[0] 1541 : PBHelper.convert( 1542 partList.toArray(new HdfsFileStatusProto[partList.size()])), 1543 dl.getRemainingEntries()); 1544 } 1545 1546 public static DirectoryListingProto convert(DirectoryListing d) { 1547 if (d == null) 1548 return null; 1549 return DirectoryListingProto.newBuilder(). 1550 addAllPartialListing(Arrays.asList( 1551 PBHelper.convert(d.getPartialListing()))). 1552 setRemainingEntries(d.getRemainingEntries()). 1553 build(); 1554 } 1555 1556 public static long[] convert(GetFsStatsResponseProto res) { 1557 long[] result = new long[7]; 1558 result[ClientProtocol.GET_STATS_CAPACITY_IDX] = res.getCapacity(); 1559 result[ClientProtocol.GET_STATS_USED_IDX] = res.getUsed(); 1560 result[ClientProtocol.GET_STATS_REMAINING_IDX] = res.getRemaining(); 1561 result[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX] = res.getUnderReplicated(); 1562 result[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX] = res.getCorruptBlocks(); 1563 result[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX] = res.getMissingBlocks(); 1564 result[ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX] = 1565 res.getMissingReplOneBlocks(); 1566 return result; 1567 } 1568 1569 public static GetFsStatsResponseProto convert(long[] fsStats) { 1570 GetFsStatsResponseProto.Builder result = GetFsStatsResponseProto 1571 .newBuilder(); 1572 if (fsStats.length >= ClientProtocol.GET_STATS_CAPACITY_IDX + 1) 1573 result.setCapacity(fsStats[ClientProtocol.GET_STATS_CAPACITY_IDX]); 1574 if (fsStats.length >= ClientProtocol.GET_STATS_USED_IDX + 1) 1575 result.setUsed(fsStats[ClientProtocol.GET_STATS_USED_IDX]); 1576 if (fsStats.length >= ClientProtocol.GET_STATS_REMAINING_IDX + 1) 1577 result.setRemaining(fsStats[ClientProtocol.GET_STATS_REMAINING_IDX]); 1578 if (fsStats.length >= ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX + 1) 1579 result.setUnderReplicated( 1580 fsStats[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX]); 1581 if (fsStats.length >= ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX + 1) 1582 result.setCorruptBlocks( 1583 fsStats[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX]); 1584 if (fsStats.length >= ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX + 1) 1585 result.setMissingBlocks( 1586 fsStats[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX]); 1587 if (fsStats.length >= ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX + 1) 1588 result.setMissingReplOneBlocks( 1589 fsStats[ClientProtocol.GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX]); 1590 return result.build(); 1591 } 1592 1593 public static DatanodeReportTypeProto 1594 convert(DatanodeReportType t) { 1595 switch (t) { 1596 case ALL: return DatanodeReportTypeProto.ALL; 1597 case LIVE: return DatanodeReportTypeProto.LIVE; 1598 case DEAD: return DatanodeReportTypeProto.DEAD; 1599 case DECOMMISSIONING: return DatanodeReportTypeProto.DECOMMISSIONING; 1600 default: 1601 throw new IllegalArgumentException("Unexpected data type report:" + t); 1602 } 1603 } 1604 1605 public static DatanodeReportType 1606 convert(DatanodeReportTypeProto t) { 1607 switch (t) { 1608 case ALL: return DatanodeReportType.ALL; 1609 case LIVE: return DatanodeReportType.LIVE; 1610 case DEAD: return DatanodeReportType.DEAD; 1611 case DECOMMISSIONING: return DatanodeReportType.DECOMMISSIONING; 1612 default: 1613 throw new IllegalArgumentException("Unexpected data type report:" + t); 1614 } 1615 } 1616 1617 public static SafeModeActionProto convert( 1618 SafeModeAction a) { 1619 switch (a) { 1620 case SAFEMODE_LEAVE: 1621 return SafeModeActionProto.SAFEMODE_LEAVE; 1622 case SAFEMODE_ENTER: 1623 return SafeModeActionProto.SAFEMODE_ENTER; 1624 case SAFEMODE_GET: 1625 return SafeModeActionProto.SAFEMODE_GET; 1626 default: 1627 throw new IllegalArgumentException("Unexpected SafeModeAction :" + a); 1628 } 1629 } 1630 1631 public static SafeModeAction convert( 1632 ClientNamenodeProtocolProtos.SafeModeActionProto a) { 1633 switch (a) { 1634 case SAFEMODE_LEAVE: 1635 return SafeModeAction.SAFEMODE_LEAVE; 1636 case SAFEMODE_ENTER: 1637 return SafeModeAction.SAFEMODE_ENTER; 1638 case SAFEMODE_GET: 1639 return SafeModeAction.SAFEMODE_GET; 1640 default: 1641 throw new IllegalArgumentException("Unexpected SafeModeAction :" + a); 1642 } 1643 } 1644 1645 public static RollingUpgradeActionProto convert(RollingUpgradeAction a) { 1646 switch (a) { 1647 case QUERY: 1648 return RollingUpgradeActionProto.QUERY; 1649 case PREPARE: 1650 return RollingUpgradeActionProto.START; 1651 case FINALIZE: 1652 return RollingUpgradeActionProto.FINALIZE; 1653 default: 1654 throw new IllegalArgumentException("Unexpected value: " + a); 1655 } 1656 } 1657 1658 public static RollingUpgradeAction convert(RollingUpgradeActionProto a) { 1659 switch (a) { 1660 case QUERY: 1661 return RollingUpgradeAction.QUERY; 1662 case START: 1663 return RollingUpgradeAction.PREPARE; 1664 case FINALIZE: 1665 return RollingUpgradeAction.FINALIZE; 1666 default: 1667 throw new IllegalArgumentException("Unexpected value: " + a); 1668 } 1669 } 1670 1671 public static RollingUpgradeStatusProto convertRollingUpgradeStatus( 1672 RollingUpgradeStatus status) { 1673 return RollingUpgradeStatusProto.newBuilder() 1674 .setBlockPoolId(status.getBlockPoolId()) 1675 .setFinalized(status.isFinalized()) 1676 .build(); 1677 } 1678 1679 public static RollingUpgradeStatus convert(RollingUpgradeStatusProto proto) { 1680 return new RollingUpgradeStatus(proto.getBlockPoolId(), 1681 proto.getFinalized()); 1682 } 1683 1684 public static RollingUpgradeInfoProto convert(RollingUpgradeInfo info) { 1685 return RollingUpgradeInfoProto.newBuilder() 1686 .setStatus(convertRollingUpgradeStatus(info)) 1687 .setCreatedRollbackImages(info.createdRollbackImages()) 1688 .setStartTime(info.getStartTime()) 1689 .setFinalizeTime(info.getFinalizeTime()) 1690 .build(); 1691 } 1692 1693 public static RollingUpgradeInfo convert(RollingUpgradeInfoProto proto) { 1694 RollingUpgradeStatusProto status = proto.getStatus(); 1695 return new RollingUpgradeInfo(status.getBlockPoolId(), 1696 proto.getCreatedRollbackImages(), 1697 proto.getStartTime(), proto.getFinalizeTime()); 1698 } 1699 1700 public static CorruptFileBlocks convert(CorruptFileBlocksProto c) { 1701 if (c == null) 1702 return null; 1703 List<String> fileList = c.getFilesList(); 1704 return new CorruptFileBlocks(fileList.toArray(new String[fileList.size()]), 1705 c.getCookie()); 1706 } 1707 1708 public static CorruptFileBlocksProto convert(CorruptFileBlocks c) { 1709 if (c == null) 1710 return null; 1711 return CorruptFileBlocksProto.newBuilder(). 1712 addAllFiles(Arrays.asList(c.getFiles())). 1713 setCookie(c.getCookie()). 1714 build(); 1715 } 1716 1717 public static ContentSummary convert(ContentSummaryProto cs) { 1718 if (cs == null) return null; 1719 return new ContentSummary( 1720 cs.getLength(), cs.getFileCount(), cs.getDirectoryCount(), cs.getQuota(), 1721 cs.getSpaceConsumed(), cs.getSpaceQuota()); 1722 } 1723 1724 public static ContentSummaryProto convert(ContentSummary cs) { 1725 if (cs == null) return null; 1726 return ContentSummaryProto.newBuilder(). 1727 setLength(cs.getLength()). 1728 setFileCount(cs.getFileCount()). 1729 setDirectoryCount(cs.getDirectoryCount()). 1730 setQuota(cs.getQuota()). 1731 setSpaceConsumed(cs.getSpaceConsumed()). 1732 setSpaceQuota(cs.getSpaceQuota()). 1733 build(); 1734 } 1735 1736 public static NNHAStatusHeartbeat convert(NNHAStatusHeartbeatProto s) { 1737 if (s == null) return null; 1738 switch (s.getState()) { 1739 case ACTIVE: 1740 return new NNHAStatusHeartbeat(HAServiceState.ACTIVE, s.getTxid()); 1741 case STANDBY: 1742 return new NNHAStatusHeartbeat(HAServiceState.STANDBY, s.getTxid()); 1743 default: 1744 throw new IllegalArgumentException("Unexpected NNHAStatusHeartbeat.State:" + s.getState()); 1745 } 1746 } 1747 1748 public static NNHAStatusHeartbeatProto convert(NNHAStatusHeartbeat hb) { 1749 if (hb == null) return null; 1750 NNHAStatusHeartbeatProto.Builder builder = 1751 NNHAStatusHeartbeatProto.newBuilder(); 1752 switch (hb.getState()) { 1753 case ACTIVE: 1754 builder.setState(NNHAStatusHeartbeatProto.State.ACTIVE); 1755 break; 1756 case STANDBY: 1757 builder.setState(NNHAStatusHeartbeatProto.State.STANDBY); 1758 break; 1759 default: 1760 throw new IllegalArgumentException("Unexpected NNHAStatusHeartbeat.State:" + 1761 hb.getState()); 1762 } 1763 builder.setTxid(hb.getTxId()); 1764 return builder.build(); 1765 } 1766 1767 public static DatanodeStorageProto convert(DatanodeStorage s) { 1768 return DatanodeStorageProto.newBuilder() 1769 .setState(PBHelper.convertState(s.getState())) 1770 .setStorageType(PBHelper.convertStorageType(s.getStorageType())) 1771 .setStorageUuid(s.getStorageID()).build(); 1772 } 1773 1774 private static StorageState convertState(State state) { 1775 switch(state) { 1776 case READ_ONLY_SHARED: 1777 return StorageState.READ_ONLY_SHARED; 1778 case NORMAL: 1779 default: 1780 return StorageState.NORMAL; 1781 } 1782 } 1783 1784 public static List<StorageTypeProto> convertStorageTypes( 1785 StorageType[] types) { 1786 return convertStorageTypes(types, 0); 1787 } 1788 1789 public static List<StorageTypeProto> convertStorageTypes( 1790 StorageType[] types, int startIdx) { 1791 if (types == null) { 1792 return null; 1793 } 1794 final List<StorageTypeProto> protos = new ArrayList<StorageTypeProto>( 1795 types.length); 1796 for (int i = startIdx; i < types.length; ++i) { 1797 protos.add(convertStorageType(types[i])); 1798 } 1799 return protos; 1800 } 1801 1802 public static StorageTypeProto convertStorageType(StorageType type) { 1803 switch(type) { 1804 case DISK: 1805 return StorageTypeProto.DISK; 1806 case SSD: 1807 return StorageTypeProto.SSD; 1808 case ARCHIVE: 1809 return StorageTypeProto.ARCHIVE; 1810 case RAM_DISK: 1811 return StorageTypeProto.RAM_DISK; 1812 default: 1813 throw new IllegalStateException( 1814 "BUG: StorageType not found, type=" + type); 1815 } 1816 } 1817 1818 public static DatanodeStorage convert(DatanodeStorageProto s) { 1819 return new DatanodeStorage(s.getStorageUuid(), 1820 PBHelper.convertState(s.getState()), 1821 PBHelper.convertStorageType(s.getStorageType())); 1822 } 1823 1824 private static State convertState(StorageState state) { 1825 switch(state) { 1826 case READ_ONLY_SHARED: 1827 return DatanodeStorage.State.READ_ONLY_SHARED; 1828 case NORMAL: 1829 default: 1830 return DatanodeStorage.State.NORMAL; 1831 } 1832 } 1833 1834 public static StorageType convertStorageType(StorageTypeProto type) { 1835 switch(type) { 1836 case DISK: 1837 return StorageType.DISK; 1838 case SSD: 1839 return StorageType.SSD; 1840 case ARCHIVE: 1841 return StorageType.ARCHIVE; 1842 case RAM_DISK: 1843 return StorageType.RAM_DISK; 1844 default: 1845 throw new IllegalStateException( 1846 "BUG: StorageTypeProto not found, type=" + type); 1847 } 1848 } 1849 1850 public static StorageType[] convertStorageTypes( 1851 List<StorageTypeProto> storageTypesList, int expectedSize) { 1852 final StorageType[] storageTypes = new StorageType[expectedSize]; 1853 if (storageTypesList.size() != expectedSize) { // missing storage types 1854 Preconditions.checkState(storageTypesList.isEmpty()); 1855 Arrays.fill(storageTypes, StorageType.DEFAULT); 1856 } else { 1857 for (int i = 0; i < storageTypes.length; ++i) { 1858 storageTypes[i] = convertStorageType(storageTypesList.get(i)); 1859 } 1860 } 1861 return storageTypes; 1862 } 1863 1864 public static StorageReportProto convert(StorageReport r) { 1865 StorageReportProto.Builder builder = StorageReportProto.newBuilder() 1866 .setBlockPoolUsed(r.getBlockPoolUsed()).setCapacity(r.getCapacity()) 1867 .setDfsUsed(r.getDfsUsed()).setRemaining(r.getRemaining()) 1868 .setStorageUuid(r.getStorage().getStorageID()) 1869 .setStorage(convert(r.getStorage())); 1870 return builder.build(); 1871 } 1872 1873 public static StorageReport convert(StorageReportProto p) { 1874 return new StorageReport( 1875 p.hasStorage() ? 1876 convert(p.getStorage()) : 1877 new DatanodeStorage(p.getStorageUuid()), 1878 p.getFailed(), p.getCapacity(), p.getDfsUsed(), p.getRemaining(), 1879 p.getBlockPoolUsed()); 1880 } 1881 1882 public static StorageReport[] convertStorageReports( 1883 List<StorageReportProto> list) { 1884 final StorageReport[] report = new StorageReport[list.size()]; 1885 for (int i = 0; i < report.length; i++) { 1886 report[i] = convert(list.get(i)); 1887 } 1888 return report; 1889 } 1890 1891 public static List<StorageReportProto> convertStorageReports(StorageReport[] storages) { 1892 final List<StorageReportProto> protos = new ArrayList<StorageReportProto>( 1893 storages.length); 1894 for(int i = 0; i < storages.length; i++) { 1895 protos.add(convert(storages[i])); 1896 } 1897 return protos; 1898 } 1899 1900 public static VolumeFailureSummary convertVolumeFailureSummary( 1901 VolumeFailureSummaryProto proto) { 1902 List<String> failedStorageLocations = proto.getFailedStorageLocationsList(); 1903 return new VolumeFailureSummary( 1904 failedStorageLocations.toArray(new String[failedStorageLocations.size()]), 1905 proto.getLastVolumeFailureDate(), proto.getEstimatedCapacityLostTotal()); 1906 } 1907 1908 public static VolumeFailureSummaryProto convertVolumeFailureSummary( 1909 VolumeFailureSummary volumeFailureSummary) { 1910 VolumeFailureSummaryProto.Builder builder = 1911 VolumeFailureSummaryProto.newBuilder(); 1912 for (String failedStorageLocation: 1913 volumeFailureSummary.getFailedStorageLocations()) { 1914 builder.addFailedStorageLocations(failedStorageLocation); 1915 } 1916 builder.setLastVolumeFailureDate( 1917 volumeFailureSummary.getLastVolumeFailureDate()); 1918 builder.setEstimatedCapacityLostTotal( 1919 volumeFailureSummary.getEstimatedCapacityLostTotal()); 1920 return builder.build(); 1921 } 1922 1923 public static JournalInfo convert(JournalInfoProto info) { 1924 int lv = info.hasLayoutVersion() ? info.getLayoutVersion() : 0; 1925 int nsID = info.hasNamespaceID() ? info.getNamespaceID() : 0; 1926 return new JournalInfo(lv, info.getClusterID(), nsID); 1927 } 1928 1929 /** 1930 * Method used for converting {@link JournalInfoProto} sent from Namenode 1931 * to Journal receivers to {@link NamenodeRegistration}. 1932 */ 1933 public static JournalInfoProto convert(JournalInfo j) { 1934 return JournalInfoProto.newBuilder().setClusterID(j.getClusterId()) 1935 .setLayoutVersion(j.getLayoutVersion()) 1936 .setNamespaceID(j.getNamespaceId()).build(); 1937 } 1938 1939 public static SnapshottableDirectoryStatus[] convert( 1940 SnapshottableDirectoryListingProto sdlp) { 1941 if (sdlp == null) 1942 return null; 1943 List<SnapshottableDirectoryStatusProto> list = sdlp 1944 .getSnapshottableDirListingList(); 1945 if (list.isEmpty()) { 1946 return new SnapshottableDirectoryStatus[0]; 1947 } else { 1948 SnapshottableDirectoryStatus[] result = 1949 new SnapshottableDirectoryStatus[list.size()]; 1950 for (int i = 0; i < list.size(); i++) { 1951 result[i] = PBHelper.convert(list.get(i)); 1952 } 1953 return result; 1954 } 1955 } 1956 1957 public static SnapshottableDirectoryListingProto convert( 1958 SnapshottableDirectoryStatus[] status) { 1959 if (status == null) 1960 return null; 1961 SnapshottableDirectoryStatusProto[] protos = 1962 new SnapshottableDirectoryStatusProto[status.length]; 1963 for (int i = 0; i < status.length; i++) { 1964 protos[i] = PBHelper.convert(status[i]); 1965 } 1966 List<SnapshottableDirectoryStatusProto> protoList = Arrays.asList(protos); 1967 return SnapshottableDirectoryListingProto.newBuilder() 1968 .addAllSnapshottableDirListing(protoList).build(); 1969 } 1970 1971 public static DiffReportEntry convert(SnapshotDiffReportEntryProto entry) { 1972 if (entry == null) { 1973 return null; 1974 } 1975 DiffType type = DiffType.getTypeFromLabel(entry 1976 .getModificationLabel()); 1977 return type == null ? null : new DiffReportEntry(type, entry.getFullpath() 1978 .toByteArray(), entry.hasTargetPath() ? entry.getTargetPath() 1979 .toByteArray() : null); 1980 } 1981 1982 public static SnapshotDiffReportEntryProto convert(DiffReportEntry entry) { 1983 if (entry == null) { 1984 return null; 1985 } 1986 ByteString sourcePath = ByteString 1987 .copyFrom(entry.getSourcePath() == null ? DFSUtil.EMPTY_BYTES : entry 1988 .getSourcePath()); 1989 String modification = entry.getType().getLabel(); 1990 SnapshotDiffReportEntryProto.Builder builder = SnapshotDiffReportEntryProto 1991 .newBuilder().setFullpath(sourcePath) 1992 .setModificationLabel(modification); 1993 if (entry.getType() == DiffType.RENAME) { 1994 ByteString targetPath = ByteString 1995 .copyFrom(entry.getTargetPath() == null ? DFSUtil.EMPTY_BYTES : entry 1996 .getTargetPath()); 1997 builder.setTargetPath(targetPath); 1998 } 1999 return builder.build(); 2000 } 2001 2002 public static SnapshotDiffReport convert(SnapshotDiffReportProto reportProto) { 2003 if (reportProto == null) { 2004 return null; 2005 } 2006 String snapshotDir = reportProto.getSnapshotRoot(); 2007 String fromSnapshot = reportProto.getFromSnapshot(); 2008 String toSnapshot = reportProto.getToSnapshot(); 2009 List<SnapshotDiffReportEntryProto> list = reportProto 2010 .getDiffReportEntriesList(); 2011 List<DiffReportEntry> entries = new ArrayList<DiffReportEntry>(); 2012 for (SnapshotDiffReportEntryProto entryProto : list) { 2013 DiffReportEntry entry = convert(entryProto); 2014 if (entry != null) 2015 entries.add(entry); 2016 } 2017 return new SnapshotDiffReport(snapshotDir, fromSnapshot, toSnapshot, 2018 entries); 2019 } 2020 2021 public static SnapshotDiffReportProto convert(SnapshotDiffReport report) { 2022 if (report == null) { 2023 return null; 2024 } 2025 List<DiffReportEntry> entries = report.getDiffList(); 2026 List<SnapshotDiffReportEntryProto> entryProtos = 2027 new ArrayList<SnapshotDiffReportEntryProto>(); 2028 for (DiffReportEntry entry : entries) { 2029 SnapshotDiffReportEntryProto entryProto = convert(entry); 2030 if (entryProto != null) 2031 entryProtos.add(entryProto); 2032 } 2033 2034 SnapshotDiffReportProto reportProto = SnapshotDiffReportProto.newBuilder() 2035 .setSnapshotRoot(report.getSnapshotRoot()) 2036 .setFromSnapshot(report.getFromSnapshot()) 2037 .setToSnapshot(report.getLaterSnapshotName()) 2038 .addAllDiffReportEntries(entryProtos).build(); 2039 return reportProto; 2040 } 2041 2042 public static DataChecksum.Type convert(HdfsProtos.ChecksumTypeProto type) { 2043 return DataChecksum.Type.valueOf(type.getNumber()); 2044 } 2045 2046 public static CacheDirectiveInfoProto convert 2047 (CacheDirectiveInfo info) { 2048 CacheDirectiveInfoProto.Builder builder = 2049 CacheDirectiveInfoProto.newBuilder(); 2050 if (info.getId() != null) { 2051 builder.setId(info.getId()); 2052 } 2053 if (info.getPath() != null) { 2054 builder.setPath(info.getPath().toUri().getPath()); 2055 } 2056 if (info.getReplication() != null) { 2057 builder.setReplication(info.getReplication()); 2058 } 2059 if (info.getPool() != null) { 2060 builder.setPool(info.getPool()); 2061 } 2062 if (info.getExpiration() != null) { 2063 builder.setExpiration(convert(info.getExpiration())); 2064 } 2065 return builder.build(); 2066 } 2067 2068 public static CacheDirectiveInfo convert 2069 (CacheDirectiveInfoProto proto) { 2070 CacheDirectiveInfo.Builder builder = 2071 new CacheDirectiveInfo.Builder(); 2072 if (proto.hasId()) { 2073 builder.setId(proto.getId()); 2074 } 2075 if (proto.hasPath()) { 2076 builder.setPath(new Path(proto.getPath())); 2077 } 2078 if (proto.hasReplication()) { 2079 builder.setReplication(Shorts.checkedCast( 2080 proto.getReplication())); 2081 } 2082 if (proto.hasPool()) { 2083 builder.setPool(proto.getPool()); 2084 } 2085 if (proto.hasExpiration()) { 2086 builder.setExpiration(convert(proto.getExpiration())); 2087 } 2088 return builder.build(); 2089 } 2090 2091 public static CacheDirectiveInfoExpirationProto convert( 2092 CacheDirectiveInfo.Expiration expiration) { 2093 return CacheDirectiveInfoExpirationProto.newBuilder() 2094 .setIsRelative(expiration.isRelative()) 2095 .setMillis(expiration.getMillis()) 2096 .build(); 2097 } 2098 2099 public static CacheDirectiveInfo.Expiration convert( 2100 CacheDirectiveInfoExpirationProto proto) { 2101 if (proto.getIsRelative()) { 2102 return CacheDirectiveInfo.Expiration.newRelative(proto.getMillis()); 2103 } 2104 return CacheDirectiveInfo.Expiration.newAbsolute(proto.getMillis()); 2105 } 2106 2107 public static CacheDirectiveStatsProto convert(CacheDirectiveStats stats) { 2108 CacheDirectiveStatsProto.Builder builder = 2109 CacheDirectiveStatsProto.newBuilder(); 2110 builder.setBytesNeeded(stats.getBytesNeeded()); 2111 builder.setBytesCached(stats.getBytesCached()); 2112 builder.setFilesNeeded(stats.getFilesNeeded()); 2113 builder.setFilesCached(stats.getFilesCached()); 2114 builder.setHasExpired(stats.hasExpired()); 2115 return builder.build(); 2116 } 2117 2118 public static CacheDirectiveStats convert(CacheDirectiveStatsProto proto) { 2119 CacheDirectiveStats.Builder builder = new CacheDirectiveStats.Builder(); 2120 builder.setBytesNeeded(proto.getBytesNeeded()); 2121 builder.setBytesCached(proto.getBytesCached()); 2122 builder.setFilesNeeded(proto.getFilesNeeded()); 2123 builder.setFilesCached(proto.getFilesCached()); 2124 builder.setHasExpired(proto.getHasExpired()); 2125 return builder.build(); 2126 } 2127 2128 public static CacheDirectiveEntryProto convert(CacheDirectiveEntry entry) { 2129 CacheDirectiveEntryProto.Builder builder = 2130 CacheDirectiveEntryProto.newBuilder(); 2131 builder.setInfo(PBHelper.convert(entry.getInfo())); 2132 builder.setStats(PBHelper.convert(entry.getStats())); 2133 return builder.build(); 2134 } 2135 2136 public static CacheDirectiveEntry convert(CacheDirectiveEntryProto proto) { 2137 CacheDirectiveInfo info = PBHelper.convert(proto.getInfo()); 2138 CacheDirectiveStats stats = PBHelper.convert(proto.getStats()); 2139 return new CacheDirectiveEntry(info, stats); 2140 } 2141 2142 public static CachePoolInfoProto convert(CachePoolInfo info) { 2143 CachePoolInfoProto.Builder builder = CachePoolInfoProto.newBuilder(); 2144 builder.setPoolName(info.getPoolName()); 2145 if (info.getOwnerName() != null) { 2146 builder.setOwnerName(info.getOwnerName()); 2147 } 2148 if (info.getGroupName() != null) { 2149 builder.setGroupName(info.getGroupName()); 2150 } 2151 if (info.getMode() != null) { 2152 builder.setMode(info.getMode().toShort()); 2153 } 2154 if (info.getLimit() != null) { 2155 builder.setLimit(info.getLimit()); 2156 } 2157 if (info.getMaxRelativeExpiryMs() != null) { 2158 builder.setMaxRelativeExpiry(info.getMaxRelativeExpiryMs()); 2159 } 2160 return builder.build(); 2161 } 2162 2163 public static CachePoolInfo convert (CachePoolInfoProto proto) { 2164 // Pool name is a required field, the rest are optional 2165 String poolName = checkNotNull(proto.getPoolName()); 2166 CachePoolInfo info = new CachePoolInfo(poolName); 2167 if (proto.hasOwnerName()) { 2168 info.setOwnerName(proto.getOwnerName()); 2169 } 2170 if (proto.hasGroupName()) { 2171 info.setGroupName(proto.getGroupName()); 2172 } 2173 if (proto.hasMode()) { 2174 info.setMode(new FsPermission((short)proto.getMode())); 2175 } 2176 if (proto.hasLimit()) { 2177 info.setLimit(proto.getLimit()); 2178 } 2179 if (proto.hasMaxRelativeExpiry()) { 2180 info.setMaxRelativeExpiryMs(proto.getMaxRelativeExpiry()); 2181 } 2182 return info; 2183 } 2184 2185 public static CachePoolStatsProto convert(CachePoolStats stats) { 2186 CachePoolStatsProto.Builder builder = CachePoolStatsProto.newBuilder(); 2187 builder.setBytesNeeded(stats.getBytesNeeded()); 2188 builder.setBytesCached(stats.getBytesCached()); 2189 builder.setBytesOverlimit(stats.getBytesOverlimit()); 2190 builder.setFilesNeeded(stats.getFilesNeeded()); 2191 builder.setFilesCached(stats.getFilesCached()); 2192 return builder.build(); 2193 } 2194 2195 public static CachePoolStats convert (CachePoolStatsProto proto) { 2196 CachePoolStats.Builder builder = new CachePoolStats.Builder(); 2197 builder.setBytesNeeded(proto.getBytesNeeded()); 2198 builder.setBytesCached(proto.getBytesCached()); 2199 builder.setBytesOverlimit(proto.getBytesOverlimit()); 2200 builder.setFilesNeeded(proto.getFilesNeeded()); 2201 builder.setFilesCached(proto.getFilesCached()); 2202 return builder.build(); 2203 } 2204 2205 public static CachePoolEntryProto convert(CachePoolEntry entry) { 2206 CachePoolEntryProto.Builder builder = CachePoolEntryProto.newBuilder(); 2207 builder.setInfo(PBHelper.convert(entry.getInfo())); 2208 builder.setStats(PBHelper.convert(entry.getStats())); 2209 return builder.build(); 2210 } 2211 2212 public static CachePoolEntry convert (CachePoolEntryProto proto) { 2213 CachePoolInfo info = PBHelper.convert(proto.getInfo()); 2214 CachePoolStats stats = PBHelper.convert(proto.getStats()); 2215 return new CachePoolEntry(info, stats); 2216 } 2217 2218 public static HdfsProtos.ChecksumTypeProto convert(DataChecksum.Type type) { 2219 return HdfsProtos.ChecksumTypeProto.valueOf(type.id); 2220 } 2221 2222 public static DatanodeLocalInfoProto convert(DatanodeLocalInfo info) { 2223 DatanodeLocalInfoProto.Builder builder = DatanodeLocalInfoProto.newBuilder(); 2224 builder.setSoftwareVersion(info.getSoftwareVersion()); 2225 builder.setConfigVersion(info.getConfigVersion()); 2226 builder.setUptime(info.getUptime()); 2227 return builder.build(); 2228 } 2229 2230 public static DatanodeLocalInfo convert(DatanodeLocalInfoProto proto) { 2231 return new DatanodeLocalInfo(proto.getSoftwareVersion(), 2232 proto.getConfigVersion(), proto.getUptime()); 2233 } 2234 2235 public static InputStream vintPrefixed(final InputStream input) 2236 throws IOException { 2237 final int firstByte = input.read(); 2238 if (firstByte == -1) { 2239 throw new EOFException("Premature EOF: no length prefix available"); 2240 } 2241 2242 int size = CodedInputStream.readRawVarint32(firstByte, input); 2243 assert size >= 0; 2244 return new ExactSizeInputStream(input, size); 2245 } 2246 2247 private static AclEntryScopeProto convert(AclEntryScope v) { 2248 return AclEntryScopeProto.valueOf(v.ordinal()); 2249 } 2250 2251 private static AclEntryScope convert(AclEntryScopeProto v) { 2252 return castEnum(v, ACL_ENTRY_SCOPE_VALUES); 2253 } 2254 2255 private static AclEntryTypeProto convert(AclEntryType e) { 2256 return AclEntryTypeProto.valueOf(e.ordinal()); 2257 } 2258 2259 private static AclEntryType convert(AclEntryTypeProto v) { 2260 return castEnum(v, ACL_ENTRY_TYPE_VALUES); 2261 } 2262 2263 private static XAttrNamespaceProto convert(XAttr.NameSpace v) { 2264 return XAttrNamespaceProto.valueOf(v.ordinal()); 2265 } 2266 2267 private static XAttr.NameSpace convert(XAttrNamespaceProto v) { 2268 return castEnum(v, XATTR_NAMESPACE_VALUES); 2269 } 2270 2271 public static FsActionProto convert(FsAction v) { 2272 return FsActionProto.valueOf(v != null ? v.ordinal() : 0); 2273 } 2274 2275 public static FsAction convert(FsActionProto v) { 2276 return castEnum(v, FSACTION_VALUES); 2277 } 2278 2279 public static List<AclEntryProto> convertAclEntryProto( 2280 List<AclEntry> aclSpec) { 2281 ArrayList<AclEntryProto> r = Lists.newArrayListWithCapacity(aclSpec.size()); 2282 for (AclEntry e : aclSpec) { 2283 AclEntryProto.Builder builder = AclEntryProto.newBuilder(); 2284 builder.setType(convert(e.getType())); 2285 builder.setScope(convert(e.getScope())); 2286 builder.setPermissions(convert(e.getPermission())); 2287 if (e.getName() != null) { 2288 builder.setName(e.getName()); 2289 } 2290 r.add(builder.build()); 2291 } 2292 return r; 2293 } 2294 2295 public static List<AclEntry> convertAclEntry(List<AclEntryProto> aclSpec) { 2296 ArrayList<AclEntry> r = Lists.newArrayListWithCapacity(aclSpec.size()); 2297 for (AclEntryProto e : aclSpec) { 2298 AclEntry.Builder builder = new AclEntry.Builder(); 2299 builder.setType(convert(e.getType())); 2300 builder.setScope(convert(e.getScope())); 2301 builder.setPermission(convert(e.getPermissions())); 2302 if (e.hasName()) { 2303 builder.setName(e.getName()); 2304 } 2305 r.add(builder.build()); 2306 } 2307 return r; 2308 } 2309 2310 public static AclStatus convert(GetAclStatusResponseProto e) { 2311 AclStatusProto r = e.getResult(); 2312 return new AclStatus.Builder().owner(r.getOwner()).group(r.getGroup()) 2313 .stickyBit(r.getSticky()) 2314 .addEntries(convertAclEntry(r.getEntriesList())).build(); 2315 } 2316 2317 public static GetAclStatusResponseProto convert(AclStatus e) { 2318 AclStatusProto r = AclStatusProto.newBuilder().setOwner(e.getOwner()) 2319 .setGroup(e.getGroup()).setSticky(e.isStickyBit()) 2320 .addAllEntries(convertAclEntryProto(e.getEntries())).build(); 2321 return GetAclStatusResponseProto.newBuilder().setResult(r).build(); 2322 } 2323 2324 public static XAttrProto convertXAttrProto(XAttr a) { 2325 XAttrProto.Builder builder = XAttrProto.newBuilder(); 2326 builder.setNamespace(convert(a.getNameSpace())); 2327 if (a.getName() != null) { 2328 builder.setName(a.getName()); 2329 } 2330 if (a.getValue() != null) { 2331 builder.setValue(getByteString(a.getValue())); 2332 } 2333 return builder.build(); 2334 } 2335 2336 public static List<XAttrProto> convertXAttrProto( 2337 List<XAttr> xAttrSpec) { 2338 if (xAttrSpec == null) { 2339 return Lists.newArrayListWithCapacity(0); 2340 } 2341 ArrayList<XAttrProto> xAttrs = Lists.newArrayListWithCapacity( 2342 xAttrSpec.size()); 2343 for (XAttr a : xAttrSpec) { 2344 XAttrProto.Builder builder = XAttrProto.newBuilder(); 2345 builder.setNamespace(convert(a.getNameSpace())); 2346 if (a.getName() != null) { 2347 builder.setName(a.getName()); 2348 } 2349 if (a.getValue() != null) { 2350 builder.setValue(getByteString(a.getValue())); 2351 } 2352 xAttrs.add(builder.build()); 2353 } 2354 return xAttrs; 2355 } 2356 2357 /** 2358 * The flag field in PB is a bitmask whose values are the same a the 2359 * emum values of XAttrSetFlag 2360 */ 2361 public static int convert(EnumSet<XAttrSetFlag> flag) { 2362 int value = 0; 2363 if (flag.contains(XAttrSetFlag.CREATE)) { 2364 value |= XAttrSetFlagProto.XATTR_CREATE.getNumber(); 2365 } 2366 if (flag.contains(XAttrSetFlag.REPLACE)) { 2367 value |= XAttrSetFlagProto.XATTR_REPLACE.getNumber(); 2368 } 2369 return value; 2370 } 2371 2372 public static EnumSet<XAttrSetFlag> convert(int flag) { 2373 EnumSet<XAttrSetFlag> result = 2374 EnumSet.noneOf(XAttrSetFlag.class); 2375 if ((flag & XAttrSetFlagProto.XATTR_CREATE_VALUE) == 2376 XAttrSetFlagProto.XATTR_CREATE_VALUE) { 2377 result.add(XAttrSetFlag.CREATE); 2378 } 2379 if ((flag & XAttrSetFlagProto.XATTR_REPLACE_VALUE) == 2380 XAttrSetFlagProto.XATTR_REPLACE_VALUE) { 2381 result.add(XAttrSetFlag.REPLACE); 2382 } 2383 return result; 2384 } 2385 2386 public static XAttr convertXAttr(XAttrProto a) { 2387 XAttr.Builder builder = new XAttr.Builder(); 2388 builder.setNameSpace(convert(a.getNamespace())); 2389 if (a.hasName()) { 2390 builder.setName(a.getName()); 2391 } 2392 if (a.hasValue()) { 2393 builder.setValue(a.getValue().toByteArray()); 2394 } 2395 return builder.build(); 2396 } 2397 2398 public static List<XAttr> convertXAttrs(List<XAttrProto> xAttrSpec) { 2399 ArrayList<XAttr> xAttrs = Lists.newArrayListWithCapacity(xAttrSpec.size()); 2400 for (XAttrProto a : xAttrSpec) { 2401 XAttr.Builder builder = new XAttr.Builder(); 2402 builder.setNameSpace(convert(a.getNamespace())); 2403 if (a.hasName()) { 2404 builder.setName(a.getName()); 2405 } 2406 if (a.hasValue()) { 2407 builder.setValue(a.getValue().toByteArray()); 2408 } 2409 xAttrs.add(builder.build()); 2410 } 2411 return xAttrs; 2412 } 2413 2414 public static List<XAttr> convert(GetXAttrsResponseProto a) { 2415 List<XAttrProto> xAttrs = a.getXAttrsList(); 2416 return convertXAttrs(xAttrs); 2417 } 2418 2419 public static GetXAttrsResponseProto convertXAttrsResponse( 2420 List<XAttr> xAttrs) { 2421 GetXAttrsResponseProto.Builder builder = GetXAttrsResponseProto 2422 .newBuilder(); 2423 if (xAttrs != null) { 2424 builder.addAllXAttrs(convertXAttrProto(xAttrs)); 2425 } 2426 return builder.build(); 2427 } 2428 2429 public static List<XAttr> convert(ListXAttrsResponseProto a) { 2430 final List<XAttrProto> xAttrs = a.getXAttrsList(); 2431 return convertXAttrs(xAttrs); 2432 } 2433 2434 public static ListXAttrsResponseProto convertListXAttrsResponse( 2435 List<XAttr> names) { 2436 ListXAttrsResponseProto.Builder builder = 2437 ListXAttrsResponseProto.newBuilder(); 2438 if (names != null) { 2439 builder.addAllXAttrs(convertXAttrProto(names)); 2440 } 2441 return builder.build(); 2442 } 2443 2444 public static EncryptionZoneProto convert(EncryptionZone zone) { 2445 return EncryptionZoneProto.newBuilder() 2446 .setId(zone.getId()) 2447 .setPath(zone.getPath()) 2448 .setSuite(convert(zone.getSuite())) 2449 .setCryptoProtocolVersion(convert(zone.getVersion())) 2450 .setKeyName(zone.getKeyName()) 2451 .build(); 2452 } 2453 2454 public static EncryptionZone convert(EncryptionZoneProto proto) { 2455 return new EncryptionZone(proto.getId(), proto.getPath(), 2456 convert(proto.getSuite()), convert(proto.getCryptoProtocolVersion()), 2457 proto.getKeyName()); 2458 } 2459 2460 public static ShortCircuitShmSlotProto convert(SlotId slotId) { 2461 return ShortCircuitShmSlotProto.newBuilder(). 2462 setShmId(convert(slotId.getShmId())). 2463 setSlotIdx(slotId.getSlotIdx()). 2464 build(); 2465 } 2466 2467 public static ShortCircuitShmIdProto convert(ShmId shmId) { 2468 return ShortCircuitShmIdProto.newBuilder(). 2469 setHi(shmId.getHi()). 2470 setLo(shmId.getLo()). 2471 build(); 2472 2473 } 2474 2475 public static SlotId convert(ShortCircuitShmSlotProto slotId) { 2476 return new SlotId(PBHelper.convert(slotId.getShmId()), 2477 slotId.getSlotIdx()); 2478 } 2479 2480 public static ShmId convert(ShortCircuitShmIdProto shmId) { 2481 return new ShmId(shmId.getHi(), shmId.getLo()); 2482 } 2483 2484 private static Event.CreateEvent.INodeType createTypeConvert(InotifyProtos.INodeType 2485 type) { 2486 switch (type) { 2487 case I_TYPE_DIRECTORY: 2488 return Event.CreateEvent.INodeType.DIRECTORY; 2489 case I_TYPE_FILE: 2490 return Event.CreateEvent.INodeType.FILE; 2491 case I_TYPE_SYMLINK: 2492 return Event.CreateEvent.INodeType.SYMLINK; 2493 default: 2494 return null; 2495 } 2496 } 2497 2498 private static InotifyProtos.MetadataUpdateType metadataUpdateTypeConvert( 2499 Event.MetadataUpdateEvent.MetadataType type) { 2500 switch (type) { 2501 case TIMES: 2502 return InotifyProtos.MetadataUpdateType.META_TYPE_TIMES; 2503 case REPLICATION: 2504 return InotifyProtos.MetadataUpdateType.META_TYPE_REPLICATION; 2505 case OWNER: 2506 return InotifyProtos.MetadataUpdateType.META_TYPE_OWNER; 2507 case PERMS: 2508 return InotifyProtos.MetadataUpdateType.META_TYPE_PERMS; 2509 case ACLS: 2510 return InotifyProtos.MetadataUpdateType.META_TYPE_ACLS; 2511 case XATTRS: 2512 return InotifyProtos.MetadataUpdateType.META_TYPE_XATTRS; 2513 default: 2514 return null; 2515 } 2516 } 2517 2518 private static Event.MetadataUpdateEvent.MetadataType metadataUpdateTypeConvert( 2519 InotifyProtos.MetadataUpdateType type) { 2520 switch (type) { 2521 case META_TYPE_TIMES: 2522 return Event.MetadataUpdateEvent.MetadataType.TIMES; 2523 case META_TYPE_REPLICATION: 2524 return Event.MetadataUpdateEvent.MetadataType.REPLICATION; 2525 case META_TYPE_OWNER: 2526 return Event.MetadataUpdateEvent.MetadataType.OWNER; 2527 case META_TYPE_PERMS: 2528 return Event.MetadataUpdateEvent.MetadataType.PERMS; 2529 case META_TYPE_ACLS: 2530 return Event.MetadataUpdateEvent.MetadataType.ACLS; 2531 case META_TYPE_XATTRS: 2532 return Event.MetadataUpdateEvent.MetadataType.XATTRS; 2533 default: 2534 return null; 2535 } 2536 } 2537 2538 private static InotifyProtos.INodeType createTypeConvert(Event.CreateEvent.INodeType 2539 type) { 2540 switch (type) { 2541 case DIRECTORY: 2542 return InotifyProtos.INodeType.I_TYPE_DIRECTORY; 2543 case FILE: 2544 return InotifyProtos.INodeType.I_TYPE_FILE; 2545 case SYMLINK: 2546 return InotifyProtos.INodeType.I_TYPE_SYMLINK; 2547 default: 2548 return null; 2549 } 2550 } 2551 2552 public static EventBatchList convert(GetEditsFromTxidResponseProto resp) throws 2553 IOException { 2554 final InotifyProtos.EventsListProto list = resp.getEventsList(); 2555 final long firstTxid = list.getFirstTxid(); 2556 final long lastTxid = list.getLastTxid(); 2557 2558 List<EventBatch> batches = Lists.newArrayList(); 2559 if (list.getEventsList().size() > 0) { 2560 throw new IOException("Can't handle old inotify server response."); 2561 } 2562 for (InotifyProtos.EventBatchProto bp : list.getBatchList()) { 2563 long txid = bp.getTxid(); 2564 if ((txid != -1) && ((txid < firstTxid) || (txid > lastTxid))) { 2565 throw new IOException("Error converting TxidResponseProto: got a " + 2566 "transaction id " + txid + " that was outside the range of [" + 2567 firstTxid + ", " + lastTxid + "]."); 2568 } 2569 List<Event> events = Lists.newArrayList(); 2570 for (InotifyProtos.EventProto p : bp.getEventsList()) { 2571 switch (p.getType()) { 2572 case EVENT_CLOSE: 2573 InotifyProtos.CloseEventProto close = 2574 InotifyProtos.CloseEventProto.parseFrom(p.getContents()); 2575 events.add(new Event.CloseEvent(close.getPath(), 2576 close.getFileSize(), close.getTimestamp())); 2577 break; 2578 case EVENT_CREATE: 2579 InotifyProtos.CreateEventProto create = 2580 InotifyProtos.CreateEventProto.parseFrom(p.getContents()); 2581 events.add(new Event.CreateEvent.Builder() 2582 .iNodeType(createTypeConvert(create.getType())) 2583 .path(create.getPath()) 2584 .ctime(create.getCtime()) 2585 .ownerName(create.getOwnerName()) 2586 .groupName(create.getGroupName()) 2587 .perms(convert(create.getPerms())) 2588 .replication(create.getReplication()) 2589 .symlinkTarget(create.getSymlinkTarget().isEmpty() ? null : 2590 create.getSymlinkTarget()) 2591 .defaultBlockSize(create.getDefaultBlockSize()) 2592 .overwrite(create.getOverwrite()).build()); 2593 break; 2594 case EVENT_METADATA: 2595 InotifyProtos.MetadataUpdateEventProto meta = 2596 InotifyProtos.MetadataUpdateEventProto.parseFrom(p.getContents()); 2597 events.add(new Event.MetadataUpdateEvent.Builder() 2598 .path(meta.getPath()) 2599 .metadataType(metadataUpdateTypeConvert(meta.getType())) 2600 .mtime(meta.getMtime()) 2601 .atime(meta.getAtime()) 2602 .replication(meta.getReplication()) 2603 .ownerName( 2604 meta.getOwnerName().isEmpty() ? null : meta.getOwnerName()) 2605 .groupName( 2606 meta.getGroupName().isEmpty() ? null : meta.getGroupName()) 2607 .perms(meta.hasPerms() ? convert(meta.getPerms()) : null) 2608 .acls(meta.getAclsList().isEmpty() ? null : convertAclEntry( 2609 meta.getAclsList())) 2610 .xAttrs(meta.getXAttrsList().isEmpty() ? null : convertXAttrs( 2611 meta.getXAttrsList())) 2612 .xAttrsRemoved(meta.getXAttrsRemoved()) 2613 .build()); 2614 break; 2615 case EVENT_RENAME: 2616 InotifyProtos.RenameEventProto rename = 2617 InotifyProtos.RenameEventProto.parseFrom(p.getContents()); 2618 events.add(new Event.RenameEvent.Builder() 2619 .srcPath(rename.getSrcPath()) 2620 .dstPath(rename.getDestPath()) 2621 .timestamp(rename.getTimestamp()) 2622 .build()); 2623 break; 2624 case EVENT_APPEND: 2625 InotifyProtos.AppendEventProto reopen = 2626 InotifyProtos.AppendEventProto.parseFrom(p.getContents()); 2627 events.add(new Event.AppendEvent.Builder() 2628 .path(reopen.getPath()) 2629 .build()); 2630 break; 2631 case EVENT_UNLINK: 2632 InotifyProtos.UnlinkEventProto unlink = 2633 InotifyProtos.UnlinkEventProto.parseFrom(p.getContents()); 2634 events.add(new Event.UnlinkEvent.Builder() 2635 .path(unlink.getPath()) 2636 .timestamp(unlink.getTimestamp()) 2637 .build()); 2638 break; 2639 default: 2640 throw new RuntimeException("Unexpected inotify event type: " + 2641 p.getType()); 2642 } 2643 } 2644 batches.add(new EventBatch(txid, events.toArray(new Event[0]))); 2645 } 2646 return new EventBatchList(batches, resp.getEventsList().getFirstTxid(), 2647 resp.getEventsList().getLastTxid(), resp.getEventsList().getSyncTxid()); 2648 } 2649 2650 public static GetEditsFromTxidResponseProto convertEditsResponse(EventBatchList el) { 2651 InotifyProtos.EventsListProto.Builder builder = 2652 InotifyProtos.EventsListProto.newBuilder(); 2653 for (EventBatch b : el.getBatches()) { 2654 List<InotifyProtos.EventProto> events = Lists.newArrayList(); 2655 for (Event e : b.getEvents()) { 2656 switch (e.getEventType()) { 2657 case CLOSE: 2658 Event.CloseEvent ce = (Event.CloseEvent) e; 2659 events.add(InotifyProtos.EventProto.newBuilder() 2660 .setType(InotifyProtos.EventType.EVENT_CLOSE) 2661 .setContents( 2662 InotifyProtos.CloseEventProto.newBuilder() 2663 .setPath(ce.getPath()) 2664 .setFileSize(ce.getFileSize()) 2665 .setTimestamp(ce.getTimestamp()).build().toByteString() 2666 ).build()); 2667 break; 2668 case CREATE: 2669 Event.CreateEvent ce2 = (Event.CreateEvent) e; 2670 events.add(InotifyProtos.EventProto.newBuilder() 2671 .setType(InotifyProtos.EventType.EVENT_CREATE) 2672 .setContents( 2673 InotifyProtos.CreateEventProto.newBuilder() 2674 .setType(createTypeConvert(ce2.getiNodeType())) 2675 .setPath(ce2.getPath()) 2676 .setCtime(ce2.getCtime()) 2677 .setOwnerName(ce2.getOwnerName()) 2678 .setGroupName(ce2.getGroupName()) 2679 .setPerms(convert(ce2.getPerms())) 2680 .setReplication(ce2.getReplication()) 2681 .setSymlinkTarget(ce2.getSymlinkTarget() == null ? 2682 "" : ce2.getSymlinkTarget()) 2683 .setDefaultBlockSize(ce2.getDefaultBlockSize()) 2684 .setOverwrite(ce2.getOverwrite()).build().toByteString() 2685 ).build()); 2686 break; 2687 case METADATA: 2688 Event.MetadataUpdateEvent me = (Event.MetadataUpdateEvent) e; 2689 InotifyProtos.MetadataUpdateEventProto.Builder metaB = 2690 InotifyProtos.MetadataUpdateEventProto.newBuilder() 2691 .setPath(me.getPath()) 2692 .setType(metadataUpdateTypeConvert(me.getMetadataType())) 2693 .setMtime(me.getMtime()) 2694 .setAtime(me.getAtime()) 2695 .setReplication(me.getReplication()) 2696 .setOwnerName(me.getOwnerName() == null ? "" : 2697 me.getOwnerName()) 2698 .setGroupName(me.getGroupName() == null ? "" : 2699 me.getGroupName()) 2700 .addAllAcls(me.getAcls() == null ? 2701 Lists.<AclEntryProto>newArrayList() : 2702 convertAclEntryProto(me.getAcls())) 2703 .addAllXAttrs(me.getxAttrs() == null ? 2704 Lists.<XAttrProto>newArrayList() : 2705 convertXAttrProto(me.getxAttrs())) 2706 .setXAttrsRemoved(me.isxAttrsRemoved()); 2707 if (me.getPerms() != null) { 2708 metaB.setPerms(convert(me.getPerms())); 2709 } 2710 events.add(InotifyProtos.EventProto.newBuilder() 2711 .setType(InotifyProtos.EventType.EVENT_METADATA) 2712 .setContents(metaB.build().toByteString()) 2713 .build()); 2714 break; 2715 case RENAME: 2716 Event.RenameEvent re = (Event.RenameEvent) e; 2717 events.add(InotifyProtos.EventProto.newBuilder() 2718 .setType(InotifyProtos.EventType.EVENT_RENAME) 2719 .setContents( 2720 InotifyProtos.RenameEventProto.newBuilder() 2721 .setSrcPath(re.getSrcPath()) 2722 .setDestPath(re.getDstPath()) 2723 .setTimestamp(re.getTimestamp()).build().toByteString() 2724 ).build()); 2725 break; 2726 case APPEND: 2727 Event.AppendEvent re2 = (Event.AppendEvent) e; 2728 events.add(InotifyProtos.EventProto.newBuilder() 2729 .setType(InotifyProtos.EventType.EVENT_APPEND) 2730 .setContents( 2731 InotifyProtos.AppendEventProto.newBuilder() 2732 .setPath(re2.getPath()).build().toByteString() 2733 ).build()); 2734 break; 2735 case UNLINK: 2736 Event.UnlinkEvent ue = (Event.UnlinkEvent) e; 2737 events.add(InotifyProtos.EventProto.newBuilder() 2738 .setType(InotifyProtos.EventType.EVENT_UNLINK) 2739 .setContents( 2740 InotifyProtos.UnlinkEventProto.newBuilder() 2741 .setPath(ue.getPath()) 2742 .setTimestamp(ue.getTimestamp()).build().toByteString() 2743 ).build()); 2744 break; 2745 default: 2746 throw new RuntimeException("Unexpected inotify event: " + e); 2747 } 2748 } 2749 builder.addBatch(InotifyProtos.EventBatchProto.newBuilder(). 2750 setTxid(b.getTxid()). 2751 addAllEvents(events)); 2752 } 2753 builder.setFirstTxid(el.getFirstTxid()); 2754 builder.setLastTxid(el.getLastTxid()); 2755 builder.setSyncTxid(el.getSyncTxid()); 2756 return GetEditsFromTxidResponseProto.newBuilder().setEventsList( 2757 builder.build()).build(); 2758 } 2759 2760 public static CipherOptionProto convert(CipherOption option) { 2761 if (option != null) { 2762 CipherOptionProto.Builder builder = CipherOptionProto. 2763 newBuilder(); 2764 if (option.getCipherSuite() != null) { 2765 builder.setSuite(convert(option.getCipherSuite())); 2766 } 2767 if (option.getInKey() != null) { 2768 builder.setInKey(ByteString.copyFrom(option.getInKey())); 2769 } 2770 if (option.getInIv() != null) { 2771 builder.setInIv(ByteString.copyFrom(option.getInIv())); 2772 } 2773 if (option.getOutKey() != null) { 2774 builder.setOutKey(ByteString.copyFrom(option.getOutKey())); 2775 } 2776 if (option.getOutIv() != null) { 2777 builder.setOutIv(ByteString.copyFrom(option.getOutIv())); 2778 } 2779 return builder.build(); 2780 } 2781 return null; 2782 } 2783 2784 public static CipherOption convert(CipherOptionProto proto) { 2785 if (proto != null) { 2786 CipherSuite suite = null; 2787 if (proto.getSuite() != null) { 2788 suite = convert(proto.getSuite()); 2789 } 2790 byte[] inKey = null; 2791 if (proto.getInKey() != null) { 2792 inKey = proto.getInKey().toByteArray(); 2793 } 2794 byte[] inIv = null; 2795 if (proto.getInIv() != null) { 2796 inIv = proto.getInIv().toByteArray(); 2797 } 2798 byte[] outKey = null; 2799 if (proto.getOutKey() != null) { 2800 outKey = proto.getOutKey().toByteArray(); 2801 } 2802 byte[] outIv = null; 2803 if (proto.getOutIv() != null) { 2804 outIv = proto.getOutIv().toByteArray(); 2805 } 2806 return new CipherOption(suite, inKey, inIv, outKey, outIv); 2807 } 2808 return null; 2809 } 2810 2811 public static List<CipherOptionProto> convertCipherOptions( 2812 List<CipherOption> options) { 2813 if (options != null) { 2814 List<CipherOptionProto> protos = 2815 Lists.newArrayListWithCapacity(options.size()); 2816 for (CipherOption option : options) { 2817 protos.add(convert(option)); 2818 } 2819 return protos; 2820 } 2821 return null; 2822 } 2823 2824 public static List<CipherOption> convertCipherOptionProtos( 2825 List<CipherOptionProto> protos) { 2826 if (protos != null) { 2827 List<CipherOption> options = 2828 Lists.newArrayListWithCapacity(protos.size()); 2829 for (CipherOptionProto proto : protos) { 2830 options.add(convert(proto)); 2831 } 2832 return options; 2833 } 2834 return null; 2835 } 2836 2837 public static CipherSuiteProto convert(CipherSuite suite) { 2838 switch (suite) { 2839 case UNKNOWN: 2840 return CipherSuiteProto.UNKNOWN; 2841 case AES_CTR_NOPADDING: 2842 return CipherSuiteProto.AES_CTR_NOPADDING; 2843 default: 2844 return null; 2845 } 2846 } 2847 2848 public static CipherSuite convert(CipherSuiteProto proto) { 2849 switch (proto) { 2850 case AES_CTR_NOPADDING: 2851 return CipherSuite.AES_CTR_NOPADDING; 2852 default: 2853 // Set to UNKNOWN and stash the unknown enum value 2854 CipherSuite suite = CipherSuite.UNKNOWN; 2855 suite.setUnknownValue(proto.getNumber()); 2856 return suite; 2857 } 2858 } 2859 2860 public static List<CryptoProtocolVersionProto> convert( 2861 CryptoProtocolVersion[] versions) { 2862 List<CryptoProtocolVersionProto> protos = 2863 Lists.newArrayListWithCapacity(versions.length); 2864 for (CryptoProtocolVersion v: versions) { 2865 protos.add(convert(v)); 2866 } 2867 return protos; 2868 } 2869 2870 public static CryptoProtocolVersion[] convertCryptoProtocolVersions( 2871 List<CryptoProtocolVersionProto> protos) { 2872 List<CryptoProtocolVersion> versions = 2873 Lists.newArrayListWithCapacity(protos.size()); 2874 for (CryptoProtocolVersionProto p: protos) { 2875 versions.add(convert(p)); 2876 } 2877 return versions.toArray(new CryptoProtocolVersion[] {}); 2878 } 2879 2880 public static CryptoProtocolVersion convert(CryptoProtocolVersionProto 2881 proto) { 2882 switch(proto) { 2883 case ENCRYPTION_ZONES: 2884 return CryptoProtocolVersion.ENCRYPTION_ZONES; 2885 default: 2886 // Set to UNKNOWN and stash the unknown enum value 2887 CryptoProtocolVersion version = CryptoProtocolVersion.UNKNOWN; 2888 version.setUnknownValue(proto.getNumber()); 2889 return version; 2890 } 2891 } 2892 2893 public static CryptoProtocolVersionProto convert(CryptoProtocolVersion 2894 version) { 2895 switch(version) { 2896 case UNKNOWN: 2897 return CryptoProtocolVersionProto.UNKNOWN_PROTOCOL_VERSION; 2898 case ENCRYPTION_ZONES: 2899 return CryptoProtocolVersionProto.ENCRYPTION_ZONES; 2900 default: 2901 return null; 2902 } 2903 } 2904 2905 public static HdfsProtos.FileEncryptionInfoProto convert( 2906 FileEncryptionInfo info) { 2907 if (info == null) { 2908 return null; 2909 } 2910 return HdfsProtos.FileEncryptionInfoProto.newBuilder() 2911 .setSuite(convert(info.getCipherSuite())) 2912 .setCryptoProtocolVersion(convert(info.getCryptoProtocolVersion())) 2913 .setKey(getByteString(info.getEncryptedDataEncryptionKey())) 2914 .setIv(getByteString(info.getIV())) 2915 .setEzKeyVersionName(info.getEzKeyVersionName()) 2916 .setKeyName(info.getKeyName()) 2917 .build(); 2918 } 2919 2920 public static HdfsProtos.PerFileEncryptionInfoProto convertPerFileEncInfo( 2921 FileEncryptionInfo info) { 2922 if (info == null) { 2923 return null; 2924 } 2925 return HdfsProtos.PerFileEncryptionInfoProto.newBuilder() 2926 .setKey(getByteString(info.getEncryptedDataEncryptionKey())) 2927 .setIv(getByteString(info.getIV())) 2928 .setEzKeyVersionName(info.getEzKeyVersionName()) 2929 .build(); 2930 } 2931 2932 public static HdfsProtos.ZoneEncryptionInfoProto convert( 2933 CipherSuite suite, CryptoProtocolVersion version, String keyName) { 2934 if (suite == null || version == null || keyName == null) { 2935 return null; 2936 } 2937 return HdfsProtos.ZoneEncryptionInfoProto.newBuilder() 2938 .setSuite(convert(suite)) 2939 .setCryptoProtocolVersion(convert(version)) 2940 .setKeyName(keyName) 2941 .build(); 2942 } 2943 2944 public static FileEncryptionInfo convert( 2945 HdfsProtos.FileEncryptionInfoProto proto) { 2946 if (proto == null) { 2947 return null; 2948 } 2949 CipherSuite suite = convert(proto.getSuite()); 2950 CryptoProtocolVersion version = convert(proto.getCryptoProtocolVersion()); 2951 byte[] key = proto.getKey().toByteArray(); 2952 byte[] iv = proto.getIv().toByteArray(); 2953 String ezKeyVersionName = proto.getEzKeyVersionName(); 2954 String keyName = proto.getKeyName(); 2955 return new FileEncryptionInfo(suite, version, key, iv, keyName, 2956 ezKeyVersionName); 2957 } 2958 2959 public static FileEncryptionInfo convert( 2960 HdfsProtos.PerFileEncryptionInfoProto fileProto, 2961 CipherSuite suite, CryptoProtocolVersion version, String keyName) { 2962 if (fileProto == null || suite == null || version == null || 2963 keyName == null) { 2964 return null; 2965 } 2966 byte[] key = fileProto.getKey().toByteArray(); 2967 byte[] iv = fileProto.getIv().toByteArray(); 2968 String ezKeyVersionName = fileProto.getEzKeyVersionName(); 2969 return new FileEncryptionInfo(suite, version, key, iv, keyName, 2970 ezKeyVersionName); 2971 } 2972 2973 public static BlockReportContext convert(BlockReportContextProto proto) { 2974 return new BlockReportContext(proto.getTotalRpcs(), 2975 proto.getCurRpc(), proto.getId()); 2976 } 2977 2978 public static BlockReportContextProto convert(BlockReportContext context) { 2979 return BlockReportContextProto.newBuilder(). 2980 setTotalRpcs(context.getTotalRpcs()). 2981 setCurRpc(context.getCurRpc()). 2982 setId(context.getReportId()). 2983 build(); 2984 } 2985}