Module: Vmpooler::API::Helpers
Constant Summary
InputValidator::HOSTNAME_PATTERN, InputValidator::INTEGER_PATTERN, InputValidator::MAX_HOSTNAME_LENGTH, InputValidator::MAX_POOL_NAME_LENGTH, InputValidator::MAX_REASON_LENGTH, InputValidator::MAX_TAG_KEY_LENGTH, InputValidator::MAX_TAG_VALUE_LENGTH, InputValidator::MAX_TOKEN_LENGTH, InputValidator::POOL_NAME_PATTERN, InputValidator::TAG_KEY_PATTERN, InputValidator::TOKEN_PATTERN
Instance Method Summary
collapse
-
#authenticate(auth, username_str, password_str) ⇒ Object
-
#authenticate_ldap(port, host, encryption_hash, user_object, base, username_str, password_str, service_account_hash = nil) ⇒ Object
-
#authorized? ⇒ Boolean
-
#export_tags(backend, hostname, tags) ⇒ Object
-
#filter_tags(tags) ⇒ Object
-
#get_capacity_metrics(pools, backend) ⇒ Object
-
#get_list_across_pools_redis_hget(pools, key, backend) ⇒ Object
Takes the pools and a key to run hget on returns a hash with each pool name as key and the value as string.
-
#get_list_across_pools_redis_scard(pools, key, backend) ⇒ Object
Takes the pools and a key to run scard on returns a hash with each pool name as key and the value being the count as integer.
-
#get_queue_metrics(pools, backend) ⇒ Object
-
#get_tag_metrics(backend, date_str, opts = {}) ⇒ Object
-
#get_tag_summary(backend, from_date, to_date, opts = {}) ⇒ Object
-
#get_task_metrics(backend, task_str, date_str, opts = {}) ⇒ Object
-
#get_task_summary(backend, task_str, from_date, to_date, opts = {}) ⇒ Object
-
#get_task_times(backend, task, date_str) ⇒ Object
-
#get_total_across_pools_redis_scard(pools, key, backend) ⇒ Object
Takes the pools and a key to run scard on returns an integer for the total count.
-
#has_token? ⇒ Boolean
-
#hostname_shorten(hostname) ⇒ Object
-
#is_integer?(x) ⇒ Boolean
-
#mean(list) ⇒ Object
-
#open_socket(host, domain = nil, timeout = 1, port = 22, &_block) ⇒ Object
-
#pool_index(pools) ⇒ Object
-
#template_ready?(pool, backend) ⇒ Boolean
-
#tracer ⇒ Object
-
#valid_token?(backend) ⇒ Boolean
-
#validate_auth(backend) ⇒ Object
-
#validate_date_str(date_str) ⇒ Object
-
#validate_token(backend) ⇒ Object
#sanitize_json_body, #validate_disk_size, #validate_hostname, #validate_integer, #validate_lifetime, #validate_pool_name, #validate_reason, #validate_tag, #validate_token_format, #validate_vm_count, #validation_error?
Instance Method Details
#authenticate(auth, username_str, password_str) ⇒ Object
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
|
# File 'lib/vmpooler/api/helpers.rb', line 121
def authenticate(auth, username_str, password_str)
tracer.in_span(
"Vmpooler::API::Helpers.#{__method__}",
attributes: {
'enduser.id' => username_str
}
) do
case auth['provider']
when 'dummy'
return (username_str != password_str)
when 'ldap'
ldap_base = auth[:ldap]['base']
ldap_port = auth[:ldap]['port'] || 389
ldap_user_obj = auth[:ldap]['user_object']
ldap_host = auth[:ldap]['host']
ldap_encryption_hash = auth[:ldap]['encryption'] || {
:method => :start_tls,
:tls_options => { :ssl_version => 'TLSv1' }
}
service_account_hash = auth[:ldap]['service_account_hash']
unless ldap_base.is_a? Array
ldap_base = ldap_base.split
end
unless ldap_user_obj.is_a? Array
ldap_user_obj = ldap_user_obj.split
end
ldap_base.each do |search_base|
ldap_user_obj.each do |search_user_obj|
result = authenticate_ldap(
ldap_port,
ldap_host,
ldap_encryption_hash,
search_user_obj,
search_base,
username_str,
password_str,
service_account_hash
)
return true if result
end
end
return false
end
end
end
|
#authenticate_ldap(port, host, encryption_hash, user_object, base, username_str, password_str, service_account_hash = nil) ⇒ Object
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
# File 'lib/vmpooler/api/helpers.rb', line 74
def authenticate_ldap(port, host, encryption_hash, user_object, base, username_str, password_str, service_account_hash = nil)
tracer.in_span(
"Vmpooler::API::Helpers.#{__method__}",
attributes: {
'net.peer.name' => host,
'net.peer.port' => port,
'net.transport' => 'ip_tcp',
'enduser.id' => username_str
},
kind: :client
) do
if service_account_hash
username = service_account_hash[:user_dn]
password = service_account_hash[:password]
else
username = "#{user_object}=#{username_str},#{base}"
password = password_str
end
ldap = Net::LDAP.new(
:host => host,
:port => port,
:encryption => encryption_hash,
:base => base,
:auth => {
:method => :simple,
:username => username,
:password => password
}
)
if service_account_hash
return true if ldap.bind_as(
:base => base,
:filter => "(#{user_object}=#{username_str})",
:password => password_str
)
elsif ldap.bind
return true
else
return false
end
return false
end
end
|
#authorized? ⇒ Boolean
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/vmpooler/api/helpers.rb', line 58
def authorized?
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
@auth ||= Rack::Auth::Basic::Request.new(request.env)
if @auth.provided? and @auth.basic? and @auth.credentials
username, password = @auth.credentials
if authenticate(Vmpooler::API.settings.config[:auth], username, password)
return true
end
end
return false
end
end
|
171
172
173
174
175
176
177
178
179
180
181
182
|
# File 'lib/vmpooler/api/helpers.rb', line 171
def export_tags(backend, hostname, tags)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
backend.pipelined do |pipeline|
tags.each_pair do |tag, value|
next if value.nil? or value.empty?
pipeline.hset("vmpooler__vm__#{hostname}", "tag:#{tag}", value)
pipeline.hset("vmpooler__tag__#{Date.today}", "#{hostname}:#{tag}", value)
end
end
end
end
|
184
185
186
187
188
189
190
191
192
193
194
195
196
|
# File 'lib/vmpooler/api/helpers.rb', line 184
def filter_tags(tags)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
return unless Vmpooler::API.settings.config[:tagfilter]
tags.each_pair do |tag, value|
next unless filter = Vmpooler::API.settings.config[:tagfilter][tag]
tags[tag] = value.match(filter).captures.join if value.match(filter)
end
tags
end
end
|
#get_capacity_metrics(pools, backend) ⇒ Object
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
|
# File 'lib/vmpooler/api/helpers.rb', line 270
def get_capacity_metrics(pools, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
capacity = {
current: 0,
total: 0,
percent: 0
}
pools.each do |pool|
capacity[:total] += pool['size'].to_i
end
capacity[:current] = get_total_across_pools_redis_scard(pools, 'vmpooler__ready__', backend)
if capacity[:total] > 0
capacity[:percent] = (capacity[:current].fdiv(capacity[:total]) * 100.0).round(1)
end
capacity
end
end
|
#get_list_across_pools_redis_hget(pools, key, backend) ⇒ Object
Takes the pools and a key to run hget on returns a hash with each pool name as key and the value as string
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
# File 'lib/vmpooler/api/helpers.rb', line 253
def get_list_across_pools_redis_hget(pools, key, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
temp_hash = {}
res = backend.pipelined do |pipeline|
pools.each do |pool|
pipeline.hget(key, pool['name'])
end
end
pools.each_with_index do |pool, i|
temp_hash[pool['name']] = res[i].to_s
end
temp_hash
end
end
|
#get_list_across_pools_redis_scard(pools, key, backend) ⇒ Object
Takes the pools and a key to run scard on returns a hash with each pool name as key and the value being the count as integer
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
# File 'lib/vmpooler/api/helpers.rb', line 234
def get_list_across_pools_redis_scard(pools, key, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
temp_hash = {}
res = backend.pipelined do |pipeline|
pools.each do |pool|
pipeline.scard(key + pool['name'])
end
end
pools.each_with_index do |pool, i|
temp_hash[pool['name']] = res[i].to_i
end
temp_hash
end
end
|
#get_queue_metrics(pools, backend) ⇒ Object
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
|
# File 'lib/vmpooler/api/helpers.rb', line 292
def get_queue_metrics(pools, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
queue = {
requested: 0,
pending: 0,
cloning: 0,
booting: 0,
ready: 0,
running: 0,
completed: 0,
total: 0
}
results = backend.pipelined do |pipeline|
pools.each do |pool|
pipeline.scard("vmpooler__provisioning__request#{pool['name']}") pipeline.scard("vmpooler__provisioning__processing#{pool['name']}") pipeline.scard("vmpooler__odcreate__task#{pool['name']}") pipeline.scard("vmpooler__pending__#{pool['name']}") pipeline.scard("vmpooler__ready__#{pool['name']}") pipeline.scard("vmpooler__running__#{pool['name']}") pipeline.scard("vmpooler__completed__#{pool['name']}") end
pipeline.get('vmpooler__tasks__clone') pipeline.get('vmpooler__tasks__ondemandclone') end
n = pools.length
queue[:requested] = (results[0...n] || []).sum(&:to_i) +
(results[n...(2 * n)] || []).sum(&:to_i) +
(results[(2 * n)...(3 * n)] || []).sum(&:to_i)
queue[:pending] = (results[(3 * n)...(4 * n)] || []).sum(&:to_i)
queue[:ready] = (results[(4 * n)...(5 * n)] || []).sum(&:to_i)
queue[:running] = (results[(5 * n)...(6 * n)] || []).sum(&:to_i)
queue[:completed] = (results[(6 * n)...(7 * n)] || []).sum(&:to_i)
queue[:cloning] = (results[7 * n] || 0).to_i + (results[7 * n + 1] || 0).to_i
queue[:booting] = queue[:pending].to_i - queue[:cloning].to_i
queue[:booting] = 0 if queue[:booting] < 0
queue[:total] = queue[:requested] + queue[:pending].to_i + queue[:ready].to_i + queue[:running].to_i + queue[:completed].to_i
queue
end
end
|
#get_tag_metrics(backend, date_str, opts = {}) ⇒ Object
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
|
# File 'lib/vmpooler/api/helpers.rb', line 339
def get_tag_metrics(backend, date_str, opts = {})
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
opts = {:only => false}.merge(opts)
tags = {}
backend.hgetall("vmpooler__tag__#{date_str}").each do |key, value|
hostname = 'unknown'
tag = 'unknown'
if key =~ /:/
hostname, tag = key.split(':', 2)
end
next if opts[:only] && tag != opts[:only]
tags[tag] ||= {}
tags[tag][value] ||= 0
tags[tag][value] += 1
tags[tag]['total'] ||= 0
tags[tag]['total'] += 1
end
tags
end
end
|
#get_tag_summary(backend, from_date, to_date, opts = {}) ⇒ Object
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
|
# File 'lib/vmpooler/api/helpers.rb', line 367
def get_tag_summary(backend, from_date, to_date, opts = {})
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
opts = {:only => false}.merge(opts)
result = {
tag: {},
daily: []
}
(from_date..to_date).each do |date|
daily = {
date: date.to_s,
tag: get_tag_metrics(backend, date.to_s, opts)
}
result[:daily].push(daily)
end
result[:daily].each do |daily|
daily[:tag].each_key do |tag|
result[:tag][tag] ||= {}
daily[:tag][tag].each do |key, value|
result[:tag][tag][key] ||= 0
result[:tag][tag][key] += value
end
end
end
result
end
end
|
#get_task_metrics(backend, task_str, date_str, opts = {}) ⇒ Object
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
|
# File 'lib/vmpooler/api/helpers.rb', line 399
def get_task_metrics(backend, task_str, date_str, opts = {})
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
opts = {:bypool => false, :only => false}.merge(opts)
task = {
duration: {
average: 0,
min: 0,
max: 0,
total: 0
},
count: {
total: 0
}
}
task[:count][:total] = backend.hlen("vmpooler__#{task_str}__#{date_str}").to_i
if task[:count][:total] > 0
if opts[:bypool] == true
task_times_bypool = {}
task[:count][:pool] = {}
task[:duration][:pool] = {}
backend.hgetall("vmpooler__#{task_str}__#{date_str}").each do |key, value|
pool = 'unknown'
hostname = 'unknown'
if key =~ /:/
pool, hostname = key.split(':')
else
hostname = key
end
task[:count][:pool][pool] ||= {}
task[:duration][:pool][pool] ||= {}
task_times_bypool[pool] ||= []
task_times_bypool[pool].push(value.to_f)
end
task_times_bypool.each_key do |pool|
task[:count][:pool][pool][:total] = task_times_bypool[pool].length
task[:duration][:pool][pool][:total] = task_times_bypool[pool].reduce(:+).to_f
task[:duration][:pool][pool][:average] = (task[:duration][:pool][pool][:total] / task[:count][:pool][pool][:total]).round(1)
task[:duration][:pool][pool][:min], task[:duration][:pool][pool][:max] = task_times_bypool[pool].minmax
end
end
task_times = get_task_times(backend, task_str, date_str)
task[:duration][:total] = task_times.reduce(:+).to_f
task[:duration][:average] = (task[:duration][:total] / task[:count][:total]).round(1)
task[:duration][:min], task[:duration][:max] = task_times.minmax
end
if opts[:only]
task.each_key do |key|
task.delete(key) unless key.to_s == opts[:only]
end
end
task
end
end
|
#get_task_summary(backend, task_str, from_date, to_date, opts = {}) ⇒ Object
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
|
# File 'lib/vmpooler/api/helpers.rb', line 467
def get_task_summary(backend, task_str, from_date, to_date, opts = {})
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
opts = {:bypool => false, :only => false}.merge(opts)
task_sym = task_str.to_sym
result = {
task_sym => {},
daily: []
}
(from_date..to_date).each do |date|
daily = {
date: date.to_s,
task_sym => get_task_metrics(backend, task_str, date.to_s, opts)
}
result[:daily].push(daily)
end
daily_task = {}
daily_task_bypool = {} if opts[:bypool] == true
result[:daily].each do |daily|
daily[task_sym].each_key do |type|
result[task_sym][type] ||= {}
daily_task[type] ||= {}
['min', 'max'].each do |key|
if daily[task_sym][type][key]
daily_task[type][:data] ||= []
daily_task[type][:data].push(daily[task_sym][type][key])
end
end
result[task_sym][type][:total] ||= 0
result[task_sym][type][:total] += daily[task_sym][type][:total]
if opts[:bypool] == true
result[task_sym][type][:pool] ||= {}
daily_task_bypool[type] ||= {}
next unless daily[task_sym][type][:pool]
daily[task_sym][type][:pool].each_key do |pool|
result[task_sym][type][:pool][pool] ||= {}
daily_task_bypool[type][pool] ||= {}
['min', 'max'].each do |key|
if daily[task_sym][type][:pool][pool][key.to_sym]
daily_task_bypool[type][pool][:data] ||= []
daily_task_bypool[type][pool][:data].push(daily[task_sym][type][:pool][pool][key.to_sym])
end
end
result[task_sym][type][:pool][pool][:total] ||= 0
result[task_sym][type][:pool][pool][:total] += daily[task_sym][type][:pool][pool][:total]
end
end
end
end
result[task_sym].each_key do |type|
if daily_task[type][:data]
result[task_sym][type][:min], result[task_sym][type][:max] = daily_task[type][:data].minmax
result[task_sym][type][:average] = mean(daily_task[type][:data])
end
if opts[:bypool] == true
result[task_sym].each_key do |type|
result[task_sym][type][:pool].each_key do |pool|
if daily_task_bypool[type][pool][:data]
result[task_sym][type][:pool][pool][:min], result[task_sym][type][:pool][pool][:max] = daily_task_bypool[type][pool][:data].minmax
result[task_sym][type][:pool][pool][:average] = mean(daily_task_bypool[type][pool][:data])
end
end
end
end
end
result
end
end
|
#get_task_times(backend, task, date_str) ⇒ Object
211
212
213
214
215
|
# File 'lib/vmpooler/api/helpers.rb', line 211
def get_task_times(backend, task, date_str)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
backend.hvals("vmpooler__#{task}__" + date_str).map(&:to_f)
end
end
|
#get_total_across_pools_redis_scard(pools, key, backend) ⇒ Object
Takes the pools and a key to run scard on returns an integer for the total count
219
220
221
222
223
224
225
226
227
228
229
230
|
# File 'lib/vmpooler/api/helpers.rb', line 219
def get_total_across_pools_redis_scard(pools, key, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
res = backend.pipelined do |pipeline|
pools.each do |pool|
pipeline.scard(key + pool['name'])
end
end
res.inject(0) { |m, x| m + x }.to_i
end
end
|
#has_token? ⇒ Boolean
16
17
18
|
# File 'lib/vmpooler/api/helpers.rb', line 16
def has_token?
request.env['HTTP_X_AUTH_TOKEN'].nil? ? false : true
end
|
#hostname_shorten(hostname) ⇒ Object
207
208
209
|
# File 'lib/vmpooler/api/helpers.rb', line 207
def hostname_shorten(hostname)
hostname[/[^.]+/]
end
|
#is_integer?(x) ⇒ Boolean
570
571
572
573
574
575
|
# File 'lib/vmpooler/api/helpers.rb', line 570
def is_integer?(x)
Integer(x)
true
rescue StandardError
false
end
|
#mean(list) ⇒ Object
198
199
200
201
|
# File 'lib/vmpooler/api/helpers.rb', line 198
def mean(list)
s = list.map(&:to_f).reduce(:+).to_f
(s > 0 && list.length > 0) ? s / list.length.to_f : 0
end
|
#open_socket(host, domain = nil, timeout = 1, port = 22, &_block) ⇒ Object
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
|
# File 'lib/vmpooler/api/helpers.rb', line 577
def open_socket(host, domain = nil, timeout = 1, port = 22, &_block)
tracer.in_span(
"Vmpooler::API::Helpers.#{__method__}",
attributes: {
'net.peer.port' => port,
'net.transport' => 'ip_tcp'
},
kind: :client
) do
target_host = host
target_host = "#{host}.#{domain}" if domain
span = OpenTelemetry::Trace.current_span
span.set_attribute('net.peer.name', target_host)
sock = TCPSocket.new(target_host, port, connect_timeout: timeout)
begin
yield sock if block_given?
ensure
sock.close
end
end
end
|
#pool_index(pools) ⇒ Object
550
551
552
553
554
555
556
557
558
|
# File 'lib/vmpooler/api/helpers.rb', line 550
def pool_index(pools)
pools_hash = {}
index = 0
pools.each do |pool|
pools_hash[pool['name']] = index
index += 1
end
pools_hash
end
|
#template_ready?(pool, backend) ⇒ Boolean
560
561
562
563
564
565
566
567
568
|
# File 'lib/vmpooler/api/helpers.rb', line 560
def template_ready?(pool, backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
prepared_template = backend.hget('vmpooler__template__prepared', pool['name'])
return false if prepared_template.nil?
return true if pool['template'] == prepared_template
return false
end
end
|
#tracer ⇒ Object
12
13
14
|
# File 'lib/vmpooler/api/helpers.rb', line 12
def tracer
@tracer ||= OpenTelemetry.tracer_provider.tracer('api', Vmpooler::VERSION)
end
|
#valid_token?(backend) ⇒ Boolean
20
21
22
23
24
25
26
|
# File 'lib/vmpooler/api/helpers.rb', line 20
def valid_token?(backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
return false unless has_token?
backend.exists?("vmpooler__token__#{request.env['HTTP_X_AUTH_TOKEN']}") ? true : false
end
end
|
#validate_auth(backend) ⇒ Object
45
46
47
48
49
50
51
52
53
54
55
56
|
# File 'lib/vmpooler/api/helpers.rb', line 45
def validate_auth(backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
return if authorized?
content_type :json
result = { 'ok' => false }
['WWW-Authenticate'] = 'Basic realm="Authentication required"'
halt 401, JSON.pretty_generate(result)
end
end
|
#validate_date_str(date_str) ⇒ Object
203
204
205
|
# File 'lib/vmpooler/api/helpers.rb', line 203
def validate_date_str(date_str)
/^\d{4}-\d{2}-\d{2}$/ === date_str
end
|
#validate_token(backend) ⇒ Object
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
# File 'lib/vmpooler/api/helpers.rb', line 28
def validate_token(backend)
tracer.in_span("Vmpooler::API::Helpers.#{__method__}") do
if valid_token?(backend)
backend.hset("vmpooler__token__#{request.env['HTTP_X_AUTH_TOKEN']}", 'last', Time.now.to_s)
return true
end
content_type :json
result = { 'ok' => false }
['WWW-Authenticate'] = 'Basic realm="Authentication required"'
halt 401, JSON.pretty_generate(result)
end
end
|