Revision e6a57b0f

View differences:

src/sunstone/routes/vcenter.rb
88 88
            error 404, error.to_json
89 89
        end
90 90

  
91
        rs = dc_folder.get_unimported_hosts(hpool)
91
        rs = dc_folder.get_unimported_hosts(hpool,vcenter_client.vim.host)
92 92
        [200, rs.to_json]
93 93
    rescue Exception => e
94 94
        logger.error("[vCenter] " + e.message)
......
110 110
            error 404, error.to_json
111 111
        end
112 112

  
113
        templates = dc_folder.get_unimported_templates(vcenter_client, tpool)
113
        templates = dc_folder.get_unimported_templates(vcenter_client, tpool, vcenter_client.vim.host)
114 114

  
115 115
        if templates.nil?
116 116
            msg = "No datacenter found"
......
131 131
    begin
132 132
        t = {}
133 133
        t[:one] = ""
134
        template_copy_ref = nil
135
        template = nil
136
        append = true
137
        lc_error = nil
134 138

  
135
        template = VCenterDriver::VirtualMachine.new_from_ref(params[:vcenter_ref], vcenter_client)
139
        ref = params[:vcenter_ref]
136 140

  
141
        if !ref || ref.empty?
142
            msg = "No template ref specified"
143
            logger.error("[vCenter] " + msg)
144
            error = Error.new(msg)
145
            error 404, error.to_json
146
        end
147

  
148
        template = VCenterDriver::Template.new_from_ref(ref, vcenter_client)
137 149
        vc_uuid = vcenter_client.vim.serviceContent.about.instanceUuid
138 150
        dpool = VCenterDriver::VIHelper.one_pool(OpenNebula::DatastorePool)
139 151
        ipool = VCenterDriver::VIHelper.one_pool(OpenNebula::ImagePool)
140 152
        npool = VCenterDriver::VIHelper.one_pool(OpenNebula::VirtualNetworkPool)
141 153

  
154
        # POST params
155
        if @request_body && !@request_body.empty?
156
            body_hash = JSON.parse(@request_body)
157
            use_linked_clones = body_hash['use_linked_clones'] || false
158
            create_copy = body_hash['create_copy'] || false
159
            template_name = body_hash['template_name'] || ""
160

  
161
            if !use_linked_clones && (create_copy || !template_name.empty?)
162
                msg = "Should not set create template copy or template copy name if not using linked clones"
163
                logger.error("[vCenter] " + msg)
164
                error = Error.new(msg)
165
                error 403, error.to_json
166
            end
167

  
168
            if use_linked_clones && !create_copy && !template_name.empty?
169
                msg = "Should not set template copy name if create template copy hasn't been selected"
170
                logger.error("[vCenter] " + msg)
171
                error = Error.new(msg)
172
                error 403, error.to_json
173
            end
174

  
175
            if create_copy
176

  
177
                lc_error, template_copy_ref = template.create_template_copy(template_name)
178

  
179
                if template_copy_ref
180

  
181
                    template = VCenterDriver::Template.new_from_ref(template_copy_ref, vi_client)
182

  
183
                    one_template = VCenterDriver::Template.get_xml_template(template, vc_uuid, vi_client, vcenter_client.vim.host)
184

  
185
                    if one_template
186

  
187
                        lc_error, use_lc = template.create_delta_disks
188
                        if !lc_error
189
                            one_template[:one] << "\nVCENTER_LINKED_CLONES=\"YES\"\n"
190
                            t = one_template
191
                            append = false # t[:one] replaces the current template
192
                        end
193
                    else
194
                        lc_error = "Could not obtain the info from the template's copy"
195
                        template.delete_template if template_copy_ref
196
                    end
197
                end
198

  
199
            else
200
                lc_error, use_lc = template.create_delta_disks
201
                if !lc_error
202
                    append = true
203
                    t[:one] << "\nVCENTER_LINKED_CLONES=\"YES\"\n" if use_lc
204
                end
205
            end
206
        end
207

  
142 208
        # Create images or get disks information for template
143 209
        error, template_disks = template.import_vcenter_disks(vc_uuid, dpool, ipool)
144 210

  
145 211
        if !error.empty?
212
            append = false
213
            template.delete_template if template_copy_ref
146 214
            msg = error
147 215
            logger.error("[vCenter] " + msg)
148 216
            error = Error.new(msg)
......
155 223
        error, template_nics = template.import_vcenter_nics(vc_uuid, npool)
156 224

  
157 225
        if !error.empty?
226
            append = false
227
            template.delete_template if template_copy_ref
158 228
            msg = error
159 229
            logger.error("[vCenter] " + msg)
160 230
            error = Error.new(msg)
......
163 233

  
164 234
        t[:one] << template_nics
165 235

  
236
        t[:lc_error] = lc_error
237
        t[:append] = append
238

  
166 239
        [200, t.to_json]
167 240
    rescue Exception => e
241
        template.delete_template if template_copy_ref
168 242
        logger.error("[vCenter] " + e.message)
169 243
        error = Error.new(e.message)
170 244
        error 403, error.to_json
......
184 258
            error 404, error.to_json
185 259
        end
186 260

  
187
        networks = dc_folder.get_unimported_networks(npool)
261
        networks = dc_folder.get_unimported_networks(npool,vcenter_client.vim.host)
188 262

  
189 263
        if networks.nil?
190 264
            msg = "No datacenter found"
......
231 305
    begin
232 306
        dc_folder = VCenterDriver::DatacenterFolder.new(vcenter_client)
233 307

  
234
        hpool = VCenterDriver::VIHelper.one_pool(OpenNebula::DatastorePool, false)
308
        dpool = VCenterDriver::VIHelper.one_pool(OpenNebula::DatastorePool, false)
309

  
310
        if dpool.respond_to?(:message)
311
            msg = "Could not get OpenNebula DatastorePool: #{dpool.message}"
312
            logger.error("[vCenter] " + msg)
313
            error = Error.new(msg)
314
            error 404, error.to_json
315
        end
316

  
317

  
318
        hpool = VCenterDriver::VIHelper.one_pool(OpenNebula::HostPool, false)
235 319

  
236 320
        if hpool.respond_to?(:message)
237
            msg = "Could not get OpenNebula DatastorePool: #{hpool.message}"
321
            msg = "Could not get OpenNebula HostPool: #{hpool.message}"
238 322
            logger.error("[vCenter] " + msg)
239 323
            error = Error.new(msg)
240 324
            error 404, error.to_json
241 325
        end
242 326

  
243
        datastores = dc_folder.get_unimported_datastores(hpool)
327

  
328
        datastores = dc_folder.get_unimported_datastores(dpool, vcenter_client.vim.host, hpool)
244 329
        if datastores.nil?
245 330
            msg = "No datacenter found"
246 331
            logger.error("[vCenter] " + msg)
src/vmm_mad/remotes/lib/vcenter_driver/datacenter.rb
1 1
module VCenterDriver
2

  
2
require 'set'
3 3
class DatacenterFolder
4 4
    attr_accessor :items
5 5

  
......
38 38
        @vi_client.vim.serviceContent.about.instanceUuid
39 39
    end
40 40

  
41
    def get_vcenter_instance_name
42
        @vi_client.vim.serviceContent.setting.setting.select{|set| set.key == 'VirtualCenter.InstanceName'}.first.value rescue nil
43
    end
44

  
45 41
    def get_vcenter_api_version
46 42
        @vi_client.vim.serviceContent.about.apiVersion
47 43
    end
48 44

  
49
    def get_clusters
50

  
51
        clusters = {}
