001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.hadoop.hdfs.server.datanode;
019    
020    import java.io.File;
021    import java.io.FileOutputStream;
022    import java.io.IOException;
023    import java.io.RandomAccessFile;
024    
025    import org.apache.hadoop.hdfs.protocol.Block;
026    import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState;
027    import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi;
028    import org.apache.hadoop.hdfs.server.datanode.fsdataset.ReplicaOutputStreams;
029    import org.apache.hadoop.io.IOUtils;
030    import org.apache.hadoop.util.DataChecksum;
031    
032    /** 
033     * This class defines a replica in a pipeline, which
034     * includes a persistent replica being written to by a dfs client or
035     * a temporary replica being replicated by a source datanode or
036     * being copied for the balancing purpose.
037     * 
038     * The base class implements a temporary replica
039     */
040    public class ReplicaInPipeline extends ReplicaInfo
041                            implements ReplicaInPipelineInterface {
042      private long bytesAcked;
043      private long bytesOnDisk;
044      private byte[] lastChecksum;  
045      private Thread writer;
046      
047      /**
048       * Constructor for a zero length replica
049       * @param blockId block id
050       * @param genStamp replica generation stamp
051       * @param vol volume where replica is located
052       * @param dir directory path where block and meta files are located
053       */
054      public ReplicaInPipeline(long blockId, long genStamp, 
055            FsVolumeSpi vol, File dir) {
056        this( blockId, 0L, genStamp, vol, dir, Thread.currentThread());
057      }
058    
059      /**
060       * Constructor
061       * @param block a block
062       * @param vol volume where replica is located
063       * @param dir directory path where block and meta files are located
064       * @param writer a thread that is writing to this replica
065       */
066      ReplicaInPipeline(Block block, 
067          FsVolumeSpi vol, File dir, Thread writer) {
068        this( block.getBlockId(), block.getNumBytes(), block.getGenerationStamp(),
069            vol, dir, writer);
070      }
071    
072      /**
073       * Constructor
074       * @param blockId block id
075       * @param len replica length
076       * @param genStamp replica generation stamp
077       * @param vol volume where replica is located
078       * @param dir directory path where block and meta files are located
079       * @param writer a thread that is writing to this replica
080       */
081      ReplicaInPipeline(long blockId, long len, long genStamp,
082          FsVolumeSpi vol, File dir, Thread writer ) {
083        super( blockId, len, genStamp, vol, dir);
084        this.bytesAcked = len;
085        this.bytesOnDisk = len;
086        this.writer = writer;
087      }
088    
089      /**
090       * Copy constructor.
091       * @param from
092       */
093      public ReplicaInPipeline(ReplicaInPipeline from) {
094        super(from);
095        this.bytesAcked = from.getBytesAcked();
096        this.bytesOnDisk = from.getBytesOnDisk();
097        this.writer = from.writer;
098      }
099    
100      @Override
101      public long getVisibleLength() {
102        return -1;
103      }
104      
105      @Override  //ReplicaInfo
106      public ReplicaState getState() {
107        return ReplicaState.TEMPORARY;
108      }
109      
110      @Override // ReplicaInPipelineInterface
111      public long getBytesAcked() {
112        return bytesAcked;
113      }
114      
115      @Override // ReplicaInPipelineInterface
116      public void setBytesAcked(long bytesAcked) {
117        this.bytesAcked = bytesAcked;
118      }
119      
120      @Override // ReplicaInPipelineInterface
121      public long getBytesOnDisk() {
122        return bytesOnDisk;
123      }
124      
125      @Override // ReplicaInPipelineInterface
126      public synchronized void setLastChecksumAndDataLen(long dataLength, byte[] lastChecksum) {
127        this.bytesOnDisk = dataLength;
128        this.lastChecksum = lastChecksum;
129      }
130      
131      @Override // ReplicaInPipelineInterface
132      public synchronized ChunkChecksum getLastChecksumAndDataLen() {
133        return new ChunkChecksum(getBytesOnDisk(), lastChecksum);
134      }
135    
136      /**
137       * Set the thread that is writing to this replica
138       * @param writer a thread writing to this replica
139       */
140      public void setWriter(Thread writer) {
141        this.writer = writer;
142      }
143      
144      @Override  // Object
145      public boolean equals(Object o) {
146        return super.equals(o);
147      }
148      
149      /**
150       * Interrupt the writing thread and wait until it dies
151       * @throws IOException the waiting is interrupted
152       */
153      public void stopWriter() throws IOException {
154        if (writer != null && writer != Thread.currentThread() && writer.isAlive()) {
155          writer.interrupt();
156          try {
157            writer.join();
158          } catch (InterruptedException e) {
159            throw new IOException("Waiting for writer thread is interrupted.");
160          }
161        }
162      }
163      
164      @Override  // Object
165      public int hashCode() {
166        return super.hashCode();
167      }
168      
169      @Override // ReplicaInPipelineInterface
170      public ReplicaOutputStreams createStreams(boolean isCreate, 
171          DataChecksum requestedChecksum) throws IOException {
172        File blockFile = getBlockFile();
173        File metaFile = getMetaFile();
174        if (DataNode.LOG.isDebugEnabled()) {
175          DataNode.LOG.debug("writeTo blockfile is " + blockFile +
176                             " of size " + blockFile.length());
177          DataNode.LOG.debug("writeTo metafile is " + metaFile +
178                             " of size " + metaFile.length());
179        }
180        long blockDiskSize = 0L;
181        long crcDiskSize = 0L;
182        
183        // the checksum that should actually be used -- this
184        // may differ from requestedChecksum for appends.
185        DataChecksum checksum;
186        
187        RandomAccessFile metaRAF = new RandomAccessFile(metaFile, "rw");
188        
189        if (!isCreate) {
190          // For append or recovery, we must enforce the existing checksum.
191          // Also, verify that the file has correct lengths, etc.
192          boolean checkedMeta = false;
193          try {
194            BlockMetadataHeader header = BlockMetadataHeader.readHeader(metaRAF);
195            checksum = header.getChecksum();
196            
197            if (checksum.getBytesPerChecksum() !=
198                requestedChecksum.getBytesPerChecksum()) {
199              throw new IOException("Client requested checksum " +
200                  requestedChecksum + " when appending to an existing block " +
201                  "with different chunk size: " + checksum);
202            }
203            
204            int bytesPerChunk = checksum.getBytesPerChecksum();
205            int checksumSize = checksum.getChecksumSize();
206            
207            blockDiskSize = bytesOnDisk;
208            crcDiskSize = BlockMetadataHeader.getHeaderSize() +
209              (blockDiskSize+bytesPerChunk-1)/bytesPerChunk*checksumSize;
210            if (blockDiskSize>0 && 
211                (blockDiskSize>blockFile.length() || crcDiskSize>metaFile.length())) {
212              throw new IOException("Corrupted block: " + this);
213            }
214            checkedMeta = true;
215          } finally {
216            if (!checkedMeta) {
217              // clean up in case of exceptions.
218              IOUtils.closeStream(metaRAF);
219            }
220          }
221        } else {
222          // for create, we can use the requested checksum
223          checksum = requestedChecksum;
224        }
225        
226        FileOutputStream blockOut = null;
227        FileOutputStream crcOut = null;
228        try {
229          blockOut = new FileOutputStream(
230              new RandomAccessFile( blockFile, "rw" ).getFD() );
231          crcOut = new FileOutputStream(metaRAF.getFD() );
232          if (!isCreate) {
233            blockOut.getChannel().position(blockDiskSize);
234            crcOut.getChannel().position(crcDiskSize);
235          }
236          return new ReplicaOutputStreams(blockOut, crcOut, checksum);
237        } catch (IOException e) {
238          IOUtils.closeStream(blockOut);
239          IOUtils.closeStream(metaRAF);
240          throw e;
241        }
242      }
243      
244      @Override
245      public String toString() {
246        return super.toString()
247            + "\n  bytesAcked=" + bytesAcked
248            + "\n  bytesOnDisk=" + bytesOnDisk;
249      }
250    }