Class: Macinbox::Actions::CreateImageFromInstaller

Inherits:
Object
  • Object
show all
Defined in:
lib/macinbox/actions/create_image_from_installer.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ CreateImageFromInstaller

Returns a new instance of CreateImageFromInstaller.

Raises:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 15

def initialize(opts)
  @installer_app     = opts[:installer_path]  or raise ArgumentError.new(":installer_path not specified")
  @output_path       = opts[:image_path]      or raise ArgumentError.new(":image_path not specified")
  @vmware_fusion_app = opts[:vmware_path]
  @parallels_app     = opts[:parallels_path]

  @disk_size         = opts[:disk_size]       or raise ArgumentError.new(":disk_size not specified")
  @fstype            = opts[:fstype]          or raise ArgumentError.new(":fstype not specified")
  @short_name        = opts[:short_name]      or raise ArgumentError.new(":short_name not specified")
  @full_name         = opts[:full_name]       or raise ArgumentError.new(":full_name not specified")
  @password          = opts[:password]        or raise ArgumentError.new(":password not specified")

  @box_format        = opts[:box_format]
          = opts[:auto_login]
  @skip_mini_buddy   = opts[:skip_mini_buddy]
  @hidpi             = opts[:hidpi]

  @collector         = opts[:collector]       or raise ArgumentError.new(":collector not specified")
  @debug             = opts[:debug]

  raise Macinbox::Error.new("Installer app not found") unless File.exist? @installer_app

  raise ArgumentError.new(":vmware_path not specified") if @box_format == "vmware_desktop" && !opts[:vmware_path]
  raise ArgumentError.new(":parallels_path not specified") if @box_format == "parallels" && !opts[:parallels_path]
end

Instance Method Details

#automate_user_account_creationObject



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 268

def 
  Logger.info "Configuring the primary user account..." do
    scratch_installer_configuration_file = "#{@scratch_mountpoint}/private/var/db/.InstallerConfiguration"
    File.write scratch_installer_configuration_file, "      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n      <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n      <plist version=\"1.0\">\n      <dict>\n        <key>Users</key>\n        <array>\n          <dict>\n            <key>admin</key>\n            <true/>\n            <key>autologin</key>\n            <\#{@auto_login ? true : false}/>\n            <key>fullName</key>\n            <string>\#{@full_name}</string>\n            <key>shortName</key>\n            <string>\#{@short_name}</string>\n            <key>password</key>\n            <string>\#{@password}</string>\n            <key>skipMiniBuddy</key>\n            <\#{@skip_mini_buddy ? true : false}/>\n          </dict>\n        </array>\n      </dict>\n      </plist>\n    EOF\n  end\nend\n"

#automate_vagrant_ssh_key_installationObject



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 299

def automate_vagrant_ssh_key_installation
  if @short_name == "vagrant"
    Logger.info "Installing the default insecure vagrant ssh key..." do
      contents = "        #!/bin/sh\n        rm /etc/rc.vagrant\n        while [ ! -e /Users/vagrant ]; do\n          sleep 1\n        done\n        if [ ! -e /Users/vagrant/.ssh ]; then\n          mkdir /Users/vagrant/.ssh\n          chmod 0700 /Users/vagrant/.ssh\n          chown `stat -f %u /Users/vagrant` /Users/vagrant/.ssh\n        fi\n        echo \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key\" >> /Users/vagrant/.ssh/authorized_keys\n        chmod 0600 /Users/vagrant/.ssh/authorized_keys\n        chown `stat -f %u /Users/vagrant` /Users/vagrant/.ssh/authorized_keys\n      EOF\n      File.write @scratch_rc_vagrant, contents, mode: 'a'\n    end\n  end\nend\n"

#check_macos_versionsObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 68