52

  
53
        vcenter_uuid = get_vcenter_instance_uuid
54

  
55
        pool = VCenterDriver::VIHelper.one_pool(OpenNebula::HostPool, false)
56
        if pool.respond_to?(:message)
57
            raise "Could not get OpenNebula Pool: #{pool.message}"
58
        end
59

  
60
        fetch! if @items.empty? #Get datacenters
61

  
62
        # Add datacenter to hash and store in an array all clusters
63
        @items.values.each do |dc|
64
            dc_name = dc.item.name
65
            clusters[dc_name] = []
66

  
67
            host_folder = dc.host_folder
68
            host_folder.fetch_clusters!
69

  
70
            host_folder.items.values.each do |ccr|
71
                cluster = {}
72
                cluster[:ref]  = ccr['_ref']
73
                cluster[:name] = ccr['name']
74
                attribute = "TEMPLATE/VCENTER_CCR_REF"
75
                one_host = VCenterDriver::VIHelper.find_by_ref(OpenNebula::HostPool,
76
                                                               attribute,
77
                                                               ccr['_ref'],
78
                                                               vcenter_uuid,
79
                                                               pool)
80

  
81
                next if one_host.nil? #Cluster hasn't been imported'
82

  
83
                cluster[:host_id] = one_host['ID']
84
                clusters[dc_name] << cluster
85
            end
86
        end
87

  
88
        clusters
89
    end
90

  
91
    def get_unimported_hosts(hpool)
45
    def get_unimported_hosts(hpool, vcenter_instance_name)
92 46
        host_objects = {}
93 47

  
94 48
        vcenter_uuid = get_vcenter_instance_uuid
......
116 70
                rpools = cluster.get_resource_pool_list.select {|rp| !rp[:name].empty?}
117 71

  
118 72
                host_info = {}
119
                host_info[:cluster_name]     = ccr['name'].tr(" ", "_")
73
                cluster_name = "[#{vcenter_instance_name} - #{dc_name}] #{ccr['name'].tr(" ", "_")}"
74
                host_info[:cluster_name]     = cluster_name
120 75
                host_info[:cluster_ref]      = ccr['_ref']
121 76
                host_info[:vcenter_uuid]     = vcenter_uuid
122 77
                host_info[:vcenter_version]  = vcenter_version
......
129 84
        return host_objects
130 85
    end
131 86

  
132
    def get_unimported_datastores(hpool)
87
    def get_unimported_datastores(dpool, vcenter_instance_name, hpool)
88

  
133 89
        ds_objects = {}
134 90

  
135 91
        vcenter_uuid = get_vcenter_instance_uuid
136 92

  
137
        vcenter_instance_name = get_vcenter_instance_name
138

  
139 93
        fetch! if @items.empty? #Get datacenters
140 94

  
141
        one_clusters = get_clusters
95
        one_clusters = {}
142 96

  
143 97
        @items.values.each do |dc|
144 98
            dc_name = dc.item.name
99

  
100
            one_clusters[dc_name] = []
101

  
102
            host_folder = dc.host_folder
103
            host_folder.fetch_clusters!
104

  
105
            host_folder.items.values.each do |ccr|
106
                cluster = {}
107
                cluster[:ref]  = ccr['_ref']
108
                cluster[:name] = ccr['name']
109
                attribute = "TEMPLATE/VCENTER_CCR_REF"
110
                one_host = VCenterDriver::VIHelper.find_by_ref(OpenNebula::HostPool,
111
                                                               attribute,
112
                                                               ccr['_ref'],
113
                                                               vcenter_uuid,
114
                                                               hpool)
115

  
116
                if !!one_host
117
                    one_clusters[:host_id] = one_host['ID']
118
                    one_clusters[dc_name] << cluster
119
                end
120
            end
121

  
145 122
            next if one_clusters[dc_name].empty? #No clusters imported, continue
146 123
            ds_objects[dc_name] = []
147 124

  
......
155 132
                    clusters_in_ds = {}
156 133

  
157 134
                    hosts_in_ds.each do |host|
158
                        if !clusters_in_ds[host.key.parent._ref.to_s]
159
                            clusters_in_ds[host.key.parent._ref.to_s] = host.key.parent.name
135
                        cluster_ref = host.key.parent._ref
136
                        if !clusters_in_ds[cluster_ref]
137
                            clusters_in_ds[cluster_ref] = host.key.parent.name
160 138
                        end
161 139
                    end
162 140

  
163 141
                    clusters_in_ds.each do |ccr_ref, ccr_name|
164
                        already_image_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "IMAGE_DS", hpool)
142
                        already_image_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "IMAGE_DS", dpool)
165 143

  
166 144
                        if !already_image_ds
167 145
                            object = ds.to_one_template(one_clusters[dc_name], ccr_ref, ccr_name, "IMAGE_DS", vcenter_uuid, vcenter_instance_name, dc_name)
168 146
                            ds_objects[dc_name] << object if !object.nil?
169 147
                        end
170 148

  
171
                        already_system_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "SYSTEM_DS", hpool)
149
                        already_system_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "SYSTEM_DS", dpool)
172 150

  
173 151
                        if !already_system_ds
174 152
                            object = ds.to_one_template(one_clusters[dc_name], ccr_ref, ccr_name, "SYSTEM_DS", vcenter_uuid, vcenter_instance_name, dc_name)
......
184 162
                    ds_in_spod.each do |sp_ds|
185 163
                        hosts_in_ds = sp_ds.host
186 164
                        hosts_in_ds.each do |host|
187
                            if !clusters_in_spod[host.key.parent._ref.to_s]
188
                                clusters_in_spod[host.key.parent._ref.to_s] = host.key.parent.name
165
                            cluster_ref = host.key.parent._ref
166
                            if !clusters_in_spod[cluster_ref]
167
                                clusters_in_spod[cluster_ref] = host.key.parent.name
189 168
                            end
190 169
                        end
191 170
                    end
192 171

  
193 172
                    clusters_in_spod.each do |ccr_ref, ccr_name|
194
                        already_system_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "SYSTEM_DS", hpool)
173
                        already_system_ds = VCenterDriver::Storage.exists_one_by_ref_ccr_and_type?(ds["_ref"], ccr_ref, vcenter_uuid, "SYSTEM_DS", dpool)
195 174

  
196 175
                        if !already_system_ds
197 176
                            object = ds.to_one_template(one_clusters[dc_name], ccr_ref, ccr_name, "SYSTEM_DS", vcenter_uuid, vcenter_instance_name, dc_name)
......
201 180
                end
202 181
            end
203 182
        end
204

  
205 183
        ds_objects
206 184
    end
207 185

  
......
209 187
        template_objects = {}
210 188
        vcenter_uuid = get_vcenter_instance_uuid
211 189

  
190
        vcenter_instance_name = vi_client.vim.host
191

  
212 192
        fetch! if @items.empty? #Get datacenters
213 193

  
214 194
        @items.values.each do |dc|
215

  
195
            rp_cache = {}
216 196
            dc_name = dc.item.name
217 197
            template_objects[dc_name] = []
218 198

  
219
            #Get templates defined in a datacenter
220
            vm_folder = dc.vm_folder
221
            vm_folder.fetch_templates!
222
            vm_folder.items.values.each do |template|
199

  
200
            view = vi_client.vim.serviceContent.viewManager.CreateContainerView({
201
                container: dc.item.vmFolder,
202
                type:      ['VirtualMachine'],
203
                recursive: true
204
            })
205

  
206
            pc = vi_client.vim.serviceContent.propertyCollector
