This file is indexed.

/usr/bin/oneflow is in opennebula-tools 4.12.3+dfsg-3.1build1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
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
198
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2010-2015, C12G Labs S.L.                                        #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

ONE_LOCATION=ENV["ONE_LOCATION"]

if !ONE_LOCATION
    RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
    RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end

$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+'/cli'

require 'command_parser'
require 'opennebula/oneflow_client'

require 'cli_helper'
require 'one_helper/onevm_helper'

require 'json'

USER_AGENT = "CLI"

# Base Path representing the resource to be used in the requests
RESOURCE_PATH = "/service"

#
# Table
#

SERVICE_TABLE = CLIHelper::ShowTable.new(nil, self) do
    column :ID, "ID", :size=>10 do |d|
        d["ID"]
    end

    column :USER, "Username", :left, :size=>15 do |d|
        d["UNAME"]
    end

    column :GROUP, "Group", :left, :size=>15 do |d|
        d["GNAME"]
    end

    column :NAME, "Name", :size=>25, :left=>true do |d|
        d["NAME"]
    end

    column :STATE, "State", :size=>11, :left=>true do |d|
        Service.state_str(d["TEMPLATE"]["BODY"]['state'])
    end

    default :ID, :USER, :GROUP, :NAME, :STATE
end

NODE_TABLE = CLIHelper::ShowTable.new(nil, self) do
    column :VM_ID, "ONE identifier for Virtual Machine", :size=>6 do |d|
        st = ""
        if d['scale_up']
            st << "\u2191 "
        elsif d['disposed']
            st << "\u2193 "
        end

        if d['vm_info'].nil?
            st << d['deploy_id'].to_s
        else
            st << d['vm_info']['VM']["ID"]
        end

        st
    end

    column :NAME, "Name of the Virtual Machine", :left,
            :size=>23 do |d|
        if !d['vm_info'].nil?
            if d['vm_info']['VM']["RESCHED"] == "1"
                "*#{d["NAME"]}"
            else
                d['vm_info']['VM']["NAME"]
            end
        else
            ""
        end
    end

    column :USER, "Username of the Virtual Machine owner", :left,
            :size=>8 do |d|
        if !d['vm_info'].nil?
            d['vm_info']['VM']["UNAME"]
        else
            ""
        end
    end

    column :GROUP, "Group of the Virtual Machine", :left,
            :size=>8 do |d|
        if !d['vm_info'].nil?
            d['vm_info']['VM']["GNAME"]
        else
            ""
        end
    end

    column :STAT, "Actual status", :size=>4 do |d,e|
        if !d['vm_info'].nil?
            OneVMHelper.state_to_str(d['vm_info']['VM']["STATE"], d['vm_info']['VM']["LCM_STATE"])
        else
            ""
        end
    end

    column :UCPU, "CPU percentage used by the VM", :size=>4 do |d|
        if !d['vm_info'].nil?
            d['vm_info']['VM']["CPU"]
        else
            ""
        end
    end

    column :UMEM, "Memory used by the VM", :size=>7 do |d|
        if !d['vm_info'].nil?
            OpenNebulaHelper.unit_to_str(d['vm_info']['VM']["MEMORY"].to_i, {})
        else
            ""
        end
    end

    column :HOST, "Host where the VM is running", :left, :size=>20 do |d|
        if !d['vm_info'].nil?
            if d['vm_info']['VM']['HISTORY_RECORDS'] && d['vm_info']['VM']['HISTORY_RECORDS']['HISTORY']
                state_str = VirtualMachine::VM_STATE[d['vm_info']['VM']['STATE'].to_i]
                if %w{ACTIVE SUSPENDED}.include? state_str
                    history = if d['vm_info']['VM']['HISTORY_RECORDS']['HISTORY'].instance_of?(Array)
                        d['vm_info']['VM']['HISTORY_RECORDS']['HISTORY'].last
                    else
                        d['vm_info']['VM']['HISTORY_RECORDS']['HISTORY']
                    end

                    history['HOSTNAME']
                end
            end
        else
            ""
        end
    end

    column :TIME, "Time since the VM was submitted", :size=>10 do |d|
        if !d['vm_info'].nil?
            stime = d['vm_info']['VM']["STIME"].to_i
            etime = d['vm_info']['VM']["ETIME"]=="0" ? Time.now.to_i : d['vm_info']['VM']["ETIME"].to_i
            dtime = etime-stime
            OpenNebulaHelper.period_to_str(dtime, false)
        else
            ""
        end
    end

    default :VM_ID, :NAME, :STAT, :UCPU, :UMEM, :HOST, :TIME
