Sha256: a8caa4f9916d145e0445eb0ec1443a8c0d1d9f69fdfb2866929fdf561d855931

Contents?: true

Size: 1.54 KB

Versions: 322

Compression:

Stored size: 1.54 KB

Contents

require 'bosh/core/shell'
require 'tmpdir'

module Bosh::Stemcell
  class DiskImage

    attr_reader :image_mount_point

    def initialize(options)
      @image_file_path   = options.fetch(:image_file_path)
      @image_mount_point = options.fetch(:image_mount_point, Dir.mktmpdir)
      @verbose           = options.fetch(:verbose, false)
      @shell             = Bosh::Core::Shell.new
    end

    def mount
      device_path   = stemcell_loopback_device_name
      mount_command = "sudo mount #{device_path} #{image_mount_point}"
      shell.run(mount_command, output_command: verbose)
    rescue => e
      raise e unless e.message.include?(mount_command)

      sleep 0.5
      shell.run(mount_command, output_command: verbose)
    end

    def unmount
      shell.run("sudo umount #{image_mount_point}", output_command: verbose)
    ensure
      unmap_image
    end

    def while_mounted
      mount
      yield self
    ensure
      unmount
    end

    private

    attr_reader :image_file_path, :verbose, :shell, :device

    def stemcell_loopback_device_name
      split_output = map_image.split(' ')
      device_name  = split_output[2]

      File.join('/dev/mapper', device_name)
    end

    def map_image
      @device = shell.run("sudo losetup --show --find #{image_file_path}", output_command: verbose)
      shell.run("sudo kpartx -av #{device}", output_command: verbose)
    end

    def unmap_image
      shell.run("sudo kpartx -dv #{device}", output_command: verbose)
      shell.run("sudo losetup -dv #{device}", output_command: verbose)
    end
  end
end

Version data entries

322 entries across 322 versions & 1 rubygems

Version Path
bosh-stemcell-1.3146.10.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.9.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.8.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.7.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.6.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.5.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.4.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.3.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.2.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3146.1.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3169.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3167.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3165.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3163.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3160.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3157.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3156.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3155.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3153.0 lib/bosh/stemcell/disk_image.rb
bosh-stemcell-1.3149.0 lib/bosh/stemcell/disk_image.rb