207

  
208
            filterSpec = RbVmomi::VIM.PropertyFilterSpec(
209
            :objectSet => [
210
                :obj => view,
211
                :skip => true,
212
                :selectSet => [
213
                RbVmomi::VIM.TraversalSpec(
214
                    :name => 'traverseEntities',
215
                    :type => 'ContainerView',
216
                    :path => 'view',
217
                    :skip => false
218
                )
219
                ]
220
            ],
221
            :propSet => [
222
                { :type => 'VirtualMachine', :pathSet => ['config.template'] }
223
            ]
224
            )
225

  
226
            result = pc.RetrieveProperties(:specSet => [filterSpec])
227

  
228
            vms = {}
229
                result.each do |r|
230
                vms[r.obj._ref] = r.to_hash if r.obj.is_a?(RbVmomi::VIM::VirtualMachine)
231
            end
232
            templates = []
233
            vms.each do |ref,value|
234
                if value["config.template"]
235
                    templates << VCenterDriver::Template.new_from_ref(ref, vi_client)
236
                end
237
            end
238

  
239
            view.DestroyView # Destroy the view
240

  
241

  
242
            templates.each do |template|
243

  
223 244
                one_template = VCenterDriver::VIHelper.find_by_ref(OpenNebula::TemplatePool,
224 245
                                                                   "TEMPLATE/VCENTER_TEMPLATE_REF",
225 246
                                                                   template['_ref'],
226 247
                                                                   vcenter_uuid,
227 248
                                                                   tpool)
228
                next if one_template #If the template has been already imported
229 249

  
230
                template_ccr  = template['runtime.host.parent']
231

  
232
                # Check if template has nics or disks to be imported later
233
                has_nics_and_disks = false
250
                next if one_template #If the template has been already imported
234 251

  
235
                template["config.hardware.device"].each do |device|
236
                    if VCenterDriver::Storage.is_disk_or_iso?(device)
237
                        has_nics_and_disks = true
238
                        break
239
                    end
252
                one_template = VCenterDriver::Template.get_xml_template(template, vcenter_uuid, vi_client, vcenter_instance_name, dc_name, rp_cache)
240 253

  
241
                    if VCenterDriver::Network.is_nic?(device)
242
                        has_nics_and_disks = true
243
                        break
244
                    end
245
                end
254
                template_objects[dc_name] << one_template if !!one_template
255
            end
256
        end
246 257

  
247
                #Get resource pools
248
                rp_cache = {}
249
                if !rp_cache[template_ccr.name.to_s]
250
                    tmp_cluster = VCenterDriver::ClusterComputeResource.new_from_ref(template_ccr._ref, vi_client)
251
                    rp_list = tmp_cluster.get_resource_pool_list
252
                    rp = ""
253
                    if !rp_list.empty?
254
                        rp_name_list = []
255
                        rp_list.each do |rp_hash|
256
                            rp_name_list << rp_hash[:name]
257
                        end
258
                        rp =  "O|list|Which resource pool you want this VM to run in? "
259
                        rp << "|#{rp_name_list.join(",")}" #List of RP
260
                        rp << "|#{rp_name_list.first}" #Default RP
261
                    end
262
                    rp_cache[template_ccr.name.to_s] = rp
263
                end
264
                rp = rp_cache[template_ccr.name.to_s]
265

  
266
                object = template.to_one_template(template,
267
                                                  has_nics_and_disks,
268
                                                  rp,
269
                                                  rp_list,
270
                                                  vcenter_uuid)
271

  
272
                template_objects[dc_name] << object if !object.nil?
273
            end #template loop
274
        end #datacenter loop
275
        return template_objects
258
        template_objects
276 259
    end
277 260

  
278
    def get_unimported_networks(npool)
261
    def get_unimported_networks(npool,vcenter_instance_name)
279 262

  
280 263
        network_objects = {}
281 264
        vcenter_uuid = get_vcenter_instance_uuid
282 265

  
266
        pc = @vi_client.vim.serviceContent.propertyCollector
267

  
268
        #Get all port groups and distributed port groups in vcenter instance
269
        view = @vi_client.vim.serviceContent.viewManager.CreateContainerView({
270
                container: @vi_client.vim.rootFolder,
271
                type:      ['Network','DistributedVirtualPortgroup'],
272
                recursive: true
273
        })
274

  
275
        filterSpec = RbVmomi::VIM.PropertyFilterSpec(
276
            :objectSet => [
277
                :obj => view,
278
                :skip => true,
279
                :selectSet => [
280
                RbVmomi::VIM.TraversalSpec(
281
                    :name => 'traverseEntities',
282
                    :type => 'ContainerView',
283
                    :path => 'view',
284
                    :skip => false
285
                )
286
                ]
287
            ],
288
            :propSet => [
289
                { :type => 'Network', :pathSet => ['name'] },
290
                { :type => 'DistributedVirtualPortgroup', :pathSet => ['name'] }
291
            ]
292
        )
293

  
294
        result = pc.RetrieveProperties(:specSet => [filterSpec])
295

  
296
        networks = {}
297
            result.each do |r|
298
            networks[r.obj._ref] = r.to_hash if r.obj.is_a?(RbVmomi::VIM::DistributedVirtualPortgroup) || r.obj.is_a?(RbVmomi::VIM::Network)
299
            networks[r.obj._ref][:network_type] = r.obj.is_a?(RbVmomi::VIM::DistributedVirtualPortgroup) ? "Distributed Port Group" : "Port Group"
300
        end
301

  
302
        view.DestroyView # Destroy the view
303

  
283 304
        fetch! if @items.empty? #Get datacenters
284 305

  
285 306
        @items.values.each do |dc|
......
287 308
            dc_name = dc.item.name
288 309
            network_objects[dc_name] = []
289 310

  
290
            #Get networks defined in a datacenter
291
            network_folder = dc.network_folder
292
            network_folder.fetch!
293
            network_folder.items.values.each do |network|
311
            view = @vi_client.vim.serviceContent.viewManager.CreateContainerView({
312
                container: dc.item,
313
                type:      ['ClusterComputeResource'],
314
                recursive: true
315
            })
316

  
317
            filterSpec = RbVmomi::VIM.PropertyFilterSpec(
318
                :objectSet => [
319
                    :obj => view,
320
                    :skip => true,
321
                    :selectSet => [
322
                    RbVmomi::VIM.TraversalSpec(
323
                        :name => 'traverseEntities',
324
                        :type => 'ContainerView',
325
                        :path => 'view',
326
                        :skip => false
327
                    )
328
                    ]
329
                ],
330
                :propSet => [
331
                    { :type => 'ClusterComputeResource', :pathSet => ['name','network'] }
332
                ]
333
            )
334

  
335
            result = pc.RetrieveProperties(:specSet => [filterSpec])
336

  
337
            clusters = {}
338
                result.each do |r|
339
                clusters[r.obj._ref] = r.to_hash if r.obj.is_a?(RbVmomi::VIM::ClusterComputeResource)
340
            end
341

  
342
            view.DestroyView # Destroy the view
343

  
344
            clusters.each do |ref, info|
294 345

  
295
                next if network.instance_of? VCenterDriver::DistributedVirtualSwitch
346
                network_obj = info['network']
296 347

  
297
                one_network = VCenterDriver::VIHelper.find_by_ref(OpenNebula::VirtualNetworkPool,
298
                                                                  "TEMPLATE/VCENTER_NET_REF",
299
                                                                  network['_ref'],
300
                                                                  vcenter_uuid,
301
                                                                  npool)
302
                next if one_network #If the network has been already imported
348
                network_obj.each do |n|
349
                    network_ref  = n._ref
350
                    network_name = networks[network_ref]['name']
