Class: VCenterDriver::VcImporter

Inherits:
Object
  • Object
show all
Defined in:
lib/vcenter_importer.rb

Overview

Class VcImporter

Defined Under Namespace

Classes: Raction

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(one_client, vi_client) ⇒ VcImporter

Builds a vCenter importer

Parameters:



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/vcenter_importer.rb', line 58

def initialize(one_client, vi_client)
    @vi_client  = vi_client
    @one_client = one_client

    @list = {}

    @info = {}
    @info[:clusters] = {}
    @info[:success] = []
    @info[:error]   = []
end

Instance Attribute Details

#listObject

Returns the value of attribute list.



45
46
47
# File 'lib/vcenter_importer.rb', line 45

def list
  @list
end

Class Method Details

.import_clusters(con_ops, options) ⇒ Object



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
# File 'lib/vcenter_importer.rb', line 240

def self.import_clusters(con_ops, options)
    begin
        STDOUT.print "\nConnecting to vCenter: #{options[:vcenter]}..."

        use_defaults = options.key?(:defaults)

        vi_client = VCenterDriver::VIClient.new(con_ops)

        STDOUT.print "done!\n\n"

        STDOUT.print 'Exploring vCenter resources...'

        dc_folder = VCenterDriver::DatacenterFolder.new(vi_client)

        vcenter_instance_name = vi_client.vim.host

        # OpenNebula's ClusterPool
        cpool = VCenterDriver::VIHelper
                .one_pool(OpenNebula::ClusterPool, false)
        if cpool.respond_to?(:message)
            raise "Could not get OpenNebula ClusterPool: \
                  #{cpool.message}"
        end

        cluster_list = {}
        cpool.each do |c|
            name = VCenterDriver::VcImporter.sanitize(
                c['NAME']
            )
            cluster_list[c['ID']] = name if c['ID'].to_i != 0
        end

        # Get OpenNebula's host pool
        hpool = VCenterDriver::VIHelper
                .one_pool(OpenNebula::HostPool, false)
        if hpool.respond_to?(:message)
            raise "Could not get OpenNebula HostPool: #{hpool.message}"
        end

        rs = dc_folder.get_unimported_hosts(hpool,
                                            vcenter_instance_name)

        # Select just cluster with this reference
        if options[:cluster_ref]
            rs.each do |_, clusters|
                clusters.select! do |c|
                    c[:cluster_ref] == options[:cluster_ref]
                end
            end
        end

        STDOUT.print "done!\n\n"

        rs.each do |dc, clusters|
            if !use_defaults
                # rubocop:disable Layout/LineLength
                STDOUT.print "Do you want to process datacenter #{dc} (y/[n])? "
                # rubocop:enable Layout/LineLength
                next if STDIN.gets.strip.downcase != 'y'
            end

            if clusters.empty?
                STDOUT.puts "\n    No new clusters found in #{dc}..."
                next
            end

            clusters.each do |cluster|
                one_cluster_id = nil
                rpool = nil

                # Handle OpenNebula cluster creation or reuse
                if !use_defaults
                    # rubocop:disable Layout/LineLength
                    STDOUT.print "\n  * vCenter cluster found:\n"\
                                 "      - Name       : \e[92m#{cluster[:simple_name]}\e[39m\n"\
                                 "      - Location   : #{cluster[:cluster_location]}\n"\
                                 '    Import cluster (y/[n])? '
                    # rubocop:enable Layout/LineLength
                    next if STDIN.gets.strip.downcase != 'y'

                    if !cluster_list.empty?
                        # rubocop:disable Layout/LineLength
                        STDOUT.print "\n    In which OpenNebula cluster do you want the vCenter cluster to be included?\n "
                        # rubocop:enable Layout/LineLength

                        cluster_list_str = "\n"
                        cluster_list.each do |key, value|
                            name = VCenterDriver::VcImporter.sanitize(
                                value
                            )
                            cluster_list_str << "      - \e[94mID: " \
                                             << key \
                                             << "\e[39m - NAME: " \
                                             << name << "\n"
                        end

                        STDOUT.print "\n    #{cluster_list_str}"
                        # rubocop:disable Layout/LineLength
                        STDOUT.print "\n    Specify the ID of the cluster or press Enter if you want OpenNebula to create a new cluster for you: "
                        # rubocop:enable Layout/LineLength
                        answer = STDIN.gets.strip

                        if !answer.empty?
                            one_cluster_id = answer
                        end
                    end
                end

                cluster_name = VCenterDriver::VcImporter.sanitize(
                    cluster[:cluster_name]
                )

                # Check if the OpenNebula Cluster exists, and reuse it
                one_cluster_id ||= cluster_list
                                   .key(cluster_name)

                if !one_cluster_id
                    one_cluster = VCenterDriver::VIHelper
                                  .new_one_item(OpenNebula::Cluster)
                    rc = one_cluster
                         .allocate(cluster_name.to_s)
                    if ::OpenNebula.is_error?(rc)
                        # rubocop:disable Layout/LineLength
                        STDOUT.puts "    Error creating OpenNebula cluster: #{rc.message}\n"
                        # rubocop:enable Layout/LineLength
                        next
                    end
                    one_cluster_id = one_cluster.id
                end

                # Generate host template and allocate new host
                one_host = VCenterDriver::ClusterComputeResource
                           .to_one(cluster,
                                   con_ops,
                                   rpool,
                                   one_cluster_id)
                # rubocop:disable Layout/LineLength
                STDOUT.puts "\n    OpenNebula host \e[92m#{cluster_name}\e[39m with"\
                            " ID \e[94m#{one_host.id}\e[39m successfully created."
                STDOUT.puts
                # rubocop:enable Layout/LineLength
            end
        end
    rescue Interrupt
        puts "\n"
        exit 0 # Ctrl+C
    rescue StandardError => e
        error_msg = "\nError: #{e.message}\n"
        error_msg << "#{e.backtrace}\n" \
                      if VCenterDriver::CONFIG[:debug_information]
        STDERR.puts error_msg
        raise_error = true
    ensure
        vi_client.close_connection if vi_client
        raise if raise_error
    end
