-
Notifications
You must be signed in to change notification settings - Fork 2
/
oneswap_helper.rb
1790 lines (1607 loc) · 67.1 KB
/
oneswap_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
314
315
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
345
346
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
516
517
518
519
520
521
522
523
524
525
526
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
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
578
579
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
730
731
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
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
809
810
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
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
965
966
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
994
995
996
997
998
999
1000
# coding: utf-8
# -------------------------------------------------------------------------- #
# Copyright 2002-2024, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
require 'one_helper'
class String
def black; "\e[30m#{self}\e[0m" end
def red; "\e[31m#{self}\e[0m" end
def green; "\e[32m#{self}\e[0m" end
def brown; "\e[33m#{self}\e[0m" end
def blue; "\e[34m#{self}\e[0m" end
def magenta; "\e[35m#{self}\e[0m" end
def cyan; "\e[36m#{self}\e[0m" end
def gray; "\e[37m#{self}\e[0m" end
def bg_black; "\e[40m#{self}\e[0m" end
def bg_red; "\e[41m#{self}\e[0m" end
def bg_green; "\e[42m#{self}\e[0m" end
def bg_brown; "\e[43m#{self}\e[0m" end
def bg_blue; "\e[44m#{self}\e[0m" end
def bg_magenta; "\e[45m#{self}\e[0m" end
def bg_cyan; "\e[46m#{self}\e[0m" end
def bg_gray; "\e[47m#{self}\e[0m" end
def bold; "\e[1m#{self}\e[22m" end
def italic; "\e[3m#{self}\e[23m" end
def underline; "\e[4m#{self}\e[24m" end
def blink; "\e[5m#{self}\e[25m" end
def reverse_color; "\e[7m#{self}\e[27m" end
end
# Ruby 3.x+ deprecated URI.escape, however rbvmomi still relies on it
if RUBY_VERSION.split('.')[0].to_i >= 3
# Monkey patch the escape functionality
module URI
def self.escape(url)
URI::Parser.new.escape url
end
end
end
##############################################################################
# Module OneVcenterHelper
##############################################################################
class OneSwapHelper < OpenNebulaHelper::OneHelper
# true to log to /var/log/one/oneswap.*
DEBUG = false
@props, @options = []
@dotskip = false # temporarily skip dots, for progress dots.
# vCenter importer will divide rbvmomi resources
# in this group, makes parsing easier.
module VOBJECT
VM = 1
DATACENTER = 2
CLUSTER = 3
end
#
# onevcenter helper main constant
# This will control everything displayed on STDOUT
# Resources (above) uses this table
#
# struct: [Array] LIST FORMAT for opennebula cli
# related methods: * cli_format
#
# columns: [Hash(column => Integer)] Will be used in the list command,
# Integer represent nbytes
# related methods: * format_list
#
# cli: [Array] with mandatory args, for example image
# listing needs a datastore
# related methods: * parse_opts
#
# dialogue: [Lambda] Used only for Vobject that require a previous
# dialogue with the user, will be triggered
# on importation process
# related methods: * network_dialogue
# * template_dialogue
#
TABLE = {
VOBJECT::VM => {
:struct => ['VM_LIST', 'VM'],
:columns => { :IMID => 8, :NAME => 20, :STATE => 10, :HOST => 10, :CPU => 3, :MEM => 7, :REF => 35 },
:cli => [],
:dialogue => ->(arg) {}
},
VOBJECT::DATACENTER => {
:struct => ['DATACENTER_LIST', 'DATACENTER'],
:columns => { :DATACENTER => 30 },
:cli => [],
:dialogue => ->(arg) {}
},
VOBJECT::CLUSTER => {
:struct => ['CLUSTER_LIST', 'CLUSTER'],
:columns => { :NAME => 30, :VMCOUNT => 35 },
:cli => [],
:dialgoue => ->(arg) {}
}
}
if DEBUG
LOGGER = {
:stdout => File.open('/var/log/one/oneswap.stdout', 'a'),
:stderr => File.open('/var/log/one/oneswap.stderr', 'a')
}
LOGGER[:stdout].sync = true
LOGGER[:stderr].sync = true
end
########################
# In list command you can use this method to print a header
#
# @param vcenter_host [String] this text will be displayed
#
def show_header(vcenter_host)
CLIHelper.scr_bold
CLIHelper.scr_underline
puts "# vCenter: #{vcenter_host}".ljust(50)
CLIHelper.scr_restore
puts
end
# Using for parse a String into a VOBJECT
# We will use VOBJECT instances for handle any operatiion
#
# @param type [String] String representing the vCenter resource
#
def object_update(type)
if type.nil?
type = 'vms'
else
type = type.downcase
end
case type
when 'networks'
@vobject = VOBJECT::NETWORK
when 'datacenters'
@vobject = VOBJECT::DATACENTER
when 'clusters'
@vobject = VOBJECT::CLUSTER
when 'vms'
@vobject = VOBJECT::VM
else
raise 'Invalid object type, must be any of: '\
'[ networks, datacenters, clusters, vms ]'
end
end
# Handles connection to vCenter.
#
# @param options [Hash] options for the connection
#
def connection_options(object_name, options)
if options[:host].nil? && ( options[:vcenter].nil? && options[:vuser].nil? )
raise 'vCenter connection parameters are mandatory'\
" #{object_name}:\n"\
"\t --vcenter vCenter hostname\n"\
"\t --vuser username to login in vcenter\n"\
"got: #{options}"
end
password = options[:vpass] || OpenNebulaHelper::OneHelper.get_password
{
:user => options[:vuser],
:password => password,
:host => options[:vcenter],
:port => options[:port],
:insecure => true
}
end
def cli_format(hash)
{
TABLE[@vobject][:struct].first =>
{
TABLE[@vobject][:struct].last =>
hash.values
}
}
end
# handles :cli section of TABLE
# used for executing the dialogue in some VOBJECTS
#
# @param object_info [Hash] This is the object
# with all the info related to the object
# that will be imported
#
def cli_dialogue(object_info)
TABLE[@vobject][:dialogue].call(object_info)
end
# This method iterates over the possible options for certain resources
# and will raise an error in case of missing mandatory param
#
# @param opts [Hash] options object passed to the onecenter tool
#
def parse_opts(opts)
object_update(opts[:object])
res = {}
TABLE[@vobject][:cli].each do |arg|
raise "#{arg} it's mandadory for this op" if opts[arg].nil?
res[arg] = method(arg).call(opts[arg])
end
res[:config] = parse_file(opts[:configuration]) if opts[:configuration]
res
end
# This method will parse a yaml
# Only used for a feature that adds the posibility
# of import resources with custom params (bulk)
#
# @param path [String] Path of the file
#
def parse_file(path)
begin
_config = YAML.safe_load(File.read(path))
rescue StandardError => _e
str_error="Unable to read '#{path}'. Invalid YAML syntax:\n"
raise str_error
end
end
# Use the attributes provided by TABLE
# with the purpose of build a complete CLI list
# OpenNebula way
#
def format_list
config = TABLE[@vobject][:columns]
CLIHelper::ShowTable.new do
column :DATACENTER, :left, :expand,
'DATACENTER', :size => config[:DATACENTER] || 15 do |d|
d[:datacenter]
end
column :IMID, 'OBJECT ID', :size=>config[:IMID] || 4 do |d|
d[:imid]
end
column :REF, 'REF', :left, :adjust, :size=>config[:REF] || 15 do |d|
d[:ref] || d[:cluster_ref]
end
column :NAME, 'NAME', :left, :expand,
:size=>config[:NAME] || 20 do |d|
d[:name] || d[:simple_name]
end
column :CLUSTERS, 'CLUSTERS', :left, :expand,
:size=>config[:CLUSTERS] || 10 do |d|
d = d[:clusters] if d[:clusters]
d[:one_ids] || d[:cluster].to_s
end
column :PATH, 'PATH', :left, :expand,
:size=>config[:PATH] || 10 do |d|
d[:path]
end
column :VMCOUNT, '# VMS', :left, :expand,
:size=>config[:PATH] || 7 do |d|
d[:vm_count]
end
column :STATE, 'STATE', :left, :expand,
:size=>config[:STATE] || 10 do |d|
d[:state]
end
column :HOST, 'HOST', :left, :expand,
:size=>config[:HOST] || 15 do |d|
d[:host]
end
column :CPU, 'CPU', :left, :expand,
:size=>config[:CPU] || 5 do |d|
d[:cpu]
end
column :MEM, 'MEM', :left, :expand,
:size=>config[:MEM] || 7 do |d|
d[:mem]
end
default(*config.keys)
end
end
def check_one_connectivity
user = OpenNebula::User.new_with_id(OpenNebula::User::SELF, @client)
rc = user.info
if rc.class == OpenNebula::Error
raise 'Failed to get User info, indicating authentication failed'
end
end
def cleanup_passwords
puts "Deleting password files."
File.delete("#{@options[:work_dir]}/vpassfile")
File.delete("#{@options[:work_dir]}/esxpassfile")
end
def cleanup_disks
if @options[:delete]
puts "Deleting vdisks in #{"#{@options[:work_dir]}/conversions"}"
FileUtils.rm_rf("#{@options[:work_dir]}/conversions")
if Dir.exist?("#{@options[:work_dir]}/transfers")
FileUtils.rm_rf("#{@options[:work_dir]}/transfers")
end
else
puts "Delete not enabled, leaving disks in #{"#{@options[:work_dir]}/conversions"}"
end
end
def cleanup_dirs
if @options[:delete]
puts "Deleting everything in and including #{"#{@options[:work_dir]}"}"
FileUtils.rm_rf("#{@options[:work_dir]}")
else
puts "Delete not enabled, leaving #{@options[:work_dir]} alone."
end
end
def cleanup_all
cleanup_passwords
cleanup_disks
cleanup_dirs
end
def create_base_template
vm_template_config = {
"NAME" => "#{@props['name']}",
"CPU" => "#{@props['config'][:hardware][:numCPU]}",
"vCPU" => "#{@props['config'][:hardware][:numCPU]}",
"MEMORY" => "#{@props['config'][:hardware][:memoryMB]}",
"HYPERVISOR" => "kvm"
}
if @options[:cpu_model]
vm_template_config["CPU_MODEL"] = {"MODEL" => "#{@options[:cpu_model]}"}
end
if !@options[:disable_contextualization]
vm_template_config["CONTEXT"] = {
"NETWORK" => "YES",
"SSH_PUBLIC_KEY" => "$USER[SSH_PUBLIC_KEY]"
}
end
if @options[:cpu]
vm_template_config["CPU"] = "#{@options[:cpu]}"
end
if @options[:vcpu]
vm_template_config["vCPU"] = "#{@options[:vcpu]}"
end
if @props['config'][:memoryHotAddEnabled]
vm_template_config["MEMORY_RESIZE_MODE"] = "HOTPLUG"
vm_template_config["MEMORY_MAX"] = "#{@props['config'][:hardware][:memoryMB]}"
if @options[:memory_max]
vm_template_config["MEMORY_MAX"] = "#{@options[:memory_max]}"
end
if vm_template_config.include?("HOT_RESIZE")
vm_template_config["HOT_RESIZE"]["MEMORY_HOT_ADD_ENABLED"] = "YES"
else
vm_template_config["HOT_RESIZE"] = { "MEMORY_HOT_ADD_ENABLED" => "YES" }
end
end
if @props['config'][:cpuHotAddEnabled]
vm_template_config["VCPU_MAX"] = "#{@props['config'][:hardware][:numCPU]}"
if @options[:vcpu_max]
vm_template_config["VCPU_MAX"] = "#{@options[:vcpu_max]}"
end
if vm_template_config.include?("HOT_RESIZE")
vm_template_config["HOT_RESIZE"]["CPU_HOT_ADD_ENABLED"] = "YES"
else
vm_template_config["HOT_RESIZE"] = { "CPU_HOT_ADD_ENABLED" => "YES" }
end
end
if @options[:graphics_type]
possible_options = ['spice', 'vnc', 'sdl']
if possible_options.include?(@options[:graphics_type].downcase)
vm_template_config["GRAPHICS"] = {}
vm_template_config["GRAPHICS"]["TYPE"] = @options[:graphics_type].upcase
if @options[:graphics_port]
vm_template_config["GRAPHICS"]["PORT"] = @options[:graphics_port]
end
if @options[:graphics_password]
vm_template_config["GRAPHICS"]["PASSWD"] = @options[:graphics_password]
end
if @options[:graphics_keymap]
vm_template_config["GRAPHICS"]["KEYMAP"] = @options[:graphics_keymap]
end
if @options[:graphics_listen]
vm_template_config["GRAPHICS"]["LISTEN"] = @options[:graphics_listen]
end
if @options[:graphics_command]
vm_template_config["GRAPHICS"]["COMMAND"] = @options[:graphics_command]
end
else
puts "Invalid graphics type. Please use one of the following: #{possible_options.join(', ')}"
end
end
vmt = OpenNebula::Template.new(OpenNebula::Template.build_xml, @client)
vmt.add_element('//VMTEMPLATE', vm_template_config)
vmt
end
def template_firmware
fw = { "OS" => { "FIRMWARE" => "BIOS" }}
if @props['config'][:firmware] == 'efi'
if @props['config'][:bootOptions][:efiSecureBootEnabled]
fw['OS']['FIRMWARE'] = '/usr/share/OVMF/OVMF_CODE.secboot.fd'
fw['OS']['FIRMWARE_SECURE'] = 'YES'
else
fw['OS']['FIRMWARE'] = '/usr/share/OVMF/OVMF_CODE.fd'
end
fw['OS']['MACHINE'] = 'q35'
end
fw
end
#SCHED_DS_REQUIREMENTS = "ID=\"110\""
#SCHED_REQUIREMENTS = "ID=\"0\" | CLUSTER_ID=\"0\""
def template_scheduling(vmt)
sched = {}
if @options[:one_cluster] or @options[:one_host]
sched['SCHED_REQUIREMENTS'] = ''
if @options[:one_host]
sched['SCHED_REQUIREMENTS'] << "ID=\"#{@options[:one_host]}\""
end
if @options[:one_host] and @options[:one_cluster]
sched['SCHED_REQUIREMENTS'] << ' | '
end
if @options[:one_cluster]
sched['SCHED_REQUIREMENTS'] << "CLUSTER_ID=\"#{@options[:one_cluster]}\""
end
vmt.add_element('//VMTEMPLATE', sched)
sched = {}
end
if @options[:one_datastore] or @options[:one_datastore_cluster]
sched['SCHED_DS_REQUIREMENTS'] = ''
if @options[:one_datastore]
sched['SCHED_DS_REQUIREMENTS'] << "ID=\"#{@options[:one_datastore]}\""
end
if @options[:one_datastore] and @options[:one_datastore_cluster]
sched['SCHED_DS_REQUIREMENTS'] << ' | '
end
if @options[:one_datastore_cluster]
sched['SCHED_DS_REQUIREMENTS'] << "CLUSTER_ID=\"#{@options[:one_datastore_cluster]}\""
end
vmt.add_element('//VMTEMPLATE', sched)
end
vmt
end
# Translate vCenter Definition to OpenNebula Template
def create_vm_template
vmt = create_base_template
vmt.add_element('//VMTEMPLATE', template_firmware)
# add any notes as the description
if @props['config'][:annotation] && !@props['config'][:annotation].empty?
notes = @props['config'][:annotation]
.gsub('\\', '\\\\')
.gsub('"', '\\"')
vmt.add_element('//VMTEMPLATE', { "DESCRIPTION" => "#{notes}" })
end
vmt = template_scheduling(vmt)
# detect icon
logo = nil
case @props['guest.guestFullName']
when /CentOS/i; logo = 'images/logos/centos.png'
when /Debian/i; logo = 'images/logos/debian.png'
when /Red Hat/i; logo = 'images/logos/redhat.png'
when /Ubuntu/i; logo = 'images/logos/ubuntu.png'
when /Windows XP/i; logo = 'images/logos/windowsxp.png'
when /Windows/i; logo = 'images/logos/windows8.png'
when /Linux/i; logo = 'images/logos/linux.png'
end
vmt.add_element('//VMTEMPLATE', {'LOGO' => logo}) if logo
vmt
end
def ip_version(ip_address)
ip = IPAddr.new(ip_address) rescue nil
return nil if !ip
return 'IP4' if ip.ipv4?
return 'IP6' if ip.ipv6?
end
# Yoinked from StackOverflow question 10262235
def show_wait_spinner(fps=10)
chars = %w[| / - \\]
delay = 1.0/fps
iter = 0
spinner = Thread.new do
while iter do # Keep spinning until told otherwise
print chars[(iter+=1) % chars.length]
sleep delay
print "\b"
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
def next_suffix(suffix)
return 'a' if suffix.empty?
chars = suffix.chars
if chars.last == 'z'
chars.pop
return next_suffix(chars.join) + 'a'
end
chars[-1] = chars.last.succ
chars.join
end
# Runs a command and reports its execution status and output.
#
# @param cmd [String] The command to be executed.
# @param out [Boolean] (optional) Whether to return the output or not.
# @return [Array] Returns an array containing the stdout and status if out is true.
def run_cmd_report(cmd, out=false)
t0 = Time.now
stdout, stderr, status = nil
show_wait_spinner {
stdout, stderr, status = Open3.capture3(cmd)
}
t1 = (Time.now - t0).round(2)
puts !status.success? ? "Failed (#{t1}s)".red : "Success (#{t1}s)".green
if !status.success? and DEBUG
LOGGER[:stderr].puts(" STDERR:")
LOGGER[:stderr].puts(stderr)
LOGGER[:stderr].puts("------------")
end
return stdout, status if out
end
def detect_distro(disk)
print 'Inspecting disk...'
t0 = Time.now
distro_info = {}
inspector_cmd = 'virt-inspector -a '\
"#{disk} "\
'--no-applications --no-icon'
disk_xml = nil
show_wait_spinner {
stdout, _status = Open3.capture2(inspector_cmd)
disk_xml = REXML::Document.new(stdout).root.elements
}
xprefix = '//operatingsystems/operatingsystem'
if !disk_xml[xprefix]
return nil
end
distro_info['distro'] = disk_xml["#{xprefix}/distro"].text
distro_info['name'] = disk_xml["#{xprefix}/name"].text
distro_info['os'] = disk_xml["#{xprefix}/osinfo"].text
if distro_info['distro'] != 'windows'
distro_info['pkg'] = disk_xml["#{xprefix}/package_format"].text
end
distro_info['mounts'] = {}
mounts = disk_xml["#{xprefix}/mountpoints"].select { |d| d.is_a?(REXML::Element) }
mounts.each do |mp|
distro_info['mounts'][mp.text] = mp['dev'] # mountpath is the key, dev is value
end
distro_info['product_name'] = disk_xml["#{xprefix}/product_name"].text
puts "Done (#{(Time.now - t0).round(2)}s)".green
distro_info
end
def detect_context_package(distro)
case distro
when 'rhel8'
c_files = Dir.glob("#{@options[:context]}/one-context*el8*rpm")
when 'rhel9'
c_files = Dir.glob("#{@options[:context]}/one-context*el9*rpm")
when 'debian'
c_files = Dir.glob("#{@options[:context]}/one-context*deb")
when 'alpine'
c_files = Dir.glob("#{@options[:context]}/one-context*apk")
when 'alt'
c_files = Dir.glob("#{@options[:context]}/one-context*alt*rpm")
when 'opensuse'
c_files = Dir.glob("#{@options[:context]}/one-context*suse*rpm")
when 'freebsd'
c_files = Dir.glob("#{@options[:context]}/one-context*txz")
when 'windows'
c_files = Dir.glob("#{@options[:context]}/one-context*msi")
end
if c_files.length == 1
c_files[0]
elsif c_files.length > 1
latest = c_files.max_by { |f| Gem::Version.new(f.match(/(\d+\.\d+\.\d+)\.msi$/)[1])}
latest
else
# download the correct one
return false
end
end
def context_command(disk, osinfo)
# puts "context_command"
cmd = nil
if osinfo['name'] == 'windows'
context_fullpath = detect_context_package('windows')
context_basename = File.basename(context_fullpath)
cmd = 'virt-customize -q'\
" -a #{disk}"\
' --mkdir /Temp'\
" --copy-in #{context_fullpath}:/Temp"\
" --firstboot-command 'msiexec -i c:\\Temp\\#{context_basename} /quiet && del c:\\Temp\\#{context_basename}'"
else
# os gives versions, so check that instead of distro
if osinfo['os'] =~ /^(redhat-based|rhel|ubuntu|debian)/ # start_with any of these
if osinfo['os'].start_with?('redhat-based8') || osinfo['os'].start_with?('rhel8')
context_fullpath = detect_context_package('rhel8')
elsif osinfo['os'].start_with?('redhat-based9') || osinfo['os'].start_with?('rhel9')
context_fullpath = detect_context_package('rhel9')
elsif osinfo['os'].start_with?('ubuntu') || osinfo['os'].start_with?('debian')
context_fullpath = detect_context_package('debian')
end
context_basename = File.basename(context_fullpath)
cmd = 'virt-customize -q'\
" -a #{disk}"\
' --install epel-release'\
" --copy-in #{context_fullpath}:/tmp"\
" --install /tmp/#{context_basename}"\
" --delete /tmp/#{context_basename}"\
" --run-command 'systemctl enable network.service || exit 0'"
fallback_cmd = 'virt-customize -q'\
" -a #{disk}"\
' --firstboot-install epel-release'\
" --copy-in #{context_fullpath}:/tmp"\
" --firstboot-install /tmp/#{context_basename}"\
" --run-command 'systemctl enable network.service || exit 0'"
end
if osinfo['os'].start_with?('alt') || osinfo['os'].start_with?('opensuse')
if osinfo['os'].start_with('alt')
context_fullpath = detect_context_package('alt')
elsif osinfo['os'].start_with('opensuse')
context_fullpath = detect_context_package('opensuse')
end
context_basename = File.basename(context_fullpath)
cmd = 'virt-customize -q'\
" -a #{disk}"\
" --copy-in #{context_fullpath}:/tmp"\
" --install /tmp/#{context_basename}"\
" --delete /tmp/#{context_basename}"
fallback_cmd = 'virt-customize -q'\
" -a #{disk}"\
" --copy-in #{context_fullpath}:/tmp"\
" --firstboot-install /tmp/#{context_basename}"
end
if osinfo['os'].start_with?('freebsd')
# may not mount properly sometimes due to internal fs
context_fullpath = detect_context_package('freebsd')
context_basename = File.basename(context_fullpath)
cmd = 'virt-customize -q'\
" -a #{disk}"\
' --install curl,bash,sudo,base64,ruby,open-vm-tools-nox11'\
" --copy-in #{context_fullpath}:/tmp"\
" --install /tmp/#{context_basename}"\
" --delete /tmp/#{context_basename}"
fallback_cmd = 'virt-customize -q'\
" -a #{disk}"\
' --firstboot-install curl,bash,sudo,base64,ruby,open-vm-tools-nox11'\
" --copy-in #{context_fullpath}:/tmp"\
" --firstboot-install /tmp/#{context_basename}"
end
if osinfo['os'].start_with?('alpine')
puts 'Alpine is not compatible with offline install, please install context manually.'.brown
end
return false if not context_fullpath
end
return cmd, fallback_cmd
end
def get_win_controlset(disk)
cmd = 'virt-win-reg'\
" #{disk}"\
" 'HKLM\\SYSTEM\\Select'"
print 'Checking Windows ControlSet...'
stdout, _status = run_cmd_report(cmd, true)
ccs = stdout.split("\n").find { |s| s.start_with?('"Current"') }.split(':')[1].to_i
ccs
end
def win_context_inject(disk, osinfo)
puts "win_context_inject"
cmd = "guestfish <<_EOF_
add #{disk}
run
mount #{osinfo['mounts']['/']} /
upload #{@options[:virt_tools]}/rhsrvany.exe /rhsrvany.exe
upload #{detect_context_package('windows')} /one-context.msi
_EOF_"
print "Uploading context files to Windows disk..."
puts 'win_context_inject cmd: ' + cmd
run_cmd_report(cmd)
ccs = get_win_controlset(disk)
regfile = File.open("#{@options[:work_dir]}/service.reg", 'w')
regfile.puts("[HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet#{"%03d" % ccs}\\services\\RHSrvAnyContext]")
regfile.puts('"Type"=dword:00000010')
regfile.puts('"Start"=dword:00000002')
regfile.puts('"ErrorControl"=dword:00000001')
regfile.puts('"ImagePath"="c:\\rhsrvany.exe"')
regfile.puts('"DisplayName"="RHSrvAnyContext"')
regfile.puts('"ObjectName"="LocalSystem"')
regfile.puts
regfile.puts("[HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet#{"%03d" % ccs}\\services\\RHSrvAnyContext\\Parameters]")
regfile.puts('"CommandLine"="msiexec -i c:\\one-context.msi"')
regfile.puts('"PWD"="c:\\Temp"')
regfile.flush
regfile.close
cmd = 'virt-win-reg'\
' --merge'\
" #{disk}"\
" #{@options[:work_dir]}/service.reg"
print "Merging service registry entry to install on boot..."
run_cmd_report(cmd)
end
def win_virtio_command(disk)
# requires newer version of virt-customize actually
cmd = 'virt-customize'\
" -a #{disk}"\
" --inject-virtio-win #{@options[:virtio_path]}"
puts 'win_virtio_command cmd: ' + cmd
cmd
end
def qemu_ga_command(disk)
cmd = 'virt-customize'\
" -a #{disk}"\
" --inject-qemu-ga #{@options[:virtio_path]}"
puts 'qemu_ga_command cmd: ' + cmd
cmd
end
def pkg_install_command(disk, pkg)
cmd = 'virt-customize'\
" -a #{disk}"\
" --install #{pkg}"
cmd
end
def install_pkg(disk, pkg)
print "Installing #{pkg}..."
run_cmd_report(pkg_install_command(disk, pkg))
end
def guest_run_cmd(disk, cmd)
cmd = 'guestfish'\
" -a #{disk}"\
' -i'\
" #{cmd}"
_stdout, _stderr, _status = Open3.capture3(cmd)
end
def package_injection(disk, osinfo)
injector_cmd, fallback_cmd = context_command(disk, osinfo)
if !injector_cmd
if osinfo['name'] == 'windows'
win_context_inject(disk, osinfo)
else
puts 'Unsupported guest OS or couldn\'t find context file for context injection. Please install manually.'.brown
end
elsif @options[:skip_context]
print 'Skipping context injection...'
return
else
# Perhaps have a separet function that does a bit more....stuff...
print 'Injecting one-context...'
_stdout, status = run_cmd_report(injector_cmd, true)
if !status.success?
print 'Context injection command appears to have failed. Attempting fallback'.brown
_stdout, status = run_cmd_report(fallback_cmd, true)
if !status.success?
puts 'Context injection fallback command failed somehow, please install context manually.'.red
return
end
print 'Context will install on first boot, you may need to boot it twice.'.brown
end
end
if osinfo['name'] == 'windows' && @options[:virtio_path]
injector_cmd = win_virtio_command(disk)
print 'Injecting VirtIO to Windows...'
run_cmd_report(injector_cmd)
end
if @options[:qemu_ga_win] && osinfo['name'] == 'windows'
injector_cmd = qemu_ga_command(disk)
print 'Injecting QEMU Guest Agent...'
run_cmd_report(injector_cmd)
end
if @options[:qemu_ga_linux] && osinfo['name'] != 'windows'
install_pkg(disk, 'qemu-guest-agent')
end
end
def get_objects(vim, type, properties, folder = nil)
pc = vim.serviceInstance.content.propertyCollector
viewmgr = vim.serviceInstance.content.viewManager
# determine if we need to look in specific folders
if folder
if folder.key?(:datacenter)
rootFolder = vim.serviceInstance.find_datacenter(folder[:datacenter])
if not rootFolder
raise 'Unable to find Datacenter with name '\
"'#{folder[:datacenter]}'."
end
if folder.key?(:cluster)
clusterFolder = rootFolder.find_compute_resource(folder[:cluster])
if not clusterFolder
raise 'Unable to find Cluster with name '\
"'#{folder[:cluster]}' in Datacenter "\
"'#{folder[:datacenter]}'."
end
rootFolder = clusterFolder
end
end
else
rootFolder = vim.serviceInstance.content.rootFolder
end
view = viewmgr.CreateContainerView({
:container => rootFolder,
:type => [type],
:recursive => true
});
filterSpec = RbVmomi::VIM.PropertyFilterSpec(
:objectSet => [
:obj => view,
:skip => true,
:selectSet => [
RbVmomi::VIM.TraversalSpec(
:name => "traverseEntities",
:type => "ContainerView",
:path => "view",
:skip => false
)]
],
:propSet => [
{ :type => type, :pathSet => properties }
]
);
pc.RetrieveProperties(:specSet => [filterSpec])
end
def build_v2v_hybrid_cmd(xml_file)
# virt-v2v
# -i disk
# '/path/to/local/disk'
# -o local
# -os /path/to/working/folder
# -of [qcow2|raw]
command = "#{@options[:v2v_path]} -v --machine-readable"\
' -i libvirtxml'\
" #{xml_file}"\
' -o local'\
' --root first'\
" -os #{@options[:work_dir]}/conversions/"\
" -of #{@options[:format]}"
command
end
def build_v2v_vc_cmd
# virt-v2v
# -ic 'vpx://UserName@vCenter.Host.FQDN
# /Datacenter/Cluster/Host?no_verify=1'
# -ip password_file.txt ### Should be a 0600 file with only the password, no newline
# 'virtual-machine-name'
# -o local
# -os /path/to/working/folder
# -of [qcow2|raw]
dc,cluster,host = nil
pobj = @props['runtime.host']
while dc.nil? || cluster.nil? || host.nil?
host = pobj if pobj.class == RbVmomi::VIM::HostSystem
cluster = pobj if pobj.class == RbVmomi::VIM::ClusterComputeResource
cluster = false if pobj.class == RbVmomi::VIM::ComputeResource
dc = pobj if pobj.class == RbVmomi::VIM::Datacenter
pobj = pobj[:parent]
if pobj.nil?
raise "Unable to find Host, Cluster, and Datacenter of VM"
end
end
if cluster == false
url = "vpx://#{CGI::escape(@options[:vuser])}@#{@options[:vcenter]}"\
"/#{dc[:name]}/#{host[:name]}?no_verify=1"
else
url = "vpx://#{CGI::escape(@options[:vuser])}@#{@options[:vcenter]}"\
"/#{dc[:name]}/#{cluster[:name]}/#{host[:name]}?no_verify=1"
end
command = "#{@options[:v2v_path]} -v --machine-readable"\
" -ic #{url}"\
" -ip #{@options[:work_dir]}/vpassfile"\
' -o local'\
" -os #{@options[:work_dir]}/conversions/"\
" -of #{@options[:format]}"\
" '#{@props['name']}'"
command
end
def build_v2v_esx_cmd
# virt-v2v
# -i vmx
# -ic 'ssh://UserName@ESXI.host.fqdn
# /vmfs/volumes/datastore/vmpath/vmfile.vmx
# -ip password_file.txt ### Should be a 0600 file with only the password, no newline
# -o local
# -os /path/to/working/folder
# -of [qcow2|raw]
# [datastore1] example-vm/example-vm.vmx
ds_name, vmx_relpath = @props['config'][:files][:vmPathName].split('] ', 2)
ds_name.delete!('[')
# /vmfs/volumes/65de2b62-8488ae37-d55b-3cecefcef5a6
ds_path = @props['config'][:datastoreUrl].find { |ds| ds[:name] == ds_name }
vmx_fullpath = "#{ds_path[:url]}/#{vmx_relpath}"
url = "ssh://#{CGI::escape(@options[:esxi_user])}@#{@options[:esxi_ip]}"\
"/#{vmx_fullpath}"
command = "#{@options[:v2v_path]} -v --machine-readable"\
' -i vmx'\
' -it ssh'\
" #{url}"\
" -ip #{@options[:work_dir]}/esxpassfile"\
' -o local'\
" -os #{@options[:work_dir]}/conversions/"\
" -of #{@options[:format]}"
command
end
def build_v2v_vddk_cmd
# openssl s_client -connect 147.75.45.11:443 </dev/null 2>/dev/null |
# openssl x509 -in /dev/stdin -fingerprint -sha1 -noout 2>/dev/null
# virt-v2v
# -ic 'vpx://UserName@vCenter.Host.FQDN/Datacenter/Cluster/Host?no_verify=1'
# -ip password_file.txt ### Should be a 0600 file with only the password, no newline
# -it vddk
# -io vddk-libdir=/path/to/vmware-vix-disklib-distrib
# -io vddk-thumbprint=xx:xx:xx:xx... # gather this