351
                    network_type = networks[network_ref][:network_type]
303 352

  
304
                network_name = network['name']
305
                network_ref  = network['_ref']
353
                    one_network = VCenterDriver::VIHelper.find_by_ref(OpenNebula::VirtualNetworkPool,
354
                                                                    "TEMPLATE/VCENTER_NET_REF",
355
                                                                    network_ref,
356
                                                                    vcenter_uuid,
357
                                                                    npool)
358
                    next if one_network #If the network has been already imported
306 359

  
307
                network.clusters.each do |ccr_ref, ccr_name|
308 360
                    one_vnet = VCenterDriver::Network.to_one_template(network_name,
309
                                                                      network_ref,
310
                                                                      network.network_type,
311
                                                                      ccr_ref,
312
                                                                      ccr_name,
313
                                                                      vcenter_uuid)
361
                                                                        network_ref,
362
                                                                        network_type,
363
                                                                        ref,
364
                                                                        info['name'],
365
                                                                        vcenter_uuid,
366
                                                                        vcenter_instance_name,
367
                                                                        dc_name)
314 368
                    network_objects[dc_name] << one_vnet
315
                end #network clusters loop
369
                end
370

  
316 371
            end # network loop
317 372
        end #datacenters loop
318 373

  
src/vmm_mad/remotes/lib/vcenter_driver/datastore.rb
160 160

  
161 161
        return nil if one_cluster.nil?
162 162

  
163
        name, capacity, freeSpace = @item.collect("name","summary.capacity","summary.freeSpace")
164

  
163 165
        ds_name = ""
164 166

  
165 167
        if type == "IMAGE_DS"
166
            ds_name << "[#{vcenter_instance_name} - #{dc_name}] #{self['name']} - #{ccr_name} (IMG)"
168
            ds_name << "[#{vcenter_instance_name} - #{dc_name}] #{name} - #{ccr_name.tr(" ", "_")} (IMG)"
167 169
        else
168
            ds_name << "[#{vcenter_instance_name} - #{dc_name}] #{self['name']} - #{ccr_name} (SYS)"
170
            ds_name << "[#{vcenter_instance_name} - #{dc_name}] #{name} - #{ccr_name.tr(" ", "_")} (SYS)"
169 171
            ds_name << " [StorDRS]" if self.class == VCenterDriver::StoragePod
170 172
        end
171 173

  
172 174
        one_tmp = {
173 175
            :name     => ds_name,
174
            :total_mb => ((self['summary.capacity'].to_i / 1024) / 1024),
175
            :free_mb  => ((self['summary.freeSpace'].to_i / 1024) / 1024),
176
            :total_mb => ((capacity.to_i / 1024) / 1024),
177
            :free_mb  => ((freeSpace.to_i / 1024) / 1024),
176 178
            :cluster  => ccr_name,
177 179
            :one  => to_one(ds_name, vcenter_uuid, ccr_ref, one_cluster[:host_id])
178 180
        }
src/vmm_mad/remotes/lib/vcenter_driver/host.rb
27 27

  
28 28
class ClusterComputeResource
29 29
    attr_accessor :item
30
    attr_accessor :rp_list
30 31

  
31 32
    include Memoize
32 33

  
33 34
    def initialize(item, vi_client=nil)
34 35
        @item = item
35 36
        @vi_client = vi_client
37
        @rp_list
36 38
    end
37 39

  
38 40
    def fetch_resource_pools(rp, rp_array = [])
......
53 55
        @resource_pools
54 56
    end
55 57

  
56
    def get_resource_pool_list(rp = nil, parent_prefix = "", rp_array = [])
57

  
58
    def get_resource_pool_list(rp = @item.resourcePool, parent_prefix = "", rp_array = [])
58 59
        current_rp = ""
59 60

  
60
        if rp.nil?
61
            rp = @item.resourcePool
62
        else
63
            if !parent_prefix.empty?
64
                current_rp << parent_prefix
65
                current_rp << "/"
66
            end
67
            current_rp << rp.name
61
        if !parent_prefix.empty?
62
            current_rp << parent_prefix
63
            current_rp << "/"
68 64
        end
69 65

  
70
        if rp.resourcePool.size == 0
71
            rp_info = {}
72
            rp_info[:name] = current_rp
73
            rp_info[:ref]  = rp._ref
74
            rp_array << rp_info
75
        else
76
            rp.resourcePool.each do |child_rp|
77
                get_resource_pool_list(child_rp, current_rp, rp_array)
78
            end
79
            rp_info = {}
80
            rp_info[:name] = current_rp
81
            rp_info[:ref]  = rp._ref
82
            rp_array << rp_info if !current_rp.empty?
66
        resource_pool, name = rp.collect("resourcePool","name")
67
        current_rp << name if name != "Resources"
68

  
69
        resource_pool.each do |child_rp|
70
            get_resource_pool_list(child_rp, current_rp, rp_array)
83 71
        end
84 72

  
73
        rp_info = {}
74
        rp_info[:name] = current_rp
75
        rp_info[:ref]  = rp._ref
76
        rp_array << rp_info if !current_rp.empty?
77

  
85 78
        rp_array
86 79
    end
87 80

  
88 81
    def monitor
89
        #Load the host systems
90
        summary = @item.summary
82
        total_cpu,
83
        num_cpu_cores,
84
        effective_cpu,
85
        total_memory,
86
        effective_mem,
87
        num_hosts,
88
        num_eff_hosts = @item.collect("summary.totalCpu",
89
                                      "summary.numCpuCores",
90
                                      "summary.effectiveCpu",
91
                                      "summary.totalMemory",
92
                                      "summary.effectiveMemory",
93
                                      "summary.numHosts",
94
                                      "summary.numEffectiveHosts"
95
        )
91 96

  
92
        mhz_core = summary.totalCpu.to_f / summary.numCpuCores.to_f
93
        eff_core = summary.effectiveCpu.to_f / mhz_core
97
        mhz_core = total_cpu.to_f / num_cpu_cores.to_f
98
        eff_core = effective_cpu.to_f / mhz_core
94 99

  
95 100
        free_cpu  = sprintf('%.2f', eff_core * 100).to_f
96
        total_cpu = summary.numCpuCores.to_f * 100
101
        total_cpu = num_cpu_cores.to_f * 100
97 102
        used_cpu  = sprintf('%.2f', total_cpu - free_cpu).to_f
98 103

  
99
        total_mem = summary.totalMemory.to_i / 1024
100
        free_mem  = summary.effectiveMemory.to_i * 1024
104
        total_mem = total_memory.to_i / 1024
105
        free_mem  = effective_mem.to_i * 1024
101 106

  
102 107
        str_info = ""
103 108

  
......
106 111

  
107 112
        # System
108 113
        str_info << "HYPERVISOR=vcenter\n"
109
        str_info << "TOTALHOST=" << summary.numHosts.to_s << "\n"
110
        str_info << "AVAILHOST=" << summary.numEffectiveHosts.to_s << "\n"
114
        str_info << "TOTALHOST=" << num_hosts.to_s << "\n"
115
        str_info << "AVAILHOST=" << num_eff_hosts.to_s << "\n"
111 116

  
112 117
        # CPU
113 118
        str_info << "CPUSPEED=" << mhz_core.to_s   << "\n"
......
118 123
        # Memory
119 124
        str_info << "TOTALMEMORY=" << total_mem.to_s << "\n"
120 125
        str_info << "FREEMEMORY="  << free_mem.to_s << "\n"
121
        str_info << "USEDMEMORY="  << (total_mem - free_mem).to_s
