Class: OpenNebula::ServiceTemplate

Inherits:
DocumentJSON show all
Defined in:
lib/models/service_template.rb

Overview

Service Tempalte

Constant Summary collapse

ROLE_SCHEMA =
{
    :type => :object,
    :properties => {
        'name' => {
            :type => :string,
            :required => true,
            :regex => /^\w+$/
        },
        'cardinality' => {
            :type => :integer,
            :default => 1,
            :minimum => 0
        },
        'vm_template' => {
            :type => :integer,
            :required => true
        },
        'vm_template_contents' => {
            :type => :string,
            :required => false
        },
        'parents' => {
            :type => :array,
            :items => {
                :type => :string
            }
        },
        'shutdown_action' => {
            :type => :string,
            :enum => %w[
                terminate
                terminate-hard
                shutdown
                shutdown-hard
            ],
            :required => false
        },
        'min_vms' => {
            :type => :integer,
            :required => false,
            :minimum => 0
        },
        'max_vms' => {
            :type => :integer,
            :required => false,
            :minimum => 0
        },
        'cooldown' => {
            :type => :integer,
            :required => false,
            :minimum => 0
        },
        'elasticity_policies' => {
            :type => :array,
            :items => {
                :type => :object,
                :properties => {
                    'type' => {
                        :type => :string,
                        :enum => %w[
                            CHANGE
                            CARDINALITY
                            PERCENTAGE_CHANGE
                        ],
                        :required => true
                    },
                    'adjust' => {
                        :type => :integer,
                        :required => true
                    },
                    'min_adjust_step' => {
                        :type => :integer,
                        :required => false,
                        :minimum => 1
                    },
                    'period_number' => {
                        :type => :integer,
                        :required => false,
                        :minimum => 0
                    },
                    'period' => {
                        :type => :integer,
                        :required => false,
                        :minimum => 0
                    },
                    'expression' => {
                        :type => :string,
                        :required => true
                    },
                    'cooldown' => {
                        :type => :integer,
                        :required => false,
                        :minimum => 0
                    }
                    # 'statistic' => {
                    # # SampleCount | Average | Sum | Minimum | Maximum
                    #    :type => :string
                    # }
                }
            }
        },
        'scheduled_policies' => {
            :type => :array,
            :items => {
                :type => :object,
                :properties => {
                    'type' => {
                        :type => :string,
                        :enum => %w[
                            CHANGE
                            CARDINALITY
                            PERCENTAGE_CHANGE
                        ],
                        :required => true
                    },
                    'adjust' => {
                        :type => :integer,
                        :required => true
                    },
                    'min_adjust_step' => {
                        :type => :integer,
                        :required => false,
                        :minimum => 1
                    },
                    'start_time' => {
                        :type => :string,
                        :required => false
                    },
                    'recurrence' => {
                        :type => :string,
                        :required => false
                    }
                }
            }
        }
    }
}
SCHEMA =
{
    :type => :object,
    :properties => {
        'name' => {
            :type => :string,
            :required => true
        },
        'deployment' => {
            :type => :string,
            :enum => %w[none straight],
            :default => 'none'
        },
        'description' => {
            :type => :string,
            :default => ''
        },
        'shutdown_action' => {
            :type => :string,
            :enum => %w[
                terminate
                terminate-hard
                shutdown
                shutdown-hard
            ],
            :required => false
        },
        'roles' => {
            :type => :array,
            :items => ROLE_SCHEMA,
            :required => true
        },
        'custom_attrs' => {
            :type => :object,
            :properties => {},
            :required => false
        },
        'custom_attrs_values' => {
            :type => :object,
            :properties => {},
            :required => false
        },
        'ready_status_gate' => {
            :type => :boolean,
            :required => false
        },
        'networks' => {
            :type => :object,
            :properties => {},
            :required => false
        },
        'networks_values' => {
            :type => :array,
            :items => {
                :type => :object,
                :properties => {}
            },
            :required => false
        }
    }
}
DOCUMENT_TYPE =
101

Constants inherited from DocumentJSON

DocumentJSON::TEMPLATE_TAG

Constants inherited from Document

Document::DOCUMENT_METHODS

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from DocumentJSON

#info, #load_body, #to_json

Methods inherited from Document

build_xml, #chmod, #chmod_octet, #chown, #clone, #delete, #document_type, #gid, #info, #initialize, #lock, #owner_id, #public?, #rename, #unlock

