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.



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/vagrant-zones/driver.rb', line 29

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.



26
27
28
# File 'lib/vagrant-zones/driver.rb', line 26

def executor
  @executor
end

#machineObject (readonly)

Returns the value of attribute machine.



27
28
29
# File 'lib/vagrant-zones/driver.rb', line 27

def machine
  @machine
end

#pfexecObject (readonly)

Returns the value of attribute pfexec.



27
28
29
# File 'lib/vagrant-zones/driver.rb', line 27

def pfexec
  @pfexec
end

Instance Method Details

#allowedaddress(uii, opts) ⇒ Object

This Sanitizes the AllowedIP Address to set for Cloudinit



288
289
290
291
292
293
294
295
# File 'lib/vagrant-zones/driver.rb', line 288

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



219
220
221
222
223
# File 'lib/vagrant-zones/driver.rb', line 219

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



1035
1036
1037
1038
1039
1040
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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/vagrant-zones/driver.rb', line 1035

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

#configure_pty_encoding(pty_read) ⇒ Object

Set up a PTY read stream for safe binary reading from zone consoles



114
115
116
# File 'lib/vagrant-zones/driver.rb', line 114

def configure_pty_encoding(pty_read)
  pty_read.set_encoding('ASCII-8BIT')
end

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

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



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/vagrant-zones/driver.rb', line 170

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

#console_encodingObject

Validate and return the configured console encoding



100
101
102
103
104
105
106
# File 'lib/vagrant-zones/driver.rb', line 100

def console_encoding
  config = @machine.provider_config
  encoding_name = config.console_encoding || 'UTF-8'
  Encoding.find(encoding_name)
rescue ArgumentError
  raise Errors::InvalidConsoleEncoding, encoding: encoding_name
end

#control(uii, action) ⇒ Object

Control the zone from inside the zone OS



138
139
140
141
142
# File 'lib/vagrant-zones/driver.rb', line 138

def control(uii, action)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.control')) if config.debug
  strategy.control(uii, action)
end

#create_dataset(uii) ⇒ Object

This helps us create all the datasets for the zone



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# File 'lib/vagrant-zones/driver.rb', line 657

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



732
733
734
735
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
# File 'lib/vagrant-zones/driver.rb', line 732

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



1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
# File 'lib/vagrant-zones/driver.rb', line 1502

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

#dhcp_reserved_ipObject

Return the known reserved IP when using DHCP setup method



306
307
308
309
310
311
312
313
314
315
316
# File 'lib/vagrant-zones/driver.rb', line 306

def dhcp_reserved_ip
  config = @machine.provider_config
  return nil unless config.setup_method == 'dhcp'

  @machine.config.vm.networks.each do |(_adaptertype, opts)|
    next unless opts[:dhcp4] && opts[:managed] && !opts[:ip].to_s.empty?

    return opts[:ip].to_s.gsub("\t", '')
  end
  nil
end

#dnsservers(uii, opts) ⇒ Object

This Sanitizes the DNS Records



258
259
260
261
262
263
# File 'lib/vagrant-zones/driver.rb', line 258

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

#etherstub_name(opts) ⇒ Object

Derive the etherstub name from network opts or generate per-VM name



467
468
469
470
# File 'lib/vagrant-zones/driver.rb', line 467

def etherstub_name(opts)
  config = @machine.provider_config
  opts[:etherstub] || "stub_#{config.partition_id}_#{opts[:nic_number]}"
end

#etherstubcreate(uii, opts) ⇒ Object

Create etherstubs for Zones



484
485
486
487
488
489
490
491
# File 'lib/vagrant-zones/driver.rb', line 484

def etherstubcreate(uii, opts)
  ether_name = etherstub_name(opts)
  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



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/vagrant-zones/driver.rb', line 503

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]}"

  # Check if gateway IP already exists on this etherstub (shared etherstub)
  if opts[:etherstub]
    existing_ip = execute(false, "#{@pfexec} ipadm show-addr -o ADDR | grep #{defrouter}/#{shrtsubnet} || true")
    unless existing_ip.strip.empty?
      uii.info(I18n.t('vagrant_zones.shared_etherstub_reusing'))
      uii.info("  #{etherstub} #{defrouter}/#{shrtsubnet}")
      return
    end
  end

  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



451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/vagrant-zones/driver.rb', line 451

def etherstubdelete(uii, opts)
  config = @machine.provider_config
  if opts[:etherstub]
    uii.info(I18n.t('vagrant_zones.shared_etherstub_skip_delete'))
    uii.info("  #{opts[:etherstub]}")
    return
  end
  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



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/vagrant-zones/driver.rb', line 434

def etherstubdelhvnic(uii, opts)
  config = @machine.provider_config
  if opts[:etherstub]
    uii.info(I18n.t('vagrant_zones.shared_hvnic_skip_delete'))
    uii.info("  #{opts[:etherstub]}")
    return
  end
  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



