Create a Filesystem with Ruby and FUSE

Here I’ll show in simple steps how to create a file system (CowFS) with Ruby and FUSE. In 5 minutes you will be able to create your own file system.

Commands

sudo gem install rfusefs

Basic code

# main.rb
require 'rfusefs'

class CowFS
  def contents(path)
    ['rose.txt']
  end

  def file?(path)
    path == '/rose.txt'
  end

  def read_file(path)
    "Moo?!\n"
  end
end

cowfs = CowFS.new
FuseFS.start(cowfs, '/mnt/test')

Then, run (in one terminal) and test (in another):

> ruby main.rb
> ls /mnt/test
> cat /mnt/test/rose.txt

Binary files

def contents(path)
  ['rose.txt', 'bessie.jpg']
end

def read_file(path)
  if path == '/rose.txt'
    "Moo?!\n"
  else
    File.binread('/home/daniel/Pictures/some_picture.jpg')
  end
end

Size / Time

def size(path)
  if path == '/rose.txt'
    6
  elsif path == '/bessie.jpg'
    888_000
  else
    raw_read(path).length
  end
end

def times(path)
  if path == '/rose.txt'
    year, month, day, hour, min, sec = [2017, 4, 17, 13, 20, 59.99]
    atime = mtime = ctime = Time.new(year, month, day, hour, min, sec).to_f
    return [atime, mtime, ctime]
  else
    return [0, 0, 0]
  end
end

RAW

def raw_open(path, mode, raw)
  {path: path}
end

def raw_read(path, offset, size, raw)
  if raw[:path] == '/rose.txt'
    "Moo?!\n"
  else
    File.binread('/home/daniel/Pictures/some_picture.jpg', size, offset)
  end
end

Compiling

source 'https://rubygems.org' do
  gem 'rfusefs'
end
FuseFS.mount() { |options| cowfs }
> rb2exe main.rb --add=. --daemon -o mount.cowfs
> chmod +x mount.cowfs
> mv mount.cowfs /usr/sbin

On boot (fstab)

> rb2exe main.rb --add=. --daemon -o mount.cowfs
> chmod +x mount.cowfs
> mv mount.cowfs /usr/sbin
/usr/sbin/mount.cowfs /mnt/cows fuse user,noauto    0    0

Links

Close Menu