126
        str_info << "USEDMEMORY="  << (total_mem - free_mem).to_s << "\n"
127

  
128
        str_info << "VCENTER_LAST_PERF_POLL=" << Time.now.to_i.to_s << "\n"
129

  
130
        str_info << monitor_resource_pools(mhz_core)
131
    end
132

  
133
    def monitor_resource_pools(mhz_core)
134

  
135
        @rp_list = get_resource_pool_list
136

  
137
        view = @vi_client.vim.serviceContent.viewManager.CreateContainerView({
138
            container: @item, #View for RPs inside this cluster
139
            type:      ['ResourcePool'],
140
            recursive: true
141
        })
142

  
143
        pc = @vi_client.vim.serviceContent.propertyCollector
144

  
145
        monitored_properties = [
146
            "config.cpuAllocation.expandableReservation",
147
            "config.cpuAllocation.limit",
148
            "config.cpuAllocation.reservation",
149
            "config.cpuAllocation.shares.level",
150
            "config.cpuAllocation.shares.shares",
151
            "config.memoryAllocation.expandableReservation",
152
            "config.memoryAllocation.limit",
153
            "config.memoryAllocation.reservation",
154
            "config.memoryAllocation.shares.level",
155
            "config.memoryAllocation.shares.shares"
156
        ]
157

  
158
        filterSpec = RbVmomi::VIM.PropertyFilterSpec(
159
            :objectSet => [
160
                :obj => view,
161
                :skip => true,
162
                :selectSet => [
163
                RbVmomi::VIM.TraversalSpec(
164
                    :name => 'traverseEntities',
165
                    :type => 'ContainerView',
166
                    :path => 'view',
167
                    :skip => false
168
                )
169
                ]
170
            ],
171
            :propSet => [
172
                { :type => 'ResourcePool', :pathSet => monitored_properties }
173
            ]
174
        )
122 175

  
176
        result = pc.RetrieveProperties(:specSet => [filterSpec])
123 177

  
124
        str_info << monitor_resource_pools(@item.resourcePool, "", mhz_core)
125
    end
178
        rps = {}
179
        result.each do |r|
180
            hashed_properties = r.to_hash
181
            if r.obj.is_a?(RbVmomi::VIM::ResourcePool)
182
                rps[r.obj._ref] = hashed_properties
183
            end
184
        end
126 185

  
127
    def monitor_resource_pools(parent_rp, parent_prefix, mhz_core)
128
        return "" if parent_rp.resourcePool.size == 0
186
        return "" if rps.empty?
129 187

  
130 188
        rp_info = ""