95
96
97
# File 'lib/vagrant-zones/driver.rb', line 95

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

#firmware(uii) ⇒ Object

This filters the firmware



1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
# File 'lib/vagrant-zones/driver.rb', line 1218

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

Get the guest’s primary IPv4 address via the configured setup strategy.



319
320
321
# File 'lib/vagrant-zones/driver.rb', line 319

def get_ip_address(uii)
  strategy.get_ip_address(uii)
end

#halt(uii) ⇒ Object

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



1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
# File 'lib/vagrant-zones/driver.rb', line 1478

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

#host_vnic_name(opts) ⇒ Object

Find the host VNIC name - use per-VM name or find existing one on shared etherstub



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

def host_vnic_name(opts)
  config = @machine.provider_config
  if opts[:etherstub]
    defrouter = opts[:gateway].to_s
    result = execute(false, "#{@pfexec} ipadm show-addr -o ADDROBJ,ADDR | grep #{defrouter} | awk -F/ '{ print $1 }' | head -n 1 || true")
    return result.strip unless result.strip.empty?
  end
  "h_vnic_#{config.partition_id}_#{opts[:nic_number]}"
end

#install(uii) ⇒ Object

Begin installation for zone



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/vagrant-zones/driver.rb', line 119

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



276
277
278
279
280
281
282
283
284
285
# File 'lib/vagrant-zones/driver.rb', line 276

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



266
267
268
269
270
271
272
273
# File 'lib/vagrant-zones/driver.rb', line 266

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

#natnicconfig(uii, opts) ⇒ Object

