require 'downloader' require 'system' require_relative 'data/resources/iso-images' require 'vm/qemu' require 'vm/archive' module VirtualMachine def self.distro(name, arch, type = :install) ISO_URLS[name][arch][type] end def self.vm_root_path ENV["DAT_VM_DATA"] || File.join(User.cache_path, "vm") end def self.vm_dir(options) File.join(vm_root_path, "image", "#{options[:distro].to_s}-#{options[:arch].to_s}", options[:name]) end def self.archive_dir(options) File.join(vm_root_path, "archive", "#{options[:distro].to_s}-#{options[:arch].to_s}", options[:name]) end def self.create_archive_path(options) File.join(archive_dir(options), "archive.tar.zst") end def self.get_recent_archive_path(options) File.join(archive_dir(options), "archive.tar.zst") end # https://artur.gurgul.pro/vm/ # https://artur.gurgul.pro/vm/debian-arm64/debian/archive.tar.zst def self.vm_archive_url(options) return nil unless ENV["DAT_VM_REPO_URL"] end def self.root_img_path(options) File.join(vm_dir(options), "root.img") end def self.fill_defaults(options) if options[:name] == nil options[:name] = options[:distro] end if options[:arch] == nil options[:arch] = System::ARCH else options[:arch] = System.arch_to_symbol(options[:arch]) end end def self.archive(options) fill_defaults(options) Archive.create(vm_dir(options), out: create_archive_path(options)) end def self.restore(options) fill_defaults(options) Archive.restore(get_recent_archive_path(options), vm_dir(options)) end def self.run(options) fill_defaults(options) disk_img_path = root_img_path(options) # TODO: # - if image path not exists, check the cache # - if cache do not exists try to download puts "Starting image: #{disk_img_path}" Qemu.launch( options[:arch], disk_img_path, cpus: [1, System.cpus - 2].max, detach: true ) end def self.setup(options) fill_defaults(options) url = distro(options[:name], options[:arch], :install) disk_img_path = root_img_path(options) Downloader.get(url) do |path| create_disk_image(disk_img_path, 64000) Qemu.launch( options[:arch], disk_img_path, cpus: [1, System.cpus - 2].max, cdrom: path, detach: true ) end end # size in MB # lsof /Users/artur/.cache/dat/vm/debian/arm64/debian/root.img def self.create_disk_image(path, size) size_in_bytes = 1024 * 1024 * size # Ensure the directory exists dir = File.dirname(path) FileUtils.mkdir_p(dir) unless Dir.exist?(dir) File.open(path, "wb") do |f| f.truncate(size_in_bytes) # f.seek(size_in_bytes - 1) # f.write("\0") end end end