Class: VagrantPlugins::ProviderZone::Driver

Inherits:
Object
  • Object
show all
Includes:
Vagrant::Util::Retryable
Defined in:
lib/vagrant-zones/driver.rb

Overview

This class does the heavy lifting of the zone provider

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(machine) ⇒ Driver

Returns a new instance of Driver.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/vagrant-zones/driver.rb', line 26

def initialize(machine)
  @logger = Log4r::Logger.new('vagrant_zones::driver')
  @machine = machine
  @executor = Executor::Exec.new
  @pfexec = if Process.uid.zero?
              ''
            elsif system('sudo -v')
              'sudo'
            else
              'pfexec'
            end
end

Instance Attribute Details

#executorObject

Returns the value of attribute executor.



24
25
26
# File 'lib/vagrant-zones/driver.rb', line 24

def executor
  @executor
end

Instance Method Details

#allowedaddress(uii, opts) ⇒ Object

This Sanitizes the AllowedIP Address to set for Cloudinit



242
243
244
245
246
247
248
249
# File 'lib/vagrant-zones/driver.rb', line 242

def allowedaddress(uii, opts)
  config = @machine.provider_config
  ip = ipaddress(uii, opts)
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  allowed_address = "#{ip}/#{shrtsubnet}"
  uii.info(I18n.t('vagrant_zones.allowedaddress') + allowed_address) if config.debug
  allowed_address
end

#boot(uii) ⇒ Object

Boot the Machine



173
174
175
176
177
# File 'lib/vagrant-zones/driver.rb', line 173

def boot(uii)
  name = @machine.name
  uii.info(I18n.t('vagrant_zones.starting_zone'))
  execute(false, "#{@pfexec} zoneadm -z #{name} boot")
end

#check_zone_support(uii) ⇒ Object

This ensures the zone is safe to boot



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
# File 'lib/vagrant-zones/driver.rb', line 1156

def check_zone_support(uii)
  uii.info(I18n.t('vagrant_zones.preflight_checks'))
  config = @machine.provider_config
  ## Detect if Virtualbox is Running
  ## LX, KVM, and Bhyve cannot run conncurently with Virtualbox:
  ### https://illumos.topicbox-beta.com/groups/omnios-discuss/Tce3bbd08cace5349-M5fc864e9c1a7585b94a7c080
  uii.info(I18n.t('vagrant_zones.vbox_run_check'))
  result = execute(true, "#{@pfexec} VBoxManage list runningvms")
  raise Errors::VirtualBoxRunningConflictDetected if result.zero?

  ## https://man.omnios.org/man5/brands
  case config.brand
  when 'lx'
    uii.info(I18n.t('vagrant_zones.lx_check'))
  when 'ipkg'
    uii.info(I18n.t('vagrant_zones.ipkg_check'))
  when 'lipkg'
    uii.info(I18n.t('vagrant_zones.lipkg_check'))
  when 'pkgsrc'
    uii.info(I18n.t('vagrant_zones.pkgsrc_check'))
  when 'sparse'
    uii.info(I18n.t('vagrant_zones.sparse_check'))
  when 'kvm'
    ## https://man.omnios.org/man5/kvm
    uii.info(I18n.t('vagrant_zones.kvm_check'))
  when 'illumos'
    uii.info(I18n.t('vagrant_zones.illumos_check'))
  when 'bhyve'
    ## https://man.omnios.org/man5/bhyve
    ## Check for bhhwcompat
    result = execute(true, "#{@pfexec} test -f /usr/sbin/bhhwcompat ; echo $?")
    if result == 1
      bhhwcompaturl = 'https://downloads.omnios.org/misc/bhyve/bhhwcompat'
      execute(true, "#{@pfexec} curl -o /usr/sbin/bhhwcompat #{bhhwcompaturl} && #{@pfexec} chmod +x /usr/sbin/bhhwcompat")
      result = execute(true, "#{@pfexec} test -f /usr/sbin/bhhwcompat ; echo $?")
      raise Errors::MissingCompatCheckTool if result.zero?
    end

    # Check whether OmniOS version is lower than r30
    cutoff_release = '1510380'
    cutoff_release = cutoff_release[0..-2].to_i
    uii.info(I18n.t('vagrant_zones.bhyve_check'))
    uii.info("  #{cutoff_release}")
    release = File.open('/etc/release', &:readline)
    release = release.scan(/\w+/).values_at(-1)
    release = release[0][1..-2].to_i
    raise Errors::SystemVersionIsTooLow if release < cutoff_release

    # Check Bhyve compatability
    uii.info(I18n.t('vagrant_zones.bhyve_compat_check'))
    result = execute(false, "#{@pfexec} bhhwcompat -s")
    raise Errors::MissingBhyve if result.length == 1
  end
end

#console(uii, command, ip, port, exit) ⇒ Object

Function to provide console, vnc, or webvnc access Future To-Do: Should probably split this up



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/vagrant-zones/driver.rb', line 124

def console(uii, command, ip, port, exit)
  uii.info(I18n.t('vagrant_zones.console'))
  detach = exit[:detach]
  kill = exit[:kill]
  name = @machine.name
  config = @machine.provider_config
  if port.nil?
    port = if config.consoleport.nil?
             ''
           else
             config.consoleport
           end
  end
  ipaddr = '0.0.0.0'
  ipaddr = config.consolehost if config.consolehost =~ Resolv::IPv4::Regex
  ipaddr = ip if ip =~ Resolv::IPv4::Regex
  netport = "#{ipaddr}:#{port}"
  pid = 0
  if File.exist?("#{name}.pid")
    pid = File.readlines("#{name}.pid")[0].strip
    ctype = File.readlines("#{name}.pid")[1].strip
    ts = File.readlines("#{name}.pid")[2].strip
    vmname = File.readlines("#{name}.pid")[3].strip
    nport = File.readlines("#{name}.pid")[4].strip
    uii.info("Session running with PID: #{pid} since: #{ts} as console type: #{ctype} served at: #{nport}\n") if vmname[name.to_s]
    if kill == 'yes'
      File.delete("#{name}.pid")
      Process.kill 'TERM', pid.to_i
      Process.detach pid.to_i
      uii.info('Session Terminated')
    end
  else
    case command
    when /vnc/
      run = "pfexec zadm #{command} #{netport} #{name}"
      pid = spawn(run)
      Process.wait pid if detach == 'no'
      Process.detach(pid) if detach == 'yes'
      time = Time.new.strftime('%Y-%m-%d-%H:%M:%S')
      File.write("#{name}.pid", "#{pid}\n#{command}\n#{time}\n#{name}\n#{netport}") if detach == 'yes'
      uii.info("Session running with PID: #{pid} as console type: #{command} served at: #{netport}") if detach == 'yes'
    when 'zlogin'
      run = "#{@pfexec} zadm console #{name}"
      exec(run)
    end
  end
end

#control(uii, control) ⇒ Object

Control the zone from inside the zone OS



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/vagrant-zones/driver.rb', line 81

def control(uii, control)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.control')) if config.debug
  case control
  when 'rmatch(/estart'
    command = 'sudo shutdown -r'
    command = config.safe_restart unless config.safe_restart.nil?
    ssh_run_command(uii, command)
  when 'shutdown'
    command = 'sudo init 0 || true'
    command = config.safe_shutdown unless config.safe_shutdown.nil?
    ssh_run_command(uii, command)
  else
    uii.info(I18n.t('vagrant_zones.control_no_cmd'))
  end
end

#create_dataset(uii) ⇒ Object

This helps us create all the datasets for the zone



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'lib/vagrant-zones/driver.rb', line 736

def create_dataset(uii)
  config = @machine.provider_config
  name = @machine.name
  bootconfigs = config.boot
  datasetpath = "#{bootconfigs['array']}/#{bootconfigs['dataset']}/#{name}"
  datasetroot = "#{datasetpath}/#{bootconfigs['volume_name']}"
  sparse = '-s '
  sparse = '' unless bootconfigs['sparse']
  refres = "-o refreservation=#{bootconfigs['refreservation']}" unless bootconfigs['refreservation'].nil?
  refres = '-o refreservation=none' if bootconfigs['refreservation'] == 'none' || bootconfigs['refreservation'].nil?
  uii.info(I18n.t('vagrant_zones.begin_create_datasets'))
  ## Create Boot Volume
  case config.brand
  when 'lx'
    uii.info(I18n.t('vagrant_zones.lx_zone_dataset'))
    uii.info("  #{datasetroot}")
    execute(false, "#{@pfexec} zfs create -o zoned=on -p #{datasetroot}")
  when 'bhyve'
    ## Create root dataset
    uii.info(I18n.t('vagrant_zones.bhyve_zone_dataset_root'))
    uii.info("  #{datasetpath}")
    execute(false, "#{@pfexec} zfs create #{datasetpath}")

    # Create boot volume
    cinfo = "#{datasetroot}, #{bootconfigs['size']}"
    uii.info(I18n.t('vagrant_zones.bhyve_zone_dataset_boot'))
    uii.info("  #{cinfo}")
    execute(false, "#{@pfexec} zfs create #{sparse} #{refres} -V #{bootconfigs['size']} #{datasetroot}")

    ## Import template to boot volume
    commandtransfer = "#{@pfexec} pv -n #{@machine.box.directory.join('box.zss')} | #{@pfexec} zfs recv -u -v -F #{datasetroot}"
    uii.info(I18n.t('vagrant_zones.template_import_path'))
    uii.info("  #{@machine.box.directory.join('box.zss')}")
    Util::Subprocess.new commandtransfer do |_stdout, stderr, _thread|
      uii.rewriting do |uiprogress|
        uiprogress.clear_line
        uiprogress.info(I18n.t('vagrant_zones.importing_box_image_to_disk') + "#{datasetroot} ", new_line: false)
        uiprogress.report_progress(stderr, 100, false)
      end
    end
    uii.clear_line

    uii.info(I18n.t('vagrant_zones.template_import_path_set_size'))
    execute(false, "#{@pfexec} zfs set volsize=#{bootconfigs['size']} #{datasetroot}")

  when 'illumos' || 'kvm'
    raise Errors::NotYetImplemented
  else
    raise Errors::InvalidBrand
  end
  ## Create Additional Disks
  return if config.additional_disks.nil?

  config.additional_disks.each do |disk|
    shrtpath = "#{disk['array']}/#{disk['dataset']}/#{name}"
    dataset = "#{shrtpath}/#{disk['volume_name']}"
    sparse = '-s '
    sparse = '' unless disk['sparse']
    refres = "-o refreservation=#{bootconfigs['refreservation']}" unless bootconfigs['refreservation'].nil?
    refres = '-o refreservation=none' if bootconfigs['refreservation'] == 'none' || bootconfigs['refreservation'].nil?
    ## If the root data set doesn't exist create it
    addsrtexists = execute(false, "#{@pfexec} zfs list | grep #{shrtpath} | awk '{ print $1 }' | head -n 1 || true")
    cinfo = shrtpath.to_s
    uii.info(I18n.t('vagrant_zones.bhyve_zone_dataset_additional_volume_root')) unless addsrtexists == shrtpath.to_s
    uii.info("  #{cinfo}") unless addsrtexists == shrtpath.to_s
    ## Create the Additional volume
    execute(false, "#{@pfexec} zfs create #{shrtpath}") unless addsrtexists == shrtpath.to_s
    cinfo = "#{dataset}, #{disk['size']}"
    uii.info(I18n.t('vagrant_zones.bhyve_zone_dataset_additional_volume'))
    uii.info("  #{cinfo}")
    execute(false, "#{@pfexec} zfs create #{sparse} #{refres} -V #{disk['size']} #{dataset}")
  end
end

#delete_dataset(uii) ⇒ Object

This helps us delete any associated datasets of the zone



811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/vagrant-zones/driver.rb', line 811

