F #4132: Redesign oneflow internal logic

co-authored-by: Christian González <cgonzalez@opennebula.systems>
co-authored-by: Alejandro Huertas Herrero <ahuertas@opennebula.systems>
co-authored-by: Jorge Lobo <jlobo@opennebula.systems>
This commit is contained in:
committed 2020-02-18 15:53:30 +01:00
1 parent a94e2f6ee8
commit da969c5fd3
35 files changed
+3332 -1897

No files matched your search

+317
View File
@@ -0,0 +1,317 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems #
# #
# 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. #
#--------------------------------------------------------------------------- #
require 'one_helper'
# Oneflow command helper
class OneFlowHelper < OpenNebulaHelper::OneHelper
# Get client to make request
#
# @options [Hash] CLI options
def client(options)
Service::Client.new(
:username => options[:username],
:password => options[:password],
:url => options[:server],
:user_agent => USER_AGENT
)
end
# Get service pool table
def format_service_pool
# TODO: config file
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
end
# List service pool
#
# @param client [Service::Client] Petition client
# @param options [Hash] CLI options
def list_service_pool(client, options)
response = client.get(RESOURCE_PATH)
if CloudClient.is_error?(response)
[response.code.to_i, response.to_s]
else
array_list = JSON.parse(response.body)
array_list = array_list['DOCUMENT_POOL']['DOCUMENT']
array_list = [] if array_list.nil?
unless options.key? :done
# remove from list flows in DONE state
array_list.reject! do |value|
value['TEMPLATE']['BODY']['state'] == 5
end
end
if options[:json]
if array_list.empty?
0
else
[0, JSON.pretty_generate(array_list)]
end
else
format_service_pool.show(array_list)
0
end
end
end
# List service pool continiously
#
# @param client [Service::Client] Petition client
# @param options [Hash] CLI options
def top_service_pool(client, options)
# TODO: make default delay configurable
options[:delay] ? delay = options[:delay] : delay = 4
begin
loop do
CLIHelper.scr_cls
CLIHelper.scr_move(0, 0)
list_service_pool(client, options)
sleep delay
end
rescue StandardError => e
STDERR.puts e.message
exit(-1)
end
0
end
# Show service detailed information
#
# @param client [Service::Client] Petition client
# @param service [Integer] Service ID
# @param options [Hash] CLI options
def format_resource(client, service, options)
response = client.get("#{RESOURCE_PATH}/#{service}")
if CloudClient.is_error?(response)
[response.code.to_i, response.to_s]
else
if options[:json]
[0, response.body]
else
str_h1 = '%-80s'
document = JSON.parse(response.body)['DOCUMENT']
template = document['TEMPLATE']['BODY']
CLIHelper.print_header(
str_h1 % "SERVICE #{document['ID']} INFORMATION"
)
print_service_info(document)
print_roles_info(template['roles'])
return 0 unless template['log']
CLIHelper.print_header(str_h1 % 'LOG MESSAGES', false)
template['log'].each do |log|
t = Time.at(log['timestamp']).strftime('%m/%d/%y %H:%M')
puts "#{t} [#{log['severity']}] #{log['message']}"
end
0
end
end
end
private
# Get nodes pool table
def format_node_pool
# TODO: config file
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 => 24 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 => 15 do |d|
if !d['vm_info'].nil?
d['vm_info']['VM']['UNAME']
else
''
end
end
column :GROUP,
'Group of the Virtual Machine',
:left,
:size => 15 do |d|
if !d['vm_info'].nil?
d['vm_info']['VM']['GNAME']
else
''
end
end
default :VM_ID, :NAME, :USER, :GROUP
end
end
# Print service information
#
# @param document [Hash] Service document information
def print_service_info(document)
str = '%-20s: %-20s'
str_h1 = '%-80s'
template = document['TEMPLATE']['BODY']
puts Kernel.format(str, 'ID', document['ID'])
puts Kernel.format(str, 'NAME', document['NAME'])
puts Kernel.format(str, 'USER', document['UNAME'])
puts Kernel.format(str, 'GROUP', document['GNAME'])
puts Kernel.format(str, 'STRATEGY', template['deployment'])
puts Kernel.format(str,
'SERVICE STATE',
Service.state_str(template['state']))
if template['shutdown_action']
puts Kernel.format(str, 'SHUTDOWN', template['shutdown_action'])
end
puts
CLIHelper.print_header(str_h1 % 'PERMISSIONS', false)
%w[OWNER GROUP OTHER].each do |e|
mask = '---'
permissions_hash = document['PERMISSIONS']
mask[0] = 'u' if permissions_hash["#{e}_U"] == '1'
mask[1] = 'm' if permissions_hash["#{e}_M"] == '1'
mask[2] = 'a' if permissions_hash["#{e}_A"] == '1'
puts Kernel.format(str, e, mask)
end
puts
end
# Print service roles information
#
# @param roles [Array] Service roles information
def print_roles_info(roles)
str = '%-20s: %-20s'
roles.each do |role|
CLIHelper.print_header("ROLE #{role['name']}", false)
puts Kernel.format(str,
'ROLE STATE',
Role.state_str(role['state']))
if role['parents']
puts Kernel.format(str,
'PARENTS',
role['parents'].join(', '))
end
puts Kernel.format(str, 'VM TEMPLATE', role['vm_template'])
puts Kernel.format(str, 'CARDINALITY', role['cardinality'])
if role['min_vms']
puts Kernel.format(str, 'MIN VMS', role['min_vms'])
end
if role['max_vms']
puts Kernel.format(str, 'MAX VMS', role['max_vms'])
end
if role['coolddown']
puts Kernel.format(str, 'COOLDOWN', "#{role['cooldown']}s")
end
if role['shutdown_action']
puts Kernel.format(str, 'SHUTDOWN', role['shutdown_action'])
end
CLIHelper.print_header('NODES INFORMATION', false)
format_node_pool.show(role['nodes'])
puts
end
puts
end
end
@@ -0,0 +1,145 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems #
# #
# 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. #
#--------------------------------------------------------------------------- #
require 'one_helper'
# Oneflow Template command helper
class OneFlowTemplateHelper < OpenNebulaHelper::OneHelper
# Get service template pool
def format_service_template_pool
# TODO: config file
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', :left, :size => 37 do |d|
d['NAME']
end
default :ID, :USER, :GROUP, :NAME
end
end
# List service template pool
#
# @param client [Service::Client] Petition client
# @param options [Hash] CLI options
def list_service_template_pool(client, options)
response = client.get(RESOURCE_PATH)
if CloudClient.is_error?(response)
[response.code.to_i, response.to_s]
else
if options[:json]
[0, response.body]
else
documents = JSON.parse(response.body)['DOCUMENT_POOL']
format_service_template_pool.show(documents['DOCUMENT'])
0
end
end
end
# List service template pool continiously
#
# @param client [Service::Client] Petition client
# @param options [Hash] CLI options
def top_service_template_pool(client, options)
# TODO: make default delay configurable
options[:delay] ? delay = options[:delay] : delay = 4
begin
loop do
CLIHelper.scr_cls
CLIHelper.scr_move(0, 0)
list_service_template_pool(client, options)
sleep delay
end
rescue StandardError => e
STDERR.puts e.message
exit(-1)
end
0
end
# Show service template detailed information
#
# @param client [Service::Client] Petition client
# @param service_template [Integer] Service template ID
# @param options [Hash] CLI options
def format_resource(client, service_template, options)
response = client.get("#{RESOURCE_PATH}/#{service_template}")
if CloudClient.is_error?(response)
[response.code.to_i, response.to_s]
else
if options[:json]
[0, response.body]
else
str = '%-20s: %-20s'
str_h1 = '%-80s'
document = JSON.parse(response.body)['DOCUMENT']
template = document['TEMPLATE']['BODY']
CLIHelper.print_header(
str_h1 % "SERVICE TEMPLATE #{document['ID']} INFORMATION"
)
puts Kernel.format str, 'ID', document['ID']
puts Kernel.format str, 'NAME', document['NAME']
puts Kernel.format str, 'USER', document['UNAME']
puts Kernel.format str, 'GROUP', document['GNAME']
puts
CLIHelper.print_header(str_h1 % 'PERMISSIONS', false)
%w[OWNER GROUP OTHER].each do |e|
mask = '---'
permissions_hash = document['PERMISSIONS']
mask[0] = 'u' if permissions_hash["#{e}_U"] == '1'
mask[1] = 'm' if permissions_hash["#{e}_M"] == '1'
mask[2] = 'a' if permissions_hash["#{e}_A"] == '1'
puts Kernel.format str, e, mask
end
puts
CLIHelper.print_header(str_h1 % 'TEMPLATE CONTENTS', false)
puts JSON.pretty_generate(template)
0
end
end
end
end
+100 -556
View File
@@ -33,370 +33,17 @@ end
$LOAD_PATH << RUBY_LIB_LOCATION
$LOAD_PATH << RUBY_LIB_LOCATION + '/cli'
require 'json'
require 'command_parser'
require 'opennebula/oneflow_client'
require 'cli_helper'
require 'one_helper/onevm_helper'
require 'json'
require 'one_helper/oneflow_helper'
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, _|
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]
history = d['vm_info']['VM']['HISTORY_RECORDS']['HISTORY']
if %w[ACTIVE SUSPENDED].include? state_str
history = history.last if history.instance_of?(Array)
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
if d['vm_info']['VM']['ETIME'] == '0'
etime = Time.now.to_i
else
etime = d['vm_info']['VM']['ETIME'].to_i
end
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 [Hash] options
# @return [[Integer, String], Integer] Returns the exit_code and optionally
# a String to be printed
def list_services(client, 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']
str_header = "SERVICE #{document_hash['DOCUMENT']['ID']} "\
'INFORMATION'
CLIHelper.print_header(str_h1 % str_header)
puts Kernel.format(str, 'ID', document_hash['DOCUMENT']['ID'])
puts Kernel.format(str, 'NAME', document_hash['DOCUMENT']['NAME'])
puts Kernel.format(str, 'USER', document_hash['DOCUMENT']['UNAME'])
puts Kernel.format(str, 'GROUP', document_hash['DOCUMENT']['GNAME'])
puts Kernel.format(str, 'STRATEGY', template['deployment'])
puts Kernel.format(str,
'SERVICE STATE',
Service.state_str(template['state']))
if template['shutdown_action']
puts Kernel.format(str, 'SHUTDOWN', template['shutdown_action'])
end
puts
CLIHelper.print_header(str_h1 % 'PERMISSIONS', false)
%w[OWNER GROUP OTHER].each do |e|
mask = '---'
permissions_hash = document_hash['DOCUMENT']['PERMISSIONS']
mask[0] = 'u' if permissions_hash["#{e}_U"] == '1'
mask[1] = 'm' if permissions_hash["#{e}_M"] == '1'
mask[2] = 'a' if permissions_hash["#{e}_A"] == '1'
puts Kernel.format(str, e, mask)
end
puts
template['roles'].each do |role|
CLIHelper.print_header("ROLE #{role['name']}", false)
puts Kernel.format(str,
'ROLE STATE',
Role.state_str(role['state']))
if role['parents']
puts Kernel.format(str,
'PARENTS',
role['parents'].join(', '))
end
puts Kernel.format(str, 'VM TEMPLATE', role['vm_template'])
puts Kernel.format(str, 'CARDINALITY', role['cardinality'])
if role['min_vms']
puts Kernel.format(str, 'MIN VMS', role['min_vms'])
end
if role['max_vms']
puts Kernel.format(str, 'MAX VMS', role['max_vms'])
end
if role['coolddown']
puts Kernel.format(str, 'COOLDOWN', "#{role['cooldown']}s")
end
if role['shutdown_action']
puts Kernel.format(str, 'SHUTDOWN', role['shutdown_action'])
end
puts 'NODES INFORMATION'
NODE_TABLE.show(role['nodes'])
if !role['elasticity_policies'].nil? &&
!role['elasticity_policies'].empty? ||
!role['scheduled_policies'].nil? &&
!role['scheduled_policies'].empty?
puts
puts 'ELASTICITY RULES'
if role['elasticity_policies'] &&
!role['elasticity_policies'].empty?
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'].empty?
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
end
puts
CLIHelper.print_header(str_h1 % 'LOG MESSAGES', false)
if template['log']
template['log'].each do |log|
t = Time.at(log['timestamp']).strftime('%m/%d/%y %H:%M')
puts "#{t} [#{log['severity']}] #{log['message']}"
end
end
0
end
end
end
def adjust_str(policy)
policy['adjust'].to_i >= 0 ? sign = '+' : sign = '-'
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
#
CommandParser::CmdParser.new(ARGV) do
usage '`oneflow` <command> [<args>] [<options>]'
version OpenNebulaHelper::ONE_VERSION
@@ -405,9 +52,19 @@ CommandParser::CmdParser.new(ARGV) do
set :option, CommandParser::VERSION
set :option, CommandParser::HELP
#
DONE = {
:name => 'done',
:large => '--done',
:description => 'Show services in DONE state'
}
# create helper object
helper = OneFlowHelper.new
############################################################################
# Formatters for arguments
#
############################################################################
set :format, :groupid, OpenNebulaHelper.rname_to_id_desc('GROUP') do |arg|
OpenNebulaHelper.rname_to_id(arg, 'GROUP')
end
@@ -424,326 +81,213 @@ CommandParser::CmdParser.new(ARGV) do
Service.list_to_id(arg, 'SERVICE')
end
set :format, :vm_action,
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: "\
[-1, "Action '#{arg}' is not supported. Supported actions: " \
"#{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, options)
command :list, list_desc, :options => [Service::JSON_FORMAT, DONE] do
helper.list_service_pool(helper.client(options), options)
end
#
# Show
#
###
top_desc = <<-EOT.unindent
Top the available services
EOT
command :top, top_desc, :options => [CLIHelper::DELAY, DONE] do
Signal.trap('INT') { exit(-1) }
helper.top_service_pool(helper.client(options), options)
0
end
###
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)
helper.format_resource(helper.client(options), args[0], 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
)
options[:delay] ? delay = options[:delay] : delay = 3
begin
loop do
CLIHelper.scr_cls
CLIHelper.scr_move(0, 0)
if args[0]
rc, message = show_service(client, args, options)
else
rc, message = list_services(client, options)
end
raise message if rc
sleep delay
end
rescue StandardError => 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]) do |service_id|
client.delete("#{RESOURCE_PATH}/#{service_id}")
helper.client(options).delete("#{RESOURCE_PATH}/#{service_id}")
end
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]) do |service_id|
json_action = Service.build_json_action('shutdown')
client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
end
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 COOLDOWN the Service is set to running ignoring the cooldown
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]) do |service_id|
json_action = Service.build_json_action('recover')
client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/action",
Service.build_json_action('recover'))
end
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
)
command :scale,
scale_desc,
:service_id,
:role_name,
:cardinality,
:options => [Service::FORCE] do
if args[2] !~ /^\d+$/
puts 'Cardinality must be an integer number'
STDERR.puts 'Cardinality must be an integer number'
exit(-1)
end
exit_code = 0
json = "{ \"cardinality\" : #{args[2]},\n" \
" \"force\" : #{options[:force] == true}, " \
" \"role_name\" : \"#{args[1]}\"}"
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
Service.perform_action(args[0]) do |service_id|
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/scale",
json)
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]) do |service_id|
params = {}
params['group_id'] = args[1].to_i
json_action = Service.build_json_action('chgrp', params)
json = Service.build_json_action('chgrp', params)
client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/action",
json)
end
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
)
command :chown,
chown_desc,
[:range, :service_id_list],
:userid,
[:groupid, nil] do
Service.perform_actions(args[0]) do |service_id|
params = {}
params['owner_id'] = args[1]
params['group_id'] = args[2] if args[2]
json_action = Service.build_json_action('chown', params)
json = Service.build_json_action('chown', params)
client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/action",
json)
end
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
)
if !/\A\d+\z/.match(args[1])
STDERR.puts "Invalid '#{args[1]}' octed permissions"
exit(-1)
end
Service.perform_actions(args[0]) do |service_id|
params = {}
params['octet'] = args[1]
json_action = Service.build_json_action('chmod', params)
json = Service.build_json_action('chmod', params)
client.post("#{RESOURCE_PATH}/#{service_id}/action", json_action)
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/action",
json)
end
end
###
rename_desc = <<-EOT.unindent
Renames the Service
EOT
command :rename, rename_desc, :service_id, :name do
client = Service::Client.new(
:username => options[:username],
:password => options[:password],
:url => options[:server],
:user_agent => USER_AGENT
)
Service.perform_action(args[0]) do |service_id|
params = {}
params['name'] = args[1]
params = {}
params['name'] = args[1]
json = Service.build_json_action('rename', params)
json_action = Service.build_json_action('rename', params)
response = client
.post("#{RESOURCE_PATH}/#{args[0]}/action", json_action)
if CloudClient.is_error?(response)
[response.code.to_i, response.to_s]
else
response.code.to_i
helper.client(options).post("#{RESOURCE_PATH}/#{service_id}/action",
json)
end
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,
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]]) do |service_id|
Service.perform_action(args[0]) do |service_id|
params = {}
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)
json = Service.build_json_action(args[2], params)
client = helper.client(options)
client.post("#{RESOURCE_PATH}/#{service_id}/role/#{args[1]}/action",
json_action)
json)
end
end
end
+46 -165
View File
@@ -33,125 +33,19 @@ end
$LOAD_PATH << RUBY_LIB_LOCATION
$LOAD_PATH << RUBY_LIB_LOCATION + '/cli'
require 'json'
require 'English'
require 'command_parser'
require 'opennebula/oneflow_client'
require 'English'
require 'cli_helper'
require 'one_helper'
require 'json'
require 'one_helper/oneflowtemplate_helper'
USER_AGENT = 'CLI'
# Base Path representing the resource to be used in the requests
RESOURCE_PATH = '/service_template'
#
# Table
#
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', :left, :size => 37 do |d|
d['NAME']
end
default :ID, :USER, :GROUP, :NAME
end
# Show the service template 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_template(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 TEMPLATE #{document_hash['DOCUMENT']['ID']} "\
'INFORMATION')
puts Kernel.format str, 'ID', document_hash['DOCUMENT']['ID']
puts Kernel.format str, 'NAME', document_hash['DOCUMENT']['NAME']
puts Kernel.format str, 'USER', document_hash['DOCUMENT']['UNAME']
puts Kernel.format str, 'GROUP', document_hash['DOCUMENT']['GNAME']
puts
CLIHelper.print_header(str_h1 % 'PERMISSIONS', false)
%w[OWNER GROUP OTHER].each do |e|
mask = '---'
permissions_hash = document_hash['DOCUMENT']['PERMISSIONS']
mask[0] = 'u' if permissions_hash["#{e}_U"] == '1'
mask[1] = 'm' if permissions_hash["#{e}_M"] == '1'
mask[2] = 'a' if permissions_hash["#{e}_A"] == '1'
puts Kernel.format str, e, mask
end
puts
CLIHelper.print_header(str_h1 % 'TEMPLATE CONTENTS', false)
puts JSON.pretty_generate(template)
0
end
end
end
# List the services. This method is used in top and list commands
# @param [Service::Client] client
# @param [Hash] options
# @return [[Integer, String], Integer] Returns the exit_code and optionally
# a String to be printed
def list_service_templates(client, 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)
TABLE.show(array_list['DOCUMENT_POOL']['DOCUMENT'])
0
end
end
end
#
# Commands
#
CommandParser::CmdParser.new(ARGV) do
usage '`oneflow-template` <command> [<args>] [<options>]'
version OpenNebulaHelper::ONE_VERSION
@@ -160,9 +54,12 @@ CommandParser::CmdParser.new(ARGV) do
set :option, CommandParser::VERSION
set :option, CommandParser::HELP
#
# create helper object
helper = OneFlowTemplateHelper.new
############################################################################
# Formatters for arguments
#
############################################################################
set :format, :groupid, OpenNebulaHelper.rname_to_id_desc('GROUP') do |arg|
OpenNebulaHelper.rname_to_id(arg, 'GROUP')
end
@@ -181,9 +78,7 @@ CommandParser::CmdParser.new(ARGV) do
Service.list_to_id(arg, 'SERVICE TEMPLATE')
end
#
# List
#
###
list_desc = <<-EOT.unindent
List the available Service Templates
@@ -197,12 +92,10 @@ CommandParser::CmdParser.new(ARGV) do
:user_agent => USER_AGENT
)
list_service_templates(client, options)
helper.list_service_template_pool(client, options)
end
#
# Top
#
###
top_desc = <<-EOT.unindent
List the available Service Templates continuously
@@ -219,30 +112,29 @@ CommandParser::CmdParser.new(ARGV) do
:user_agent => USER_AGENT
)
options[:delay] ? delay = options[:delay] : delay = 3
Signal.trap('INT') { exit(-1) }
begin
loop do
CLIHelper.scr_cls
CLIHelper.scr_move(0, 0)
rc, message = list_service_templates(client, options)
if rc != 0
raise message
end
sleep delay
end
rescue StandardError => e
puts e.message
-1
end
helper.top_service_template_pool(client, options)
end
#
# Create
#
###
show_desc = <<-EOT.unindent
Show detailed information of a given Service Template
EOT
command :show, show_desc, :templateid, :options => Service::JSON_FORMAT do
client = Service::Client.new(
:username => options[:username],
:password => options[:password],
:url => options[:server],
:user_agent => USER_AGENT
)
helper.format_resource(client, args[0], options)
end
###
create_desc = <<-EOT.unindent
Create a new Service Template
@@ -271,28 +163,7 @@ CommandParser::CmdParser.new(ARGV) do
end
end
#
# Show
#
show_desc = <<-EOT.unindent
Show detailed information of a given Service Template
EOT
command :show, show_desc, :templateid, :options => Service::JSON_FORMAT do
client = Service::Client.new(
:username => options[:username],
:password => options[:password],
:url => options[:server],
:user_agent => USER_AGENT
)
show_service_template(client, args, options)
end
#
# Delete
#
###
delete_desc = <<-EOT.unindent
Delete a given Service Template
@@ -311,9 +182,7 @@ CommandParser::CmdParser.new(ARGV) do
end
end
#
# Instantiate
#
###
instantiate_desc = <<-EOT.unindent
Instantiate a Service Template
@@ -351,6 +220,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
chgrp_desc = <<-EOT.unindent
Changes the service template group
EOT
@@ -373,6 +244,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
chown_desc = <<-EOT.unindent
Changes the service template owner and group
EOT
@@ -397,6 +270,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
chmod_desc = <<-EOT.unindent
Changes the service template permissions
EOT
@@ -419,6 +294,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
clone_desc = <<-EOT.unindent
Creates a new Service Template from an existing one
EOT
@@ -452,6 +329,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
rename_desc = <<-EOT.unindent
Renames the Service Template
EOT
@@ -479,6 +358,8 @@ CommandParser::CmdParser.new(ARGV) do
end
end
###
update_desc = <<-EOT.unindent
Update the template contents. If a path is not provided the editor will
be launched to modify the current content.