end

# List the services. This method is used in top and list commands
# @param [Service::Client] client
# @param [Array] args
# @param [Hash] options
# @return [[Integer, String], Integer] Returns the exit_code and optionally
#   a String to be printed
def list_services(client, args, options)
    response = client.get(RESOURCE_PATH)

    if CloudClient::is_error?(response)
        [response.code.to_i, response.to_s]
    else
        #[0,response.body]
        if options[:json]
            [0,response.body]
        else
            array_list = JSON.parse(response.body)
            SERVICE_TABLE.show(array_list['DOCUMENT_POOL']['DOCUMENT'])
            0
        end
    end
end

# Show the service information. This method is used in top and show commands
# @param [Service::Client] client
# @param [Array] args
# @param [Hash] options
# @return [[Integer, String], Integer] Returns the exit_code and optionally
#   a String to be printed
def show_service(client, args, options)
    response = client.get("#{RESOURCE_PATH}/#{args[0]}")

    if CloudClient::is_error?(response)
        [response.code.to_i, response.to_s]
    else
        #[0,response.body]
        if options[:json]
            [0,response.body]
        else
            str="%-20s: %-20s"
            str_h1="%-80s"

            document_hash = JSON.parse(response.body)
            template = document_hash['DOCUMENT']['TEMPLATE']['BODY']

            CLIHelper.print_header(str_h1 % "SERVICE #{document_hash['DOCUMENT']['ID']} INFORMATION")

            puts str % ["ID",   document_hash['DOCUMENT']['ID']]
            puts str % ["NAME", document_hash['DOCUMENT']['NAME']]
            puts str % ["USER", document_hash['DOCUMENT']['UNAME']]
            puts str % ["GROUP",document_hash['DOCUMENT']['GNAME']]

            puts str % ["STRATEGY", template['deployment']]
            puts str % ["SERVICE STATE", Service.state_str(template['state'])]
            puts str % ["SHUTDOWN", template['shutdown_action']] if template['shutdown_action']

            puts

            CLIHelper.print_header(str_h1 % "PERMISSIONS",false)

            ["OWNER", "GROUP", "OTHER"].each { |e|
                mask = "---"
                mask[0] = "u" if document_hash['DOCUMENT']['PERMISSIONS']["#{e}_U"] == "1"
                mask[1] = "m" if document_hash['DOCUMENT']['PERMISSIONS']["#{e}_M"] == "1"
                mask[2] = "a" if document_hash['DOCUMENT']['PERMISSIONS']["#{e}_A"] == "1"

                puts str % [e,  mask]
            }

            puts

            template['roles'].each {|role|
                CLIHelper.print_header("ROLE #{role['name']}", false)

                puts str % ["ROLE STATE", Role.state_str(role['state'])]
                puts str % ["PARENTS", role['parents'].join(', ')] if role['parents']
                puts str % ["VM TEMPLATE", role['vm_template']]
                puts str % ["CARDINALITY", role['cardinality']]
                puts str % ["MIN VMS", role['min_vms']] if role['min_vms']
                puts str % ["MAX VMS", role['max_vms']] if role['max_vms']
                puts str % ["COOLDOWN", "#{role['cooldown']}s"] if role['cooldown']
                puts str % ["SHUTDOWN", role['shutdown_action']] if role['shutdown_action']

                puts "NODES INFORMATION"
                NODE_TABLE.show(role['nodes'])

                if !role['elasticity_policies'].nil? && role['elasticity_policies'].size > 0 || !role['scheduled_policies'].nil? && role['scheduled_policies'].size > 0
                    puts
                    puts "ELASTICITY RULES"

                    if role['elasticity_policies'] && role['elasticity_policies'].size > 0
                        puts
#                        puts "ELASTICITY POLICIES"
                        CLIHelper::ShowTable.new(nil, self) do
                            column :ADJUST, "", :left, :size=>12 do |d|
                                adjust_str(d)
                            end

                            column :EXPRESSION, "", :left, :size=>48 do |d|
                                if !d['expression_evaluated'].nil?
                                    d['expression_evaluated']
                                else
                                    d['expression']
                                end
                            end

                            column :'EVALS', "", :right, :size=>5 do |d|
                                if d['period_number']
                                    "#{d['true_evals'].to_i} / #{d['period_number']}"
                                else
                                    "-"
                                end
                            end

                            column :PERIOD, "", :size=>6 do |d|
                                d['period'] ?  "#{d['period']}s" : '-'
                            end

                            column :COOL, "", :size=>5 do |d|
                                d['cooldown'] ? "#{d['cooldown']}s" : '-'
                            end

                            default :ADJUST, :EXPRESSION, :EVALS, :PERIOD, :COOL
                        end.show([role['elasticity_policies']].flatten, {})
                    end

                    if role['scheduled_policies'] && role['scheduled_policies'].size > 0
                        puts
#                        puts "SCHEDULED POLICIES"
                        CLIHelper::ShowTable.new(nil, self) do
                            column :ADJUST, "", :left, :size=>12 do |d|
                                adjust_str(d)
                            end

                            column :TIME, "", :left, :size=>67 do |d|
                                if d['start_time']
                                    Time.parse(d['start_time']).to_s
                                else
                                    d['recurrence']
                                end
                            end

                            default :ADJUST, :TIME
                        end.show([role['scheduled_policies']].flatten, {})
                    end
                end

                puts
            }

            puts

            CLIHelper.print_header(str_h1 % "LOG MESSAGES",false)

            if template['log']
                template['log'].each { |log|
                    t = Time.at(log['timestamp']).strftime("%m/%d/%y %H:%M")
                    puts "#{t} [#{log['severity']}] #{log['message']}"
                }
            end

            0
        end
    end