Methods inherited from PoolElement

#id, #name, new_with_id, #replace, #to_str

Methods inherited from XMLElement

#[], #add_element, #attr, build_xml, #delete_element, #each, #each_xpath, #element_xml, #has_elements?, #initialize, #initialize_xml, #name, #retrieve_elements, #retrieve_xmlelements, #set_content, #template_like_str, #template_str, #template_xml, #text, #to_hash, #to_xml, #xml_nil?

Constructor Details

This class inherits a constructor from OpenNebula::Document

Class Method Details

.init_default_vn_name_template(vn_name_template) ⇒ Object



223
224
225
226
227
# File 'lib/models/service_template.rb', line 223

def self.init_default_vn_name_template(vn_name_template)
    # rubocop:disable Style/ClassVars
    @@vn_name_template = vn_name_template
    # rubocop:enable Style/ClassVars
end

.validate(template) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
# File 'lib/models/service_template.rb', line 353

def self.validate(template)
    validator = Validator::Validator.new(
        :default_values => true,
        :delete_extra_properties => false,
        :allow_extra_properties => true
    )

    validator.validate!(template, SCHEMA)

    validate_values(template)
end

.validate_values(template) ⇒ Object



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
# File 'lib/models/service_template.rb', line 392

def self.validate_values(template)
    parser = ElasticityGrammarParser.new

    roles = template['roles']

    roles.each_with_index do |role, role_index|
        roles[role_index+1..-1].each do |other_role|
            if role['name'] == other_role['name']
                raise Validator::ParseException,
                      "Role name '#{role['name']}' is repeated"
            end
        end

        if !role['min_vms'].nil? &&
           role['min_vms'].to_i > role['cardinality'].to_i

            raise Validator::ParseException,
                  "Role '#{role['name']}' 'cardinality' must be " \
                  "greater than or equal to 'min_vms'"
        end

        if !role['max_vms'].nil? &&
           role['max_vms'].to_i < role['cardinality'].to_i

            raise Validator::ParseException,
                  "Role '#{role['name']}' 'cardinality' must be " \
                  "lower than or equal to 'max_vms'"
        end

        if (role['elasticity_policies'] &&
            !role['elasticity_policies'].empty?) ||
           (role['scheduled_policies'] &&
           !role['scheduled_policies'].empty?)

            if role['min_vms'].nil? || role['max_vms'].nil?
                raise Validator::ParseException,
                      "Role '#{role['name']}' with " \
                      " 'elasticity_policies' or " \
                      "'scheduled_policies'must define both 'min_vms'" \
                      " and 'max_vms'"
            end
        end

        if role['elasticity_policies']
            role['elasticity_policies'].each_with_index do |policy,
                                                            index|
                exp = policy['expression']

                if exp.empty?
                    raise Validator::ParseException,
                          "Role '#{role['name']}', elasticity policy " \
                          "##{index} 'expression' cannot be empty"
                end

                treetop = parser.parse(exp)
                next unless treetop.nil?

                raise Validator::ParseException,
                      "Role '#{role['name']}', elasticity policy " \
                      "##{index} 'expression' parse error: " \
                      "#{parser.failure_reason}"
            end
        end

        next unless role['scheduled_policies']

        role['scheduled_policies'].each_with_index do |policy, index|
            start_time = policy['start_time']
            recurrence = policy['recurrence']

            if !start_time.nil?
                if !policy['recurrence'].nil?
                    raise Validator::ParseException,
                          "Role '#{role['name']}', scheduled policy "\
                          "##{index} must define "\
                          "'start_time' or 'recurrence', but not both"
                end

                begin
                    next if start_time.match(/^\d+$/)

                    Time.parse(start_time)
                rescue ArgumentError
                    raise Validator::ParseException,
                          "Role '#{role['name']}', scheduled policy " \
                          "##{index} 'start_time' is not a valid " \
                          'Time. Try with YYYY-MM-DD hh:mm:ss or ' \
                          '0YYY-MM-DDThh:mm:ssZ'
                end
            elsif !recurrence.nil?
                begin
                    cron_parser = CronParser.new(recurrence)
                    cron_parser.next
                rescue StandardError
                    raise Validator::ParseException,
                          "Role '#{role['name']}', scheduled policy " \
                          "##{index} 'recurrence' is not a valid " \
                          'cron expression'
                end
            else
                raise Validator::ParseException,
                      "Role '#{role['name']}', scheduled policy #" \
                      "#{index} needs to define either " \
                      "'start_time' or 'recurrence'"
            end
        end
    end