def check_macos_versions
  Logger.info "Checking macOS versions..." do
    install_info_plist = "#{@installer_app}/Contents/SharedSupport/InstallInfo.plist"
    raise Macinbox::Error.new("InstallInfo.plist not found in installer app bundle") unless File.exist? install_info_plist

    installer_os_version = Task.backtick %W[ /usr/libexec/PlistBuddy -c #{'Print :System\ Image\ Info:version'} #{install_info_plist} ]
    installer_os_version_components = installer_os_version.split(".") rescue [0, 0, 0]
    installer_os_version_major = installer_os_version_components[0]
    installer_os_version_minor = installer_os_version_components[1]
    Logger.info "Installer macOS version detected: #{installer_os_version}" if @debug

    host_os_version = Task.backtick %W[ sw_vers -productVersion ]
    host_os_version_components = host_os_version.split(".") rescue [0, 0, 0]
    host_os_version_major = host_os_version_components[0]
    host_os_version_minor = host_os_version_components[1]
    Logger.info "Host macOS version detected: #{host_os_version}" if @debug

    if installer_os_version_major != host_os_version_major || installer_os_version_minor != host_os_version_minor
      Logger.error "Warning: host OS version (#{host_os_version}) and installer OS version (#{installer_os_version}) do not match"
      # raise Macinbox::Error.new("host OS version (#{host_os_version}) and installer OS version (#{installer_os_version}) do not match")
    end
  end
end

#create_rc_vagrantObject



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 132

def create_rc_vagrant
  scratch_rc_installer_cleanup = "#{@scratch_mountpoint}/private/etc/rc.installer_cleanup"
  @scratch_rc_vagrant = "#{@scratch_mountpoint}/private/etc/rc.vagrant"
  File.write scratch_rc_installer_cleanup, "    #!/bin/sh\n    rm -f /etc/rc.installer_cleanup\n    /etc/rc.vagrant &\n    exit 0\n  EOF\n  FileUtils.chmod 0755, scratch_rc_installer_cleanup\n  File.write @scratch_rc_vagrant, <<~EOF\n    #!/bin/sh\n    rm -f /etc/rc.vagrant\n  EOF\n  FileUtils.chmod 0755, @scratch_rc_vagrant\nend\n"

#create_scratch_imageObject



105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 105

def create_scratch_image
  Logger.info "Creating and attaching a new blank disk image..." do
    @collector.on_cleanup do
      %x( /usr/bin/hdiutil detach -quiet -force #{@scratch_mountpoint.shellescape} > /dev/null 2>&1 ) if @scratch_mountpoint
    end
    @scratch_mountpoint = "#{@temp_dir}/scratch_mountpoint"
    @scratch_image = "#{@temp_dir}/scratch.sparseimage"
    FileUtils.mkdir @scratch_mountpoint
    quiet_flag = @debug ? [] : %W[ -quiet ]
    Task.run %W[ /usr/bin/hdiutil create -size #{@disk_size}g -type SPARSE -fs #{@fstype} -volname #{"Macintosh HD"} -uid 0 -gid 80 -mode 1775 #{@scratch_image} ] + quiet_flag
    Task.run %W[ /usr/bin/hdiutil attach #{@scratch_image} -mountpoint #{@scratch_mountpoint} -nobrowse -owners on ] + quiet_flag
  end
end

#create_temp_dirObject



63
64
65
66
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 63

def create_temp_dir
  @temp_dir = Task.backtick %W[ /usr/bin/mktemp -d -t create_image_from_installer ]
  @collector.add_temp_dir @temp_dir
end

#create_wrapper_imageObject



92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 92

def create_wrapper_image
  Logger.info "Creating and attaching wrapper disk image..." do
    @collector.on_cleanup do
      %x( /usr/bin/hdiutil detach -quiet -force #{@wrapper_mountpoint.shellescape} > /dev/null 2>&1 ) if @wrapper_mountpoint
    end
    @wrapper_mountpoint = "/Volumes/#{File.basename @installer_app, ".app"}"
    @wrapper_image = "#{@temp_dir}/wrapper.dmg"
    quiet_flag = @debug ? [] : %W[ -quiet ]
    Task.run %W[ /usr/bin/hdiutil create -srcfolder #{@installer_app} #{@wrapper_image} ] + quiet_flag
    Task.run %W[ /usr/bin/hdiutil attach #{@wrapper_image} -nobrowse ] + quiet_flag
  end
end

#enable_hidpiObject



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 341

def enable_hidpi
  if @hidpi
    Logger.info "Enabling HiDPI resolutions..." do
      scratch_windowserver_preferences = "#{@scratch_mountpoint}/Library/Preferences/com.apple.windowserver.plist"
      File.write scratch_windowserver_preferences, "        <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n        <plist version=\"1.0\">\n        <dict>\n          <key>DisplayResolutionEnabled</key>\n          <true/>\n        </dict>\n        </plist>\n      EOF\n    end\n  end\nend\n"

#enable_passwordless_sudoObject



322
323
324
325
326
327
328
329
330
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 322

def enable_passwordless_sudo
  Logger.info "Enabling password-less sudo..." do
    scratch_sudoers_d_user_rule_file = "#{@scratch_mountpoint}/private/etc/sudoers.d/#{@short_name}"
    File.write scratch_sudoers_d_user_rule_file, "      \#{@short_name} ALL=(ALL) NOPASSWD: ALL\n    EOF\n    FileUtils.chmod 0440, scratch_sudoers_d_user_rule_file\n  end\nend\n"

#enable_sshdObject



332
333
334
335
336
337
338
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 332

def enable_sshd
  Logger.info "Enabling sshd..." do
    scratch_launchd_disabled_plist = "#{@scratch_mountpoint}/private/var/db/com.apple.xpc.launchd/disabled.plist"
    opts = @debug ? {} : { :out => File::NULL }
    Task.run %W[ /usr/libexec/PlistBuddy -c #{'Add :com.openssh.sshd bool False'} #{scratch_launchd_disabled_plist} ] + [opts]
  end
end

#install_macosObject



119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 119

def install_macos
  Logger.info "Installing macOS..." do
    activity = Logger.prefix + "installer"
    install_info_plist = "#{@wrapper_mountpoint}/#{File.basename @installer_app}/Contents/SharedSupport/InstallInfo.plist"
    Task.run %W[ /usr/bin/touch #{@scratch_mountpoint}/.macinbox ]
    cmd = %W[ /usr/sbin/installer -verboseR -dumplog -pkg #{install_info_plist} -target #{@scratch_mountpoint} ]
    opts = @debug ? {} : { :err => [:child, :out] }
    Task.run_with_progress activity, cmd, opts do |line|
      /^installer:%(.*)$/.match(line)[1].to_f rescue nil
    end
  end
end

#install_parallels_toolsObject



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 210

def install_parallels_tools

  @collector.on_cleanup do
    %x( /usr/bin/hdiutil detach -quiet -force #{@tools_mountpoint.shellescape} > /dev/null 2>&1 ) if @tools_mountpoint
  end

  Logger.info "Installing the Parallels Tools..." do

    @tools_mountpoint = "#{@temp_dir}/tools_mountpoint"
    FileUtils.mkdir @tools_mountpoint

    quiet_flag = @debug ? [] : %W[ -quiet ]

    tools_image = "#{@parallels_app}/Contents/Resources/Tools/prl-tools-mac.iso"

    Task.run %W[ /usr/bin/hdiutil attach #{tools_image} -mountpoint #{@tools_mountpoint} -nobrowse ] + quiet_flag

    tools_packages_dir = "#{@tools_mountpoint}/Install.app/Contents/Resources/Install.mpkg/Contents/Packages"

    tools_packages = [
      "Parallels Tools Audio 10.9.pkg",
      "Parallels Tools Coherence.pkg",
      "Parallels Tools CopyPaste.pkg",
      "Parallels Tools DragDrop.pkg",
      "Parallels Tools HostTime.pkg",
      "Parallels Tools InstallationAgent.pkg",
      "Parallels Tools Network 10.9.pkg",
      "Parallels Tools SharedFolders.pkg",
      "Parallels Tools TimeSync.pkg",
      "Parallels Tools ToolGate 10.9.pkg",
      "Parallels Tools Utilities.pkg",
      "Parallels Tools Video 10.9.pkg"
    ]

    tools_expanded_packages_dir = "#{@temp_dir}/tools_packages"
    FileUtils.mkdir tools_expanded_packages_dir

    tools_packages.each do |package|
      Task.run %W[ /usr/sbin/pkgutil --expand #{tools_packages_dir}/#{package} #{tools_expanded_packages_dir}/#{package} ]
      Task.run %W[ /usr/bin/ditto -x -z #{tools_expanded_packages_dir}/#{package}/Payload #{@scratch_mountpoint} ]
    end

    prl_nettool_source = "/Library/Parallels Guest Tools/prl_nettool"
    prl_nettool_target = "#{@scratch_mountpoint}/usr/local/bin/prl_nettool"

    FileUtils.mkdir_p File.dirname(prl_nettool_target)
    FileUtils.ln_s prl_nettool_source, prl_nettool_target

    prl_fsd_plist = "#{@scratch_mountpoint}/Library/LaunchDaemons/com.parallels.vm.prl_fsd.plist"
    Task.run %W[ /usr/bin/sed -i #{''} s/PARALLELS_ADDITIONAL_ARGS/--share/ #{prl_fsd_plist} ]

    contents = "/Library/Parallels\ Guest\ Tools/dynres --enable-retina\n"
    File.write @scratch_rc_vagrant, contents, mode: 'a'

  end

end

#install_vmware_toolsObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 149

def install_vmware_tools
  @collector.on_cleanup do
    %x( /usr/bin/hdiutil detach -quiet -force #{@tools_mountpoint.shellescape} > /dev/null 2>&1 ) if @tools_mountpoint
  end

  tools_image = "#{@vmware_fusion_app}/Contents/Library/isoimages/darwin.iso"

  unless File.exist? tools_image
    Logger.info "Downloading the VMware Tools..." do
      bundle_version = Task.backtick %W[ defaults read #{"/Applications/VMware Fusion.app/Contents/Info.plist"} CFBundleVersion ]
      bundle_short_version = Task.backtick %W[ defaults read #{"/Applications/VMware Fusion.app/Contents/Info.plist"} CFBundleShortVersionString ]
      darwin_iso_url = "http://softwareupdate.vmware.com/cds/vmw-desktop/fusion/#{bundle_short_version}/#{bundle_version}/packages/com.vmware.fusion.tools.darwin.zip.tar"
      Dir.chdir(@temp_dir) do
        Task.run %W[ /usr/bin/curl #{darwin_iso_url} -O ] + (@debug ? [] : %W[ -s -S ])
        Task.run %W[ /usr/bin/tar -xf com.vmware.fusion.tools.darwin.zip.tar com.vmware.fusion.tools.darwin.zip ]
        Task.run %W[ /usr/bin/unzip ] + (@debug ? [] : %W[ -qq ]) + %W[ com.vmware.fusion.tools.darwin.zip payload/darwin.iso ]
      end
      tools_image = "#{@temp_dir}/payload/darwin.iso"
    end
  end

  Logger.info "Installing the VMware Tools..." do
    @tools_mountpoint = "#{@temp_dir}/tools_mountpoint"
    FileUtils.mkdir @tools_mountpoint

    tools_package = "#{@tools_mountpoint}/Install VMware Tools.app/Contents/Resources/VMware Tools.pkg"
    tools_package_dir = "#{@temp_dir}/tools_package"

    quiet_flag = @debug ? [] : %W[ -quiet ]

    Task.run %W[ /usr/bin/hdiutil attach #{tools_image} -mountpoint #{@tools_mountpoint} -nobrowse ] + quiet_flag
    Task.run %W[ /usr/sbin/pkgutil --expand #{tools_package} #{tools_package_dir} ]
    Task.run %W[ /usr/bin/ditto -x -z #{tools_package_dir}/files.pkg/Payload #{@scratch_mountpoint} ]

    scratch_vmhgfs_filesystem_resources = "#{@scratch_mountpoint}/Library/Filesystems/vmhgfs.fs/Contents/Resources"

    FileUtils.mkdir_p scratch_vmhgfs_filesystem_resources
    FileUtils.ln_s "/Library/Application Support/VMware Tools/mount_vmhgfs", "#{scratch_vmhgfs_filesystem_resources}/"
  end
end

#runObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 41

def run
  create_temp_dir
  check_macos_versions
  create_wrapper_image
  create_scratch_image
  install_macos
  create_rc_vagrant
  case @box_format
  when /^vmware_(fusion|desktop)$/
    install_vmware_tools
    set_spc_kextpolicy
  when /^parallels$/
    install_parallels_tools
  end
  
  automate_vagrant_ssh_key_installation
  enable_passwordless_sudo
  enable_sshd
  enable_hidpi
  save_image
end

#save_imageObject



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 359

def save_image
  Logger.info "Saving the image..." do
    # detaching sometimes fails at first so we pause to let the disk
    # quiesce and then retry again a few times before giving up
    max_attempts = 5
    for attempt in 1..max_attempts
      begin
        Logger.info "Detaching the image..." if @debug
        quiet_flag = @debug ? [] : %W[ -quiet ]
        Task.run %W[ /usr/bin/hdiutil detach #{@scratch_mountpoint} ] + quiet_flag
        break
      rescue Macinbox::Error => error
        raise if attempt == max_attempts
        Logger.info "#{error.message}. Sleeping and retrying..." if @debug
        sleep 15
      end
    end
    FileUtils.mv @scratch_image, "#{@temp_dir}/macinbox.dmg"
    FileUtils.chown ENV["SUDO_USER"], nil, "#{@temp_dir}/macinbox.dmg"
    FileUtils.mv "#{@temp_dir}/macinbox.dmg", @output_path
  end
end

#set_spc_kextpolicyObject



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/macinbox/actions/create_image_from_installer.rb', line 190

def set_spc_kextpolicy
  Logger.info "Setting the KextPolicy to allow loading the VMware kernel extensions..." do
    scratch_spc_kextpolicy = "#{@scratch_mountpoint}/private/var/db/SystemPolicyConfiguration/KextPolicy"
    Task.run_with_input %W[ /usr/bin/sqlite3 #{scratch_spc_kextpolicy} ] do |pipe|
      pipe.write "        PRAGMA foreign_keys=OFF;\n        BEGIN TRANSACTION;\n        CREATE TABLE kext_load_history_v3 ( path TEXT PRIMARY KEY, team_id TEXT, bundle_id TEXT, boot_uuid TEXT, created_at TEXT, last_seen TEXT, flags INTEGER );\n        CREATE TABLE kext_policy ( team_id TEXT, bundle_id TEXT, allowed BOOLEAN, developer_name TEXT, flags INTEGER, PRIMARY KEY (team_id, bundle_id) );\n        INSERT INTO kext_policy VALUES('EG7KH642X6','com.vmware.kext.VMwareGfx',1,'VMware, Inc.',1);\n        INSERT INTO kext_policy VALUES('EG7KH642X6','com.vmware.kext.vmmemctl',1,'VMware, Inc.',1);\n        INSERT INTO kext_policy VALUES('EG7KH642X6','com.vmware.kext.vmhgfs',1,'VMware, Inc.',1);\n        CREATE TABLE kext_policy_mdm ( team_id TEXT, bundle_id TEXT, allowed BOOLEAN, payload_uuid TEXT, PRIMARY KEY (team_id, bundle_id) );\n        CREATE TABLE settings ( name TEXT, value TEXT, PRIMARY KEY (name) );\n        COMMIT;\n      EOF\n    end\n  end\nend\n"