end

.new_child(one_client, vi_client, type) ⇒ VCImporter

Allow us to spawn a specific importer child

Parameters:

Returns:

  • (VCImporter)

    the vCenter importer that will handle any operation



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/vcenter_importer.rb', line 80

def self.new_child(one_client, vi_client, type)
    case type.downcase
    when 'hosts'
        VCenterDriver::VcImporter.new(one_client, vi_client)
    when 'datastores'
        VCenterDriver::DsImporter.new(one_client, vi_client)
    when 'templates'
        VCenterDriver::VmImporter.new(one_client, vi_client)
    when 'networks'
        VCenterDriver::NetImporter.new(one_client, vi_client)
    when 'images'
        VCenterDriver::ImageImporter.new(one_client, vi_client)
    else
        raise 'unknown object type'
    end
end

.sanitize(text) ⇒ Object



398
399
400
401
402
403
404
# File 'lib/vcenter_importer.rb', line 398

def self.sanitize(text)
    bad_chars = ['|']
    bad_chars.each do |bad_char|
        text.gsub!(bad_char, '_')
    end
    text
end

Instance Method Details

#get_indexes(args = nil) ⇒ Object

Parse arguments usually given by command line interface with the purpose of retrieve a list of selected indexes by the users.

@ return [Aarray] the list of selected indexes

Parameters:

  • args (nil | Array | String) (defaults to: nil)

    range, names or nil



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
# File 'lib/vcenter_importer.rb', line 144

def get_indexes(args = nil)
    raise 'the list is empty' if list_empty?

    list = @list.values[0]
    indexes = ''
    keys = list.keys

    return keys.join(',') unless args

    if args.include?('..')
        range = Range.new(*args.split('..').map(&:to_i))

        if range.first != range.last
            range.each do |i|
                indexes << "#{keys[i]}, "
            end

            return indexes
        end
    end

    if args !~ /\D/
        ind = args.to_i

        return keys[ind]
    end

    args
end

#one_strString

Returns the object type of the importer.

Returns:

  • (String)

    the object type of the importer



100
101
102
103
104
# File 'lib/vcenter_importer.rb', line 100

def one_str
    return @one_class.to_s.split('::').last if @one_class

    'OpenNebula object'
end

#outputObject

Importer return value

@ return [Hash=>[[]] , :error => {}



131
132
133
# File 'lib/vcenter_importer.rb', line 131

def output
    { :success => @info[:success], :error => @info[:error] }
end

#process_import(indexes, opts = {}, &block) ⇒ Object

This method handles all the importation. Will be in charge of call the specific import operation of the specific importer.

points to the selected object of the list. In sunstone context this options will contain every index associated to his own resource opt

Example: => {:linked_clone: ‘0’, :copy: ‘0’…

@ return [Hash] the list of unimported resources

Parameters:

  • indexes (Array)

    Array with all the indexes that

  • opts (Hash) (defaults to: {})

    Hash with the options.



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
# File 'lib/vcenter_importer.rb', line 209

def process_import(indexes, opts = {}, &block)
    raise 'the list is empty' if list_empty?

    indexes = indexes.gsub(/\s*\,\s*/, ',').strip.split(',')

    indexes.each do |index|
        begin
            @rollback = []
            @info[index] = {}

            selected = get_element(index)

            if block_given?
                @info[index][:opts] = block.call(selected)
            elsif opts[index]
                @info[index][:opts] = opts[index]
            else
                @info[index][:opts] = defaults
            end

            # import the object
            @info[:success] << import(selected)
        rescue StandardError => e
            @info[:error] << { index => e.message }
            @info[index][:e] = e

            apply_rollback
        end
    end
end

#retrieve_resources(opts = {}) ⇒ Object

Wrapper of get_list, needed for clean the cache get_list populates @ref_hash cache at vCenter driver level, with this function you still can reuse the importer.

@ return [Hash] the list of unimported resources

Parameters:

  • opts (Hash) (defaults to: {})

    Hash with the needed arguments



183
184
185
186
187
188
189
190
191
# File 'lib/vcenter_importer.rb', line 183

def retrieve_resources(opts = {})
    VCenterDriver::VIHelper.clean_ref_hash

    list = get_list(opts)

    @defaults = opts[:config] if opts[:config]

    list
end

#stdoutObject

Prints feedback of the realized import operations throught STDOUT



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/vcenter_importer.rb', line 110

def stdout
    @info[:success].each do |o|
        o[:id].each do |id|
            puts "ID: #{id}"
        end
    end

    puts

    @info[:error].each do |error|
        index = error.first[0]
        e = @info[index][:e]
        puts "Error: Couldn't import #{index} due to #{e.message}!"
        puts
    end
end