end

Instance Method Details

#allocate(template_json) ⇒ Object



231
232
233
234
235
236
237
# File 'lib/models/service_template.rb', line 231

def allocate(template_json)
    template = JSON.parse(template_json)

    ServiceTemplate.validate(template)

    super(template.to_json, template['name'])
end

#clone_recursively(name, mode) ⇒ Integer

Clone service template and the VM templates asssociated to it

Parameters:

  • name (String)

    New template name

  • mode (Symbol)

    Cloning mode (:all, :templates)

Returns:

  • (Integer)

    New document ID



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
# File 'lib/models/service_template.rb', line 276

def clone_recursively(name, mode)
    recursive = mode == 'all'

    # clone the document to get new ID
    new_id = clone(name)

    return new_id if OpenNebula.is_error?(new_id)

    doc = OpenNebula::ServiceTemplate.new_with_id(new_id, @client)
    rc  = doc.info

    return rc if OpenNebula.is_error?(rc)

    body             = JSON.parse(doc["TEMPLATE/#{TEMPLATE_TAG}"])
    cloned_templates = {}

    # iterate over roles to clone templates
    rc = body['roles'].each do |role|
        t_id = role['vm_template']

        # if the template has already been cloned, just update the value
        if cloned_templates.keys.include?(t_id)
            role['vm_template'] = cloned_templates[t_id]
            next
        end

        template = OpenNebula::Template.new_with_id(t_id, @client)
        rc       = template.info

        break rc if OpenNebula.is_error?(rc)

        rc = template.clone("#{template.name}-#{name}", recursive)

        break rc if OpenNebula.is_error?(rc)

        # add new ID to the hash
        cloned_templates[t_id] = rc

        role['vm_template'] = rc
    end

    # if any error, rollback and delete the left templates
    if OpenNebula.is_error?(rc)
        cloned_templates.each do |_, value|
            template = OpenNebula::Template.new_with_id(value, @client)

            rc = template.info

            break rc if OpenNebula.is_error?(rc)

            rc = template.delete(recursive)

            break rc if OpenNebula.is_error?(rc)
        end

        return rc
    end

    # update the template with the new body
    doc.update(body.to_json)

    # return the new document ID
    new_id
end

#instantiate(merge_template) ⇒ Object



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
# File 'lib/models/service_template.rb', line 365

def instantiate(merge_template)
    rc = nil

    if merge_template.nil?
        instantiate_template = JSON.parse(@body.to_json)
    else
        instantiate_template = JSON.parse(@body.to_json)
                                   .merge(merge_template)
    end

    begin
        ServiceTemplate.validate(instantiate_template)

        xml     = OpenNebula::Service.build_xml
        service = OpenNebula::Service.new(xml, @client)

        rc = service.allocate(instantiate_template.to_json)
    rescue Validator::ParseException, JSON::ParserError => e
        return e
    end

    return rc if OpenNebula.is_error?(rc)

    service.info
    service
end

#templateString

Retrieves the template

Returns:

  • (String)

    json template



242
243
244
# File 'lib/models/service_template.rb', line 242

def template
    @body.to_json
end

#update(template_json, append = false) ⇒ nil, OpenNebula::Error

Replaces the template contents

Parameters:

  • template_json (String)

    New template contents

  • append (true, false) (defaults to: false)

    True to append new attributes instead of replace the whole template

Returns:



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/models/service_template.rb', line 254

def update(template_json, append = false)
    template = JSON.parse(template_json)

    if append
        rc = info

        return rc if OpenNebula.is_error?(rc)

        template = @body.merge(template)
    end

    ServiceTemplate.validate(template)

    super(template.to_json)
end

#update_raw(template_raw, append = false) ⇒ nil, OpenNebula::Error

Replaces the raw template contents

Parameters:

  • template (String)

    New template contents, in the form KEY = VAL

  • append (true, false) (defaults to: false)

    True to append new attributes instead of replace the whole template

Returns:



349
350
351
# File 'lib/models/service_template.rb', line 349

def update_raw(template_raw, append = false)
    super(template_raw, append)
end