From 7551c47553adf176417c8d9323b00560aef11eca Mon Sep 17 00:00:00 2001 From: Daniel Molina Date: Tue, 7 Jun 2011 16:58:40 +0200 Subject: [PATCH 01/43] feature #661: Remove old CLI libraries --- src/cli/client_utilities.rb | 381 ------------------------------------ src/cli/command_parse.rb | 170 ---------------- 2 files changed, 551 deletions(-) delete mode 100644 src/cli/client_utilities.rb delete mode 100644 src/cli/command_parse.rb diff --git a/src/cli/client_utilities.rb b/src/cli/client_utilities.rb deleted file mode 100644 index 90e7307bd1..0000000000 --- a/src/cli/client_utilities.rb +++ /dev/null @@ -1,381 +0,0 @@ -# -------------------------------------------------------------------------- # -# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) # -# # -# 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 'OpenNebula' - -##################### -# CONSOLE UTILITIES # -##################### - -BinarySufix = ["K", "M", "G", "T" ] - -def humanize_size(value) - i=0 - - while value > 1024 && i < 3 do - value /= 1024.0 - i+=1 - end - - value = (value * 10).round / 10.0 - - value = value.to_i if value - value.round == 0 - st = value.to_s + BinarySufix[i] - - return st -end - -# Sets bold font -def scr_bold - print "\33[1m" -end - -# Sets underline -def scr_underline - print "\33[4m" -end - -# Restore normal font -def scr_restore - print "\33[0m" -end - -# Clears screen -def scr_cls - print "\33[2J\33[H" -end - -# Moves the cursor -def scr_move(x,y) - print "\33[#{x};#{y}H" -end - -# Print header -def print_header(format_str, str, underline) - scr_bold - scr_underline if underline - print format_str % str - scr_restore - puts -end - -################################## -# Class show configurable tables # -################################## - -ShowTableExample={ - :id => { - :name => "ID", - :size => 4, - :proc => lambda {|d,e| d["OID"] } - }, - :name => { - :name => "NAME", - :size => 8, - :proc => lambda {|d,e| d["DEPLOY_ID"] } - }, - :stat => { - :name => "STAT", - :size => 4, - :proc => lambda {|d,e| e[:vm].get_state(d) } - }, - :default => [:id, :name, :stat] -} - -# Class to print tables -class ShowTable - attr_accessor :ext, :columns - - # table => definition of the table to print - # ext => external variables (Hash), @ext - def initialize(table, ext=nil) - @table=table - @ext=Hash.new - @ext=ext if ext.kind_of?(Hash) - @columns=@table[:default] - end - - # Returns a formated string for header - def header_str - @columns.collect {|c| - if @table[c] - #{}"%#{@table[c][:size]}s" % [@table[c][:name]] - format_data(c, @table[c][:name]) - else - nil - end - }.compact.join(' ') - end - - # Returns an array with header titles - def header_array - @columns.collect {|c| - if @table[c] - @table[c][:name].to_s - else - "" - end - }.compact - end - - def data_str(data, options=nil) - # TODO: Use data_array so it can be ordered and/or filtered - res_data=data_array(data, options) - - res_data.collect {|d| - (0..(@columns.length-1)).collect {|c| - dat=d[c] - col=@columns[c] - - dat = humanize_size( Float(dat) ) if( @table[col][:kbytes] ) - - format_data(col, dat) if @table[col] - }.join(' ') - }.join("\n") - - #data.collect {|d| - # @columns.collect {|c| - # format_data(c, @table[c][:proc].call(d, @ext)) if @table[c] - # }.join(' ') - #}.join("\n") - end - - def data_array(data, options=nil) - res_data=data.collect {|d| - @columns.collect {|c| - @table[c][:proc].call(d, @ext).to_s if @table[c] - } - } - - if options - filter_data!(res_data, options[:filter]) if options[:filter] - sort_data!(res_data, options[:order]) if options[:order] - end - - res_data - end - - def format_data(field, data) - minus=( @table[field][:left] ? "-" : "" ) - size=@table[field][:size] - "%#{minus}#{size}.#{size}s" % [ data.to_s ] - end - - def get_order_column(column) - desc=column.match(/^-/) - col_name=column.gsub(/^-/, '') - index=@columns.index(col_name.to_sym) - [index, desc] - end - - def sort_data!(data, order) - data.sort! {|a,b| - # rows are equal by default - res=0 - order.each {|o| - # compare - pos, dec=get_order_column(o) - break if !pos - - r = (b[pos]<=>a[pos]) - - # if diferent set res (return value) and exit loop - if r!=0 - # change sign if the order is decreasing - r=-r if dec - res=r - break - end - } - res - } - end - - def filter_data!(data, filters) - filters.each {|key, value| - pos=@columns.index(key.downcase.to_sym) - if pos - data.reject! {|d| - if !d[pos] - true - else - !d[pos].downcase.match(value.downcase) - end - } - end - } - end - - def print_help - text=[] - @table.each {|option, data| - next if option==:default - text << "%9s (%2d) => %s" % [option, data[:size], data[:desc]] - } - text.join("\n") - end - -end - - -################ -# Miscelaneous # -################ - -def get_one_client(session=nil) - OpenNebula::Client.new(session) -end - -def is_error?(result) - OpenNebula.is_error?(result) -end - -def is_successful?(result) - !OpenNebula.is_error?(result) -end - -def check_parameters(name, number) - if ARGV.length < number - print "Command #{name} requires " - if number>1 - puts "#{number} parameters to run." - else - puts "one parameter to run" - end - exit -1 - end -end - - - -def get_entity_id(name, pool_class) - return name if name.match(/^[0123456789]+$/) - - # TODO: get vm's from the actual user - pool=pool_class.new(get_one_client) - result=pool.info - - class_name=pool_class.name.split('::').last.gsub(/Pool$/, '') - - if( OpenNebula.is_error?(result) ) - puts "Error: #{class_name} Pool info could not be retrieved. " + - result.message - exit -1 - end - - objects=pool.select {|object| object.name==name } - - if objects.length>0 - if objects.length>1 - puts "There are multiple #{class_name}s with name #{name}." - exit -1 - else - result=objects.first.id - end - else - puts "#{class_name} named #{name} not found." - exit -1 - end - - result -end - -def get_vm_id(name) - get_entity_id(name, OpenNebula::VirtualMachinePool) -end - -def get_host_id(name) - get_entity_id(name, OpenNebula::HostPool) -end - -def get_vn_id(name) - get_entity_id(name, OpenNebula::VirtualNetworkPool) -end - -def get_user_id(name) - get_entity_id(name, OpenNebula::UserPool) -end - -def get_image_id(name) - get_entity_id(name, OpenNebula::ImagePool) -end - -def get_cluster_id(name) - get_entity_id(name, OpenNebula::ClusterPool) -end - -def get_template_id(name) - get_entity_id(name, OpenNebula::TemplatePool) -end - -def str_running_time(data) - stime=Time.at(data["STIME"].to_i) - if data["ETIME"]=="0" - etime=Time.now - else - etime=Time.at(data["ETIME"].to_i) - end - dtime=Time.at(etime-stime).getgm - - "%02d %02d:%02d:%02d" % [dtime.yday-1, dtime.hour, dtime.min, dtime.sec] -end - -def str_register_time(data) - regtime=Time.at(data["REGTIME"].to_i).getgm - regtime.strftime("%b %d, %Y %H:%M") -end - - -REG_RANGE=/(.*)\[(\d+)([+-])(\d+)\](.*)/ - -def expand_range(param) - if match=param.match(REG_RANGE) - pre=match[1] - start=match[2] - operator=match[3] - last=match[4] - post=match[5] - size=0 - - result=Array.new - - if operator=='-' - range=(start.to_i..last.to_i) - size=last.size - elsif operator=='+' - size=(start.to_i+last.to_i-1).to_s.size - range=(start.to_i..(start.to_i+last.to_i-1)) - end - - if start[0]==?0 - range.each do |num| - result<] [] - -Options: -EOT - - ONE_VERSION=<<-EOT -OpenNebula 2.3.0 -Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) - -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 -EOT - - def initialize(standard_options=nil) - @options=Hash.new - if standard_options - @standard_options=standard_options - else - @standard_options=[:list, :top, :xml] - end - - @cmdparse=OptionParser.new do |opts| - opts.banner=text_banner - - execute_standard_options(opts, @options) - special_options(opts, @options) - - opts.on("-v", "--verbose", - "Tells more information if the command", - "is successful") do |o| - @options[:verbose]=true - end - - opts.on_tail("-h", "--help", "Shows this help message") do |o| - print_help - exit - end - - opts.on_tail("--version", - "Shows version and copyright information") do |o| - puts text_version - exit - end - end - end - - def parse(args) - begin - @cmdparse.parse!(args) - rescue => e - puts e.message - exit -1 - end - end - - def opts_list(opts, options) - opts.on("-l x,y,z", "--list x,y,z", Array, - "Selects columns to display with list", "command") do |o| - options[:list]=o.collect {|c| c.to_sym } - end - - opts.on("--list-columns", "Information about the columns available", - "to display, order or filter") do |o| - puts list_options - exit - end - - opts.on("-o x,y,z", "--order x,y,z", Array, - "Order by these columns, column starting", - "with - means decreasing order") do |o| - options[:order]=o - end - - opts.on("-f x,y,z", "--filter x,y,z", Array, - "Filter data. An array is specified", "with column=value pairs.") do |o| - options[:filter]=Hash.new - o.each {|i| - k,v=i.split('=') - options[:filter][k]=v - } - end - end - - def opts_top(opts, options) - opts.on("-d seconds", "--delay seconds", Integer, - "Sets the delay in seconds for top", "command") do |o| - options[:delay]=o - end - end - - def opts_xml(opts, options) - opts.on("-x", "--xml", - "Returns xml instead of human readable text") do |o| - options[:xml]=true - end - end - - def set_standard_options(options) - @standard_options=options - end - - def execute_standard_options(opts, options) - @standard_options.each do |op| - sym="opts_#{op}".to_sym - self.send(sym, opts, options) if self.respond_to?(sym) - end - end - - def special_options(opts, options) - end - - def options - @options - end - - def print_help - puts @cmdparse - puts - puts text_commands - end - - def text_commands - COMMANDS_HELP - end - - def text_command_name - "onevm" - end - - def text_banner - USAGE_BANNER.gsub("onevm", text_command_name) - end - - def text_version - ONE_VERSION - end - - def list_options - "\n\n" - end -end - From 876e36ddf9f47fcafd3e1ad9cdfdd30fe9d1e7ee Mon Sep 17 00:00:00 2001 From: Daniel Molina Date: Tue, 7 Jun 2011 16:59:55 +0200 Subject: [PATCH 02/43] feature #661: Add new CLI libraries --- src/cli/cli_helper.rb | 197 ++++++++++++++++++++++ src/cli/command_parser.rb | 333 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 530 insertions(+) create mode 100644 src/cli/cli_helper.rb create mode 100755 src/cli/command_parser.rb diff --git a/src/cli/cli_helper.rb b/src/cli/cli_helper.rb new file mode 100644 index 0000000000..5c9a6178ae --- /dev/null +++ b/src/cli/cli_helper.rb @@ -0,0 +1,197 @@ +module CLIHelper + LIST = { + :name => "list", + :short => "-l x,y,z", + :large => "--list x,y,z", + :format => Array, + :description => "Selects columns to display with list command" + } + + #ORDER = { + # :name => "order", + # :short => "-o x,y,z", + # :large => "--order x,y,z", + # :format => Array, + # :description => "Order by these columns, column starting with - means decreasing order" + #} + # + #FILTER = { + # :name => "filter", + # :short => "-f x,y,z", + # :large => "--filter x,y,z", + # :format => Array, + # :description => "Filter data. An array is specified with column=value pairs." + #} + # + #HEADER = { + # :name => "header", + # :short => "-H", + # :large => "--header", + # :description => "Shows the header of the table" + #} + + DELAY = { + :name => "delay", + :short => "-d x", + :large => "--delay x", + :format => Integer, + :description => "Sets the delay in seconds for top command" + } + + #OPTIONS = [LIST, ORDER, FILTER, HEADER, DELAY] + OPTIONS = [LIST, DELAY] + + # Sets bold font + def CLIHelper.scr_bold + print "\33[1m" + end + + # Sets underline + def CLIHelper.scr_underline + print "\33[4m" + end + + # Restore normal font + def CLIHelper.scr_restore + print "\33[0m" + end + + # Clears screen + def CLIHelper.scr_cls + print "\33[2J\33[H" + end + + # Moves the cursor + def CLIHelper.scr_move(x,y) + print "\33[#{x};#{y}H" + end + + # Print header + def CLIHelper.print_header(str, underline=true) + scr_bold + scr_underline if underline + print str + scr_restore + puts + end + + class ShowTable + include CLIHelper + + def initialize(conf=nil, ext=nil, &block) + # merge del conf con la table + @columns = Hash.new + @default_columns = Array.new + + @ext = ext + + instance_eval(&block) + end + + def column(name, desc, *conf, &block) + column = Hash.new + column[:desc] = desc + column[:size] = 5 + conf.each{|c| + if c.instance_of?(Symbol) + column[c]=true + elsif c.instance_of?(Hash) + c.each{|key,value| + column[key]=value + } + end + } + column[:proc] = block + @columns[name.to_sym] = column + @default_columns< "verbose", + :short => "-v", + :large => "--verbose", + :description => "Verbose mode" + }, + HELP={ + :name => "help", + :short => "-h", + :large => "--help", + :description => "Show this message" + } + ] + + class CmdParser + attr_reader :options, :args + + def initialize(args=[], &block) + @opts = Array.new + @commands = Hash.new + @formats = Hash.new + @script = nil + @usage = "" + + @args = args + @options = Hash.new + + set :format, :file, "" do |arg| format_file(arg) ; end + set :format, :range, "" do |arg| format_range(arg) ; end + set :format, :text, "" do |arg| format_text(arg) ; end + + instance_eval(&block) + + self.run + end + + def usage(str) + @usage = "Usage: #{str}" + end + + def set(e, *args, &block) + case e + when :option + add_option(args[0]) + when :format + add_format(args[0], args[1], block) + end + end + + def command(name, desc, *args_format, &block) + cmd = Hash.new + cmd[:desc] = desc + cmd[:arity] = 0 + cmd[:options] = [] + cmd[:args_format] = Array.new + args_format.each {|args| + if args.instance_of?(Array) + cmd[:arity]+=1 unless args.include?(nil) + cmd[:args_format] << args + elsif args.instance_of?(Hash) && args[:options] + cmd[:options] << args[:options] + else + cmd[:arity]+=1 + cmd[:args_format] << [args] + end + } + cmd[:proc] = block + @commands[name] = cmd + end + + def script(*args_format, &block) + @script=Hash.new + @script[:args_format] = Array.new + args_format.collect {|args| + if args.instance_of?(Array) + @script[:arity]+=1 unless args.include?(nil) + @script[:args_format] << args + elsif args.instance_of?(Hash) && args[:options] + @opts << args[:options] + else + @script[:arity]+=1 + @script[:args_format] << [args] + end + } + + @script[:proc] = block + end + + def run + comm_name="" + if @script + comm=@script + elsif + if @args[0] && !@args[0].match(/^-/) + comm_name=@args.shift.to_sym + comm=@commands[comm_name] + end + end + + if comm.nil? + help + exit -1 + end + + extra_options = comm[:options] if comm + parse(extra_options) + if comm + check_args!(comm_name, comm[:arity], comm[:args_format]) + + begin + rc = comm[:proc].call + rescue Exception =>e + puts e.message + exit -1 + end + + if rc.instance_of?(Array) + puts rc[1] + exit rc.first + else + exit rc + end + end + end + + def help + puts @usage + puts + print_options + puts + print_commands + puts + print_formatters + end + + private + + def print_options + puts "Options:" + + shown_opts = Array.new + opt_format = "#{' '*5}%-25s %s" + @commands.each{ |key,value| + value[:options].flatten.each { |o| + if shown_opts.include?(o[:name]) + next + else + shown_opts << o[:name] + short = o[:short].split(' ').first + printf opt_format, "#{short}, #{o[:large]}", o[:description] + puts + end + } + } + + @opts.each{ |o| + printf opt_format, "#{o[:short]}, #{o[:large]}", o[:description] + puts + } + end + + def print_commands + puts "Commands:" + + cmd_format5 = "#{' '*5}%s" + cmd_format10 = "#{' '*10}%s" + @commands.each{ |key,value| + printf cmd_format5, "* #{key}" + puts + + args_str=value[:args_format].collect{ |a| + if a.include?(nil) + "[#{a.compact.join("|")}]" + else + a.join("|") + end + }.join(' ') + printf cmd_format10, "arguments: #{args_str}" + puts + + value[:desc].split("\n").each { |l| + printf cmd_format10, l + puts + } + + unless value[:options].empty? + opts_str=value[:options].flatten.collect{|o| + o[:name] + }.join(', ') + printf cmd_format10, "options: #{opts_str}" + puts + end + puts + } + end + + def print_formatters + puts "argument formats:" + + cmd_format5 = "#{' '*5}%s" + cmd_format10 = "#{' '*10}%s" + @formats.each{ |key,value| + printf cmd_format5, "* #{key}" + puts + + value[:desc].split("\n").each { |l| + printf cmd_format10, l + puts + } + } + end + + def add_option(option) + if option.instance_of?(Array) + option.each { |o| @opts << o } + elsif option.instance_of?(Hash) + @opts << option + end + end + + def add_format(format, description, block) + @formats[format] = { + :desc => description, + :proc => block + } + end + + def parse(extra_options) + @cmdparse=OptionParser.new do |opts| + merge = @opts + merge = @opts + extra_options if extra_options + merge.flatten.each do |e| + opts.on(e[:short],e[:large], e[:format],e[:description]) do |o| + if e[:proc] + e[:proc].call + elsif e[:name]=="help" + help + #puts opts + exit + else + @options[e[:name].to_sym]=o + end + end + end + end + + begin + @cmdparse.parse!(@args) + rescue => e + puts e.message + exit -1 + end + end + + def check_args!(name, arity, args_format) + if @args.length < arity + print "Command #{name} requires " + if arity>1 + puts "#{args_format.length} parameters to run." + else + puts "one parameter to run" + end + exit -1 + else + id=0 + @args.collect!{|arg| + format = args_format[id] + argument = nil + error_msg = nil + format.each { |f| + rc = @formats[f][:proc].call(arg) if @formats[f] + if rc[0]==0 + argument=rc[1] + break + else + error_msg=rc[1] + next + end + } + + unless argument + puts error_msg if error_msg + puts "command #{name}: argument #{id} must be one of #{format.join(', ')}" + exit -1 + end + + id+=1 + argument + } + end + end + + ######################################################################## + # Formatters for arguments + ######################################################################## + def format_text(arg) + arg.instance_of?(String) ? [0,arg] : [-1] + end + + def format_file(arg) + File.exists?(arg) ? [0,arg] : [-1] + end + + REG_RANGE=/^(?:(?:\d+\.\.\d+|\d+),)*(?:\d+\.\.\d+|\d+)$/ + + def format_range(arg) + arg_s = arg.gsub(" ","").to_s + return [-1] unless arg_s.match(REG_RANGE) + + ids = Array.new + arg_s.split(',').each { |e| + if e.match(/^\d+$/) + ids << e.to_i + elsif m = e.match(/^(\d+)\.\.(\d+)$/) + ids += (m[1].to_i..m[2].to_i).to_a + else + return [-1] + end + } + + return 0,ids.uniq + end + end +end + + From b6ecf96349a30a61f9f103a7343f90b4faf15475 Mon Sep 17 00:00:00 2001 From: Daniel Molina Date: Tue, 7 Jun 2011 17:00:18 +0200 Subject: [PATCH 03/43] feature #661: Add OpenNebula CLI helper --- src/cli/one_helper.rb | 218 +++++++++++++++++++++++++++ src/cli/one_helper/onevnet_helper.rb | 100 ++++++++++++ 2 files changed, 318 insertions(+) create mode 100644 src/cli/one_helper.rb create mode 100644 src/cli/one_helper/onevnet_helper.rb diff --git a/src/cli/one_helper.rb b/src/cli/one_helper.rb new file mode 100644 index 0000000000..9ba77d22d4 --- /dev/null +++ b/src/cli/one_helper.rb @@ -0,0 +1,218 @@ +require 'cli_helper' + +require 'OpenNebula' +include OpenNebula + +module OpenNebulaHelper + XML={ + :name => "xml", + :short => "-x", + :large => "--xml", + :description => "Show the resource in xml format" + } + + class OneHelper + def initialize + @client = OpenNebula::Client.new + @translation_hash = nil + end + + def create_resource(template, options) + resource = factory + + rc = resource.allocate(template) + if OpenNebula.is_error?(rc) + return -1, rc.message + else + puts "ID: #{resource.id.to_s}" if options[:verbose] + return 0 + end + end + + def list_pool(options) + user_flag = options[:filter_flag] ? options[:filter_flag] : -2 + pool = factory_pool(user_flag) + + rc = pool.info + return -1, rc.message if OpenNebula.is_error?(rc) + + if options[:xml] + return 0, pool.to_xml(true) + else + generate_translation_hash + format_pool(pool, options) + return 0 + end + end + + def show_resource(id, options) + resource = retrieve_resource(id) + return -1, resource.message if OpenNebula.is_error?(resource) + + if options[:xml] + return 0, resource.to_xml(true) + else + generate_translation_hash + format_resource(resource) + return 0 + end + end + + def perform_action(id, args, options, verbose, &block) + resource = retrieve_resource(id) + return -1, resource.message if OpenNebula.is_error?(resource) + + rc = block.call(resource) + if OpenNebula.is_error?(rc) + return -1, rc.message + else + rname=Object.const_get(self.class.name)::RESOURCE + puts "#{rname} #{id} #{verbose}" if options[:verbose] + return 0 + end + end + + def perform_actions(ids,args,options,verbose,&block) + exit_code = 0 + ids.each do |id| + rc = perform_action(id,args,options,verbose,&block) + + unless rc[0]==0 + puts rc[1] + exit_code=rc[0] + end + end + + exit_code + end + + ######################################################################## + # Formatters for arguments + ######################################################################## + def to_id(name, pool=nil) + return 0, name if name.match(/^[0123456789]+$/) + + user_flag = -2 + pool = pool ? pool : factory_pool(user_flag) + + rc = pool.info + return -1, rc.message if OpenNebula.is_error?(rc) + + objects=pool.select {|object| object.name==name } + + if objects.length>0 + if objects.length>1 + rname=Object.const_get(self.class.name)::RESOURCE + return -1, "There are multiple #{rname}s with name #{name}." + else + result=objects.first.id + end + else + rname=Object.const_get(self.class.name)::RESOURCE + return -1, "#{rname} named #{name} not found." + end + + return 0, result + end + + def list_to_id(names) + user_flag = -2 + pool = factory_pool(user_flag) + + rc = pool.info + return -1, rc.message if OpenNebula.is_error?(rc) + + result = names.split(',').collect { |name| + rc = to_id(name) + unless rc.first==0 + return rc + end + rc[1] + } + + return 0, result + end + + def filterflag_to_i(str) + filter_flag = case str + when "a", "all" then "-2" + when "m", "mine" then "-3" + when "g", "group" then "-1" + else + if str.match(/^[0123456789]+$/) + str + else + generate_translation_hash + user = @translation_hash[:users].select { |k,v| v==str } + user.length > 0 ? user.first.first : "-2" + end + end + + return 0, filter_flag + end + + private + + def retrieve_resource(id) + resource = factory(id) + + rc = resource.info + OpenNebula.is_error?(rc) ? rc : resource + end + + def generate_translation_hash + @translation_hash ||= { + :users => generate_user_translation, + :groups => generate_group_translation + } + + end + + def generate_user_translation + user_pool = UserPool.new(@client) + user_pool.info + + hash = Hash.new + user_pool.each { |user| + hash[user["ID"]]=user["NAME"] + } + hash + end + + + def generate_group_translation + group_pool = GroupPool.new(@client) + group_pool.info + + hash = Hash.new + group_pool.each { |group| + hash[group["ID"]]=group["NAME"] + } + hash + end + end + + def OpenNebulaHelper.public_to_str(str) + if str.to_i == 1 + public_str = "Y" + else + public_str = "N" + end + end + + def OpenNebulaHelper.uid_to_str(uid, hash={}) + if hash[:users] && hash[:users][uid] + hash[:users][uid] + else + uid + end + end + + def OpenNebulaHelper.gid_to_str(gid, hash={}) + if hash[:groups] && hash[:groups][gid] + hash[:groups][gid] + else + gid + end + end +end \ No newline at end of file diff --git a/src/cli/one_helper/onevnet_helper.rb b/src/cli/one_helper/onevnet_helper.rb new file mode 100644 index 0000000000..8908004882 --- /dev/null +++ b/src/cli/one_helper/onevnet_helper.rb @@ -0,0 +1,100 @@ +require 'one_helper' + +class OneVNetHelper < OpenNebulaHelper::OneHelper + RESOURCE = "VNET" + + def create_resource(template_file, options) + template=File.read(template_file) + super(template, options) + end + + private + + def factory(id=nil) + if id + OpenNebula::VirtualNetwork.new_with_id(id, @client) + else + xml=OpenNebula::VirtualNetwork.build_xml + OpenNebula::VirtualNetwork.new(xml, @client) + end + end + + def factory_pool(user_flag=-2) + OpenNebula::VirtualNetworkPool.new(@client, user_flag) + end + + def format_resource(vn) + str_h1="%-80s" + CLIHelper.print_header(str_h1 % ["VIRTUAL NETWORK #{vn.id.to_s} INFORMATION"]) + + str="%-10s: %-20s" + puts str % ["ID: ", vn.id.to_s] + puts str % ["UID: ", vn["UID"]] + puts str % ["PUBLIC", OpenNebulaHelper.public_to_str(vn['PUBLIC'])] + puts + CLIHelper.print_header(str_h1 % ["VIRTUAL NETWORK TEMPLATE"], false) + + puts vn.template_str(false) + + leases_str = vn.template_like_str('/VNET/LEASES', false) + + if !leases_str.empty? + puts + CLIHelper.print_header(str_h1 % ["LEASES INFORMATION"], false) + puts leases_str + end + end + + def format_pool(pool, options) + st=CLIHelper::ShowTable.new(nil, @translation_hash) do + column :ID, "ONE identifier for Virtual Network", :size=>4 do |d,e| + d["ID"] + end + + column :NAME, "Name of the Virtual Network", :left, :size=>15 do |d,e| + d["NAME"] + end + + column :USER, "Username of the Virtual Network owner", :left, :size=>8 do |d,e| + OpenNebulaHelper.uid_to_str(d["UID"],e) + end + + column :GROUP, "Group of the Virtual Network", :left, :size=>8 do |d,e| + OpenNebulaHelper.gid_to_str(d["GID"],e) + end + + column :TYPE, "Type of Virtual Network", :size=>6 do |d,e| + OneVNetHelper.type_to_str(d["TYPE"]) + end + + column :SIZE, "Size of the Virtual Network", :size=>6 do |d,e| + d["SIZE"] + end + + column :BRIDGE, "Bridge associated to the Virtual Network", :size=>6 do |d,e| + d["BRIDGE"] + end + + column :PUBLIC, "Whether the Virtual Network is public or not", :size=>1 do |d,e| + OpenNebulaHelper.public_to_str(d['PUBLIC']) + end + + column :LEASES, "Number of this Virtual Network's given leases", :size=>7 do |d,e| + d["TOTAL_LEASES"] + end + + default :ID, :USER, :GROUP, :NAME, :TYPE, :BRIDGE, :PUBLIC, :LEASES + end + + st.show(pool, options) + end + + # TBD move this method to VirtualNetwork.rb (OCA) + def self.type_to_str(type) + if type=="0" + return "Ranged" + elsif type=="1" + return "Fixed" + end + end +end \ No newline at end of file From 21d4fab7e173109569a2a3adbae3afefd550f8f7 Mon Sep 17 00:00:00 2001 From: Daniel Molina Date: Tue, 7 Jun 2011 17:01:20 +0200 Subject: [PATCH 04/43] feature #661: Update onevnet command --- src/cli/onevnet | 378 ++++++++---------------------------------------- 1 file changed, 63 insertions(+), 315 deletions(-) diff --git a/src/cli/onevnet b/src/cli/onevnet index 48682d624b..d0d81dc8b2 100755 --- a/src/cli/onevnet +++ b/src/cli/onevnet @@ -25,342 +25,90 @@ else end $: << RUBY_LIB_LOCATION +$: << RUBY_LIB_LOCATION+"/cli" +require 'command_parser' +require 'one_helper/onevnet_helper' -require 'OpenNebula' -require 'client_utilities' -require 'command_parse' - - -ShowTableVN={ - :id => { - :name => "ID", - :desc => "ONE identifier for virtual network", - :size => 4, - :proc => lambda {|d,e| d.id } - }, - :name => { - :name => "NAME", - :desc => "name of the virtual network", - :size => 15, - :left => true, - :proc => lambda {|d,e| d.name } - }, - :user => { - :name => "USER", - :desc => "Username of the virtual network owner", - :size => 8, - :left => true, - :proc => lambda {|d,e| d["USERNAME"] } - }, - :type => { - :name => "TYPE", - :desc => "NType of virtual network", - :size => 6, - :proc => lambda {|d,e| - if(d["TYPE"] == "0") - return "Ranged" - else - if (d["TYPE"] == "1") - return "Fixed" - end - end - } - }, - :size => { - :name => "SIZE", - :desc => "Number of hosts (free + used) in the virtual network", - :size => 6, - :proc => lambda {|d,e| d["SIZE"] } - }, - :bridge => { - :name => "BRIDGE", - :desc => "Bridge associated to the virtual network", - :size => 6, - :proc => lambda {|d,e| d["BRIDGE"] } - }, - :public => { - :name => "PUBLIC", - :desc => "Whether the Image is public or not", - :size => 1, - :proc => lambda {|d,e| if d["PUBLIC"].to_i == 1 then "Y" else "N" end} - }, - :totalleases => { - :name => "#LEASES", - :desc => "Number of this virtual network's given leases", - :size => 7, - :proc => lambda {|d,e| d["TOTAL_LEASES"] } - }, - - :default => [:id, :user, :name, :type, :bridge, :public, :totalleases] -} - -class VNShow - def initialize(filter_flag="-2") - @vnpool=OpenNebula::VirtualNetworkPool.new(get_one_client, - filter_flag.to_i) - @table=ShowTable.new(ShowTableVN) +cmd=CommandParser::CmdParser.new(ARGV) do + usage "onevnet COMMAND [args..] [options..]" + + helper = OneVNetHelper.new + + ######################################################################## + # Global Options + ######################################################################## + set :option, CommandParser::OPTIONS + + ######################################################################## + # Formatters for arguments + ######################################################################## + oneid_desc='OpenNebula Virtual Network name or id' + set :format, :vnetid, oneid_desc do |arg| + helper.to_id(arg) end - def header_vn_small - scr_bold - scr_underline - print @table.header_str - scr_restore - puts "" + onelistid_desc='Comma-separated list of OpenNebula Virtual Network names or ids' + set :format, :vnetid_list, onelistid_desc do |arg| + helper.list_to_id(arg) end - def list_short(options=nil) - res=@vnpool.info - if options - @table.columns=options[:columns] if options[:columns] - end - - if OpenNebula.is_error?(res) - result=res - else - result=res - header_vn_small - if options[:filter_flag] - vns=@vnpool.select{|element| - element["USERNAME"]==options[:filter_flag] - } - else - vns=@vnpool - end - puts @table.data_str(vns, options) - result - end - end -end - -class OneVNParse < CommandParse - - COMMANDS_HELP=<<-EOT - -Description: - -This command enables the user to manage virtual networks in the OpenNebula -server. It provides functionality to create, get information and delete a -particular network or to list available and used IP's. - - -Commands: - -* create (Creates a new virtual network) - onevnet create