def delete_dataset(uii)
  config = @machine.provider_config
  name = @machine.name
  # datadir = machine.data_dir
  bootconfigs = config.boot
  datasetpath = "#{bootconfigs['array']}/#{bootconfigs['dataset']}/#{name}"
  datasetroot = "#{datasetpath}/#{bootconfigs['volume_name']}"
  uii.info(I18n.t('vagrant_zones.delete_disks'))

  ## Check if Boot Dataset exists
  zp = datasetpath.delete_prefix('/').to_s
  dataset_boot_exists = execute(false, "#{@pfexec} zfs list | grep #{datasetroot} | awk '{ print $1 }' || true")

  ## Destroy Boot dataset
  uii.info(I18n.t('vagrant_zones.destroy_dataset')) if dataset_boot_exists == datasetroot.to_s
  uii.info("  #{datasetroot}") if dataset_boot_exists == datasetroot.to_s
  execute(false, "#{@pfexec} zfs destroy -r #{datasetroot}") if dataset_boot_exists == datasetroot.to_s
  ## Insert Error Checking Here in case disk is busy
  uii.info(I18n.t('vagrant_zones.boot_dataset_nil')) unless dataset_boot_exists == datasetroot.to_s

  ## Destroy Additional Disks
  unless config.additional_disks.nil?
    disks = config.additional_disks
    disks.each do |disk|
      diskpath = "#{disk['array']}/#{disk['dataset']}/#{name}"
      addataset = "#{diskpath}/#{disk['volume_name']}"
      cinfo = addataset.to_s
      dataset_exists = execute(false, "#{@pfexec} zfs list | grep #{addataset} | awk '{ print $1 }' || true")
      uii.info(I18n.t('vagrant_zones.bhyve_zone_dataset_additional_volume_destroy')) if dataset_exists == addataset
      uii.info("  #{cinfo}") if dataset_exists == addataset
      execute(false, "#{@pfexec} zfs destroy -r #{addataset}") if dataset_exists == addataset
      uii.info(I18n.t('vagrant_zones.additional_dataset_nil')) unless dataset_exists == addataset
      cinfo = diskpath.to_s
      addsrtexists = execute(false, "#{@pfexec} zfs list | grep #{diskpath} | awk '{ print $1 }' | head -n 1 || true")
      uii.info(I18n.t('vagrant_zones.addtl_volume_destroy_root')) if addsrtexists == diskpath && addsrtexists != zp.to_s
      uii.info("  #{cinfo}") if addsrtexists == diskpath && addsrtexists != zp.to_s
      execute(false, "#{@pfexec} zfs destroy -r #{diskpath}") if addsrtexists == diskpath && addsrtexists != zp.to_s
    end
  end

  ## Check if root dataset exists
  dataset_root_exists = execute(false, "#{@pfexec} zfs list | grep #{zp} | awk '{ print $1 }' | grep -v path || true")
  uii.info(I18n.t('vagrant_zones.destroy_root_dataset')) if dataset_root_exists == zp.to_s
  uii.info("  #{zp}") if dataset_root_exists == zp.to_s
  execute(false, "#{@pfexec} zfs destroy -r #{zp}") if dataset_root_exists == zp.to_s
  uii.info(I18n.t('vagrant_zones.root_dataset_nil')) unless dataset_root_exists == zp.to_s
end

#destroy(id) ⇒ Object

Destroys the Zone configurations and path



1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
# File 'lib/vagrant-zones/driver.rb', line 1782

def destroy(id)
  name = @machine.name
  id.info(I18n.t('vagrant_zones.leaving'))
  id.info(I18n.t('vagrant_zones.destroy_zone'))
  vm_state = execute(false, "#{@pfexec} zoneadm -z #{name} list -p | awk -F: '{ print $3 }'")

  ## If state is installed, uninstall from zoneadm and destroy from zonecfg
  if vm_state == 'installed'
    id.info(I18n.t('vagrant_zones.bhyve_zone_config_uninstall'))
    execute(false, "#{@pfexec} zoneadm -z #{name} uninstall -F")
    id.info(I18n.t('vagrant_zones.bhyve_zone_config_remove'))
    execute(false, "#{@pfexec} zonecfg -z #{name} delete -F")
  end

  ## If state is configured or incomplete, uninstall from destroy from zonecfg
  if %w[incomplete configured].include?(vm_state)
    id.info(I18n.t('vagrant_zones.bhyve_zone_config_remove'))
    execute(false, "#{@pfexec} zonecfg -z #{name} delete -F")
  end

  ### Nic Configurations
  state = 'delete'
  id.info(I18n.t('vagrant_zones.networking_int_remove'))
  network(id, state)
end

#dnsservers(uii, opts) ⇒ Object

This Sanitizes the DNS Records



212
213
214
215
216
217
# File 'lib/vagrant-zones/driver.rb', line 212

def dnsservers(uii, opts)
  config = @machine.provider_config
  servers = opts[:dns]
  uii.info(I18n.t('vagrant_zones.nsservers') + servers.to_s) if config.debug
  servers
end

#etherstubcreate(uii, opts) ⇒ Object

Create etherstubs for Zones



450
451
452
453
454
455
456
457
458
# File 'lib/vagrant-zones/driver.rb', line 450

def etherstubcreate(uii, opts)
  config = @machine.provider_config
  ether_name = "stub_#{config.partition_id}_#{opts[:nic_number]}"
  ether_configured = execute(false, "#{@pfexec} dladm show-etherstub | grep #{ether_name} | awk '{ print $1 }' ")
  uii.info(I18n.t('vagrant_zones.creating_etherstub')) unless ether_configured == ether_name
  uii.info("  #{ether_name}") unless ether_configured == ether_name
  execute(false, "#{@pfexec} dladm create-etherstub #{ether_name}") unless ether_configured == ether_name
  ether_name
end

#etherstubcreatehvnic(uii, opts, etherstub) ⇒ Object

Create Host VNIC on etherstubs for IP for Zones DHCP



470
471
472
473
474
475
476
477
478
479
480
# File 'lib/vagrant-zones/driver.rb', line 470

def etherstubcreatehvnic(uii, opts, etherstub)
  config = @machine.provider_config
  defrouter = opts[:gateway].to_s
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  hvnic_name = "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
  uii.info(I18n.t('vagrant_zones.creating_etherhostvnic'))
  uii.info("  #{hvnic_name}")
  execute(false, "#{@pfexec} dladm create-vnic -l #{etherstub} #{hvnic_name}")
  execute(false, "#{@pfexec} ipadm create-if #{hvnic_name}")
  execute(false, "#{@pfexec} ipadm create-addr -T static -a local=#{defrouter}/#{shrtsubnet} #{hvnic_name}/v4")
end

#etherstubdelete(uii, opts) ⇒ Object

Delete etherstubs



439
440
441
442
443
444
445
446
447
# File 'lib/vagrant-zones/driver.rb', line 439

def etherstubdelete(uii, opts)
  config = @machine.provider_config
  ether_name = "stub_#{config.partition_id}_#{opts[:nic_number]}"
  ether_configured = execute(false, "#{@pfexec} dladm show-etherstub | grep #{ether_name} | awk '{ print $1 }' ")
  uii.info(I18n.t('vagrant_zones.delete_ethervnic')) if ether_configured == ether_name
  uii.info("  #{ether_name}") if ether_configured == ether_name
  uii.info(I18n.t('vagrant_zones.no_delete_ethervnic')) unless ether_configured == ether_name
  execute(false, "#{@pfexec} dladm delete-etherstub #{ether_name}") if ether_configured == ether_name
end

#etherstubdelhvnic(uii, opts) ⇒ Object

Delete etherstubs vnic



427
428
429
430
431
432
433
434
435
436
# File 'lib/vagrant-zones/driver.rb', line 427

def etherstubdelhvnic(uii, opts)
  config = @machine.provider_config
  hvnic_name = "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
  vnic_configured = execute(false, "#{@pfexec} dladm show-vnic | grep #{hvnic_name} | awk '{ print $1 }' ")
  uii.info(I18n.t('vagrant_zones.removing_host_vnic')) if vnic_configured == hvnic_name.to_s
  uii.info("  #{hvnic_name}") if vnic_configured == hvnic_name.to_s
  execute(false, "#{@pfexec} ipadm delete-if #{hvnic_name}") if vnic_configured == hvnic_name.to_s
  execute(false, "#{@pfexec} dladm delete-vnic #{hvnic_name}") if vnic_configured == hvnic_name.to_s
  uii.info(I18n.t('vagrant_zones.no_removing_host_vnic')) unless vnic_configured == hvnic_name.to_s
end

#executeObject

Execute System commands



57
58
59
# File 'lib/vagrant-zones/driver.rb', line 57

def execute(...)
  @executor.execute(...)
end

#firmware(uii) ⇒ Object

This filters the firmware



1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# File 'lib/vagrant-zones/driver.rb', line 1498

def firmware(uii)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.firmware')) if config.debug
  ft = case config.firmware_type
       when /compatability/
         'BHYVE_RELEASE_CSM'
       when /UEFI/
         'BHYVE_RELEASE'
       when /BIOS/
         'BHYVE_CSM'
       when /BHYVE_DEBUG/
         'UEFI_DEBUG'
       when /BHYVE_RELEASE_CSM/
         'BIOS_DEBUG'
       end
  ft.to_s
end

#get_ip_address(_uii) ⇒ Object

If DHCP and Zlogin, get the IP address



260
261
262
263
264
265
266
267
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/vagrant-zones/driver.rb', line 260

