Example #1
0
// acquires lease, then adds the blocks to the namenode,
// patching up the referenced inode to match
func (w *InodeWriter) addBlocksForFileWrite(inode *maggiefs.Inode, off uint64, length uint32) error {
	//	fmt.Printf("Adding/extending blocks for write at off %d length %d\n", off, length)
	newEndPos := off + uint64(length)
	if newEndPos > inode.Length {
		// if we have a last block and it's less than max length,
		// extend last block to max block length first
		//		fmt.Printf("Adding/extending blocks for file write to inode %+v\n", inode)
		if inode.Blocks != nil && len(inode.Blocks) > 0 {
			idx := int(len(inode.Blocks) - 1)
			lastBlock := inode.Blocks[idx]
			if lastBlock.Length() < BLOCKLENGTH {
				extendLength := BLOCKLENGTH - lastBlock.Length()
				if lastBlock.EndPos+extendLength > off+uint64(length) {
					// only extend as much as we need to
					extendLength = off + uint64(length) - lastBlock.EndPos
				}
				lastBlock.EndPos = lastBlock.EndPos + extendLength
				inode.Blocks[idx] = lastBlock
				inode.Length += extendLength
			}
		}
		// and add new blocks as necessary
		for newEndPos > inode.Length {
			//			fmt.Printf("New end pos %d still greater than inode length %d\n", newEndPos, inode.Length)
			newBlockLength := newEndPos - inode.Length
			if newBlockLength > BLOCKLENGTH {
				newBlockLength = BLOCKLENGTH
			}
			newBlock, err := w.names.AddBlock(inode.Inodeid, uint32(newBlockLength))
			if err != nil {
				return err
			}
			inode.Blocks = append(inode.Blocks, newBlock)
			inode.Length += newBlockLength
		}
	}
	inode.Mtime = time.Now().Unix()
	err := w.names.SetInode(inode)
	return err
}