131 189

  
132
        parent_rp.resourcePool.each{|rp|
133
            rpcpu     = rp.config.cpuAllocation
134
            rpmem     = rp.config.memoryAllocation
190
        rps.each{|ref, info|
191

  
135 192
            # CPU
136
            cpu_expandable   = rpcpu.expandableReservation ? "YES" : "NO"
137
            cpu_limit        = rpcpu.limit == "-1" ? "UNLIMITED" : rpcpu.limit
138
            cpu_reservation  = rpcpu.reservation
139
            cpu_num          = rpcpu.reservation.to_f / mhz_core
140
            cpu_shares_level = rpcpu.shares.level
141
            cpu_shares       = rpcpu.shares.shares
193
            cpu_expandable   = info["config.cpuAllocation.expandableReservation"] ? "YES" : "NO"
194
            cpu_limit        = info["config.cpuAllocation.limit"] == "-1" ? "UNLIMITED" : info["config.cpuAllocation.limit"]
195
            cpu_reservation  = info["config.cpuAllocation.reservation"]
196
            cpu_num          = cpu_reservation.to_f / mhz_core
197
            cpu_shares_level = info["config.cpuAllocation.shares.level"]
198
            cpu_shares       = info["config.cpuAllocation.shares.shares"]
142 199

  
143 200
            # MEMORY
144
            mem_expandable   = rpmem.expandableReservation ? "YES" : "NO"
145
            mem_limit        = rpmem.limit == "-1" ? "UNLIMITED" : rpmem.limit
146
            mem_reservation  = rpmem.reservation.to_f
147
            mem_shares_level = rpmem.shares.level
148
            mem_shares       = rpmem.shares.shares
201
            mem_expandable   = info["config.memoryAllocation.expandableReservation"] ? "YES" : "NO"
202
            mem_limit        = info["config.memoryAllocation.limit"] == "-1" ? "UNLIMITED" : info["config.memoryAllocation.limit"]
203
            mem_reservation  = info["config.memoryAllocation.reservation"].to_f
204
            mem_shares_level = info["config.memoryAllocation.shares.level"]
205
            mem_shares       = info["config.memoryAllocation.shares.shares"]
206

  
207
            rp_name = rp_list.select { |item| item[:ref] == ref}.first[:name] rescue ""
149 208

  
150
            rp_name          = (parent_prefix.empty? ? "" : parent_prefix + "/")
151
            rp_name         += rp.name
209
            rp_name = "Resources" if rp_name.empty?
152 210

  
153 211
            rp_info << "\nVCENTER_RESOURCE_POOL_INFO = ["
154 212
            rp_info << "NAME=\"#{rp_name}\","
......
164 222
            rp_info << "MEM_SHARES=#{mem_shares},"
165 223
            rp_info << "MEM_SHARES_LEVEL=#{mem_shares_level}"
166 224
            rp_info << "]"
167

  
168
            if rp.resourcePool.size != 0
169
               rp_info << monitor_resource_pools(rp, rp_name, mhz_core)
170
            end
171 225
        }
172 226

  
227
        view.DestroyView
228

  
173 229
        return rp_info
174 230
    end
175 231

  
176 232
    def monitor_host_systems
177 233
        host_info = ""
178 234

  
179
        @item.host.each do |h|
180
            next if h.runtime.connectionState != "connected"
235
        view = @vi_client.vim.serviceContent.viewManager.CreateContainerView({
236
            container: @item, #View for Hosts inside this cluster
237
            type:      ['HostSystem'],
238
            recursive: true
239
        })
240

  
241
        pc = @vi_client.vim.serviceContent.propertyCollector
242

  
243
        monitored_properties = [
244
            "name",
245
            "runtime.connectionState",
246
            "summary.hardware.numCpuCores",
247
            "summary.hardware.memorySize",
248
            "summary.hardware.cpuModel",
249
            "summary.hardware.cpuMhz",
250
            "summary.quickStats.overallCpuUsage",
251
            "summary.quickStats.overallMemoryUsage"
252
        ]
253

  
254
        filterSpec = RbVmomi::VIM.PropertyFilterSpec(
255
            :objectSet => [
256
                :obj => view,
257
                :skip => true,
258
                :selectSet => [
259
                RbVmomi::VIM.TraversalSpec(
260
                    :name => 'traverseEntities',
261
                    :type => 'ContainerView',
262
                    :path => 'view',
263
                    :skip => false
264
                )
265
                ]
266
            ],
267
            :propSet => [
268
                { :type => 'HostSystem', :pathSet => monitored_properties }
269
            ]
270
        )
271

  
272
        result = pc.RetrieveProperties(:specSet => [filterSpec])
273

  
274
        hosts = {}
275
        result.each do |r|
276
            hashed_properties = r.to_hash
277
            if r.obj.is_a?(RbVmomi::VIM::HostSystem)
278
                hosts[r.obj._ref] = hashed_properties
279
            end
280
        end
181 281

  
182
            summary = h.summary
183
            hw      = summary.hardware
184
            stats   = summary.quickStats
282
        hosts.each do |ref, info|
283
            next if info["runtime.connectionState"] != "connected"
185 284

  
186
            total_cpu = hw.numCpuCores * 100
187
            used_cpu  = (stats.overallCpuUsage.to_f / hw.cpuMhz.to_f) * 100
285
            total_cpu = info["summary.hardware.numCpuCores"] * 100
286
            used_cpu  = (info["summary.quickStats.overallCpuUsage"].to_f / info["summary.hardware.cpuMhz"].to_f) * 100
188 287
            used_cpu  = sprintf('%.2f', used_cpu).to_f # Trim precission
189 288
            free_cpu  = total_cpu - used_cpu
190 289

  
191
            total_memory = hw.memorySize/1024
192
            used_memory  = stats.overallMemoryUsage*1024
290
            total_memory = info["summary.hardware.memorySize"]/1024
291
            used_memory  = info["summary.quickStats.overallMemoryUsage"]*1024
193 292
            free_memory  = total_memory - used_memory
194 293

  
195 294
            host_info << "\nHOST=["
196 295
            host_info << "STATE=on,"
197
            host_info << "HOSTNAME=\""  << h.name.to_s       << "\","
198
            host_info << "MODELNAME=\"" << hw.cpuModel.to_s  << "\","
199
            host_info << "CPUSPEED="    << hw.cpuMhz.to_s    << ","
296
            host_info << "HOSTNAME=\""  << info["name"].to_s       << "\","
297
            host_info << "MODELNAME=\"" << info["summary.hardware.cpuModel"].to_s  << "\","
298
            host_info << "CPUSPEED="    << info["summary.hardware.cpuMhz"].to_s    << ","
200 299
            host_info << "MAX_CPU="     << total_cpu.to_s    << ","
201 300
            host_info << "USED_CPU="    << used_cpu.to_s     << ","
202 301
            host_info << "FREE_CPU="    << free_cpu.to_s     << ","
......
206 305
            host_info << "]"
207 306
        end
208 307

  
308
        view.DestroyView # Destroy the view
309

  
209 310
        return host_info
210 311
    end
211 312

  
212 313
    def monitor_vms
213
        str_info = ""
314

  
315
        vc_uuid = @vi_client.vim.serviceContent.about.instanceUuid
316
        cluster_name = self["name"]
317
        cluster_ref = self["_ref"]
318

  
319
        # Get info of the host where the VM/template is located
320
        host_id = nil
321
        one_host = VCenterDriver::VIHelper.find_by_ref(OpenNebula::HostPool,
322
                                                       "TEMPLATE/VCENTER_CCR_REF",
323
                                                       cluster_ref,
324
                                                       vc_uuid)
325
        host_id = one_host["ID"] if one_host
326

  
327

  
328
        # Extract CPU info for each esx host in cluster
329
        esx_host_cpu = {}
330
        @item.host.each do |esx_host|
331
            esx_host_cpu[esx_host._ref] = esx_host.summary.hardware.cpuMhz.to_f
332
        end
333

  
214 334
        @monitored_vms = Set.new
215
        resource_pools.each do |rp|
216
            str_info << monitor_vms_in_rp(rp)
335
        str_info = ""
336

  
337
        view = @vi_client.vim.serviceContent.viewManager.CreateContainerView({
338
            container: @item, #View for VMs inside this cluster
339
            type:      ['VirtualMachine'],
340
            recursive: true
341
        })
342

  
343
        pc = @vi_client.vim.serviceContent.propertyCollector
344

  
345
        monitored_properties = [
346
            "name", #VM name
347
            "config.template", #To filter out templates
348
            "summary.runtime.powerState", #VM power state
349
            "summary.quickStats.hostMemoryUsage", #Memory usage
350
            "summary.quickStats.overallCpuUsage", #CPU used by VM
351
            "runtime.host", #ESX host
352
            "resourcePool", #RP
353
            "guest.guestFullName",
354
            "guest.net", #IP addresses as seen by guest tools,
355
            "guest.guestState",
356
            "guest.toolsVersion",
357
            "guest.toolsRunningStatus",
358
            "guest.toolsVersionStatus2", #IP addresses as seen by guest tools,
359
            "config.extraConfig", #VM extraconfig info e.g opennebula.vm.running
360
            "config.hardware.numCPU",
361
            "config.hardware.memoryMB",
362
            "config.annotation"
363
        ]
364

  
365
        filterSpec = RbVmomi::VIM.PropertyFilterSpec(
366
            :objectSet => [
367
                :obj => view,
368
                :skip => true,
369
                :selectSet => [
370
                RbVmomi::VIM.TraversalSpec(
371
                    :name => 'traverseEntities',
372
                    :type => 'ContainerView',
373
                    :path => 'view',
374
                    :skip => false
375
                )
376
                ]
377
            ],
378
            :propSet => [
379
                { :type => 'VirtualMachine', :pathSet => monitored_properties }
380
            ]
381
        )
382

  
383
        result = pc.RetrieveProperties(:specSet => [filterSpec])
384

  
385
        vms = {}
386
        vm_objects = []
387
        result.each do |r|
388
            hashed_properties = r.to_hash
389
            if r.obj.is_a?(RbVmomi::VIM::VirtualMachine)
390
                #Only take care of VMs, not templates
391
                if !hashed_properties["config.template"]
392
                    vms[r.obj._ref] = hashed_properties
393
                    vm_objects << r.obj
394
                end
395
            end
217 396
        end
218 397

  
219
        return str_info
220
    end
398
        pm = @vi_client.vim.serviceContent.perfManager
221 399

  
222
    def monitor_vms_in_rp(rp)
223
        str_info = ""
400
        stats = []
224 401

  
225
        host_pool = VCenterDriver::VIHelper.one_pool(OpenNebula::HostPool)
402
        max_samples = 9
403
        refresh_rate = 20 #Real time stats takes samples every 20 seconds
226 404

  
227
        ccr_host = {}
228
        host_pool.each do |host|
229
            ccr = host['TEMPLATE/VCENTER_CCR_REF']
230
            ccr_host[ccr] = host['ID'] if ccr
405
        last_mon_time = one_host["TEMPLATE/VCENTER_LAST_PERF_POLL"]
406

  
407
        if last_mon_time
408
            interval = (Time.now.to_i - last_mon_time.to_i)
409
            interval = 3601 if interval < 0
410
            samples = (interval / refresh_rate)
411
            samples = 1 if samples == 0
412
            max_samples =  interval > 3600 ? 9 : samples
231 413
        end
232 414

  
233
        rp.vm.each do |v|
415
        stats = pm.retrieve_stats(
416
                vm_objects,
417
                ['net.transmitted','net.bytesRx','net.bytesTx','net.received',
418
                'virtualDisk.numberReadAveraged','virtualDisk.numberWriteAveraged',
419
                'virtualDisk.read','virtualDisk.write'],
420
                {max_samples: max_samples}
421
        )
422

  
423
        get_resource_pool_list if !@rp_list
424

  
425
        vms.each do |vm_ref,info|
234 426
            begin
235
                vm = VirtualMachine.new(v, @vi_client)
427
                vm = VCenterDriver::VirtualMachine.new_from_ref(vm_ref, @vi_client)
428
                info[:cluster_name] = cluster_name
429
                info[:cluster_ref] = cluster_ref
430
                info[:vc_uuid] = vc_uuid
431
                info[:host_id] = host_id
432
                info[:rp_list] = @rp_list
433

  
434
                vm.vm_info = info
236 435

  
237 436
                number = -1
238 437

  
239 438
                # Check the running flag
240
                running_flag = vm["config.extraConfig"].select do |val|
439
                running_flag = info["config.extraConfig"].select do |val|
241 440
                    val[:key] == "opennebula.vm.running"
242 441
                end
243 442

  
244
                if running_flag.size > 0 and running_flag[0]
443
                if !running_flag.empty? && running_flag.first
245 444
                    running_flag = running_flag[0][:value]
246 445
                end
247 446

  
248 447
                next if running_flag == "no"
249 448

  
250 449
                # Extract vmid if possible
251
                matches = vm["name"].match(/^one-(\d*)(-(.*))?$/)
450
                matches = info["name"].match(/^one-(\d*)(-(.*))?$/)
252 451
                number  = matches[1] if matches
253 452

  
254 453
                # Extract vmid from ref and vcenter instance uuid if possible
255
                vm_id = vm.get_vm_id
256

  
257
                number = vm_id if vm_id
454
                if number == -1
455
                    one_vm = VCenterDriver::VIHelper.find_by_ref(OpenNebula::VirtualMachinePool,
456
                                                                "DEPLOY_ID",
457
                                                                vm_ref,
458
                                                                vc_uuid)
459
                    number = one_vm["ID"] if one_vm
460
                end
258 461

  
259 462
                if number != -1
260 463
                    next if @monitored_vms.include? number
261 464
                    @monitored_vms << number
465
                    vm.one_item if vm.get_vm_id
262 466
                end
263 467

  
264
                vm.monitor
468
                vm.monitor(esx_host_cpu,stats)
265 469

  
266
                next if !vm["config"]
470
                vm_name = "#{info["name"]} - #{cluster_name}"
267 471

  
268 472
                str_info << %Q{
269 473
                VM = [
270 474
                    ID="#{number}",
271
                    VM_NAME="#{vm["name"]} - #{vm["runtime.host.parent.name"]}",
272
                    DEPLOY_ID="#{vm["_ref"]}",
475
                    VM_NAME="#{vm_name}",
476
                    DEPLOY_ID="#{vm_ref}",
273 477
                }
274 478

  
275 479
                if number == -1
276
                    vm_template_64 = Base64.encode64(vm.to_one).gsub("\n","")
480
                    vm_template_64 = Base64.encode64(vm.vm_to_one(vm_name)).gsub("\n","")
277 481

  
278 482
                    str_info << "IMPORT_TEMPLATE=\"#{vm_template_64}\","
279 483
                end
280 484

  
281 485
                str_info << "POLL=\"#{vm.info.gsub('"', "\\\"")}\"]"
486

  
282 487
            rescue Exception => e
283 488
                STDERR.puts e.inspect
284 489
                STDERR.puts e.backtrace
285 490
            end
286 491
        end
287 492

  
288
        return str_info.gsub(/^\s+/,"")
289
    end
493
        view.DestroyView # Destroy the view
290 494

  
495
        return str_info
496
    end
291 497

  
292 498
    def monitor_customizations
293 499
        customizations = self['_connection'].serviceContent.customizationSpecManager.info
src/vmm_mad/remotes/lib/vcenter_driver/importer.rb
16 16

  
17 17
        dc_folder = VCenterDriver::DatacenterFolder.new(vi_client)
18 18

  
19
        # Get vcenter intance uuid as moref is unique for each vcenter
20
        vc_uuid = vi_client.vim.serviceContent.about.instanceUuid
21

  
22
        # Get vcenter API version
23
        vc_version = vi_client.vim.serviceContent.about.apiVersion
19
        vcenter_instance_name = vi_client.vim.host
24 20

  
25 21
        # OpenNebula's ClusterPool
26 22
        cpool = VCenterDriver::VIHelper.one_pool(OpenNebula::ClusterPool, false)
......
29 25
            raise "Could not get OpenNebula ClusterPool: #{cpool.message}"
30 26
        end
31 27

  
32
        cpool.info
33

  
34 28
        cluster_list = {}
35 29
        cpool.each do |c|
36 30
            cluster_list[c["ID"]] = c["NAME"]
......
43 37
            raise "Could not get OpenNebula HostPool: #{hpool.message}"
44 38
        end
45 39

  
46
        rs = dc_folder.get_unimported_hosts(hpool)
40
        rs = dc_folder.get_unimported_hosts(hpool,vcenter_instance_name)
47 41

  
48 42
        STDOUT.print "done!\n\n"
49 43

  
......
175 169
            end
176 170

  
177 171
            tmps.each{ |t|
172
                template = nil
173
                template_copy_ref = nil
174
                template_xml = nil
178 175

  
179 176
                if !use_defaults
180 177
                    STDOUT.print "\n  * VM Template found:\n"\
......
186 183
                    next if STDIN.gets.strip.downcase != 'y'
187 184
                end
188 185

  
186
                # Linked Clones
187
                if !use_defaults
188

  
189
                    template = VCenterDriver::Template.new_from_ref(t[:vcenter_ref], vi_client)
190

  
191
                    STDOUT.print "\n    For faster deployment operations"\
192
                                 " and lower disk usage, OpenNebula"\
193
                                 " can create new VMs as linked clones."\
194
                                 "\n    Would you like to use Linked Clones with VMs based on this template (y/[n])? "
195

  
196
                    if STDIN.gets.strip.downcase == 'y'
197

  
198
                        STDOUT.print "\n    Linked clones requires that delta"\
199
                                     " disks must be created for each disk in the template."\
200
                                     " This operation may change the template contents."\
201
                                     " \n    Do you want OpenNebula to create a copy of the template,"\
202
                                     " so the original template remains untouched ([y]/n)? "
203

  
204
                        template = t[:template]
205
                        if STDIN.gets.strip.downcase != 'n'
206

  
207
                            STDOUT.print "\n    The new template will be named"\
208
                                         " adding a one- prefix to the name"\
209
                                         " of the original template. \n"\
210
                                         "    If you prefer a different name"\
211
                                         " please specify or press Enter"\
212
                                         " to use defaults: "
213

  
214
                            template_name = STDIN.gets.strip.downcase
215

  
216
                            STDOUT.print "\n    WARNING!!! The cloning operation can take some time"\
217
                                         " depending on the size of disks. Please wait...\n"
218

  
219

  
220
                            error, template_copy_ref = template.create_template_copy(template_name)
221

  
222
                            if template_copy_ref
223

  
224
                                template = VCenterDriver::Template.new_from_ref(template_copy_ref, vi_client)
225

  
226
                                one_template = VCenterDriver::Template.get_xml_template(template, vc_uuid, vi_client, options[:vcenter], dc)
227

  
228
                                if one_template
229
                                    #Now create delta disks
230
                                    STDOUT.print "\n    Delta disks are being created, please be patient..."
231

  
232
                                    lc_error, use_lc = template.create_delta_disks
233
                                    if lc_error
234
                                        STDOUT.print "\n    ERROR. Something was wrong with the create delta disks on the template operation: #{lc_error}.\n"\
235
                                                    "\n    Linked Clones will not be used with this template.\n"
236
                                    else
237
                                        one_template[:one] << "\nVCENTER_LINKED_CLONES=\"YES\"\n"
238
                                        t = one_template
239
                                    end
240
                                else
241
                                    STDOUT.print "\n    ERROR. Something was wrong obtaining the info from the template's copy.\n"\
242
                                                 "\n    Linked Clones will not be used with this template.\n"
243
                                    template.delete_template if template_copy_ref
244
                                end
245

  
246
                            else
247
                                STDOUT.print "\n    ERROR. #{error}\n"
248
                            end
249

  
250
                        else
251
                            # Create linked clones on top of the existing template
252
                            # Create a VirtualMachine object from the template_copy_ref
253
                            STDOUT.print "\n    Delta disks are being created, please be patient..."
254

  
255
                            lc_error, use_lc = template.create_delta_disks
256
                            if lc_error
257
                                STDOUT.print "\n    ERROR. Something was wrong with the create delta disks on the template operation: #{lc_error}.\n"\
258
                                             "\n    Linked Clones will not be used with this template.\n"
259
                            end
260
                            t[:one] << "\nVCENTER_LINKED_CLONES=\"YES\"\n" if use_lc
261
                        end
262
                    end
263
                end
264

  
265
                vcenter_vm_folder = ""
266
                if !use_defaults
267
                    STDOUT.print "\n\n    Do you want to specify a folder where"\
268
                                    " the deployed VMs based on this template will appear"\
269
                                    " in vSphere's VM and Templates section?"\
270
                                    "\n    If no path is set, VMs will be placed in the same"\
271
                                    " location where the template lives."\
272
                                    "\n    Please specify a path using slashes to separate folders"\
273
                                    " e.g /Management/VMs or press Enter to use defaults: "\
274

  
275
                    vcenter_vm_folder = STDIN.gets.strip
276
                    t[:one] << "VCENTER_VM_FOLDER=\"#{vcenter_vm_folder}\"\n" if !vcenter_vm_folder.empty?
277
                end
278

  
189 279
                ## Add existing disks to template (OPENNEBULA_MANAGED)
190 280

  
191
                template = t[:template]
281
                STDOUT.print "\n    The existing disks and networks in the template"\
282
                             " are being imported, please be patient..."
283

  
284
                template = t[:template] if !template
285

  
192 286

  
193 287
                error, template_disks = template.import_vcenter_disks(vc_uuid,
194 288
                                                                      dpool,
......
198 292
                    t[:one] << template_disks
199 293
                else
200 294
                    STDOUT.puts error
295
                    template.delete_template if template_copy_ref
201 296
                    next
202 297
                end
203 298

  
204 299
                error, template_nics = template.import_vcenter_nics(vc_uuid,
205
                                                                    npool)
300
                                                                   npool)
206 301
                if error.empty?
207 302
                    t[:one] << template_nics
208 303
                else
209 304
                    STDOUT.puts error
305
                    template.delete_template if template_copy_ref
210 306
                    next
211 307
                end
212 308

  
......
217 313
                if !use_defaults
218 314

  
219 315
                    if rp_split.size > 3
220
                        STDOUT.print "\n    This template is currently set to "\
316
                        STDOUT.print "\n\n    This template is currently set to "\
221 317
                            "launch VMs in the default resource pool."\
222 318
                            "\n    Press y to keep this behaviour, n to select"\
223 319
                            " a new resource pool or d to delegate the choice"\
......
238 334
                                        "\"#{list_of_rp}\""
239 335
                            input_str+= "\n    Press y to agree, or input a comma"\
240 336
                                        " separated list of resource pools to edit "\
241
                                        "[y/comma separated list] "
337
                                        "([y]/comma separated list) "
242 338
                            STDOUT.print input_str
243 339

  
244 340
                            answer = STDIN.gets.strip
245 341

  
246
                            if answer.downcase == 'y'
247
                                rp_input += rp_split[3] + "|"
248
                            else
342
                            if !answer.empty? && answer.downcase != 'y'
249 343
                                rp_input += answer + "|"
344
                            else
345
                                rp_input += rp_split[3] + "|"
250 346
                            end
251 347

  
252 348
                            # Default
......
254 350
                                            "to the end user is set to"\
255 351
                                            " \"#{default_rp}\"."
256 352
                            input_str+= "\n    Press y to agree, or input a new "\
257
                                        "resource pool [y/resource pool name] "
353
                                        "resource pool ([y]/resource pool name) "
258 354
                            STDOUT.print input_str
259 355

  
260 356
                            answer = STDIN.gets.strip
261 357

  
262
                            if answer.downcase == 'y'
263
                                rp_input += rp_split[4]
264
                            else
358
                            if !answer.empty? && answer.downcase != 'y'
265 359
                                rp_input += answer
360
                            else
361
                                rp_input += rp_split[4]
266 362
                            end
267 363
                        when 'n'
268 364

  
269 365
                            list_of_rp   = rp_split[-2]
270 366

  
271
                            input_str = "    The list of available resource pools is:\n"
272

  
273
                            STDOUT.print input_str
274

  
275
                            dashes = ""
276
                            100.times do
277
                                dashes << "-"
278
                            end
279

  
280
                            list_str = "\n    [Index] Resource pool :"\
281
                                    "\n    #{dashes}\n"
282

  
283
                            STDOUT.print list_str
367
                            STDOUT.print "    The list of available resource pools is:\n\n"
284 368

  
285 369
                            index = 1
286
                            t[:rp_list].each do |rp|
287
                                list_str = "    [#{index}] #{rp[:name]}\n"
370
                            t[:rp_list].each do |r|
371
                                list_str = "    - #{r[:name]}\n"
288 372
                                index += 1
289 373
                                STDOUT.print list_str
290 374
                            end
291 375

  
292 376
                            input_str = "\n    Please input the new default"\
293
                                        " resource pool index in the list (e.g 1): "
377
                                        " resource pool name: "
294 378

  
295 379
                            STDOUT.print input_str
296 380

  
297 381
                            answer = STDIN.gets.strip
298 382

  
299
                            t[:one] << "VCENTER_RESOURCE_POOL=\"#{t[:rp_list][answer.to_i - 1][:name]}\"\n"
383
                            t[:one] << "VCENTER_RESOURCE_POOL=\"#{answer}\"\n"
300 384
                        end
301 385
                    end
302 386
                end
......
314 398

  
315 399
                if ::OpenNebula.is_error?(rc)
316 400
                    STDOUT.puts "    Error creating template: #{rc.message}\n"
401
                    template.delete_template if template_copy_ref
317 402
                else
318 403
                    STDOUT.puts "    OpenNebula template #{one_t.id} created!\n"
319 404
                end
......
343 428

  
344 429
        dc_folder = VCenterDriver::DatacenterFolder.new(vi_client)
345 430

  
346
        # OpenNebula's ClusterPool
347
        cpool = VCenterDriver::VIHelper.one_pool(OpenNebula::ClusterPool, false)
348

  
349
        if cpool.respond_to?(:message)
350
            raise "Could not get OpenNebula ClusterPool: #{cpool.message}"
351
        end
352

  
353
        cpool.info
354

  
355
        cluster_list = {}
356
        cpool.each do |c|
357
            cluster_list[c["ID"]] = c["NAME"]
358
        end
359

  
360 431
        # OpenNebula's VirtualNetworkPool
361 432
        npool = VCenterDriver::VIHelper.one_pool(OpenNebula::VirtualNetworkPool, false)
362 433

  
......
364 435
            raise "Could not get OpenNebula VirtualNetworkPool: #{npool.message}"
365 436
        end
366 437

  
367
        rs = dc_folder.get_unimported_networks(npool)
438
        rs = dc_folder.get_unimported_networks(npool,options[:vcenter])
368 439

  
369 440
        STDOUT.print "done!\n"
370 441

  
......
393 464
                    STDOUT.print print_str
394 465

  
395 466
                    next if STDIN.gets.strip.downcase != 'y'
396

  
397
                    if cluster_list.size > 1
398
                        STDOUT.print "\n    In which OpenNebula cluster do you want the network to be included?\n "
399

  
400
                        cluster_list_str = "\n"
401
                        cluster_list.each do |key, value|
402
                            cluster_list_str << "      - ID: " << key << " - NAME: " << value << "\n"
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff