Ruby FUSE

Create a Filesystem with Ruby and FUSE

by Daniel Loureiro on 2 min read

Let's see how to create a file system (CowFS) with Ruby and FUSE in simple steps.

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
  rose.txt
cat /mnt/test/rose.txt
  Moo?!

# Binary files

# main.rb
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

# main.rb
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

# main.rb
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

# Gemfile
source 'https://rubygems.org' do
  gem 'rfusefs'
end
# main.rb
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
# /etc/fstab
/usr/sbin/mount.cowfs /mnt/cows fuse user,noauto    0    0


Comments

Copyright 2022 - Daniel Loureiro