end

def adjust_str(policy)
    sign = policy['adjust'].to_i >= 0 ? "+" : "-"
    adjust = policy['adjust'].to_i.abs

    case policy['type']
    when 'CARDINALITY'
        "= #{adjust}"
    when 'PERCENTAGE_CHANGE'
        st = "#{sign} #{adjust} %"
        if policy['min_adjust_step']
            st << " (#{policy['min_adjust_step']})"
        end

        st
    else
        "#{sign} #{adjust}"
    end
end

#
# Commands
#

cmd=CommandParser::CmdParser.new(ARGV) do
    usage "`oneflow` <command> [<args>] [<options>]"
    version OpenNebulaHelper::ONE_VERSION

    set :option, Service::DEFAULT_OPTIONS
    set :option, CommandParser::VERSION
    set :option, CommandParser::HELP

    #
    # Formatters for arguments
    #
    set :format, :groupid, OpenNebulaHelper.rname_to_id_desc("GROUP") do |arg|
        OpenNebulaHelper.rname_to_id(arg, "GROUP")
    end

    set :format, :userid, OpenNebulaHelper.rname_to_id_desc("USER") do |arg|
        OpenNebulaHelper.rname_to_id(arg, "USER")
    end

    set :format, :service_id, Service.rname_to_id_desc("SERVICE") do |arg|
        Service.rname_to_id(arg, "SERVICE")
    end

    set :format, :service_id_list, Service.list_to_id_desc("SERVICE") do |arg|
        Service.list_to_id(arg, "SERVICE")
    end

    set :format, :vm_action, "Actions supported: #{Role::SCHEDULE_ACTIONS.join(', ')}" do |arg|
        if Role::SCHEDULE_ACTIONS.include?(arg)
            [0, arg]
        else
            [-1, "Action #{arg} is not supported. Actions supported: #{Role::SCHEDULE_ACTIONS.join(', ')}"]
        end
    end

    #
    # List
    #

    list_desc = <<-EOT.unindent
        List the available services
    EOT

    command :list, list_desc, :options => Service::JSON_FORMAT do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        list_services(client, args, options)
    end

    #
    # Show
    #

    show_desc = <<-EOT.unindent
        Show detailed information of a given service
    EOT

    command :show, show_desc, :service_id, :options => Service::JSON_FORMAT do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        show_service(client, args, options)
    end

    #
    # Top
    #

    top_desc = <<-EOT.unindent
        Top the services or the extended information of the target service if a
        id is specified
    EOT

    command :top, top_desc, [:service_id, nil],
            :options => [Service::JSON_FORMAT, Service::TOP, CLIHelper::DELAY] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        delay=options[:delay] ? options[:delay] : 3

        begin
            while true
                CLIHelper.scr_cls
                CLIHelper.scr_move(0,0)

                if args[0]
                    rc, message = show_service(client, args, options)

                    if rc != 0
                        raise message
                    end
                else
                    rc, message = list_services(client, args, options)

                    if rc != 0
                        raise message
                    end
                end

                sleep delay
            end
        rescue Exception => e
            puts e.message
            -1
        end
    end

    #
    # Delete
    #

    delete_desc = <<-EOT.unindent
        Delete a given service
    EOT

    command :delete, delete_desc, [:range, :service_id_list] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            client.delete("#{RESOURCE_PATH}/#{service_id}")
        }
    end

    #
    # Shutdown
    #

    shutdown_desc = <<-EOT.unindent
        Shutdown a service.
            From RUNNING or WARNING shuts down the Service
    EOT

    command :shutdown, shutdown_desc, [:range, :service_id_list] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            json_action = Service.build_json_action('shutdown')

            client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
        }
    end

    #
    # Recover
    #

    recover_desc = <<-EOT.unindent
        Recover a failed service, cleaning the failed VMs.
            From FAILED_DEPLOYING continues deploying the Service
            From FAILED_SCALING continues scaling the Service
            From FAILED_UNDEPLOYING continues shutting down the Service
            From COOLDOWN the Service is set to running ignoring the cooldown duration
            From WARNING failed VMs are deleted, and new VMs are instantiated
    EOT

    command :recover, recover_desc, [:range, :service_id_list] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            json_action = Service.build_json_action('recover')

            client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
        }
    end

    #
    # Scale
    #

    scale_desc = <<-EOT.unindent
        Scale a role to the given cardinality
    EOT

    command :'scale', scale_desc, :service_id, :role_name,
        :cardinality, :options => [Service::FORCE] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        if !(args[2] =~ /^\d+$/)
            puts "Cardinality must be an integer number"
            exit -1
        end

        exit_code = 0

        json =  "{ \"cardinality\" : #{args[2]},\n"<<
                "  \"force\" : #{options[:force] == true} }"

        response = client.put("#{RESOURCE_PATH}/#{args[0]}/role/#{args[1]}", json)

        if CloudClient::is_error?(response)
            puts response.to_s
            exit_code = response.code.to_i
        end

        exit_code
    end

    chgrp_desc = <<-EOT.unindent
        Changes the service group
    EOT

    command :chgrp, chgrp_desc, [:range, :service_id_list], :groupid do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            params = Hash.new
            params['group_id'] = args[1].to_i

            json_action = Service.build_json_action('chgrp', params)

            client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
        }
    end

    chown_desc = <<-EOT.unindent
        Changes the service owner and group
    EOT

    command :chown, chown_desc, [:range, :service_id_list], :userid, [:groupid, nil] do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            params = Hash.new
            params['owner_id'] = args[1]
            params['group_id'] = args[2] if args[2]

            json_action = Service.build_json_action('chown', params)

            client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
        }
    end

    chmod_desc = <<-EOT.unindent
        Changes the service permissions
    EOT

    command :chmod, chmod_desc, [:range, :service_id_list], :octet do
        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions(args[0]) { |service_id|
            params = Hash.new
            params['octet'] = args[1]

            json_action = Service.build_json_action('chmod', params)

            client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
        }
    end

    action_desc = <<-EOT.unindent
        Perform an action on all the Virtual Machines of a given role.
        Actions supported: #{Role::SCHEDULE_ACTIONS.join(",")}
    EOT

    command :"action", action_desc, :service_id, :role_name, :vm_action,
        :options => [Service::PERIOD, Service::NUMBER] do

        client = Service::Client.new(
                    :username   => options[:username],
                    :password   => options[:password],
                    :url        => options[:server],
                    :user_agent => USER_AGENT)

        Service.perform_actions([args[0]]) { |service_id|
            params = Hash.new
            params[:period] = options[:period].to_i if options[:period]
            params[:number] = options[:number].to_i if options[:number]

            json_action = Service.build_json_action(args[2], params)

            client.post("#{RESOURCE_PATH}/#{service_id}/role/#{args[1]}/action", json_action)
        }
    end
end