Class: VagrantSubutai::Blueprint::VariablesController

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-subutai/blueprint/variables_controller.rb

Constant Summary collapse

KEYS =
{
  name:                  'name',
  description:           'description',
  containers:            'containers',
  hostname:              'hostname',
  template:              'template',
  size:                  'size',
  peer_criteria:         'peer-criteria',
  port_mapping:          'port-mapping',
  protocol:              'protocol',
  domain:                'domain',
  internal_port:         'internal-port',
  external_port:         'external-port',
  max_price:             'max-price',
  avg_cpu_load:          'avg-cpu-load',
  min_free_ram:          'min-free-ram',
  min_free_disk_space:   'min-free-disk-space',
  user_variables:        'user-variables',
  type:                  'type',
  default:               'default',
  validation:            'validation',
  ansible_configuration: 'ansible-configuration',
  extra_vars:            'extra-vars',
  key:                   'key',
  value:                 'value',
  source_url:            'source-url',
  ansible_playbook:      'ansible-playbook',
  groups:                'groups',
  hostnames:             'hostnames'
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(available_ram, available_disk, mode) ⇒ VariablesController

Returns a new instance of VariablesController.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 48

def initialize(available_ram, available_disk, mode)
  @required_ram   = 0
  @required_disk  = 0
  @available_ram  = available_ram
  @available_disk = available_disk
  @mode = mode

  begin
    @json = JSON.parse(File.read("#{Dir.pwd}/#{Configs::Blueprint::FILE_NAME}"))
  rescue => e
    Put.error e
    exit!
  end
end

Instance Attribute Details

#available_diskObject

Returns the value of attribute available_disk.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def available_disk
  @available_disk
end

#available_ramObject

Returns the value of attribute available_ram.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def available_ram
  @available_ram
end

#cookiesObject

Returns the value of attribute cookies.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def cookies
  @cookies
end

#jsonObject

Returns the value of attribute json.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def json
  @json
end

#modeObject

Returns the value of attribute mode.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def mode
  @mode
end

#required_diskObject

Returns the value of attribute required_disk.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def required_disk
  @required_disk
end

#required_ramObject

Returns the value of attribute required_ram.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def required_ram
  @required_ram
end

#variablesObject

Returns the value of attribute variables.



7
8
9
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 7

def variables
  @variables
end

Instance Method Details

#ansibleObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 165

def ansible

  if has_ansible?
    ansible = VagrantSubutai::Models::Ansible.new
    ansible_configuration = @json[KEYS[:ansible_configuration]]

    ansible.ansible_playbook = ansible_configuration[KEYS[:ansible_playbook]]
    ansible.source_url = ansible_configuration[KEYS[:source_url]]
    ansible.extra_vars = []
    ansible.groups = []

    ansible_configuration[KEYS[:groups]].each do |group|
      temp = group
      hostnames = []

      group[KEYS[:hostnames]].each do |hostname|
        hostnames << value(hostname)
      end
      temp[KEYS[:hostnames]] = hostnames
      ansible.groups << temp
    end

    if ansible_configuration.key?(KEYS[:extra_vars])
      ansible_configuration[KEYS[:extra_vars]].each do |obj|
        hash = {}
        hash[obj[KEYS[:key]]] = value(obj[KEYS[:value]])
        ansible.extra_vars << hash
      end
    end

    ansible
  end
end

#bazaar_params(variables) ⇒ Object



386
387
388
389
390
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 386

def bazaar_params(variables)
  variables.each do |variable|
    Put.info variable['label']
  end
end

#check_quota?(resource) ⇒ Boolean

Returns:

  • (Boolean)


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 122

def check_quota?(resource)
  resource = JSON.parse(resource)

  @free_ram = resource['RAM']['free'].to_f / 1073741824                                       # convert bytes to gb
  @free_disk = (resource['Disk']['total'].to_f - resource['Disk']['used'].to_f) / 1073741824  # convert bytes to gb

  @free_ram = @free_ram.round(3)
  @free_disk = @free_disk.round(2)

  check_required_quota

  if @free_ram >= @required_ram && @free_disk >= @required_disk
    true
  else
    Put.warn "\nNo available resources on the Peer Os\n"
    Put.info "--------------------------------------------------------------------"
    if @free_ram >= @required_ram
      Put.info "RAM:  available = #{@free_ram} gb, required minimum = #{@required_ram} gb"
    else
      Put.error "RAM:  available = #{@free_ram} gb, required minimum = #{@required_ram} gb"
    end

    Put.info "--------------------------------------------------------------------"

    if @free_disk >= @required_disk
      Put.info "DISK:  available = #{@free_disk} gb, required minimum = #{@required_disk} gb"
    else
      Put.error "DISK:  available = #{@free_disk} gb, required minimum = #{@required_disk} gb"
    end
    Put.info "--------------------------------------------------------------------"

    false
  end
end

#check_required_quotaObject

This counts how mach quota(ram, disk) required for building environment from the Peer Os



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 100

def check_required_quota
  if @json.key?(KEYS[:user_variables])
    user_variables = @json[KEYS[:user_variables]]
    keys = user_variables.keys

    keys.each do |key|
      if user_variables[key][KEYS[:type]] == 'enum' && Configs::Blueprint::CONTAINER_SIZES.include?(user_variables[key][KEYS[:default]])
        @required_ram  += (VagrantSubutai::Configs::Quota::RESOURCE[(user_variables[key][KEYS[:default]]).strip.to_sym][:RAM])
        @required_disk += (VagrantSubutai::Configs::Quota::RESOURCE[(user_variables[key][KEYS[:default]]).strip.to_sym][:DISK])
      end
    end

    @required_ram  += VagrantSubutai::Configs::Quota::RESOURCE[:TINY][:RAM] if @json.key?(KEYS[:ansible_configuration])  # default ansible container ram
    @required_disk += VagrantSubutai::Configs::Quota::RESOURCE[:TINY][:DISK] if @json.key?(KEYS[:ansible_configuration]) # default ansible container disk
  else
    @json[KEYS[:containers]].each do |container|
      @required_ram  += (VagrantSubutai::Configs::Quota::RESOURCE[(container[KEYS[:size]]).to_sym][:RAM])
      @required_disk += (VagrantSubutai::Configs::Quota::RESOURCE[(container[KEYS[:size]]).to_sym][:DISK])
    end
  end
end

#containersObject

Containers

Returns:

  • Container Models



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 269

def containers
  arr = []

  @json[KEYS[:containers]].each do |container|
    cont = VagrantSubutai::Models::Container.new

    cont.hostname = value(container[KEYS[:hostname]])
    cont.container_size = value(container[KEYS[:size]])
    cont.template = container[KEYS[:template]]
    cont.peer_criteria = container[KEYS[:peer_criteria]]
    cont.port_mapping = container[KEYS[:port_mapping]]

    arr << cont
  end

  if @json.key?(KEYS[:ansible_configuration])
    cont = VagrantSubutai::Models::Container.new
    cont.ansible
    arr << cont
  end

  arr
end

#domainObject

Domain

Returns:

  • Domain Model or nil



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 295

def domain
  @json[KEYS[:containers]].each do |container|
    if container.key?(KEYS[:port_mapping])
      container[KEYS[:port_mapping]].each do |port_map|
        if port_map[KEYS[:protocol]].downcase == 'http' || port_map[KEYS[:protocol]].downcase == 'tcp'
          domain = VagrantSubutai::Models::Domain.new

          domain.protocol = port_map[KEYS[:protocol]]
          domain.name = value(port_map[KEYS[:domain]])
          domain.internal_port = port_map[KEYS[:internal_port]]
          domain.external_port = port_map[KEYS[:external_port]]
          domain.container_hostname = value(container[KEYS[:hostname]])

          return domain
        end
      end
    end
  end

  nil
end

#environmentObject

Environment

Returns:

  • Environment model



260
261
262
263
264
265
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 260

def environment
  env = VagrantSubutai::Models::Environment.new
  env.name = value(@json[KEYS[:name]])
  env.containers = containers
  env
end

#get_input(variable_json) ⇒ Object

Gets input variable



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
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 319

def get_input(variable_json)
  if variable_json[KEYS[:type]] == 'enum'
    Put.info "\n#{variable_json[KEYS[:description]]} (Ex: #{variable_json[KEYS[:default]]}): "
    validations = variable_json[KEYS[:validation]].split(',')

    temp = nil
    validations.each_with_index do |validation, index|
      if Configs::Blueprint::CONTAINER_SIZES.include?(validation) && @available_ram >= Configs::Quota::RESOURCE[validation.strip.to_sym][:RAM] && @available_disk >= Configs::Quota::RESOURCE[validation.strip.to_sym][:DISK]
        Put.info "    #{index}. #{validation}"
        temp = index
      else
        Put.info "    #{index}. #{validation}"
        temp = index
      end
    end

    Put.info "\nChoose your container size between ( 0 to #{temp}): "
    input = STDIN.gets.strip.to_i
    validations[input]
  elsif mode == Configs::Blueprint::MODE::BAZAAR && variable_json[KEYS[:type]] == 'domain'
    Put.info "\n#Create a new domain: (Ex: YOUR_DOMAIN_NAME.envs.subutai.cloud)"
    reserve
  else
    Put.info "\n#{variable_json[KEYS[:description]]}: (Ex: #{variable_json[KEYS[:default]]})"

    STDIN.gets.strip
  end
end

#get_input_bazaar(variable) ⇒ 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
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 392

def get_input_bazaar(variable)
  Put.info "\n#{variable['label']}"

  if variable['type'] == 'enum'
    arr = []
    arr = variable['acceptableValues'] if variable.key?('acceptableValues')
    temp = -1

    arr.each_with_index do |val, index|
      Put.info "     #{index}.  #{val}"
      temp = index
    end

    Put.info "\nChoose your container size between ( 0 to #{temp}): "
    input = STDIN.gets.strip.to_i
    arr[input]
  elsif variable['type'] == 'domain'
    arr = []
    arr = variable['acceptableValues'] if variable.key?('acceptableValues')
    temp = -1

    arr.each_with_index do |val, index|
      Put.info "     #{index}.  #{val}"
      temp = index
    end
    Put.info "     #{temp+1}.  Create a new domain: (Ex: YOUR_DOMAIN_NAME.envs.subutai.cloud)"

    Put.info "\nChoose options:  ( 0 to #{temp+1}) "
    input = STDIN.gets.strip.to_i

    if temp+1 == input
      Put.success "\nCreate a new domain: (Ex: YOUR_DOMAIN_NAME.envs.subutai.cloud)"
      reserve
    else
      Put.success "\n Chosen a domain: #{arr[input]}"
      arr[input]
    end
  else
    STDIN.gets.strip
  end
end

#has_ansible?Boolean

Returns:

  • (Boolean)


157
158
159
160
161
162
163
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 157

def has_ansible?
  if @json.key?(KEYS[:ansible_configuration])
    true
  else
    false
  end
end

#is_variable?(var) ⇒ Boolean

Returns:

  • (Boolean)


250
251
252
253
254
255
256
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 250

def is_variable?(var)
  if (var =~ /\${(.*?)}/).nil?
    false
  else
    true
  end
end

#params(rh_id, peer_id) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 199

def params(rh_id, peer_id)
  env = environment
  containers = env.containers

  hash = {}
  nodes = []

  if mode == Configs::Blueprint::MODE::PEER
    containers.each do |container|
      node = {}
      node['hostname'] = container.hostname
      node['quota'] = {'containerSize' => container.container_size}
      node['templateId'] = Rest::Bazaar.template_id(container.name, container.owner)
      node['resourceHostId'] = rh_id
      node['peerId'] = peer_id
      nodes << node
    end

    hash['name'] = env.name
    hash['sshKey'] = ""
    hash['nodes'] = nodes
  elsif mode == Configs::Blueprint::MODE::BAZAAR
    containers.each do |container|
      node = {}
      node['hostname'] = container.hostname
      node['quota'] = {'containerSize' => container.container_size}
      node['templateId'] = Rest::Bazaar.template_id(container.name, container.owner)
      node['resourceHostId'] = rh_id
      node['templateName'] = container.name
      node['peerId'] = peer_id
      nodes << node
    end

    hash['environmentName'] = env.name
    hash['exchangeSshKeys'] = true
    hash['registerHosts'] = true
    hash['nodes'] = nodes
  end


  hash
end

#reserveObject



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
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 348

def reserve
  begin
    @temp = STDIN.gets.strip
    @response = VagrantSubutai::Rest::Bazaar.reserve(@cookies, @temp)

    until @response.kind_of?(Net::HTTPOK)
      Put.warn "\n-------------------------------------------------------------------"
      Put.warn "Requested \"#{@temp}.envs.subutai.cloud\" sub-domain already exists"
      Put.warn '-------------------------------------------------------------------'

      Put.info "\n#Create a new domain: (Ex: YOUR_DOMAIN_NAME.envs.subutai.cloud)"
      @temp = STDIN.gets.strip
      @response = VagrantSubutai::Rest::Bazaar.reserve(@cookies, @temp)
    end

    res = VagrantSubutai::Rest::Bazaar.domains(@cookies)
    json = JSON.parse(res.body)

    json = json.find {|domain| domain['name'].split('.').first == @temp}

    Put.info "\n Created a new domain: #{json['name']}"

    json['name']
  rescue => e
    Put.error e
  end
end

#user_variablesObject

Gives Subutai.json user variables returns json object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 65

def user_variables
  hash = {}

  if @json.key?(KEYS[:user_variables])
    conf_user_variables = SubutaiConfig.get(:USER_VARIABLES)

    if conf_user_variables.nil?
      conf_user_variables = {}
    else
      if conf_user_variables.kind_of?(String)
        begin
          conf_user_variables = JSON.parse(SubutaiConfig.get(:USER_VARIABLES))
        rescue JSON::ParserError => e
          Put.error e
          return
        end
      end
    end

    user_variables = @json[KEYS[:user_variables]]
    keys = user_variables.keys

    keys.each do |key|
      if conf_user_variables[key].nil?
        hash[key] = get_input(user_variables[key])
      else
        hash[key] = conf_user_variables[key]
      end
    end
  end

  @variables = hash
end

#validateObject

Validates Subutai.json file



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 435

def validate
  scheme = Configs::Blueprint::SCHEME

  # Check keys
  @json.keys.each do |key|
    unless scheme.key?(key.to_sym)
      Put.error "Undefined key: \"#{key}\""
      return false
    end
  end

  scheme_container = scheme[:containers].first
  scheme_port_mapping = scheme_container[KEYS[:port_mapping].to_sym].first
  # Check container keys
  @json[KEYS[:containers]].each do |container|
    container.keys.each do |key|
      unless scheme_container.key?(key.to_sym)
        Put.error "Undefined key: \"#{key}\""
        return false
      end

      if key == KEYS[:size] && !is_variable?(container[KEYS[:size]])
        unless Configs::Blueprint::CONTAINER_SIZES.include?(container[KEYS[:size]])
          Put.error "Undefined container size: #{container[KEYS[:size]]}"
          return false
        end
      end

      if container.key?(KEYS[:port_mapping])
        container[KEYS[:port_mapping]].each do |port_map|
          port_map.keys.each do |key|
            unless scheme_port_mapping.key?(key.to_sym)
              Put.error "Undefined port-mapping key: #{key}"
              return false
            end
          end
        end
      end
    end
  end

  # Check ansible configuration
  if @json.key?(KEYS[:ansible_configuration])
    @json[KEYS[:ansible_configuration]].keys.each do |key|
      unless scheme[KEYS[:ansible_configuration].to_sym].key?(key.to_sym)
        Put.error "Undefined ansible-configuration key: #{key}"
        return false
      end
    end

    # check extra-vars
    if @json[KEYS[:ansible_configuration]].key?(KEYS[:extra_vars])
      unless @json[KEYS[:ansible_configuration]][KEYS[:extra_vars]].kind_of?(Array)
        Put.error "ansible-configuration extra-vals should be JSON array \"[]\""
        return false
      end

      @json[KEYS[:ansible_configuration]][KEYS[:extra_vars]].each do |extra_var|
        unless extra_var.key?(KEYS[:key])
          Put.error "ansible-configuration extra-vals has no \"key\" key"
          return false
        end

        unless extra_var.key?(KEYS[:value])
          Put.error "ansible-configuration extra-vals has no \"value\" key"
          return false
        end
      end
    end

    # check groups
    if @json[KEYS[:ansible_configuration]].key?(KEYS[:groups])
      unless @json[KEYS[:ansible_configuration]][KEYS[:groups]].kind_of?(Array)
        Put.error "groups should be JSON array"
        return false
      end

      @json[KEYS[:ansible_configuration]][KEYS[:groups]].each do |group|
        group.keys.each do |key|
          unless scheme[KEYS[:ansible_configuration].to_sym][KEYS[:groups].to_sym].first.key?(key.to_sym)
            Put.error "Undefined groups key: #{key}"
            return false
          end
        end
      end
    end
  end

  # check peer criteria
  @json[KEYS[:peer_criteria]].each do |peer_criteria|
    peer_criteria.keys.each do |key|
      unless scheme[KEYS[:peer_criteria].to_sym].first.key?(key.to_sym)
        Put.error "Undefined peer-criteria key: #{key}"
        return false
      end
    end
  end

  # check user-variables
  if @json.key?(KEYS[:user_variables])
    @json[KEYS[:user_variables]].keys.each do |key|
      user_variable = @json[KEYS[:user_variables]][key]
      user_variable.keys.each do |key|
        unless scheme[KEYS[:user_variables].to_sym][:any_name].key?(key.to_sym)
          Put.error "Undefined user-variables key: #{key}"
          return false
        end
      end
    end
  end

  true
end

#validate_variable(var, variable_json) ⇒ Object

Validate variable



378
379
380
381
382
383
384
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 378

def validate_variable(var, variable_json)
  if (var =~ /#{Regexp.quote(variable_json[KEYS[:validation]])}/).nil?
    false
  else
    true
  end
end

#value(variable) ⇒ Object



242
243
244
245
246
247
248
# File 'lib/vagrant-subutai/blueprint/variables_controller.rb', line 242

def value(variable)
  if is_variable?(variable)
    @variables[variable[/\${(.*?)}/, 1]]
  else
    variable
  end
end