Mounting disks that is remounted after restarts requires modifying /etc/fstab file, which is difficult to do in safe manner. - If multiple processes edit the file at the same time, we might lose updates or corrupt the file. Thus a lock needs to be taken. - If OS crashes while updating the file, we might corrupt the file. Thus the operation should be done atomically. - If device path or mount point is already in the /etc/fstab file it might cause unexpected behavior, so we should check their existence before adding the related line to /etc/fstab Since there are many potential pitfalls, we are adding an utility to safely add entries to /etc/fstab file.
30 lines
798 B
Ruby
Executable File
30 lines
798 B
Ruby
Executable File
#!/bin/env ruby
|
|
# frozen_string_literal: true
|
|
|
|
require "fileutils"
|
|
|
|
require_relative "../lib/util"
|
|
|
|
if ARGV.count != 6
|
|
fail "Wrong number of arguments. Expected 6, Given #{ARGV.count}"
|
|
end
|
|
|
|
device, dir, type, options, dump, fsck = ARGV
|
|
|
|
File.open("/etc/fstab", File::RDONLY) do |f|
|
|
f.flock(File::LOCK_EX)
|
|
|
|
content = f.read
|
|
rows = content.split("\n").reject { _1.start_with?("#") }
|
|
matches = rows.select { _1.match(/\A#{device}\s|\s#{dir}\s/) }
|
|
if matches.count == 0
|
|
content += "\n#{device} #{dir} #{type} #{options} #{dump} #{fsck}"
|
|
safe_write_to_file("/etc/fstab", content)
|
|
break
|
|
end
|
|
|
|
if matches.count > 1 || matches.first !~ /\A#{device}\s#{dir}\s#{type}\s#{options}\s#{dump}\s#{fsck}\z/
|
|
fail "device path and/or mount point already exist in /etc/fstab"
|
|
end
|
|
end
|