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