zonecfg function for for nat Networking



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/vagrant-zones/driver.rb', line 527

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'
    if config.on_demand_vnics
      base_cmd = %(add net; set physical=#{vnic_name}; set global-nic=#{etherstub_name(opts)};)
      execute(false, %(#{zonecfg_cmd}"#{base_cmd} end;")) unless cie
      execute(false, %(#{zonecfg_cmd}"#{base_cmd} set allowed-address=#{allowed_address}; end;")) if cie
    else
      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
end

#network(uii, state) ⇒ Object

Manage Network Interfaces



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/vagrant-zones/driver.rb', line 324

def network(uii, state)
  config = @machine.provider_config
  if state == 'setup'
    strategy.setup_network(uii)
    @machine.config.vm.networks.each do |(adaptertype, opts)|
      zonedhcpcheckaddr(uii, opts) if adaptertype.to_s == 'private_network'
    end
    return
  end

  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
    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'
    end
  end
end

#nictype(opts) ⇒ Object

This filters the NIC Types



242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/vagrant-zones/driver.rb', line 242

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

#normalize_mac(str) ⇒ Object

Pad each octet to 2 hex digits, lowercase. Matches qga’s hardware-address output.



55
56
57
# File 'lib/vagrant-zones/driver.rb', line 55

def normalize_mac(str)
  str.to_s.split(':').map { |x| format('%02x', x.to_i(16)) }.join(':').downcase
end

#rdpport(uii) ⇒ Object

This filters the rdpport



1237
1238
1239
1240
1241
# File 'lib/vagrant-zones/driver.rb', line 1237

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

#read_vnic_mac(vnic_name) ⇒ Object

Read a VNIC’s actual MAC by querying dladm. Returns a normalized hex string (each octet padded to two digits, lowercase) or nil when dladm produces no output.



61
62
63
64
65
66
# File 'lib/vagrant-zones/driver.rb', line 61

def read_vnic_mac(vnic_name)
  out = execute(false, "#{@pfexec} dladm show-vnic #{vnic_name} | tail -n +2 | awk '{ print $4 }'")
  return nil if out.nil? || out.strip.empty?

  normalize_mac(out.strip)
end

#scrub_console_output(str) ⇒ Object

Scrub a string from the PTY console into valid text using the configured encoding



109
110
111
# File 'lib/vagrant-zones/driver.rb', line 109

def scrub_console_output(str)
  str.to_s.force_encoding(console_encoding.to_s).scrub('')
end

#setup(uii) ⇒ Object

This helps us set up the networking of the VM



1091
1092
1093
1094
1095
# File 'lib/vagrant-zones/driver.rb', line 1091

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



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/vagrant-zones/driver.rb', line 145

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



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

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



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/vagrant-zones/driver.rb', line 77

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

#strategyObject

Returns the setup strategy (zlogin, dhcp, qga) for this machine, cached.



43
44
45
46
47
48
49
50
51
52
# File 'lib/vagrant-zones/driver.rb', line 43

def strategy
  return @strategy if @strategy

  klass = case @machine.provider_config.setup_method
          when 'qga'  then SetupStrategies::QGA
          when 'dhcp' then SetupStrategies::DHCP
          else             SetupStrategies::Zlogin
          end
  @strategy = klass.new(self)
end

#user(machine) ⇒ Object

This filters the vagrantuser



1180
1181
1182
1183
1184
1185
# File 'lib/vagrant-zones/driver.rb', line 1180

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)


1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'lib/vagrant-zones/driver.rb', line 1161

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



1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
# File 'lib/vagrant-zones/driver.rb', line 1188

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



1244
1245
1246
1247
1248
# File 'lib/vagrant-zones/driver.rb', line 1244

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



298
299
300
301
302
303
# File 'lib/vagrant-zones/driver.rb', line 298

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

#vnic_mac_for(uii, opts) ⇒ Object

Resolve a NIC’s effective MAC: when configured ‘auto’ read the actual value off the created VNIC via dladm; otherwise normalize the configured MAC.



70
71
72
73
74
75
# File 'lib/vagrant-zones/driver.rb', line 70

def vnic_mac_for(uii, opts)
  mac = macaddress(uii, opts)
  return normalize_mac(mac) unless mac == 'auto'

  read_vnic_mac(vname(uii, opts))
end

#vtype(config) ⇒ Object

This filters the VM usage for VNIC Naming Purposes



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

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

Wait for the zone to be reachable via the configured setup strategy. The LX brand bootstraps a vagrant user via zlogin one-shots and is independent of strategy.



1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
# File 'lib/vagrant-zones/driver.rb', line 1099

def waitforboot(uii, metrics, interrupted)
  config = @machine.provider_config
  uii.info(I18n.t('vagrant_zones.wait_for_boot'))
  case config.brand
  when 'bhyve'
    strategy.wait_for_boot(uii, metrics, interrupted)
  when 'lx'
    unless user_exists?(uii, config.vagrant_user)
      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



1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
# File 'lib/vagrant-zones/driver.rb', line 1454

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



1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
# File 'lib/vagrant-zones/driver.rb', line 1296

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



1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
# File 'lib/vagrant-zones/driver.rb', line 1421

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



1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
# File 'lib/vagrant-zones/driver.rb', line 1374

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 [d, 'all'].include?(opts[:delete])

    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



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/vagrant-zones/driver.rb', line 1359

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 [d, 'all'].include?(opts[:list])

    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



1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
# File 'lib/vagrant-zones/driver.rb', line 1392

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



1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'lib/vagrant-zones/driver.rb', line 1320

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



1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'lib/vagrant-zones/driver.rb', line 1277

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



1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
# File 'lib/vagrant-zones/driver.rb', line 1251

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



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

def zlogin(uii, cmd)
  name = @machine.name
  config = @machine.provider_config
  rsp = []
  execute_return = ''
  PTY.spawn("pfexec zlogin -C #{name}") do |zread, zwrite, pid|
    configure_pty_encoding(zread)
    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(scrub_console_output(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
  scrub_console_output(execute_return)
end

#zlogincommand(uii, cmd) ⇒ Object

This gives the user a terminal console



1172
1173
1174
1175
1176
1177
# File 'lib/vagrant-zones/driver.rb', line 1172

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



1004
1005
1006
1007
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
# File 'lib/vagrant-zones/driver.rb', line 1004

def zonecfg(uii)
  name = @machine.name
  config = @machine.provider_config
  raise Errors::QGANotAvailable, brand: config.brand.to_s if config.setup_method == 'qga' && config.brand != 'bhyve'

  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



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
# File 'lib/vagrant-zones/driver.rb', line 893

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



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
# File 'lib/vagrant-zones/driver.rb', line 781

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;"))
  if config.setup_method == 'qga'
    slot = config.qga_slot || 9
    extra = %(-s #{slot},virtio-console,org.qemu.guest_agent.0=/tmp/qga.sock)
    execute(false, %(#{zcfg}'add attr; set name=extra; set value="#{extra}"; set type=string; end;'))
  end
  uii.info(I18n.t('vagrant_zones.bhyve_zone_config_gen'))
end

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

zonecfg function for CDROM Configurations



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
# File 'lib/vagrant-zones/driver.rb', line 867

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



934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/vagrant-zones/driver.rb', line 934

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



911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/vagrant-zones/driver.rb', line 911

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



855
856
857
858
859
860
861
862
863
864
# File 'lib/vagrant-zones/driver.rb', line 855

def zonecfgcpu(uii, _name, config, zcfg)
  uii.info(I18n.t('vagrant_zones.zonecfgcpu')) if config.debug
  if config.cpu_configuration == 'simple' && %w[bhyve kvm].include?(config.brand)
    execute(false, %(#{zcfg}"add attr; set name=vcpus; set value=#{config.cpus}; set type=string; end;"))
  elsif config.cpu_configuration == 'complex' && %w[bhyve kvm].include?(config.brand)
    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



835
836
837
838
839
840
841
842
843
844
# File 'lib/vagrant-zones/driver.rb', line 835

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



810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
# File 'lib/vagrant-zones/driver.rb', line 810

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



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
# File 'lib/vagrant-zones/driver.rb', line 967

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
                 %(add net; set physical=#{vnic_name}; #{vlan_option} set global-nic=#{opts[:bridge]};)
               else
                 %(add net; set physical=#{vnic_name};)
               end
    execute(false, %(#{zonecfg_cmd} "#{base_cmd} end;")) unless cie
    execute(false, %(#{zonecfg_cmd} "#{base_cmd} set allowed-address=#{allowed_address}; end;")) if cie && aa
    execute(false, %(#{zonecfg_cmd} "#{base_cmd} end;")) if cie && !aa
  end
end

#zonecfgnicconfigdelete(uii, opts) ⇒ Object

zonecfg function for for Networking



996
997
998
999
1000
1001
# File 'lib/vagrant-zones/driver.rb', line 996

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



885
886
887
888
889
890
# File 'lib/vagrant-zones/driver.rb', line 885

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



847
848
849
850
851
852
# File 'lib/vagrant-zones/driver.rb', line 847

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



636
637
638
639
640
641
642
# File 'lib/vagrant-zones/driver.rb', line 636

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



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
# File 'lib/vagrant-zones/driver.rb', line 595

def zonedhcpentries(uii, opts)
  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 = host_vnic_name(opts)
  mac = macaddress(uii, opts)
  mac = read_vnic_mac(vnic_name) if mac == 'auto'
  uii.info(I18n.t('vagrant_zones.configuring_dhcp'))
  unless File.exist?('/etc/dhcpd.conf')
    uii.info(I18n.t('vagrant_zones.dhcpd_conf_created'))
    execute(false, "#{@pfexec} sh -c 'echo \"authoritative;\" > /etc/dhcpd.conf'")
  end
  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
  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")
  nicsused << hvnic_name unless nicsused.include?(hvnic_name)
  dhcpcmdstr = '\('
  nicsused.each { |nic| dhcpcmdstr += %(\\"#{nic}\\") unless nic.strip.empty? }
  dhcpcmdstr += '\)'
  execute(false, "#{@pfexec} svccfg -s dhcp:ipv4 setprop config/listen_ifnames = #{dhcpcmdstr}")
  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



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
398
399
400
401
402
# File 'lib/vagrant-zones/driver.rb', line 360

def zonedhcpentriesrem(uii, opts)
  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 = host_vnic_name(opts)
  mac = macaddress(uii, opts)
  mac = read_vnic_mac(hvnic_name) if mac == 'auto'
  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}; })
  if File.exist?('/etc/dhcpd.conf')
    File.open('/etc/dhcpd.conf-temp', 'w') do |out_file|
      File.foreach('/etc/dhcpd.conf') do |entry|
        out_file.puts entry unless entry.strip == subnet.strip || entry.strip == subnetopts.strip
      end
    end
    FileUtils.mv('/etc/dhcpd.conf-temp', '/etc/dhcpd.conf')
  end
  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



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/vagrant-zones/driver.rb', line 404

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)
  if File.exist?('/etc/ipf/ipnat.conf')
    File.open('/etc/ipf/ipnat.conf-temp', 'w') do |out_file|
      File.foreach('/etc/ipf/ipnat.conf') do |entry|
        out_file.puts entry unless entry.strip == line1.strip || entry.strip == line2.strip
      end
    end
    FileUtils.mv('/etc/ipf/ipnat.conf-temp', '/etc/ipf/ipnat.conf')
  end
  execute(false, "#{@pfexec} svcadm refresh network/ipfilter")
end

#zonenatentries(uii, opts) ⇒ Object

Create nat entries for the zone



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/vagrant-zones/driver.rb', line 570

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



554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/vagrant-zones/driver.rb', line 554

def zonenatforward(uii, opts)
  hvnic_name = host_vnic_name(opts)
  bridge_exists = execute(false, "#{@pfexec} ipadm show-if #{opts[:bridge]} 2>/dev/null | grep #{opts[:bridge]} || true")
  if bridge_exists.strip.empty?
    uii.info(I18n.t('vagrant_zones.bridge_not_found'))
    uii.info("  #{opts[:bridge]}")
    return
  end
  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



494
495
496
497
498
499
500
# File 'lib/vagrant-zones/driver.rb', line 494

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



645
646
647
648
649
650
651
652
653
654
# File 'lib/vagrant-zones/driver.rb', line 645

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



424
425
426
427
428
429
430
431
# File 'lib/vagrant-zones/driver.rb', line 424

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