def get_ip_address(_uii)
  config = @machine.provider_config
  name = @machine.name
  lcheck = config.lcheck
  lcheck = ':~' if config.lcheck.nil?
  alcheck = config.alcheck
  alcheck = 'login:' if config.alcheck.nil?
  pcheck = 'Password:'

  @machine.config.vm.networks.each do |(_adaptertype, opts)|
    ip = nil
    if opts[:dhcp4] && opts[:managed]
      vnic_name = "vnic#{nictype(opts)}#{vtype(config)}_#{config.partition_id}_#{opts[:nic_number]}"
      PTY.spawn("pfexec zlogin -C #{name}") do |zlogin_read, zlogin_write, pid|
        Timeout.timeout(config.setup_wait) do
          rsp = []
          command = "ip -4 addr show dev #{vnic_name} | grep -Po 'inet \\K[\\d.]+' \r\n"
          i = 0
          logged_in = false
          loop do
            zlogin_read.expect(/\r\n/) { |line| rsp.push line }
            logged_in = true if rsp[-1].to_s.match(/(#{Regexp.quote(lcheck)})/) || rsp[-1].to_s.match(/(:~)/)
            zlogin_write.printf("\r\n") if i < 1
            i += 1

            break if logged_in || rsp[-1].to_s.match(/(#{Regexp.quote(alcheck)})/)
          end

          unless logged_in
            zlogin_write.printf("#{user(@machine)}\n") if zlogin_read.expect(/#{Regexp.quote(alcheck)}/)
            zlogin_write.printf("#{vagrantuserpass(@machine)}\n") if zlogin_read.expect(/#{Regexp.quote(pcheck)}/)
            logged_in = true if zlogin_read.expect(/#{Regexp.quote(lcheck)}/)
          end

          puts 'Gathering IP' if config.debug_boot
          zlogin_write.printf(command) if logged_in
          loop do
            zlogin_read.expect(/\r\n/) { |line| rsp.push line }
            ip = rsp[-1].to_s.match(/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/)

            break if rsp[-1].to_s.match(/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/)
          end
          Process.kill('HUP', pid)
        end
      end
      return ip[0] unless ip[0].empty? || ip[0].nil?
    elsif (opts[:dhcp4] == false || opts[:dhcp4].nil?) && opts[:managed]
      ip = opts[:ip].to_s
      return nil if ip.empty?

      return ip.gsub("\t", '')
    end
  end
end

#halt(uii) ⇒ Object

Halts the Zone, first via shutdown command, then a halt.



1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
# File 'lib/vagrant-zones/driver.rb', line 1758

def halt(uii)
  name = @machine.name
  config = @machine.provider_config

  ## Check state in zoneadm
  vm_state = execute(false, "#{@pfexec} zoneadm -z #{name} list -p | awk -F: '{ print $3 }'")
  uii.info(I18n.t('vagrant_zones.graceful_shutdown'))
  begin
    Timeout.timeout(config.clean_shutdown_time) do
      execute(false, "#{@pfexec} zoneadm -z #{name} shutdown") if vm_state == 'running'
    end
  rescue Timeout::Error
    uii.info(I18n.t('vagrant_zones.graceful_shutdown_failed') + config.clean_shutdown_time.to_s)
    begin
      Timeout.timeout(config.clean_shutdown_time) do
        execute(false, "#{@pfexec} zoneadm -z #{name} halt")
      end
    rescue Timeout::Error
      raise Errors::TimeoutHalt
    end
  end
end

#install(uii) ⇒ Object

Begin installation for zone



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/vagrant-zones/driver.rb', line 62

def install(uii)
  config = @machine.provider_config
  name = @machine.name
  case config.brand
  when 'lx'
    box = "#{@machine.data_dir}/#{@machine.config.vm.box}"
    results = execute(false, "#{@pfexec} zoneadm -z #{name} install -s #{box}")
    raise Errors::InvalidLXBrand if results.include? 'unknown brand'
  when 'bhyve'
    results = execute(false, "#{@pfexec} zoneadm -z #{name} install")
    raise Errors::InvalidbhyveBrand if results.include? 'unknown brand'
  when 'kvm' || 'illumos'
    raise Errors::NotYetImplemented
  end
  uii.info(I18n.t('vagrant_zones.installing_zone'))
  uii.info("  #{config.brand}")
end

#ipaddress(uii, opts) ⇒ Object

This Sanitizes the IP Address to set



230
231
232
233
234
235
236
237
238
239
# File 'lib/vagrant-zones/driver.rb', line 230

def ipaddress(uii, opts)
  config = @machine.provider_config
  ip = if opts[:ip].empty?
         nil
       else
         opts[:ip].gsub("\t", '')
       end
  uii.info(I18n.t('vagrant_zones.ipaddress') + ip) if config.debug
  ip
end

#macaddress(uii, opts) ⇒ Object

This Sanitizes the Mac Address



220
221
222
223
224
225
226
227
# File 'lib/vagrant-zones/driver.rb', line 220

def macaddress(uii, opts)
  config = @machine.provider_config
  regex = /^(?:[[:xdigit:]]{2}([-:]))(?:[[:xdigit:]]{2}\1){4}[[:xdigit:]]{2}$/
  mac = opts[:mac] unless opts[:mac].nil?
  mac = 'auto' unless mac.match(regex)
  uii.info(I18n.t('vagrant_zones.mac') + mac) if config.debug
  mac
end

#natloginboot(uii, metrics, interrupted) ⇒ Object



1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/vagrant-zones/driver.rb', line 1286

def natloginboot(uii, metrics, interrupted)
  metrics ||= {}
  metrics['instance_dhcp_ssh_time'] = Util::Timer.time do
    retryable(on: Errors::TimeoutError, tries: 60) do
      # If we're interrupted don't worry about waiting
      next if interrupted

      loop do
        break if interrupted
        break if @machine.communicate.ready?
      end
    end
  end
  uii.info(I18n.t('vagrant_zones.dhcp_boot_ready') + " in #{metrics['instance_dhcp_ssh_time']} Seconds")
end

#natnicconfig(uii, opts) ⇒ Object

zonecfg function for for nat Networking



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/vagrant-zones/driver.rb', line 621

def natnicconfig(uii, opts)
  config = @machine.provider_config
  allowed_address = allowedaddress(uii, opts)
  defrouter = opts[:gateway].to_s
  vnic_name = vname(uii, opts)
  uii.info(I18n.t('vagrant_zones.nat_vnic_setup'))
  uii.info("  #{vnic_name}")
  zonecfg_cmd = "#{@pfexec} zonecfg -z #{@machine.name} "
  cie = config.cloud_init_enabled
  case config.brand
  when 'lx'
    shrtstr1 = %(set allowed-address=#{allowed_address}; add property (name=gateway,value="#{defrouter}"); )
    shrtstr2 = %(add property (name=ips,value="#{allowed_address}"); add property (name=primary,value="true"); end;)
    execute(false, %(#{zonecfg_cmd}set global-nic=auto; #{shrtstr1} #{shrtstr2}"))
  when 'bhyve'
    execute(false, %(#{zonecfg_cmd}"add net; set physical=#{vnic_name}; end;")) unless cie
    execute(false, %(#{zonecfg_cmd}"add net; set physical=#{vnic_name}; set allowed-address=#{allowed_address}; end;")) if cie
  end
end

#network(uii, state) ⇒ Object

Manage Network Interfaces



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/vagrant-zones/driver.rb', line 316

def network(uii, state)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.creating_networking_interfaces')) if state == 'create' && !config.on_demand_vnics
  @machine.config.vm.networks.each do |adaptertype, opts|
    case adaptertype.to_s
    when 'public_network'
      zonenicdel(uii, opts) if state == 'delete' && !config.on_demand_vnics
      zonecfgnicconfig(uii, opts) if state == 'config'
      zonecfgnicconfigdelete(uii, opts) if state == 'delete_provisional' && config.on_demand_vnics
      zoneniccreate(uii, opts) if state == 'create' && !config.on_demand_vnics
      zonenicstpzloginsetup(uii, opts, config) if state == 'setup' && config.setup_method == 'zlogin'
    when 'private_network'
      zonenicdel(uii, opts) if state == 'delete' && !config.on_demand_vnics
      zonedhcpentriesrem(uii, opts) if state == 'delete'
      zonenatclean(uii, opts) if state == 'delete'
      etherstubdelhvnic(uii, opts) if state == 'delete'
      etherstubdelete(uii, opts) if state == 'delete'
      natnicconfig(uii, opts) if state == 'config'
      etherstub = etherstubcreate(uii, opts) if state == 'create'
      zonenatniccreate(uii, opts, etherstub) if state == 'create' && !config.on_demand_vnics
      etherstubcreatehvnic(uii, opts, etherstub) if state == 'create'
      zonenatforward(uii, opts) if state == 'create'
      zonenatentries(uii, opts) if state == 'create'
      zonedhcpentries(uii, opts) if state == 'create'
      zonedhcpcheckaddr(uii, opts) if state == 'setup'
      zonenicnatsetup(uii, opts) if state == 'setup'
    end
  end
end

#nictype(opts) ⇒ Object

This filters the NIC Types



196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/vagrant-zones/driver.rb', line 196

def nictype(opts)
  case opts[:nictype]
  when /external/ || nil
    'e'
  when /internal/
    'i'
  when /carp/
    'c'
  when /management/
    'm'
  when /host/
    'h'
  end
end

#rdpport(uii) ⇒ Object

This filters the rdpport



1517
1518
1519
1520
1521
# File 'lib/vagrant-zones/driver.rb', line 1517

def rdpport(uii)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.rdpport')) if config.debug
  config.rdpport.to_s unless config.rdpport.to_s.nil?
end

#setup(uii) ⇒ Object

This helps us set up the networking of the VM



1212
1213
1214
1215
1216
# File 'lib/vagrant-zones/driver.rb', line 1212

def setup(uii)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.network_setup')) if config.brand && !config.cloud_init_enabled
  network(uii, 'setup') if config.brand == 'bhyve' && !config.cloud_init_enabled
end

#ssh_run_command(uii, command) ⇒ Object

Run commands over SSH instead of ZLogin



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/vagrant-zones/driver.rb', line 99

def ssh_run_command(uii, command)
  config = @machine.provider_config
  ip = get_ip_address(uii)
  user = user(@machine)
  key = userprivatekeypath(@machine).to_s
  port = sshport(@machine).to_s
  port = 22 if sshport(@machine).to_s.nil?
  execute_return = ''
  Util::Timer.time do
    retryable(on: Errors::TimeoutError, tries: 60) do
      # If we're interrupted don't worry about waiting
      ssh_string = "#{@pfexec} ssh -o 'StrictHostKeyChecking=no' -p"
      execute_return = execute(false, %(#{ssh_string} #{port} -i #{key} #{user}@#{ip} "#{command}"))
      uii.info(I18n.t('vagrant_zones.ssh_run_command')) if config.debug
      uii.info(I18n.t('vagrant_zones.ssh_run_command') + command) if config.debug
      loop do
        break if @machine.communicate.ready?
      end
    end
  end
  execute_return
end

#sshport(machine) ⇒ Object

This filters the sshport



1489
1490
1491
1492
1493
1494
1495
# File 'lib/vagrant-zones/driver.rb', line 1489

def sshport(machine)
  config = machine.provider_config
  sshport = '22'
  sshport = config.sshport.to_s unless config.sshport.to_s.nil? || config.sshport.to_i.zero?
  # uii.info(I18n.t('vagrant_zones.sshport')) if config.debug
  sshport
end

#state(machine) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/vagrant-zones/driver.rb', line 39

def state(machine)
  name = machine.name
  vm_state = execute(false, "#{@pfexec} zoneadm -z #{name} list -p | awk -F: '{ print $3 }'")
  case vm_state
  when 'running'
    :running
  when 'configured'
    :preparing
  when 'installed'
    :stopped
  when 'incomplete'
    :incomplete
  else
    :not_created
  end
end

#user(machine) ⇒ Object

This filters the vagrantuser



1460
1461
1462
1463
1464
1465
# File 'lib/vagrant-zones/driver.rb', line 1460

def user(machine)
  config = machine.provider_config
  user = config.vagrant_user unless config.vagrant_user.nil?
  user = 'vagrant' if config.vagrant_user.nil?
  user
end

#user_exists?(uii, user = 'vagrant') ⇒ Boolean

This checks if the user exists on the VM, usually for LX zones

Returns:

  • (Boolean)


1441
1442
1443
1444
1445
1446
1447
1448
1449
# File 'lib/vagrant-zones/driver.rb', line 1441

def user_exists?(uii, user = 'vagrant')
  name = @machine.name
  config = @machine.provider_config
  ret = execute(true, "#{@pfexec} zlogin #{name} id -u #{user}")
  uii.info(I18n.t('vagrant_zones.userexists')) if config.debug
  return true if ret.zero?

  false
end

#userprivatekeypath(machine) ⇒ Object

This filters the userprivatekeypath



1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
# File 'lib/vagrant-zones/driver.rb', line 1468

def userprivatekeypath(machine)
  config = machine.provider_config
  userkey = config.vagrant_user_private_key_path.to_s
  if config.vagrant_user_private_key_path.to_s.nil?
    id_rsa = 'https://raw.githubusercontent.com/hashicorp/vagrant/master/keys/vagrant'
    file = './id_rsa'
    command = "#{@pfexec} curl #{id_rsa} -O #{file}"
    Util::Subprocess.new command do |_stdout, stderr, _thread|
      uii.rewriting do |uipkp|
        uipkp.clear_line
        uipkp.info(I18n.t('vagrant_zones.importing_vagrant_key'), new_line: false)
        uipkp.report_progress(stderr, 100, false)
      end
    end
    uii.clear_line
    userkey = './id_rsa'
  end
  userkey
end

#vagrantuserpass(machine) ⇒ Object

This filters the vagrantuserpass



1524
1525
1526
1527
1528
# File 'lib/vagrant-zones/driver.rb', line 1524

def vagrantuserpass(machine)
  config = machine.provider_config
  # uii.info(I18n.t('vagrant_zones.vagrantuserpass')) if config.debug
  config.vagrant_user_pass unless config.vagrant_user_pass.to_s.nil?
end

#vname(uii, opts) ⇒ Object

This Sanitizes the VNIC Name



252
253
254
255
256
257
# File 'lib/vagrant-zones/driver.rb', line 252

def vname(uii, opts)
  config = @machine.provider_config
  vnic_name = "vnic#{nictype(opts)}#{vtype(config)}_#{config.partition_id}_#{opts[:nic_number]}"
  uii.info(I18n.t('vagrant_zones.vnic_name') + vnic_name) if config.debug
  vnic_name
end

#vtype(config) ⇒ Object

This filters the VM usage for VNIC Naming Purposes



180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/vagrant-zones/driver.rb', line 180

def vtype(config)
  case config.vm_type
  when /template/
    '1'
  when /development/
    '2'
  when /production/ || nil
    '3'
  when /firewall/
    '4'
  when /other/
    '5'
  end
end

#waitforboot(uii, metrics, interrupted) ⇒ Object

This helps up wait for the boot of the vm by using zlogin



1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/vagrant-zones/driver.rb', line 1303

def waitforboot(uii, metrics, interrupted)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.wait_for_boot'))
  case config.brand
  when 'bhyve'
    return if config.cloud_init_enabled

    zloginboot(uii) if config.setup_method == 'zlogin' && !config.os_type.to_s.match(/windows/)
    zlogin_win_boot(uii) if config.setup_method == 'zlogin' && config.os_type.to_s.match(/windows/)
    natloginboot(uii, metrics, interrupted) if config.setup_method == 'dhcp'
  when 'lx'
    unless user_exists?(uii, config.vagrant_user)
      # zlogincommand(uii, %('echo nameserver 1.1.1.1 >> /etc/resolv.conf'))
      # zlogincommand(uii, %('echo nameserver 1.0.0.1 >> /etc/resolv.conf'))
      zlogincommand(uii, 'useradd -m -s /bin/bash -U vagrant')
      zlogincommand(uii, 'echo "vagrant ALL=(ALL:ALL) NOPASSWD:ALL" \\> /etc/sudoers.d/vagrant')
      zlogincommand(uii, 'mkdir -p /home/vagrant/.ssh')
      key_url = 'https://raw.githubusercontent.com/hashicorp/vagrant/master/keys/vagrant.pub'
      zlogincommand(uii, "curl #{key_url} -O /home/vagrant/.ssh/authorized_keys")

      id_rsa = 'https://raw.githubusercontent.com/hashicorp/vagrant/master/keys/vagrant'
      command = "#{@pfexec} curl #{id_rsa} -O id_rsa"
      Util::Subprocess.new command do |_stdout, stderr, _thread|
        uii.rewriting do |uisp|
          uisp.clear_line
          uisp.info(I18n.t('vagrant_zones.importing_vagrant_key'), new_line: false)
          uisp.report_progress(stderr, 100, false)
        end
      end
      uii.clear_line
      zlogincommand(uii, 'chown -R vagrant:vagrant /home/vagrant/.ssh')
      zlogincommand(uii, 'chmod 600 /home/vagrant/.ssh/authorized_keys')
    end
  end
end

#zfs(uii, job, opts) ⇒ Object

This helps us manage ZFS Snapshots



1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
# File 'lib/vagrant-zones/driver.rb', line 1734

def zfs(uii, job, opts)
  name = @machine.name
  config = @machine.provider_config
  bootconfigs = config.boot
  datasetroot = "#{bootconfigs['array']}/#{bootconfigs['dataset']}/#{name}/#{bootconfigs['volume_name']}"
  datasets = []
  datasets << datasetroot.to_s
  config.additional_disks&.each do |disk|
    additionaldataset = "#{disk['array']}/#{disk['dataset']}/#{name}/#{disk['volume_name']}"
    datasets << additionaldataset.to_s
  end
  case job
  when 'list'
    zfssnaplist(datasets, opts, uii)
  when 'create'
    zfssnapcreate(datasets, opts, uii)
  when 'destroy'
    zfssnapdestroy(datasets, opts, uii)
  when 'cron'
    zfssnapcron(datasets, opts, uii)
  end
end

#zfssnapcreate(datasets, opts, uii) ⇒ Object

Create ZFS Snapshots



1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
# File 'lib/vagrant-zones/driver.rb', line 1576

def zfssnapcreate(datasets, opts, uii)
  uii.info(I18n.t('vagrant_zones.zfs_snapshot_create'))
  if opts[:dataset] == 'all'
    datasets.each do |disk|
      uii.info("  - #{disk}@#{opts[:snapshot_name]}")
      execute(false, "#{@pfexec} zfs snapshot #{disk}@#{opts[:snapshot_name]}")
    end
  else
    ds = opts[:dataset].scan(/\D/).empty? unless opts[:dataset].nil?
    if ds
      datasets.each_with_index do |disk, index|
        next unless opts[:dataset].to_i == index.to_i

        execute(false, "#{@pfexec} zfs snapshot #{disk}@#{opts[:snapshot_name]}")
        uii.info("  - #{disk}@#{opts[:snapshot_name]}")
      end
    else
      execute(false, "#{@pfexec} zfs snapshot #{opts[:dataset]}@#{opts[:snapshot_name]}") if datasets.include?(opts[:dataset])
      uii.info("  - #{opts[:dataset]}@#{opts[:snapshot_name]}") if datasets.include?(opts[:dataset])
    end
  end
end

#zfssnapcron(datasets, opts, uii) ⇒ Object

Configure ZFS Snapshots Crons



1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
# File 'lib/vagrant-zones/driver.rb', line 1701

def zfssnapcron(datasets, opts, uii)
  name = @machine.name
  # config = @machine.provider_config
  crons = execute(false, "#{@pfexec} crontab -l").split("\n")
  rtnregex = '-p (weekly|monthly|daily|hourly)'
  opts[:dataset] = 'all' if opts[:dataset].nil?
  datasets.each do |disk|
    cronjobs = {}
    crons.each do |tasks|
      next if tasks.empty? || tasks[/^#/]

      case tasks[/#{rtnregex}/, 1]
      when 'hourly'
        hourly = tasks if tasks[/# #{name}/] && tasks[/#{disk}/]
        cronjobs.merge!(hourly: hourly) if tasks[/# #{name}/] && tasks[/#{disk}/]
      when 'daily'
        daily = tasks if tasks[/# #{name}/] && tasks[/#{disk}/]
        cronjobs.merge!(daily: daily) if tasks[/# #{name}/] && tasks[/#{disk}/]
      when 'weekly'
        weekly = tasks if tasks[/# #{name}/] && tasks[/#{disk}/]
        cronjobs.merge!(weekly: weekly) if tasks[/# #{name}/] && tasks[/#{disk}/]
      when 'monthly'
        monthly = tasks if tasks[/# #{name}/] && tasks[/#{disk}/]
        cronjobs.merge!(monthly: monthly) if tasks[/# #{name}/] && tasks[/#{disk}/]
      end
    end
    zfssnapcronlist(uii, disk, opts, cronjobs) unless opts[:list].nil?
    zfssnapcrondelete(uii, disk, opts, cronjobs) unless opts[:delete].nil?
    zfssnapcronset(uii, disk, opts, cronjobs) unless opts[:set_frequency].nil?
  end
end

#zfssnapcrondelete(uii, disk, opts, cronjobs) ⇒ Object

This will delete Cron Jobs for Snapshots to take place



1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
# File 'lib/vagrant-zones/driver.rb', line 1654

def zfssnapcrondelete(uii, disk, opts, cronjobs)
  return unless opts[:dataset].to_s == disk.to_s || opts[:dataset].to_s == 'all'

  sc = "#{@pfexec} crontab"
  rmcr = "#{sc} -l | grep -v "
  h = { h: 'hourly', d: 'daily', w: 'weekly', m: 'monthly' }
  uii.info(I18n.t('vagrant_zones.cron_delete'))
  h.each do |(_k, d)|
    next unless opts[:delete] == d || opts[:delete] == 'all'

    cj = cronjobs[d.to_sym].to_s.gsub('*', '\*')
    rc = "#{rmcr}'#{cj}' | #{sc}"
    uii.info("  - Removing Cron: #{cj}") unless cronjobs[d.to_sym].nil?
    execute(false, rc) unless cronjobs[d.to_sym].nil?
  end
end

#zfssnapcronlist(uii, disk, opts, cronjobs) ⇒ Object

This will list Cron Jobs for Snapshots to take place



1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
# File 'lib/vagrant-zones/driver.rb', line 1639

def zfssnapcronlist(uii, disk, opts, cronjobs)
  return unless opts[:dataset].to_s == disk.to_s || opts[:dataset].to_s == 'all'

  # config = @machine.provider_config
  # name = @machine.name
  uii.info(I18n.t('vagrant_zones.cron_entries'))
  h = { h: 'hourly', d: 'daily', w: 'weekly', m: 'monthly' }
  h.each do |(_k, d)|
    next unless opts[:list] == d || opts[:list] == 'all'

    uii.info(cronjobs[d.to_sym]) unless cronjobs[d.to_sym].nil?
  end
end

#zfssnapcronset(uii, disk, opts, cronjobs) ⇒ Object

This will set Cron Jobs for Snapshots to take place



1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
# File 'lib/vagrant-zones/driver.rb', line 1672

def zfssnapcronset(uii, disk, opts, cronjobs)
  return unless opts[:dataset].to_s == disk.to_s || opts[:dataset].to_s == 'all'

  config = @machine.provider_config
  name = @machine.name
  uii.info(I18n.t('vagrant_zones.cron_set'))
  snpshtr = config.snapshot_script.to_s
  shrtcr = "( #{@pfexec} crontab -l; echo "
  h = {}
  sf = { freq: opts[:set_frequency], rtn: opts[:set_frequency_rtn] }
  rtn = { h: 24, d: 8, w: 5, m: 1 }
  ct = { h: '0 1-23 * * * ', d: '0 0 * * 0-5 ', w: '0 0 * * 6 ', m: '0 0 1 * * ' }
  h[:hourly] = { rtn: rtn[:h], ct: ct[:h] }
  h[:daily] = { rtn: rtn[:d], ct: ct[:d] }
  h[:weekly] = { rtn: rtn[:w], ct: ct[:w] }
  h[:monthly] = { rtn: rtn[:m], ct: ct[:m] }
  h.each do |k, d|
    next unless (k.to_s == sf[:freq] || sf[:freq] == 'all') && cronjobs[k].nil?

    cj = "#{d[:ct]}#{snpshtr} -p #{k} -r -n #{sf[:rtn]} #{disk} # #{name}" unless sf[:rtn].nil?
    cj = "#{d[:ct]}#{snpshtr} -p #{k} -r -n #{d[:rtn]} #{disk} # #{name}" if sf[:rtn].nil?
    h[k] = { rtn: rtn[:h], ct: ct[:h], cj: cj }
    setcron = "#{shrtcr}'#{cj}' ) | #{@pfexec} crontab"
    uii.info("Setting Cron: #{setcron}")
    execute(false, setcron)
  end
end

#zfssnapdestroy(datasets, opts, uii) ⇒ Object

Destroy ZFS Snapshots



1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
# File 'lib/vagrant-zones/driver.rb', line 1600

def zfssnapdestroy(datasets, opts, uii)
  uii.info(I18n.t('vagrant_zones.zfs_snapshot_destroy'))
  if opts[:dataset].to_s == 'all'
    datasets.each do |disk|
      output = execute(false, "#{@pfexec} zfs list -t snapshot -o name | grep #{disk}")
      ## Never delete the source when doing all
      output = output.split("\n").drop(1)
      ## Delete in Reverse order
      output.reverse.each do |snaps|
        cmd = "#{@pfexec} zfs destroy #{snaps}"
        execute(false, cmd)
        uii.info("  - #{snaps}")
      end
    end
  else
    ## Specify the dataset by number
    datasets.each_with_index do |disk, dindex|
      next unless dindex.to_i == opts[:dataset].to_i

      output = execute(false, "#{@pfexec} zfs list -t snapshot -o name | grep #{disk}")
      output = output.split("\n").drop(1)
      output.each_with_index do |snaps, spindex|
        if opts[:snapshot_name].to_i == spindex && opts[:snapshot_name].to_s != 'all'
          uii.info("  - #{snaps}")
          execute(false, "#{@pfexec} zfs destroy #{snaps}")
        end
        if opts[:snapshot_name].to_s == 'all'
          uii.info("  - #{snaps}")
          execute(false, "#{@pfexec} zfs destroy #{snaps}")
        end
      end
    end
    ## Specify the Dataset by path
    cmd = "#{@pfexec} zfs destroy #{opts[:dataset]}@#{opts[:snapshot_name]}"
    execute(false, cmd) if datasets.include?("#{opts[:dataset]}@#{opts[:snapshot_name]}")
  end
end

#zfssnaplist(datasets, opts, uii) ⇒ Object

List ZFS Snapshots



1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
# File 'lib/vagrant-zones/driver.rb', line 1557

def zfssnaplist(datasets, opts, uii)
  # config = @machine.provider_config
  # name = @machine.name
  uii.info(I18n.t('vagrant_zones.zfs_snapshot_list'))
  datasets.each_with_index do |disk, index|
    zfs_snapshots = execute(false, "#{@pfexec} zfs list -t snapshot | grep #{disk} || true")
    next if zfs_snapshots.nil?

    ds = opts[:dataset].scan(/\D/).empty? unless opts[:dataset].nil?
    if ds
      next if opts[:dataset].to_i != index
    else
      next unless opts[:dataset] == disk || opts[:dataset].nil? || opts[:dataset] == 'all'
    end
    zfssnaplistdisp(zfs_snapshots, uii, index, disk)
  end
end

#zfssnaplistdisp(zfs_snapshots, uii, index, disk) ⇒ Object

List ZFS Snapshots, helper function to sort and display



1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
# File 'lib/vagrant-zones/driver.rb', line 1531

def zfssnaplistdisp(zfs_snapshots, uii, index, disk)
  uii.info("\n Disk Number: #{index}\n Disk Path: #{disk}")
  zfssnapshots = zfs_snapshots.split("\n").reverse
  zfssnapshots << "Snapshot\t\t\t\tUsed\tAvailable\tRefer\tPath"
  pml, rml, aml, uml, sml = 0
  zfssnapshots.reverse.each do |snapshot|
    ar = snapshot.gsub(/\s+/m, ' ').strip.split
    sml = ar[0].length.to_i if ar[0].length.to_i > sml.to_i
    uml = ar[1].length.to_i if ar[1].length.to_i > uml.to_i
    aml = ar[2].length.to_i if ar[2].length.to_i > aml.to_i
    rml = ar[3].length.to_i if ar[3].length.to_i > rml.to_i
    pml = ar[4].length.to_i if ar[4].length.to_i > pml.to_i
  end
  zfssnapshots.reverse.each_with_index do |snapshot, si|
    ar = snapshot.gsub(/\s+/m, ' ').strip.split
    strg1 = "%<sym>5s %<s>-#{sml}s %<u>-#{uml}s %<a>-#{aml}s %<r>-#{rml}s %<p>-#{pml}s"
    strg2 = "%<si>5s %<s>-#{sml}s %<u>-#{uml}s %<a>-#{aml}s %<r>-#{rml}s %<p>-#{pml}s"
    if si.zero?
      puts format strg1.to_s, sym: '#', s: ar[0], u: ar[1], a: ar[2], r: ar[3], p: ar[4]
    else
      puts format strg2.to_s, si: si - 2, s: ar[0], u: ar[1], a: ar[2], r: ar[3], p: ar[4]
    end
  end
end

#zlogin(uii, cmd) ⇒ Object

This gives us a console to the VM to issue commands



1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/vagrant-zones/driver.rb', line 1411

def zlogin(uii, cmd)
  name = @machine.name
  config = @machine.provider_config
  rsp = []
  execute_return = ''
  PTY.spawn("pfexec zlogin -C #{name}") do |zread, zwrite, pid|
    Timeout.timeout(config.setup_wait) do
      error_check = "echo \"Error Code: $?\"\n"
      error_check = "echo Error Code: %%ERRORLEVEL%% \r\n\r\n" if config.os_type.to_s.match(/windows/)
      runonce = true
      loop do
        zread.expect(/\n/) { |line| rsp.push line }
        puts(rsp[-1]) if config.debug
        zwrite.printf("#{cmd}\r\n") if runonce
        zwrite.printf(error_check.to_s) if runonce
        runonce = false
        execute_return = rsp[-4] if rsp[-1].to_s.match(/Error Code: 0/)
        break if rsp[-1].to_s.match(/Error Code: 0/)

        em = "#{cmd} \nFailed with ==> #{rsp[-1]}"
        uii.info(I18n.t('vagrant_zones.console_failed') + em) if rsp[-1].to_s.match(/Error Code: \b(?!0\b)\d{1,4}\b/)
        raise Errors::ConsoleFailed if rsp[-1].to_s.match(/Error Code: \b(?!0\b)\d{1,4}\b/)
      end
    end
    Process.kill('HUP', pid)
  end
  execute_return
end

#zlogin_win_boot(uii) ⇒ Object



1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
# File 'lib/vagrant-zones/driver.rb', line 1364

def zlogin_win_boot(uii)
  ## use Windows SAC to setup networking
  name = @machine.name
  config = @machine.provider_config
  event_cmd_available = 'EVENT: The CMD command is now available'
  event_channel_created = 'EVENT:   A new channel has been created'
  channel_access_prompt = 'Use any other key to view this channel'
  cmd = 'system32>'
  uii.info(I18n.t('vagrant_zones.automated-windows-zlogin'))
  PTY.spawn("pfexec zlogin -C #{name}") do |zlogin_read, zlogin_write, pid|
    Timeout.timeout(config.setup_wait) do
      uii.info(I18n.t('vagrant_zones.windows_skip_first_boot')) if zlogin_read.expect(/#{event_cmd_available}/)
      sleep(3)
      if zlogin_read.expect(/#{event_cmd_available}/)
        uii.info(I18n.t('vagrant_zones.windows_start_cmd'))
        zlogin_write.printf("cmd\n")
      end
      if zlogin_read.expect(/#{event_channel_created}/)
        uii.info(I18n.t('vagrant_zones.windows_access_session'))
        zlogin_write.printf("\e\t")
      end
      if zlogin_read.expect(/#{channel_access_prompt}/)
        uii.info(I18n.t('vagrant_zones.windows_access_session_presskey'))
        zlogin_write.printf('o')
      end
      if zlogin_read.expect(/Username:/)
        uii.info(I18n.t('vagrant_zones.windows_enter_username'))
        zlogin_write.printf("#{user(@machine)}\n")
      end
      if zlogin_read.expect(/Domain/)
        uii.info(I18n.t('vagrant_zones.windows_enter_domain'))
        zlogin_write.printf("\n")
      end
      if zlogin_read.expect(/Password/)
        uii.info(I18n.t('vagrant_zones.windows_enter_password'))
        zlogin_write.printf("#{vagrantuserpass(@machine)}\n")
      end
      if zlogin_read.expect(/#{cmd}/)
        uii.info(I18n.t('vagrant_zones.windows_cmd_accessible'))
        sleep(5)
        Process.kill('HUP', pid)
      end
    end
  end
end

#zloginboot(uii) ⇒ Object

this allows us a terminal to pass commands and manipulate the VM OS via serial/tty, I want to redo this at some point



1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
# File 'lib/vagrant-zones/driver.rb', line 1219

def zloginboot(uii)
  name = @machine.name
  config = @machine.provider_config
  lcheck = config.lcheck || ':~'
  alcheck = config.alcheck || 'login:'
  bstring = config.booted_string || ' OK '
  zunlockboot = config.zunlockboot || 'Importing ZFS root pool'
  zunlockbootkey = config.zunlockbootkey
  pcheck = 'Password:'

  uii.info(I18n.t('vagrant_zones.automated-zlogin'))

  PTY.spawn("pfexec zlogin -C #{name}") do |zlogin_read, zlogin_write, pid|
    Timeout.timeout(config.setup_wait) do
      rsp = []

      loop do
        begin
          zlogin_read.expect(/\r\n/) do |line|
            line = line.first if line.is_a?(Array)
            encoded_line = line.to_s.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')
            rsp.push encoded_line unless encoded_line.empty?
          end
        rescue ArgumentError
          # Silently ignore encoding errors
          next
        end

        uii.info(rsp[-1]) if config.debug_boot && !rsp.empty?

        if !rsp.empty? && rsp[-1].match(/#{zunlockboot}/)
          sleep(2)
          zlogin_write.printf("#{zunlockbootkey}\n") if zunlockbootkey
          zlogin_write.printf("\n")
          uii.info(I18n.t('vagrant_zones.automated-zbootunlock'))
        end

        next unless !rsp.empty? && rsp[-1].match(/#{bstring}/)

        sleep(15)
        zlogin_write.printf("\n")
        break
      end

      if zlogin_read.expect(/#{alcheck}/)
        uii.info(I18n.t('vagrant_zones.automated-zlogin-user'))
        zlogin_write.printf("#{user(@machine)}\n")
        sleep(config.)
      end

      if zlogin_read.expect(/#{pcheck}/)
        uii.info(I18n.t('vagrant_zones.automated-zlogin-pass'))
        zlogin_write.printf("#{vagrantuserpass(@machine)}\n")
        sleep(config.)
      end

      zlogin_write.printf("\n")
      if zlogin_read.expect(/#{lcheck}/)
        uii.info(I18n.t('vagrant_zones.automated-zlogin-root'))
        zlogin_write.printf("sudo su -\n")
        sleep(config.)
        Process.kill('HUP', pid)
      end
    end
  end
end

#zlogincommand(uii, cmd) ⇒ Object

This gives the user a terminal console



1452
1453
1454
1455
1456
1457
# File 'lib/vagrant-zones/driver.rb', line 1452

def zlogincommand(uii, cmd)
  name = @machine.name
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.zonelogincmd')) if config.debug
  execute(false, "#{@pfexec} zlogin #{name} #{cmd}")
end

#zonecfg(uii) ⇒ Object

This helps us set the zone configurations for the zone



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/vagrant-zones/driver.rb', line 1078

def zonecfg(uii)
  name = @machine.name
  config = @machine.provider_config
  zcfg = "#{@pfexec} zonecfg -z #{name} "
  ## Create LX zonecfg
  zonecfglx(uii, name, config, zcfg)
  ## Create bhyve zonecfg
  zonecfgbhyve(uii, name, config, zcfg)
  ## Create kvm zonecfg
  zonecfgkvm(uii, name, config, zcfg)
  ## Shared Disk Configurations
  zonecfgshareddisks(uii, name, config, zcfg)
  ## CPU Configurations
  zonecfgcpu(uii, name, config, zcfg)
  ## CDROM Configurations
  zonecfgcdrom(uii, name, config, zcfg)
  ### Passthrough PCI Devices
  zonecfgpci(uii, name, config, zcfg)
  ## Additional Disk Configurations
  zonecfgadditionaldisks(uii, name, config, zcfg)
  ## Console access configuration
  zonecfgconsole(uii, name, config, zcfg)
  ## Cloud-init settings
  zonecfgcloudinit(uii, name, config, zcfg)
  ## Nic Configurations
  network(uii, 'config')
end

#zonecfgadditionaldisks(uii, name, config, zcfg) ⇒ Object

zonecfg function for AdditionalDisks



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/vagrant-zones/driver.rb', line 967

def zonecfgadditionaldisks(uii, name, config, zcfg)
  return if config.additional_disks.nil?

  diskrun = 0
  config.additional_disks.each do |disk|
    diskname = 'disk'
    dset = "#{disk['array']}/#{disk['dataset']}/#{name}/#{disk['volume_name']}"
    cinfo = "#{dset}, #{disk['size']}"
    uii.info(I18n.t('vagrant_zones.setting_additional_disks_configurations'))
    uii.info("  #{cinfo}")
    diskname += diskrun.to_s if diskrun.positive?
    diskrun += 1
    execute(false, %(#{zcfg}"add device; set match=/dev/zvol/rdsk/#{dset}; end;"))
    execute(false, %(#{zcfg}"add attr; set name=#{diskname}; set value=#{dset}; set type=string; end;"))
  end
end

#zonecfgbhyve(uii, name, config, zcfg) ⇒ Object

zonecfg function for bhyve



860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
# File 'lib/vagrant-zones/driver.rb', line 860

def zonecfgbhyve(uii, name, config, zcfg)
  return unless config.brand == 'bhyve'

  bootconfigs = config.boot
  datasetpath = "#{bootconfigs['array']}/#{bootconfigs['dataset']}/#{name}"
  datasetroot = "#{datasetpath}/#{bootconfigs['volume_name']}"
  execute(false, %(#{zcfg}"create ; set zonepath=/#{datasetpath}/path"))
  execute(false, %(#{zcfg}"set brand=#{config.brand}"))
  execute(false, %(#{zcfg}"set autoboot=#{config.autoboot}"))
  execute(false, %(#{zcfg}"set ip-type=exclusive"))
  execute(false, %(#{zcfg}"add attr; set name=acpi; set value=#{config.acpi}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=ram; set value=#{config.memory}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=bootrom; set value=#{firmware(uii)}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=hostbridge; set value=#{config.hostbridge}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=diskif; set value=#{config.diskif}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=netif; set value=#{config.netif}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=bootdisk; set value=#{datasetroot.delete_prefix('/')}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=type; set value=#{config.os_type}; set type=string; end;"))
  execute(false, %(#{zcfg}"add attr; set name=xhci; set value=#{config.xhci_enabled}; set type=string; end;"))
  execute(false, %(#{zcfg}"add device; set match=/dev/zvol/rdsk/#{datasetroot}; end;"))
  uii.info(I18n.t('vagrant_zones.bhyve_zone_config_gen'))
end

#zonecfgcdrom(uii, _name, config, zcfg) ⇒ Object

zonecfg function for CDROM Configurations



941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
# File 'lib/vagrant-zones/driver.rb', line 941

def zonecfgcdrom(uii, _name, config, zcfg)
  return if config.cdroms.nil?

  cdroms = config.cdroms
  cdrun = 0
  cdroms.each do |cdrom|
    cdname = 'cdrom'
    uii.info(I18n.t('vagrant_zones.setting_cd_rom_configurations'))
    uii.info("  #{cdrom['path']}")
    cdname += cdrun.to_s if cdrun.positive?
    cdrun += 1
    shrtstrng = 'set type=lofs; add options nodevices; add options ro; end;'
    execute(false, %(#{zcfg}"add attr; set name=#{cdname}; set value=#{cdrom['path']}; set type=string; end;"))
    execute(false, %(#{zcfg}"add fs; set dir=#{cdrom['path']}; set special=#{cdrom['path']}; #{shrtstrng}"))
  end
end

#zonecfgcloudinit(uii, _name, config, zcfg) ⇒ Object

zonecfg function for Cloud-init



1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
# File 'lib/vagrant-zones/driver.rb', line 1008

def zonecfgcloudinit(uii, _name, config, zcfg)
  return unless config.cloud_init_enabled

  cloudconfig = 'on' if config.cloud_init_conf.nil?
  cloudconfig = config.cloud_init_conf.to_s unless config.cloud_init_conf.nil?

  uii.info(I18n.t('vagrant_zones.setting_cloud_init_access'))
  execute(false, %(#{zcfg}"add attr; set name=cloud-init; set value=#{cloudconfig}; set type=string; end;"))

  ccid = config.cloud_init_dnsdomain
  uii.info(I18n.t('vagrant_zones.setting_cloud_dnsdomain')) unless ccid.nil?
  uii.info("  #{ccid}") unless ccid.nil?
  execute(false, %(#{zcfg}"add attr; set name=dns-domain; set value=#{ccid}; set type=string; end;")) unless ccid.nil?

  ccip = config.cloud_init_password
  uii.info(I18n.t('vagrant_zones.setting_cloud_password')) unless ccip.nil?
  uii.info("  #{ccip}") unless ccip.nil?
  execute(false, %(#{zcfg}"add attr; set name=password; set value=#{ccip}; set type=string; end;")) unless ccip.nil?

  cclir = config.dns
  dservers = cclir['dns'].map { |ns| ns['nameserver'] }

  uii.info(I18n.t('vagrant_zones.setting_cloud_resolvers')) unless dservers.nil?
  uii.info("  #{dservers}") unless dservers.nil?
  execute(false, %(#{zcfg}"add attr; set name=resolvers; set value=#{dservers}; set type=string; end;")) unless dservers.nil?

  ccisk = config.cloud_init_sshkey
  uii.info(I18n.t('vagrant_zones.setting_cloud_ssh_key')) unless ccisk.nil?
  uii.info("  #{ccisk}") unless ccisk.nil?
  execute(false, %(#{zcfg}"add attr; set name=sshkey; set value=#{ccisk}; set type=string; end;")) unless ccisk.nil?
end

#zonecfgconsole(uii, _name, config, zcfg) ⇒ Object

zonecfg function for Console Access



985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
# File 'lib/vagrant-zones/driver.rb', line 985

def zonecfgconsole(uii, _name, config, zcfg)
  return if config.console.nil? || config.console == 'disabled'

  port = if %w[console].include?(config.console) && config.consoleport.nil?
           'socket,/tmp/vm.com1'
         elsif %w[webvnc].include?(config.console) || %w[vnc].include?(config.console)
           config.console = 'vnc'
           'on'
         else
           config.consoleport
         end
  port += ',wait' if config.console_onboot
  cp = config.consoleport
  ch = config.consolehost
  cb = config.console_onboot
  ct = config.console
  cinfo = "Console type: #{ct}, State: #{port}, Port: #{cp},  Host: #{ch}, Wait: #{cb}"
  uii.info(I18n.t('vagrant_zones.setting_console_access'))
  uii.info("  #{cinfo}")
  execute(false, %(#{zcfg}"add attr; set name=#{ct}; set value=#{port}; set type=string; end;"))
end

#zonecfgcpu(uii, _name, config, zcfg) ⇒ Object

zonecfg function for CPU Configurations



929
930
931
932
933
934
935
936
937
938
# File 'lib/vagrant-zones/driver.rb', line 929

def zonecfgcpu(uii, _name, config, zcfg)
  uii.info(I18n.t('vagrant_zones.zonecfgcpu')) if config.debug
  if config.cpu_configuration == 'simple' && (config.brand == 'bhyve' || config.brand == 'kvm')
    execute(false, %(#{zcfg}"add attr; set name=vcpus; set value=#{config.cpus}; set type=string; end;"))
  elsif config.cpu_configuration == 'complex' && (config.brand == 'bhyve' || config.brand == 'kvm')
    hash = config.complex_cpu_conf[0]
    cstring = %(sockets=#{hash['sockets']},cores=#{hash['cores']},threads=#{hash['threads']})
    execute(false, %(#{zcfg}'add attr; set name=vcpus; set value="#{cstring}"; set type=string; end;'))
  end
end

#zonecfgkvm(uii, name, config, _zcfg) ⇒ Object

zonecfg function for KVM



909
910
911
912
913
914
915
916
917
918
# File 'lib/vagrant-zones/driver.rb', line 909

def zonecfgkvm(uii, name, config, _zcfg)
  return unless config.brand == 'kvm'

  bootconfigs = config.boot
  config = @machine.provider_config
  datasetpath = "#{bootconfigs['array']}/#{bootconfigs['dataset']}/#{name}"
  datasetroot = "#{datasetpath}/#{bootconfigs['volume_name']}"
  uii.info(datasetroot) if config.debug
  ###### RESERVED ######
end

#zonecfglx(uii, name, config, zcfg) ⇒ Object

zonecfg function for lx



884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/vagrant-zones/driver.rb', line 884

def zonecfglx(uii, name, config, zcfg)
  return unless config.brand == 'lx'

  datasetpath = "#{config.boot['array']}/#{config.boot['dataset']}/#{name}"
  datasetroot = "#{datasetpath}/#{config.boot['volume_name']}"
  uii.info(I18n.t('vagrant_zones.lx_zone_config_gen'))
  @machine.config.vm.networks.each do |adaptertype, opts|
    next unless adaptertype.to_s == 'public_network'

    @ip = opts[:ip].to_s
    cinfo = "#{opts[:ip]}/#{opts[:netmask]}"
    @network = NetAddr.parse_net(cinfo)
    @defrouter = opts[:gateway]
  end
  execute(false, %(#{zcfg}"create ; set zonepath=/#{datasetpath}/path"))
  execute(false, %(#{zcfg}"set brand=#{config.brand}"))
  execute(false, %(#{zcfg}"set autoboot=#{config.autoboot}"))
  execute(false, %(#{zcfg}"add attr; set name=kernel-version; set value=#{config.kernel}; set type=string; end;"))
  cmss = ' add capped-memory; set physical='
  execute(false, %(#{zcfg + cmss}"#{config.memory}; set swap=#{config.kernel}; set locked=#{config.memory}; end;"))
  execute(false, %(#{zcfg}"add dataset; set name=#{datasetroot}; end;"))
  execute(false, %(#{zcfg}"set max-lwps=2000"))
end

#zonecfgnicconfig(uii, opts) ⇒ Object

zonecfg function for for Networking



1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/vagrant-zones/driver.rb', line 1041

def zonecfgnicconfig(uii, opts)
  allowed_address = allowedaddress(uii, opts)
  defrouter = opts[:gateway].to_s
  vnic_name = vname(uii, opts)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.vnic_setup'))
  uii.info("  #{vnic_name}")
  zonecfg_cmd = "#{@pfexec} zonecfg -z #{@machine.name} "
  cie = config.cloud_init_enabled
  aa = config.allowed_address
  case config.brand
  when 'lx'
    shrtstr1 = %(set allowed-address=#{allowed_address}; add property (name=gateway,value="#{defrouter}"); )
    shrtstr2 = %(add property (name=ips,value="#{allowed_address}"); add property (name=primary,value="true"); end;)
    execute(false, %(#{zonecfg_cmd}set global-nic=auto; #{shrtstr1} #{shrtstr2}"))
  when 'bhyve'
    vlan_option = opts[:vlan].nil? || opts[:vlan].zero? ? '' : "set vlan-id=#{opts[:vlan]}; "
    base_cmd = if config.on_demand_vnics
                 %(#{zonecfg_cmd}"add net; set physical=#{vnic_name}; #{vlan_option}set global-nic=#{opts[:bridge]}; )
               else
                 %(#{zonecfg_cmd}"add net; set physical=#{vnic_name}; )
               end
    execute(false, %(#{base_cmd}end;)) unless cie
    execute(false, %(#{base_cmd}set allowed-address=#{allowed_address}; end;)) if cie && aa
    execute(false, %(#{base_cmd}end;)) if cie && !aa
  end
end

#zonecfgnicconfigdelete(uii, opts) ⇒ Object

zonecfg function for for Networking



1070
1071
1072
1073
1074
1075
# File 'lib/vagrant-zones/driver.rb', line 1070

def zonecfgnicconfigdelete(uii, opts)
  vnic_name = vname(uii, opts)
  uii.info(I18n.t('vagrant_zones.vnic_conf_del')) if opts[:provisional]
  uii.info("  #{vnic_name}") if opts[:provisional]
  execute(false, "#{@pfexec} zonecfg -z #{@machine.name} remove net physical=#{vnic_name}") if opts[:provisional]
end

#zonecfgpci(uii, _name, config, _zcfg) ⇒ Object

zonecfg function for PCI Configurations



959
960
961
962
963
964
# File 'lib/vagrant-zones/driver.rb', line 959

def zonecfgpci(uii, _name, config, _zcfg)
  return if config.debug

  uii.info(I18n.t('vagrant_zones.pci')) if config.debug
  ##### RESERVED
end

#zonecfgshareddisks(uii, _name, config, zcfg) ⇒ Object

zonecfg function for Shared Disk Configurations



921
922
923
924
925
926
# File 'lib/vagrant-zones/driver.rb', line 921

def zonecfgshareddisks(uii, _name, config, zcfg)
  return unless config.shared_disk_enabled

  uii.info(I18n.t('vagrant_zones.setting_alt_shared_disk_configurations') + path.path)
  execute(false, %(#{zcfg}"add fs; set dir=/vagrant; set special=#{config.shared_dir}; set type=lofs; end;"))
end

#zonedhcpcheckaddr(uii, opts) ⇒ Object

Check if Address shows up in lease list /var/db/dhcpd ping address after



715
716
717
718
719
720
721
# File 'lib/vagrant-zones/driver.rb', line 715

def zonedhcpcheckaddr(uii, opts)
  # vnic_name = vname(uii, opts)
  # ip = ipaddress(uii, opts)
  uii.info(I18n.t('vagrant_zones.chk_dhcp_addr'))
  uii.info("  #{opts[:ip]}")
  # execute(false, "#{@pfexec} ping #{ip} ")
end

#zonedhcpentries(uii, opts) ⇒ Object

Create dhcp entries for the zone



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'lib/vagrant-zones/driver.rb', line 678

def zonedhcpentries(uii, opts)
  config = @machine.provider_config
  ip = ipaddress(uii, opts)
  name = @machine.name
  vnic_name = vname(uii, opts)
  defrouter = opts[:gateway].to_s
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  hvnic_name = "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
  ## Set Mac address from VNIC
  mac = macaddress(uii, opts)
  if mac == 'auto'
    mac = ''
    cmd = "#{@pfexec} dladm show-vnic #{vnic_name} | tail -n +2 |  awk '{ print $4 }'"
    vnicmac = execute(false, cmd.to_s)
    vnicmac.split(':').each { |x| mac += "#{format('%02x', x.to_i(16))}:" }
    mac = mac[0..-2]
  end
  uii.info(I18n.t('vagrant_zones.configuring_dhcp'))
  broadcast = IPAddr.new(defrouter).mask(shrtsubnet).to_s
  dhcpentries = execute(false, "#{@pfexec} cat /etc/dhcpd.conf").split("\n")
  subnet = %(subnet #{broadcast} netmask #{opts[:netmask]} { option routers #{defrouter}; })
  subnetopts = %(host #{name} { option host-name "#{name}"; hardware ethernet #{mac}; fixed-address #{ip}; })
  subnetexists = false
  subnetoptsexists = false
  dhcpentries.each do |entry|
    subnetexists = true if entry == subnet
    subnetoptsexists = true if entry == subnetopts
  end
  execute(false, "#{@pfexec} echo '#{subnet}' | #{@pfexec} tee -a /etc/dhcpd.conf") unless subnetexists
  execute(false, "#{@pfexec} echo '#{subnetopts}' | #{@pfexec} tee -a /etc/dhcpd.conf") unless subnetoptsexists
  execute(false, "#{@pfexec} svccfg -s dhcp:ipv4 setprop config/listen_ifnames = #{hvnic_name}")
  execute(false, "#{@pfexec} svcadm refresh dhcp:ipv4")
  execute(false, "#{@pfexec} svcadm disable dhcp:ipv4")
  execute(false, "#{@pfexec} svcadm enable dhcp:ipv4")
end

#zonedhcpentriesrem(uii, opts) ⇒ Object

Delete DHCP entries for Zones



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/vagrant-zones/driver.rb', line 347

def zonedhcpentriesrem(uii, opts)
  config = @machine.provider_config

  ip = ipaddress(uii, opts)
  name = @machine.name
  defrouter = opts[:gateway].to_s
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  hvnic_name = "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
  mac = macaddress(uii, opts)

  ## if mac is auto, then grab NIC from VNIC
  if mac == 'auto'
    mac = ''
    cmd = "#{@pfexec} dladm show-vnic #{hvnic_name} | tail -n +2 |  awk '{ print $4 }'"
    vnicmac = execute(false, cmd.to_s)
    vnicmac.split(':').each { |x| mac += "#{format('%02x', x.to_i(16))}:" }
    mac = mac[0..-2]
  end
  uii.info(I18n.t('vagrant_zones.deconfiguring_dhcp'))
  uii.info("  #{hvnic_name}")
  broadcast = IPAddr.new(defrouter).mask(shrtsubnet).to_s
  subnet = %(subnet #{broadcast} netmask #{opts[:netmask]} { option routers #{defrouter}; })
  subnetopts = %(host #{name} { option host-name "#{name}"; hardware ethernet #{mac}; fixed-address #{ip}; })
  File.open('/etc/dhcpd.conf-temp', 'w') do |out_file|
    File.foreach('/etc/dhcpd.conf') do |entry|
      out_file.puts line unless entry == subnet || subnetopts
    end
  end
  FileUtils.mv('/etc/dhcpd.conf-temp', '/etc/dhcpd.conf')
  subawk = '{ $1=""; $2=""; sub(/^[ \\t]+/, ""); print}'
  awk = %(| awk '#{subawk}' | tr ' ' '\\n' | tr -d '"')
  cmd = 'svccfg -s dhcp:ipv4 listprop config/listen_ifnames '
  nicsused = execute(false, cmd + awk.to_s).split("\n")
  newdhcpnics = []
  nicsused.each do |nic|
    newdhcpnics << nic unless nic.to_s == hvnic_name.to_s
  end
  if newdhcpnics.empty?
    dhcpcmdnewstr = '\(\"\"\)'
  else
    dhcpcmdnewstr = '\('
    newdhcpnics.each do |nic|
      dhcpcmdnewstr += %(\\"#{nic}\\")
    end
    dhcpcmdnewstr += '\)'
  end
  execute(false, "#{@pfexec} svccfg -s dhcp:ipv4 setprop config/listen_ifnames = #{dhcpcmdnewstr}")
  execute(false, "#{@pfexec} svcadm refresh dhcp:ipv4")
  execute(false, "#{@pfexec} svcadm disable dhcp:ipv4")
  execute(false, "#{@pfexec} svcadm enable dhcp:ipv4")
end

#zonenatclean(uii, opts) ⇒ Object



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/vagrant-zones/driver.rb', line 399

def zonenatclean(uii, opts)
  vnic_name = vname(uii, opts)
  defrouter = opts[:gateway].to_s
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  broadcast = IPAddr.new(defrouter).mask(shrtsubnet).to_s
  uii.info(I18n.t('vagrant_zones.deconfiguring_nat'))
  uii.info("  #{vnic_name}")
  line1 = %(map #{opts[:bridge]} #{broadcast}/#{shrtsubnet} -> 0/32  portmap tcp/udp auto)
  line2 = %(map #{opts[:bridge]} #{broadcast}/#{shrtsubnet} -> 0/32)
  File.open('/etc/ipf/ipnat.conf-temp', 'w') do |out_file|
    File.foreach('/etc/ipf/ipnat.conf') do |entry|
      out_file.puts line unless entry == line1 || line2
    end
  end
  FileUtils.mv('/etc/ipf/ipnat.conf-temp', '/etc/ipf/ipnat.conf')
  execute(false, "#{@pfexec} svcadm refresh network/ipfilter")
end

#zonenatentries(uii, opts) ⇒ Object

Create nat entries for the zone



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/vagrant-zones/driver.rb', line 653

def zonenatentries(uii, opts)
  vnic_name = vname(uii, opts)
  defrouter = opts[:gateway].to_s
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  uii.info(I18n.t('vagrant_zones.configuring_nat'))
  uii.info("  #{vnic_name}")
  broadcast = IPAddr.new(defrouter).mask(shrtsubnet).to_s
  ## Read NAT File, Check for these lines, if exist, warn, but continue
  natentries = execute(false, "#{@pfexec} cat /etc/ipf/ipnat.conf").split("\n")
  line1 = %(map #{opts[:bridge]} #{broadcast}/#{shrtsubnet} -> 0/32  portmap tcp/udp auto)
  line2 = %(map #{opts[:bridge]} #{broadcast}/#{shrtsubnet} -> 0/32)
  line1exists = false
  line2exists = false
  natentries.each do |entry|
    line1exists = true if entry == line1
    line2exists = true if entry == line2
  end
  execute(false, %(#{@pfexec} echo "#{line1}" | #{@pfexec} tee -a /etc/ipf/ipnat.conf)) unless line1exists
  execute(false, %(#{@pfexec} echo "#{line2}" | #{@pfexec} tee -a /etc/ipf/ipnat.conf)) unless line2exists
  execute(false, "#{@pfexec} svcadm refresh network/ipfilter")
  execute(false, "#{@pfexec} svcadm disable network/ipfilter")
  execute(false, "#{@pfexec} svcadm enable network/ipfilter")
end

#zonenatforward(uii, opts) ⇒ Object

Set NatForwarding on global interface



642
643
644
645
646
647
648
649
650
# File 'lib/vagrant-zones/driver.rb', line 642

def zonenatforward(uii, opts)
  config = @machine.provider_config
  hvnic_name = "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
  uii.info(I18n.t('vagrant_zones.forwarding_nat'))
  uii.info("  #{hvnic_name}")
  execute(false, "#{@pfexec} routeadm -u -e ipv4-forwarding")
  execute(false, "#{@pfexec} ipadm set-ifprop -p forwarding=on -m ipv4 #{opts[:bridge]}")
  execute(false, "#{@pfexec} ipadm set-ifprop -p forwarding=on -m ipv4 #{hvnic_name}")
end

#zonenatniccreate(uii, opts, etherstub) ⇒ Object

Create ethervnics for Zones



461
462
463
464
465
466
467
# File 'lib/vagrant-zones/driver.rb', line 461

def zonenatniccreate(uii, opts, etherstub)
  vnic_name = vname(uii, opts)
  mac = macaddress(uii, opts)
  uii.info(I18n.t('vagrant_zones.creating_ethervnic'))
  uii.info("  #{vnic_name}")
  execute(false, "#{@pfexec} dladm create-vnic -l #{etherstub} -m #{mac} #{vnic_name}")
end

#zoneniccreate(uii, opts) ⇒ Object

Create vnics for Zones



724
725
726
727
728
729
730
731
732
733
# File 'lib/vagrant-zones/driver.rb', line 724

def zoneniccreate(uii, opts)
  mac = macaddress(uii, opts)
  vnic_name = vname(uii, opts)
  uii.info(I18n.t('vagrant_zones.creating_vnic'))
  uii.info("  #{vnic_name}")
  command = "#{@pfexec} dladm create-vnic -l #{opts[:bridge]} -m #{mac}"
  command += " -v #{opts[:vlan]}" unless opts[:vlan].nil? || (opts[:vlan]).zero?
  command += " #{vnic_name}"
  execute(false, command)
end

#zonenicdel(uii, opts) ⇒ Object



417
418
419
420
421
422
423
424
# File 'lib/vagrant-zones/driver.rb', line 417

def zonenicdel(uii, opts)
  vnic_name = vname(uii, opts)
  vnic_configured = execute(false, "#{@pfexec} dladm show-vnic | grep #{vnic_name} | awk '{ print $1 }' ")
  uii.info(I18n.t('vagrant_zones.removing_vnic')) if vnic_configured == vnic_name.to_s
  uii.info("  #{vnic_name}") if vnic_configured == vnic_name.to_s
  execute(false, "#{@pfexec} dladm delete-vnic #{vnic_name}") if vnic_configured == vnic_name.to_s
  uii.info(I18n.t('vagrant_zones.no_removing_vnic')) unless vnic_configured == vnic_name.to_s
end

#zonenicnatsetup(uii, opts) ⇒ Object

Setup vnics for Zones using nat/dhcp



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/vagrant-zones/driver.rb', line 483

def zonenicnatsetup(uii, opts)
  config = @machine.provider_config
  return if config.cloud_init_enabled

  vnic_name = vname(uii, opts)
  mac = macaddress(uii, opts)
  ## if mac is auto, then grab NIC from VNIC
  if mac == 'auto'
    mac = ''
    cmd = "#{@pfexec} dladm show-vnic #{vnic_name} | tail -n +2 |  awk '{ print $4 }'"
    vnicmac = execute(false, cmd.to_s)
    vnicmac.split(':').each { |x| mac += "#{format('%02x', x.to_i(16))}:" }
    mac = mac[0..-2]
  end

  ## Code Block to Detect OS
  uii.info(I18n.t('vagrant_zones.os_detect'))
  cmd = 'uname -a'
  os_type = config.os_type
  uii.info("Zone OS configured as: #{os_type}")
  os_detected = ssh_run_command(uii, cmd.to_s)
  uii.info("Zone OS detected as: #{os_detected}")

  ## Check if Ansible is Installed to enable easier configuration
  uii.info(I18n.t('vagrant_zones.ansible_detect'))
  cmd = 'which ansible > /dev/null 2>&1 ; echo $?'
  ansible_detected = ssh_run_command(uii, cmd.to_s)
  uii.info('Ansible detected') if ansible_detected == '0'

  # Run Network Configuration
  zonenicnatsetup_netplan(uii, opts, mac) unless os_detected.to_s.match(/SunOS/)
  zonenicnatsetup_dladm(uii, opts, mac) if os_detected.to_s.match(/SunOS/)
end

#zonenicnatsetup_dladm(uii, opts, mac) ⇒ Object

Setup vnics for Zones using nat/dhcp over dladm



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/vagrant-zones/driver.rb', line 542

def zonenicnatsetup_dladm(uii, opts, mac)
  ip = ipaddress(uii, opts)
  defrouter = opts[:gateway].to_s
  vnic_name = vname(uii, opts)
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  servers = dnsservers(uii, opts).map { |server| "nameserver #{server['nameserver']}" }.join("\n") unless opts[:dns].nil?
  uii.info(I18n.t('vagrant_zones.configure_interface_using_vnic_dladm'))
  uii.info("  #{vnic_name}")

  # loop through each phys if and run code if physif matches #{mac}
  phys_if = 'pfexec dladm show-phys -m -o LINK,ADDRESS,CLIENT | tail -n +2'
  phys_if_results = ssh_run_command(uii, phys_if).split("\n")
  device = ''
  interface = ''
  phys_if_results.each do |entry|
    e_mac = ''
    entries = entry.strip.split("\r")[1].split
    entries[1].split(':').each { |x| e_mac += "#{format('%02x', x.to_i(16))}:" }
    e_mac = e_mac[0..-2]
    device = entries[0] if e_mac.match(/#{mac}/)
    interface = entries[2] if e_mac.match(/#{mac}/)
  end

  delete_if = interface.match(/--/) ? '' : "pfexec ipadm delete-if #{device} && "
  rename_link = "pfexec dladm rename-link #{device} #{vnic_name} && "
  if_create = "pfexec ipadm create-if #{vnic_name}"
  static_addr = "pfexec ipadm create-addr -T static -a #{ip}/#{shrtsubnet} #{vnic_name}/v4vagrant"
  net_cmd = "#{delete_if} #{rename_link} #{if_create} && #{static_addr}"
  uii.info(I18n.t('vagrant_zones.dladm_applied')) if ssh_run_command(uii, net_cmd)
  route_add = ''
  route_add = "pfexec route -p add default #{defrouter}" unless defrouter.nil?
  uii.info(I18n.t('vagrant_zones.dladm_route_applied')) if ssh_run_command(uii, route_add)

  dns_set = "pfexec echo '#{servers}' | pfexec tee /etc/resolv.conf" unless opts[:dns].nil?
  uii.info(I18n.t('vagrant_zones.dladm_dns_applied')) if ssh_run_command(uii, dns_set.to_s)
end

#zonenicnatsetup_netplan(uii, opts, mac) ⇒ Object

Setup vnics for Zones using nat/dhcp using netplan



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/vagrant-zones/driver.rb', line 518

def zonenicnatsetup_netplan(uii, opts, mac)
  ssh_run_command(uii, 'sudo rm -rf /etc/netplan/*.yaml')
  ip = ipaddress(uii, opts)
  defrouter = opts[:gateway].to_s
  vnic_name = vname(uii, opts)
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  servers = dnsservers(uii, opts).map { |server| server['nameserver'] }.join(', ') unless opts[:dns].nil?
  ## Begin of code block to move to Netplan function
  uii.info(I18n.t('vagrant_zones.configure_interface_using_vnic'))
  uii.info("  #{vnic_name}")
  netplan1 = %(network:\n  version: 2\n  ethernets:\n    #{vnic_name}:\n      match:\n        macaddress: #{mac}\n)
  netplan2 = %(      dhcp-identifier: mac\n      dhcp4: #{opts[:dhcp4]}\n      dhcp6: #{opts[:dhcp6]}\n)
  netplan3 = %(      set-name: #{vnic_name}\n      addresses: [#{ip}/#{shrtsubnet}]\n      routes:\n        - to: #{opts[:route]}\n          via: #{defrouter}\n)
  netplan4 = %(      nameservers:\n        addresses: [#{servers}]) unless opts[:dns].nil?
  netplan = netplan1 + netplan2 + netplan3 + netplan4
  cmd = "echo -e '#{netplan}' | sudo tee /etc/netplan/#{vnic_name}.yaml && chmod 400 /etc/netplan/#{vnic_name}.yaml"
  uii.info(I18n.t('vagrant_zones.netplan_applied_static') + "/etc/netplan/#{vnic_name}.yaml") if ssh_run_command(uii, cmd)

  ## Apply the Configuration
  uii.info(I18n.t('vagrant_zones.netplan_applied')) if ssh_run_command(uii, 'sudo netplan apply')
  ## End of code block to move to Netplan function
end

#zonenicstpzloginsetup(uii, opts, config) ⇒ Object

Setup vnics for Zones using Zlogin



1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
# File 'lib/vagrant-zones/driver.rb', line 1107

def zonenicstpzloginsetup(uii, opts, config)
  vnic_name = vname(uii, opts)
  mac = macaddress(uii, opts)
  ## if mac is auto, then grab NIC from VNIC
  if mac == 'auto'
    mac = ''
    cmd = "#{@pfexec} dladm show-vnic #{vnic_name} | tail -n +2 |  awk '{ print $4 }'"
    vnicmac = execute(false, cmd.to_s)
    vnicmac.split(':').each { |x| mac += "#{format('%02x', x.to_i(16))}:" }
    mac = mac[0..-2]
  end

  ## Code Block to Detect OS
  cmd = 'uname -a'
  uii.info(I18n.t('vagrant_zones.os_detect'))
  os_detected = zlogin(uii, cmd)
  uii.info('Zone OS detected as: OmniOS') if os_detected.to_s.match(/SunOS/)

  zoneniczloginsetup_windows(uii, opts, mac) if config.os_type.to_s.match(/windows/)
  zoneniczloginsetup_dladm(uii, opts, mac) if os_detected.to_s.match(/SunOS/)
  zoneniczloginsetup_netplan(uii, opts, mac) if !config.os_type.to_s.match(/windows/) && !os_detected.to_s.match(/SunOS/)
end

#zoneniczloginsetup_dladm(uii, opts, mac) ⇒ Object

Setup vnics for Zones using zlogin for solaris like OSes – ie dladm



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/vagrant-zones/driver.rb', line 580

def zoneniczloginsetup_dladm(uii, opts, mac)
  ip = ipaddress(uii, opts)
  defrouter = opts[:gateway].to_s
  vnic_name = vname(uii, opts)
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  servers = dnsservers(uii, opts).map { |server| "nameserver #{server['nameserver']}" }.join("\n") unless opts[:dns].nil?
  uii.info(I18n.t('vagrant_zones.configure_interface_using_vnic_dladm'))
  uii.info("  #{vnic_name}")

  # loop through each phys if and run code if physif matches #{mac}
  segments = mac.split(':')
  new_segments = segments.map { |segment| segment.to_i(16).to_s(16) }
  sanitized_mac = new_segments.join(':')
  phys_if = "pfexec dladm show-phys -m -o LINK,ADDRESS,CLIENT | tail -n +2 | grep #{sanitized_mac}"
  phys_if_results = zlogin(uii, phys_if)
  device = ''
  interface = ''
  phys_if_results.each do |entry|
    e_mac = ''
    entries = entry.strip.split("\r")[1].split
    entries[1].split(':').each { |x| e_mac += "#{format('%02x', x.to_i(16))}:" }
    e_mac = e_mac[0..-2]
    device = entries[0] if e_mac.match(/#{mac}/)
    interface = entries[2] if e_mac.match(/#{mac}/)
  end

  delete_if = interface.match(/--/) ? '' : "pfexec ipadm delete-if #{device} && "
  rename_link = "pfexec dladm rename-link #{device} #{vnic_name} && "
  if_create = "pfexec ipadm create-if #{vnic_name}"
  static_addr = "pfexec ipadm create-addr -T static -a #{ip}/#{shrtsubnet} #{vnic_name}/v4vagrant"
  net_cmd = "#{delete_if} #{rename_link} #{if_create} && #{static_addr}"
  uii.info(I18n.t('vagrant_zones.dladm_applied')) if zlogin(uii, net_cmd)
  route_add = "pfexec route -p add default #{defrouter}"
  route_add = 'echo True' if opts[:gateway].nil?
  uii.info(I18n.t('vagrant_zones.dladm_route_applied')) if zlogin(uii, route_add)

  dns_set = "pfexec echo '#{servers}' | pfexec tee /etc/resolv.conf" unless opts[:dns].nil?
  uii.info(I18n.t('vagrant_zones.dladm_dns_applied')) if zlogin(uii, dns_set.to_s)
end

#zoneniczloginsetup_netplan(uii, opts, mac) ⇒ Object

This setups the Netplan based OS Networking via Zlogin



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'lib/vagrant-zones/driver.rb', line 1131

def zoneniczloginsetup_netplan(uii, opts, mac)
  zlogin(uii, 'rm -rf /etc/netplan/*.yaml') if (opts[:nic_number]).zero?
  ip = ipaddress(uii, opts)
  vnic_name = vname(uii, opts)
  servers = dnsservers(uii, opts).map { |server| server['nameserver'] }.join(', ') unless opts[:dns].nil?
  shrtsubnet = IPAddr.new(opts[:netmask].to_s).to_i.to_s(2).count('1').to_s
  defrouter = opts[:gateway].to_s
  uii.info(I18n.t('vagrant_zones.configure_interface_using_vnic'))
  uii.info("  #{vnic_name}")
  netplan1 = %(network:\n  version: 2\n  ethernets:\n    #{vnic_name}:\n      match:\n        macaddress: #{mac}\n)
  netplan2 = ''
  netplan2 = %(      dhcp-identifier: mac\n      dhcp4: #{opts[:dhcp4]}\n      dhcp6: #{opts[:dhcp6]}\n) if opts[:dhcp4]
  netplan3 = %(      set-name: #{vnic_name}\n      addresses: [#{ip}/#{shrtsubnet}]\n)
  netplan3 = %(      set-name: #{vnic_name}\n) if opts[:dhcp4]
  netplan4 = %(      routes:\n        - to: #{opts[:route]}\n          via: #{defrouter}\n)
  netplan5 = %(      nameservers:\n        addresses: [#{servers}]) unless opts[:dns].nil?
  netplan = netplan1 + netplan2 + netplan3 + netplan5 if opts[:gateway].nil?
  netplan = netplan1 + netplan2 + netplan3 + netplan4 + netplan5 unless opts[:gateway].nil?
  cmd = "echo '#{netplan}' > /etc/netplan/#{vnic_name}.yaml && chmod 400 /etc/netplan/#{vnic_name}.yaml"
  infomessage = I18n.t('vagrant_zones.netplan_applied_static') + "/etc/netplan/#{vnic_name}.yaml"
  uii.info(infomessage) if zlogin(uii, cmd)
  uii.info(I18n.t('vagrant_zones.netplan_applied')) if zlogin(uii, 'netplan apply')
end

#zoneniczloginsetup_windows(uii, opts, _mac) ⇒ Object

This setups the Windows Networking via Zlogin



1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
# File 'lib/vagrant-zones/driver.rb', line 1340

def zoneniczloginsetup_windows(uii, opts, _mac)
  ip = ipaddress(uii, opts)
  vnic_name = vname(uii, opts)
  defrouter = opts[:gateway].to_s
  uii.info(I18n.t('vagrant_zones.configure_win_interface_using_vnic'))
  sleep(60)

  ## Insert code to get the list of interfaces by mac address in order
  ## to set the proper VNIC name if using multiple adapters
  rename_adapter = %(netsh interface set interface name = "Ethernet" newname = "#{vnic_name}")
  cmd = %(netsh interface ipv4 set address name="#{vnic_name}" static #{ip} #{opts[:netmask]} #{defrouter})
  uii.info(I18n.t('vagrant_zones.win_applied_rename_adapter')) if zlogin(uii, rename_adapter)
  uii.info(I18n.t('vagrant_zones.win_applied_static')) if zlogin(uii, cmd)
  return unless opts[:dns].nil?

  ip_addresses = dnsservers(uii, opts).map { |hash| hash['nameserver'] }
  dns1 = %(netsh int ipv4 set dns name="#{vnic_name}" static #{ip_addresses[0]} primary validate=no)
  uii.info(I18n.t('vagrant_zones.win_applied_dns1')) if zlogin(uii, dns1)
  ip_addresses[1..].each_with_index do |dns, index|
    additional_nameservers = %(netsh int ipv4 add dns name="#{vnic_name}" #{dns} index="#{index + 2}" validate=no)
    uii.info(I18n.t('vagrant_zones.win_applied_dns2')) if zlogin(uii, additional_nameservers)
  end
end