Module: OpenNebulaHelper

Defined in:
lib/one_helper.rb

Overview

OpenNebulaHelper module provides common methods for CLI helpers

Defined Under Namespace

Classes: OneHelper

Constant Summary collapse

ONE_VERSION =
<<~EOT
    OpenNebula #{OpenNebula::VERSION}
    Copyright 2002-2026, OpenNebula Project, OpenNebula Systems
EOT
TABLE_CONF_PATH =
'/etc/one/cli'
VAR_LOCATION =
'/var/lib/one'
CLI_ADDONS_LOCATION =
'/usr/lib/one/ruby/cli/addons'
XSD_PATH =
'/usr/share/one/schemas/xsd'
EDITOR_PATH =
'/usr/bin/vi'
TEMPLATE_INPUT =
'A template can be passed as a file with or the content via STDIN
Bash symbols must be escaped on STDIN passing'
XML =

Options

{
    :name  => 'xml',
    :short => '-x',
    :large => '--xml',
    :description => 'Show the resource in xml format'
}
JSON =
{
    :name => 'json',
    :short => '-j',
    :large => '--json',
    :description => 'Show the resource in JSON format',
    :proc        => lambda do |_, _|
        require 'json'
    end
}
YAML =
{
    :name => 'yaml',
    :short => '-y',
    :large => '--yaml',
    :description => 'Show the resource in YAML format'
}
NUMERIC =
{
    :name  => 'numeric',
    :short => '-n',
    :large => '--numeric',
    :description => 'Do not translate user and group IDs'
}
KILOBYTES =
{
    :name  => 'kilobytes',
    :short => '-k',
    :large => '--kilobytes',
    :description => 'Show units in kilobytes'
}
DESCRIBE =
{
    :name  => 'describe',
    :large => '--describe',
    :description => 'Describe list columns'
}
APPEND =
{
    :name => 'append',
    :short => '-a',
    :large => '--append',
    :description => 'Append new attributes to the current template'
}
FILE =
{
    :name => 'file',
    :short => '-f file',
    :large => '--file file',
    :description => 'Selects the template file',
    :format => String,
    :proc => lambda {|o, options|
        if File.file?(o)
            options[:file] = o
        else
            STDERR.puts "File `#{options[:file]}` doesn't exist"
            exit(-1)
        end
    }
}
TEMPLATE_NAME_VM =

Command line VM template options

{
    :name   => 'name',
    :large  => '--name name',
    :description =>
        'Name for the new VM',
    :format => String
}
DRY =
{
    :name  => 'dry',
    :large  => '--dry',
    :description => 'Just print the template'
}
CLIENT_OPTIONS =
[
    {
        :name   => 'user',
        :large  => '--user name',
        :description => 'User name used to connect to OpenNebula',
        :format => String,
        :proc => lambda do |o, _options|
            OneHelper.set_user(o)
            [0, o]
        end
    },
    {
        :name   => 'password',
        :large  => '--password password',
        :description => 'Password to authenticate with OpenNebula',
        :format => String,
        :proc => lambda do |o, _options|
            OneHelper.set_password(o)
            [0, o]
        end
    },
    {
        :name   => 'endpoint',
        :large  => '--endpoint endpoint',
        :description => 'URL of OpenNebula RPC frontend',
        :format => String,
        :proc => lambda do |o, _options|
            OneHelper.set_endpoint(o)
            [0, o]
        end
    },
    {
        :name   => 'grpc',
        :large  => '--grpc',
        :description => 'Use gRPC protocol to connect to OpenNebula'
    }
]
GROUP_OPTIONS =
[
    {
        :name   => 'name',
        :large  => '--name name',
        :short => '-n',
        :description =>
            'Name for the new group',
        :format => String
    },
    {
        :name   => 'admin_user',
        :large  => '--admin_user name',
        :short => '-u',
        :description =>
            'Creates an admin user for the group with name',
        :format => String
    },
    {
        :name   => 'admin_password',
        :large  => '--admin_password pass',
        :short => '-p',
        :description =>
            'Password for the admin user of the group',
        :format => String
    },
    {
        :name   => 'admin_driver',
        :large  => '--admin_driver driver',
        :short => '-d',
        :description =>
            'Auth driver for the admin user of the group',
        :format => String
    },
    {
        :name   => 'resources',
        :large  => '--resources res_str',
        :short => '-r',
        :description =>
            'Which resources can be created by group users '<<
            '(VM+NET+IMAGE+TEMPLATE by default)',
        :format => Object
    }
]
AS_USER =
{
    :name   => 'as_uid',
        :large  => '--as_uid uid',
        :format => Integer,
        :description => 'The User ID to instantiate the VM'
}
AS_GROUP =
{
    :name   => 'as_gid',
        :large  => '--as_gid gid',
        :format => Integer,
        :description => 'The Group ID to instantiate the VM'
}
TEMPLATE_OPTIONS =

NOTE: Other options defined using this array, add new options at the end

[
    {
        :name   => 'cpu',
        :large  => '--cpu cpu',
        :description =>
            "CPU percentage reserved for the VM (1=100% one\n"<<
            ' '*31<<'CPU)',
        :format => Float
    },
    {
        :name   => 'vcpu',
        :large  => '--vcpu vcpu',
        :description =>
            'Number of virtualized CPUs',
        :format => Integer
    },
    {
        :name   => 'arch',
        :large  => '--arch arch',
        :description =>
            'Architecture of the VM, e.g.: i386 or x86_64',
        :format => String
    },
    {
        :name   => 'memory',
        :large  => '--memory memory',
        :description => 'Memory amount given to the VM. By default the '<<
            "unit is megabytes. To use gigabytes add a 'g', floats "<<
            'can be used: 8g=8192, 0.5g=512',
        :format => String,
        :proc   => lambda do |o, _options|
            m=o.strip.match(/^(\d+(?:\.\d+)?)(m|mb|g|gb)?$/i)

            if !m
                [-1, 'Memory value malformed']
            else
                multiplier=case m[2]
                           when /(g|gb)/i
                               1024
                           else
                               1
                           end

                value=m[1].to_f*multiplier

                [0, value.floor]
            end
        end
    },
    {
        :name   => 'disk',
        :large  => '--disk image0,image1',
        :description => 'Disks to attach. To use an image owned by'<<
                        ' other user use user[disk]. Add any additional'<<
                        " attributes separated by ':' and in the shape of"<<
                        ' KEY=VALUE. For example, if the disk must be'<<
                        ' resized, use image0:size=1000 . Or'<<
                        ' image0:size=1000:target=vda,image1:target=vdb',
        :format => Array
    },
    {
        :name   => 'nic',
        :large  => '--nic network0,network1',
        :description => 'Networks to attach. To use a network owned by'<<
                        ' other user use user[network]. Additional'<<
                        ' attributes are supported like with the --disk'<<
                        ' option. Also you can use auto if you want that' <<
                        ' OpenNebula select automatically the network',
        :format => Array
    },
    {
        :name   => 'raw',
        :large  => '--raw string',
        :description => "Raw string to add to the template. Not to be\n"<<
                        ' '*31<<'confused with the RAW attribute',
        :format => String
    },
    {
        :name   => 'vnc',
        :large  => '--vnc',
        :description => 'Add VNC server to the VM'
    },
    {
        :name   => 'vnc_password',
        :large  => '--vnc-password password',
        :format => String,
        :description => 'VNC password'
    },
    {
        :name   => 'vnc_listen',
        :large  => '--vnc-listen ip',
        :format => String,
        :description => 'VNC IP where to listen for connections. '<<
            'By default is 0.0.0.0 (all interfaces).'
    },
    {
        :name   => 'vnc_keymap',
        :large  => '--vnc-keymap keymap',
        :format => String,
        :description => 'VNC keyboard layout'
    },
    {
        :name   => 'spice',
        :large  => '--spice',
        :description => 'Add spice server to the VM'
    },
    {
        :name   => 'spice_password',
        :large  => '--spice-password password',
        :format => String,
        :description => 'spice password'
    },
    {
        :name   => 'spice_listen',
        :large  => '--spice-listen ip',
        :format => String,
        :description => 'spice IP where to listen for connections. '<<
            'By default is 0.0.0.0 (all interfaces).'
    },
    {
        :name   => 'spice_keymap',
        :large  => '--spice-keymap keymap',
        :format => String,
        :description => 'spice keyboard layout'
    },
    {
        :name   => 'ssh',
        :large  => '--ssh [file]',
        :description => "Add an ssh public key to the context. If the \n"<<
            (' '*31) << "file is omited then the user variable \n"<<
            (' '*31) << 'SSH_PUBLIC_KEY will be used.',
        :format => String,
        :proc => lambda do |o, _options|
            if !o
                [0, true]
            else
                [0, o]
            end
        end
    },
    {
        :name   => 'net_context',
        :large  => '--net_context',
        :description => 'Add network contextualization parameters'
    },
    {
        :name   => 'context',
        :large  => '--context line1,line2,line3',
        :format => Array,
        :description => 'Replaces the context section with the specified lines'
    },
    {
        :name   => 'boot',
        :large  => '--boot device_list',
        :description => 'Set boot device list e.g. disk0,disk2,nic0',
        :format => String
    },
    {
        :name   => 'files_ds',
        :large  => '--files_ds file1,file2',
        :format => Array,
        :description => 'Add files to the contextualization CD from the' <<
            'files datastore'
    },
    {
        :name   => 'init',
        :large  => '--init script1,script2',
        :format => Array,
        :description => 'Script or scripts to start in context'
    },
    {
        :name   => 'startscript',
        :large  => '--startscript [file]',
        :format => String,
        :description => 'Start script to be executed'
    },
    {
        :name   => 'report_ready',
        :large  => '--report_ready',
        :description => 'Sends READY=YES to OneGate, useful for OneFlow'
    },
    {
        :name   => 'user_inputs',
        :large  => '--user-inputs ui1,ui2,ui3',
        :format => String,
        :description => 'Specify the user inputs values when instantiating',
        :proc => lambda do |_o, options|
            keys   = options[:user_inputs].scan(/(?:^|,)([^,=]+)=/).flatten
            values = options[:user_inputs].scan(/=(.+?)(?=,[^,]+=|$)/).flatten

            options[:user_inputs_keys] = keys

            options[:user_inputs] = keys.zip(values).map do |k, v|
                %(#{k}="#{v}")
            end.join("\n")
        end
    },
    {
        :name   => 'video',
        :large  => '--video type',
        :format => String,
        :description => 'Add a custom video device (none, vga, cirrus, virtio)'
    },
    {
        :name   => 'video_iommu',
        :large  => '--video-iommu',
        :description => 'Enable IOMMU (I/O Memory Management Unit) for the video device'
    },
    {
        :name   => 'video_ats',
        :large  => '--video-ats',
        :description => 'Enable ATS (Address Translation Services) for the video device'
    },
    {
        :name   => 'video_vram',
        :large  => '--video-vram vram',
        :description => 'VRAM allocated to the video device. By default the ' +
            "unit is megabytes. To use gigabytes add a 'g', floats " +
            'can be used: 8g=8192, 0.5g=512',
        :format => String,
        :proc   => lambda do |o, _options|
            m=o.strip.match(/^(\d+(?:\.\d+)?)(m|mb|g|gb)?$/i)

            if !m
                [-1, 'VRAM value malformed']
            else
                multiplier=case m[2]
                           when /(g|gb)/i
                               1048576 # = 1024 * 1024
                           else
                               1024
                           end

                value=m[1].to_f*multiplier

                [0, value.floor]
            end
        end
    },
    {
        :name   => 'video_resolution',
        :large  => '--video-resolution resolution',
        :format => String,
        :description => 'Video resolution, in format like: 1280x720 or 1920x1080',
        :proc   => lambda do |_o, _options|
            if !m.match?(/\d{3,4}x\d{3,4}/)
                [-1, 'Video Resolution value malformed']
            end
        end
    },
    AS_GROUP,
    AS_USER
]
FORCE =
{
    :name  => 'force',
    :large  => '--force',
    :description => 'Ignore errors (if possible)'
}
EXTENDED =
{
    :name => 'extended',
    :large => '--extended',
    :description => 'Show info extended (it only works with xml output)'
}
DECRYPT =
{
    :name => 'decrypt',
    :large => '--decrypt',
    :description => 'Get decrypted attributes'
}
SCHEDULE_OPTIONS =
[
    SCHEDULE = {
        :name => 'schedule',
        :large => '--schedule TIME',
        :description => 'Schedules this action to be executed after' \
        'the given time. For example: onevm resume 0 --schedule "09/23 14:15"',
        :format => String,
        :proc => lambda {|o, options|
            if o[0] == '+'
                options[:schedule] = o
            elsif o == 'now'
                options[:schedule] = Time.now.to_i
            else
                begin
                    options[:schedule] = Time.parse(o).to_i
                rescue StandardError
                    STDERR.puts "Error parsing time spec: #{o}"
                    exit(-1)
                end
            end
        }
    },

    WEEKLY = {
        :name => 'weekly',
        :large => '--weekly days',
        :description => 'Repeats the schedule action the days of the week ' \
        'specified, it can be a number between 0 (Sunday) to 6 (Saturday) ' \
        'separated with commas. ' \
        'For example: onevm resume 0 --schedule "09/23 14:15" --weekly 0,2,4',
        :format => String
    },

    MONTHLY = {
        :name => 'monthly',
        :large => '--monthly days',
        :description => 'Repeats the schedule action the days of the month ' \
        'specified, it can be a number between 1,31 separated with commas. ' \
        'For example: onevm resume 0 --schedule "09/23 14:15" --monthly 1,14',
        :format => String
    },

    YEARLY = {
        :name => 'yearly',
        :large => '--yearly days',
        :description => 'Repeats the schedule action the days of the year ' \
        'specified, it can be a number between 0,365 separated with commas. ' \
        'For example: onevm resume 0 --schedule "09/23 14:15" --yearly 30,60',
        :format => String
    },

    HOURLY = {
        :name => 'hourly',
        :large => '--hourly hour',
        :description => 'Repeats the schedule action with the given hourly frequency. ' \
        'For example (every 5 hours): onevm resume 0 --schedule "09/23 14:15" --hourly 5',
        :format => Numeric
    },

    END_TIME = {
        :name => 'end',
        :large => '--end number|TIME',
        :description => '----',
        :format => String
    }
]
TEMPLATE_OPTIONS_VM =
[TEMPLATE_NAME_VM] + TEMPLATE_OPTIONS + [DRY]
CAPACITY_OPTIONS_VM =
[TEMPLATE_OPTIONS[0], TEMPLATE_OPTIONS[1],
TEMPLATE_OPTIONS[3]]
UPDATECONF_OPTIONS_VM =
TEMPLATE_OPTIONS[6..15] + [TEMPLATE_OPTIONS[2],
TEMPLATE_OPTIONS[17], TEMPLATE_OPTIONS[18]]
FORMAT =
[XML, JSON, YAML]
OPTIONS =
FORMAT, EXTENDED, NUMERIC, KILOBYTES
BACKUP_MODES =
['FULL', 'INCREMENT']
BINARY_SUFFIX =
['K', 'M', 'G', 'T']

Class Method Summary collapse

Class Method Details

.append_template(id, resource, path = nil, xpath = 'TEMPLATE') ⇒ Object



1738
1739
1740
# File 'lib/one_helper.rb', line 1738

def self.append_template(id, resource, path = nil, xpath = 'TEMPLATE')
    update_template_helper(true, id, resource, path, xpath)
end

.boolean_to_str(str) ⇒ Object



1613
1614
1615
1616
1617
1618
1619
# File 'lib/one_helper.rb', line 1613

def self.boolean_to_str(str)
    if str.to_i == 1
        'Yes'
    else
        'No'
    end
end

.bytes_to_unit(value, unit = 'K') ⇒ Object



1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
# File 'lib/one_helper.rb', line 1702

def self.bytes_to_unit(value, unit = 'K')
    j = 0
    i = BINARY_SUFFIX.index(unit).to_i

    while j < i
        value /= 1024.0
        j += 1
    end

    value
end

.cluster_str(str) ⇒ String

If the cluster name is empty, returns a ‘-’ char.

Parameters:

  • str (String || Hash)

    Cluster name, or empty Hash (when <CLUSTER/>)

Returns:

  • (String)

    the same Cluster name, or ‘-’ if it is empty



1718
1719
1720
1721
1722
1723
1724
# File 'lib/one_helper.rb', line 1718

def self.cluster_str(str)
    if !str.nil? && !str.empty?
        str
    else
        '-'
    end
end

.clusters_str(clusters) ⇒ Object



1726
1727
1728
1729
1730
1731
1732
# File 'lib/one_helper.rb', line 1726

def self.clusters_str(clusters)
    if clusters.nil?
        '-'
    else
        [clusters].flatten.join(',')
    end
end

.create_ar(options) ⇒ Object



2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
# File 'lib/one_helper.rb', line 2045

def self.create_ar(options)
    ar = 'AR = [ '

    if options[:ip]
        if options[:ip6_global] || options[:ip6_ula]
            ar << 'TYPE="IP4_6"'
        elsif options[:ip6]
            ar << 'TYPE="IP4_6_STATIC"'
        else
            ar << 'TYPE="IP4"'
        end
    elsif options[:ip6]
        ar << 'TYPE="IP6_STATIC"'
    elsif options[:ip6_global] || options[:ip6_ula]
        ar << 'TYPE="IP6"'
    else
        ar << 'TYPE="ETHER"'
    end

    if options[:size]
        ar << ', SIZE = ' << options[:size]
    else
        unless options[:ip6]
            STDERR.puts 'Address range needs to specify size (-s size)'
            exit(-1)
        end
    end

    if options[:ip6]
        m = %r{([\h:]*)\/(\d.*)$}.match(options[:ip6])

        if m.nil? || m[1].nil?
            STDERR.puts 'Missing or wrong IP6'
            exit(-1)
        else
            begin
                require 'ipaddr'

                ip = IPAddr.new(m[1])

                if !ip.ipv6?
                    STDERR.puts 'Wrong IP6 format address'
                    exit(-1)
                end
            rescue StandardError
                STDERR.puts 'Wrong IP6 format address'
                exit(-1)
            end

        end

        if m[2].nil?
            STDERR.puts 'IP6 address need to set the prefix length'
            exit(-1)
        end

        ar << ", PREFIX_LENGTH=\"#{m[2]}\""

        options[:ip6] = m[1]
    end

    ar << ', IP = ' << options[:ip] if options[:ip]
    ar << ', IP6 = ' << options[:ip6] if options[:ip6]
    ar << ', MAC = ' << options[:mac] if options[:mac]
    if options[:ip6_global]
        ar << ', GLOBAL_PREFIX = ' << options[:ip6_global]
    end
    if options[:ip6_ula]
        ar << ', ULA_PREFIX = ' << options[:ip6_ula]
    end
    ar << ', GATEWAY = ' << options[:gateway] if options[:gateway]
    ar << ', MASK = '    << options[:netmask] if options[:netmask]
    ar << ', VN_MAD = '  << options[:vn_mad]  if options[:vn_mad]
    ar << ', VLAN_ID = ' << options[:vlanid]  if options[:vlanid]

    ar << ']'
end

.create_context_str(options, context_hash) ⇒ Object



1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
# File 'lib/one_helper.rb', line 1895

def self.create_context_str(options, context_hash)
    context_options = [:ssh, :net_context, :context, :init, :files_ds, :startscript,
                       :report_ready]
    if !(options.keys & context_options).empty?
        if options[:ssh]
            if options[:ssh]==true
                context_hash['SSH_PUBLIC_KEY'] = '$USER[SSH_PUBLIC_KEY]'
            else
                begin
                    key=File.read(options[:ssh]).strip
                rescue StandardError => e
                    STDERR.puts e.message
                    exit(-1)
                end
                context_hash['SSH_PUBLIC_KEY'] = key
            end
        end

        if options[:net_context]
            context_hash['NETWORK'] = 'YES'
        end

        if options[:files_ds]
            files = options[:files_ds].map {|file| %($FILE[IMAGE=\\"#{file}\\"]) }.join(' ')

            context_hash['FILES_DS'] = files
        end

        if options[:init]
            context_hash['INIT_SCRIPTS'] = options[:init].join(' ')
        end

        if options[:startscript]
            script = nil
            begin
                script = File.read(options[:startscript]).strip
            rescue StandardError => e
                STDERR.puts e.message
                exit(-1)
            end
            script = Base64.strict_encode64(script)
            context_hash['START_SCRIPT_BASE64'] = script

        end

        if options[:report_ready]
            context_hash['REPORT_READY'] = 'YES'
        end

        if context_hash.any? || options[:context]
            formatted_context = "CONTEXT=[\n"
            formatted_context << options[:context].map {|l|
                ' ' << l
            }.join(",\n") if options[:context]
            if context_hash.any?
                formatted_context << ",\n" if options[:context]
                formatted_context << context_hash.map {|k, v| "  #{k}=\"#{v}\"" }.join(",\n")
            end
            formatted_context << "\n]\n"
            formatted_context
        else
            nil
        end
    else
        nil
    end
end

.create_disk_net(objects, section, name) ⇒ Object



1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
# File 'lib/one_helper.rb', line 1843

def self.create_disk_net(objects, section, name)
    template=''

    objects.each do |obj|
        obj, *extra_attributes = obj.split(':')

        # When extra attributes do not contain = character include
        # them in the previous value. Fixes adding MAC addresses. These
        # contain ":" character also used as extra attributes separator.
        #
        # It may be needed to strip the value from start and end quotes
        # as the value could be written as this:
        #
        # --nic 'some_net:mac="00:0A:12:34:56:78"'
        #
        attrs = []
        extra_attributes.each do |str|
            if str.include?('=')
                attrs << str
            else
                attrs.last << ":#{str}"
            end
        end

        extra_attributes = attrs

        res=parse_user_object(obj)
        return [-1, "#{section.capitalize} \"#{obj}\" malformed"] unless res

        user, object=*res

        template<<"#{section.upcase}=[\n"
        if object.downcase == 'auto'
            template<<"  NETWORK_MODE=\"#{object}\"\n"
        else
            template<<"  #{name.upcase}_UNAME=\"#{user}\",\n" if user
            extra_attributes.each do |extra_attribute|
                key, value = extra_attribute.split('=')
                template<<"  #{key.upcase}=\"#{value}\",\n"
            end
            if object.match(/^\d+$/)
                template<<"  #{name.upcase}_ID=#{object}\n"
            else
                template<<"  #{name.upcase}=\"#{object}\"\n"
            end
        end
        template<<"]\n"
    end if objects

    [0, template]
end

.create_template(options, template_obj = nil) ⇒ Object



1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
# File 'lib/one_helper.rb', line 1963

def self.create_template(options, template_obj = nil)
    template=''

    template<<"NAME=\"#{options[:name]}\"\n" if options[:name]

    if options[:arch] || options[:boot]
        template<<"OS = [\n"

        lines=[]
        lines<<"  ARCH = \"#{options[:arch]}\"" if options[:arch]
        lines<<"  BOOT = \"#{options[:boot]}\"" if options[:boot]

        template<<lines.join(",\n")

        template << " ]\n"
    end

    template<<"CPU=#{options[:cpu]}\n" if options[:cpu]
    template<<"VCPU=#{options[:vcpu]}\n" if options[:vcpu]
    template<<"MEMORY=#{options[:memory]}\n" if options[:memory]
    template<<"#{options[:raw]}\n" if options[:raw]

    template<<"AS_UID=#{options[:as_uid]}\n" if options[:as_uid]
    template<<"AS_GID=#{options[:as_gid]}\n" if options[:as_gid]

    if options[:disk]
        res=create_disk_net(options[:disk], 'DISK', 'IMAGE')
        return res if res.first!=0

        template<<res.last
    end

    if options[:nic]
        res=create_disk_net(options[:nic], 'NIC', 'NETWORK')
        return res if res.first!=0

        template<<res.last
    end

    if options[:vnc]
        vnc_listen=options[:vnc_listen] || '0.0.0.0'
        template<<"GRAPHICS=[ TYPE=\"vnc\", LISTEN=\"#{vnc_listen}\""
        if options[:vnc_password]
            template << ", PASSWD=\"#{options[:vnc_password]}\""
        end
        if options[:vnc_keymap]
            template << ", KEYMAP=\"#{options[:vnc_keymap]}\""
        end
        template<<' ]' << "\n"
    end

    if options[:spice]
        spice_listen=options[:spice_listen] || '0.0.0.0'
        template<<"GRAPHICS=[ TYPE=\"spice\", LISTEN=\"#{spice_listen}\""
        if options[:spice_password]
            template << ", PASSWD=\"#{options[:spice_password]}\""
        end
        if options[:spice_keymap]
            template << ", KEYMAP=\"#{options[:spice_keymap]}\""
        end
        template<<' ]' << "\n"
    end

    if options[:video]
        template<<"VIDEO=[ TYPE=\"#{options[:video]}\""
        template<<', IOMMU="YES"' if options[:video_iommu]
        template<<', ATS="YES"' if options[:video_ats]
        template<<", VRAM=\"#{options[:video_vram]}\"" if options[:video_vram]
        template<<", RESOLUTION=\"#{options[:video_resolution]}\""
        template<<' ]' << "\n"
    end

    context_hash = {}
    if !template_obj.nil? && template_obj.has_elements?('TEMPLATE/CONTEXT')
        context_hash = template_obj.to_hash['VMTEMPLATE']['TEMPLATE']['CONTEXT']
    end
    context_str=create_context_str(options, context_hash)
    template<<context_str if context_str

    [0, template]
end

.create_template_options_used?(options, conflicting_opts) ⇒ Boolean

Returns:

  • (Boolean)


2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
# File 'lib/one_helper.rb', line 2123

def self.create_template_options_used?(options, conflicting_opts)
    # Get the template options names as symbols. options hash
    # uses symbols
    template_options=OpenNebulaHelper::TEMPLATE_OPTIONS.map do |o|
        o[:name].to_sym
    end

    # Check if at least one of the template options is in options hash
    conflicting_opts.replace(options.keys & template_options)

    !conflicting_opts.empty?
end

.editor_input(contents = nil) ⇒ Object



1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
# File 'lib/one_helper.rb', line 1802

def self.editor_input(contents = nil)
    require 'tempfile'

    tmp = Tempfile.new('one_cli')

    if contents
        tmp << contents
        tmp.flush
    end

    editor_path = ENV['EDITOR'] ? ENV['EDITOR'] : EDITOR_PATH
    system("#{editor_path} #{tmp.path}")

    unless $CHILD_STATUS.exitstatus == 0
        puts 'Editor not defined'
        exit(-1)
    end

    tmp.close

    File.read(tmp.path)
end

.get_plot(x, y, attr, title) ⇒ Object

Returns plot object to print it on the CLI

Parameters:

  • x (Array)

    Data to x axis (Time axis)

  • y (Array)

    Data to y axis

  • attr (String)

    Parameter to y axis

  • title (String)

    Plot title

Returns:

  • Gnuplot plot object



2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
# File 'lib/one_helper.rb', line 2355

def self.get_plot(x, y, attr, title)
    # Require gnuplot gem only here
    begin
        require 'gnuplot'
    rescue LoadError
        STDERR.puts(
            'Gnuplot gem is not installed, run `gem install gnuplot` '\
            'to install it'
        )
        exit(-1)
    end

    # Check if gnuplot is installed on the system
    unless system('gnuplot --version')
        STDERR.puts(
            'Gnuplot is not installed, install it depending on your distro'
        )
        exit(-1)
    end

    Gnuplot.open do |gp|
        Gnuplot::Plot.new(gp) do |p|
            p.title title

            p.xlabel 'Time'
            p.ylabel attr

            p.xdata   'time'
            p.timefmt "'%H:%M'"
            p.format  "x '%H:%M'"

            p.style    'data lines'
            p.terminal 'dumb'

            p.data << Gnuplot::DataSet.new([x, y]) do |ds|
                ds.with      = 'linespoints'
                ds.linewidth = '3'
                ds.using     = '1:2'

                ds.notitle
            end
        end
    end
end

.level_lock_to_str(str) ⇒ Object



2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
# File 'lib/one_helper.rb', line 2136

def self.level_lock_to_str(str)
    level = str.to_i
    case level
    when 0
        'None'
    when 1
        'Use'
    when 2
        'Manage'
    when 3
        'Admin'
    when 4
        'All'
    else
        '-'
    end
end

.parse_user_inputs(inputs, keys = []) ⇒ Object



2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
# File 'lib/one_helper.rb', line 2154

def self.parse_user_inputs(inputs, keys = [])
    unless inputs.keys == keys
        puts 'There are some parameters that require user input. ' \
             'Use the string <<EDITOR>> to launch an editor ' \
             '(e.g. for multi-line inputs)'
    end

    answers = {}

    inputs.each do |key, val|
        next if keys.include? key

        input_cfg = val.split('|', -1)

        if input_cfg.length < 3
            STDERR.puts 'Malformed user input. It should have at least 3 '\
                        "parts separated by '|':"
            STDERR.puts "  #{key}: #{val}"
            exit(-1)
        end

        mandatory, type, description, params, initial = input_cfg
        optional = mandatory.strip == 'O'
        type.strip!
        description.strip!

        if input_cfg.length > 3
            if input_cfg.length != 5
                STDERR.puts 'Malformed user input. It should have 5 parts'\
                            " separated by '|':"
                STDERR.puts "  #{key}: #{val}"
                exit(-1)
            end

            params.strip!
            initial.strip!
        end

        puts "  * (#{key}) #{description}"

        header = '    '
        if !initial.nil? && initial != ''
            header += "Press enter for default (#{initial}). "
        end

        case type
        when 'text', 'text64'
            print header

            answer = STDIN.readline.chop

            if answer == '<<EDITOR>>'
                answer = OpenNebulaHelper.editor_input
            end

            # use default in case it's empty
            answer = initial if answer.empty?

            if type == 'text64'
                answer = Base64.encode64(answer).strip.delete("\n")
            end

        when 'boolean'
            print header

            answer = STDIN.readline.chop

            # use default in case it's empty
            answer = initial if answer.empty?

            unless ['YES', 'NO'].include?(answer)
                STDERR.puts "Invalid boolean '#{answer}'"
                STDERR.puts 'Boolean has to be YES or NO'
                exit(-1)
            end

        when 'password'
            print header

            answer = OpenNebulaHelper::OneHelper.get_password

            # use default in case it's empty
            answer = initial if answer.empty?

        when 'number', 'number-float'
            if type == 'number'
                header += 'Integer: '
                exp = OneTemplateHelper::INT_EXP
            else
                header += 'Float: '
                exp = OneTemplateHelper::FLOAT_EXP
            end

            loop do
                print header
                answer = STDIN.readline.chop

                answer = initial if answer == ''
                noanswer = (answer == '') && optional

                break if noanswer || !(answer =~ exp).nil?
            end

            if noanswer
                next
            end

        when 'range', 'range-float'
            min, max = params.split('..')

            if min.nil? || max.nil?
                STDERR.puts 'Malformed user input. '\
                            "Parameters should be 'min..max':"
                STDERR.puts "  #{key}: #{val}"
                exit(-1)
            end

            if type == 'range'
                exp = OneTemplateHelper::INT_EXP
                min = min.to_i
                max = max.to_i

                header += "Integer in the range [#{min}..#{max}]: "
            else
                exp = OneTemplateHelper::FLOAT_EXP
                min = min.to_f
                max = max.to_f

                header += "Float in the range [#{min}..#{max}]: "
            end

            loop do
                print header
                answer = STDIN.readline.chop

                answer = initial if answer == ''

                noanswer = (answer == '') && optional

                break if noanswer || (!(answer =~ exp).nil? &&
                          answer.to_f >= min && answer.to_f <= max)
            end

            if noanswer
                next
            end

        when 'list'
            options = params.split(',')

            options.each_with_index do |opt, i|
                puts "    #{i}  #{opt}"
            end

            puts

            header += 'Please type the selection number: '

            loop do
                print header
                answer = STDIN.readline.chop

                if answer == ''
                    answer = initial
                else
                    answer = options[answer.to_i]
                end

                noanswer = (answer == '') && optional

                break if noanswer || options.include?(answer)
            end

            if noanswer
                next
            end

        when 'fixed'
            puts "    Fixed value of (#{initial}). Cannot be changed"
            answer = initial

        else
            STDERR.puts 'Wrong type for user input:'
            STDERR.puts "  #{key}: #{val}"
            exit(-1)
        end

        answers[key] = answer
    end

    answers
end

.parse_user_object(user_object) ⇒ Object



1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
# File 'lib/one_helper.rb', line 1825

def self.parse_user_object(user_object)
    reg=/^([^\[]+)(?:\[([^\]]+)\])?$/

    m=user_object.match(reg)

    return unless m

    user=nil
    if m[2]
        user=m[1]
        object=m[2]
    else
        object=m[1]
    end

    [user, object]
end

.period_to_str(time, print_seconds = true) ⇒ Object



1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
# File 'lib/one_helper.rb', line 1654

def self.period_to_str(time, print_seconds = true)
    seconds=time.to_i
    minutes, seconds=seconds.divmod(60)
    hours, minutes=minutes.divmod(60)
    days, hours=hours.divmod(24)

    if print_seconds
        format('%<days>3dd %<hours>02dh%<minutes>02dm%<seconds>02ds',
               :days => days, :hours => hours, :minutes => minutes, :seconds => seconds)
    else
        format('%<days>3dd %<hours>02dh%<minutes>02dm',
               :days => days, :hours => hours, :minutes => minutes)
    end
end

.read_stdinObject



2600
2601
2602
2603
2604
2605
2606
# File 'lib/one_helper.rb', line 2600

def self.read_stdin
    if STDIN.wait_readable(0)
        STDIN.read
    else
        ''
    end
end

.rname_to_id(name, poolname) ⇒ Object



1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
# File 'lib/one_helper.rb', line 1528

def self.rname_to_id(name, poolname)
    return 0, name.to_i if name.match(/^[0123456789]+$/)

    client=OneHelper.client

    pool = case poolname
           when 'HOST'
               require 'opennebula/host_pool'
               OpenNebula::HostPool.new(client)
           when 'HOOK'
               require 'opennebula/hook_pool'
               OpenNebula::HookPool.new(client)
           when 'GROUP'
               require 'opennebula/group_pool'
               OpenNebula::GroupPool.new(client)
           when 'USER'
               require 'opennebula/user_pool'
               OpenNebula::UserPool.new(client)
           when 'DATASTORE'
               require 'opennebula/datastore_pool'
               OpenNebula::DatastorePool.new(client)
           when 'CLUSTER'
               require 'opennebula/cluster_pool'
               OpenNebula::ClusterPool.new(client)
           when 'VNET'
               require 'opennebula/virtual_network_pool'
               OpenNebula::VirtualNetworkPool.new(client)
           when 'IMAGE'
               require 'opennebula/image_pool'
               OpenNebula::ImagePool.new(client)
           when 'VMTEMPLATE'
               require 'opennebula/template_pool'
               OpenNebula::TemplatePool.new(client)
           when 'VNTEMPLATES'
               require 'opennebula/vntemplate_pool'
               OpenNebula::VNTemplatePool.new(client)
           when 'VM'
               require 'opennebula/virtual_machine_pool'
               OpenNebula::VirtualMachinePool.new(client)
           when 'ZONE'
               require 'opennebula/zone_pool'
               OpenNebula::ZonePool.new(client)
           when 'MARKETPLACE'
               require 'opennebula/marketplace_pool'
               OpenNebula::MarketPlacePool.new(client)
           when 'FLOWTEMPLATES'
               OpenNebula::ServiceTemplatePool.new(client)
           end

    rc = pool.info
    if OpenNebula.is_error?(rc)
        return -1, "OpenNebula #{poolname} name not found," <<
                   ' use the ID instead'
    end

    OneHelper.name_to_id(name, pool, poolname)
end

.rname_to_id_desc(poolname) ⇒ Object



1609
1610
1611
# File 'lib/one_helper.rb', line 1609

def self.rname_to_id_desc(poolname)
    "OpenNebula #{poolname} id"
end

.schedule_action_tmpl(options, action, warning = nil) ⇒ Object



2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
# File 'lib/one_helper.rb', line 2451

def self.schedule_action_tmpl(options, action, warning = nil)
    str_periodic = ''

    if options.key?(:weekly)
        str_periodic << ", REPEAT = 0, DAYS = \"#{options[:weekly]}\""
    elsif options.key?(:monthly)
        str_periodic << ", REPEAT = 1, DAYS = \"#{options[:monthly]}\""
    elsif options.key?(:yearly)
        str_periodic << ", REPEAT = 2, DAYS = \"#{options[:yearly]}\""
    elsif options.key?(:hourly)
        str_periodic << ", REPEAT = 3, DAYS = \"#{options[:hourly]}\""
    end

    if options.key?(:end)
        begin
            end_date = Date.parse(options[:end])
            str_periodic << ", END_TYPE = 2, END_VALUE = #{end_date.to_time.to_i}"
        rescue ArgumentError
            if options[:end].to_i > 0
                str_periodic << ", END_TYPE = 1, END_VALUE = #{options[:end].to_i}"
            end
        end
    elsif str_periodic != ''
        str_periodic << ', END_TYPE = 0'
    end

    tmp_str = 'SCHED_ACTION = ['
    tmp_str << "ACTION  = #{action}, " if action
    tmp_str << "WARNING = #{warning}," if warning
    tmp_str << "ARGS    = \"#{options[:args]}\"," if options[:args]
    tmp_str << "TIME    = #{options[:schedule]}"
    tmp_str << str_periodic << ']'

    tmp_str
end

.scheduled_action_table(object) ⇒ Object



2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
# File 'lib/one_helper.rb', line 2487

def self.scheduled_action_table(object)
    CLIHelper::ShowTable.new(nil, object) do
        column :ID, '', :adjust => true do |d|
            warn = d['WARNING'].to_i

            prefix = ''
            prefix = '*' if d['DONE'].to_i <= 0 && warn != 0 && warn < Time.now.to_i

            prefix + d['ID']
        end

        column :ACTION, '', :adjust => true do |d|
            d['ACTION']
        end

        column :ARGS, '', :adjust => true do |d|
            d['ARGS'] && !d['ARGS'].empty? ? d['ARGS'] : '-'
        end

        column :SCHEDULED, '', :adjust => true do |d|
            t = d['TIME'].to_i

            # relative action for VMs
            if d['TIME'] !~ /^[0-9].*/ && !object['STIME'].nil?
                t += object['STIME'].to_i
            end

            OpenNebulaHelper.time_to_str(t, false) unless d.nil?
        end

        column :REPEAT, '', :adjust => true do |d|
            begin
                str_rep = ''

                case d['REPEAT']
                when '0'
                    str_rep << 'Weekly '
                when '1'
                    str_rep << 'Monthly '
                when '2'
                    str_rep << 'Yearly '
                when '3'
                    str_rep << 'Each ' << d['DAYS'] << ' hours'
                end

                if d['REPEAT'] != '3'
                    str_rep << d['DAYS']
                end

                str_rep
            rescue StandardError
                ''
            end
        end

        column :END, '', :adjust => true do |d|
            begin
                str_end = ''

                case d['END_TYPE']
                when '0'
                    str_end << 'None'
                when '1'
                    str_end << 'After ' << d['END_VALUE'] << ' times'
                when '2'
                    str_end << 'On ' << \
                        OpenNebulaHelper.time_to_str(d['END_VALUE'], false, false, true)
                end

                str_end
            rescue StandardError
                ''
            end
        end

        column :STATUS, '', :left, :size => 50 do |d|
            begin
                if d['DONE'].to_i > 0 && d['REPEAT'].to_i < 0
                    "Done on #{OpenNebulaHelper.time_to_str(d['DONE'], false)}"
                elsif d['MESSAGE'] && !d['MESSAGE'].empty?
                    "Error! #{d['MESSAGE']}"
                else
                    t1 = Time.now
                    t2 = d['TIME'].to_i

                    # relative action for VMs
                    if (d['TIME'] !~ /^[0-9].*/) && !object['STIME'].nil?
                        t2 += object['STIME'].to_i
                    end

                    t2 = Time.at(t2)

                    days    = ((t2 - t1) / (24 * 3600)).round(2)
                    hours   = ((t2 - t1) / 3600).round(2)
                    minutes = ((t2 - t1) / 60).round(2)

                    if days > 1
                        "Next in #{days} days"
                    elsif days <= 1 && hours > 1
                        "Next in #{hours} hours"
                    elsif minutes > 0
                        "Next in #{minutes} minutes"
                    else
                        'Overdue!'
                    end
                end
            rescue StandardError
                ''
            end
        end
    end
end

.short_period_to_str(time, print_seconds = true) ⇒ Object



1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
# File 'lib/one_helper.rb', line 1669

def self.short_period_to_str(time, print_seconds = true)
    seconds=time.to_i
    minutes, seconds=seconds.divmod(60)
    hours, minutes=minutes.divmod(60)

    if print_seconds
        format('%<hours>3dh%<minutes>02dm%<seconds>02ds',
               :hours => hours, :minutes => minutes, :seconds => seconds)
    else
        format('%<hours>3dh%<minutes>02dm', :hours => hours, :minutes => minutes)
    end
end

.size_in_mb(size) ⇒ Object



1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
# File 'lib/one_helper.rb', line 1586

def self.size_in_mb(size)
    m = size.match(/^(\d+(?:\.\d+)?)(t|tb|m|mb|g|gb)?$/i)

    if !m
        # return OpenNebula::Error.new('Size value malformed')
        [-1, 'Size value malformed']
    else
        multiplier=case m[2]
                   when /(t|tb)/i
                       1024*1024
                   when /(g|gb)/i
                       1024
                   else
                       1
                   end

        value=m[1].to_f*multiplier

        # return value.ceil
        [0, value.ceil]
    end
end

.time_to_str(time, print_seconds = true, print_hours = true, print_years = false) ⇒ Object



1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
# File 'lib/one_helper.rb', line 1621

def self.time_to_str(time, print_seconds = true,
                     print_hours = true, print_years = false)
    value = time.to_i

    if value==0
        value='-'
    else
        if print_hours
            if print_seconds
                if print_years
                    value=Time.at(value).strftime('%m/%d/%y %H:%M:%S')
                else
                    value=Time.at(value).strftime('%m/%d %H:%M:%S')
                end
            else
                if print_years
                    value=Time.at(value).strftime('%m/%d/%y %H:%M')
                else
                    value=Time.at(value).strftime('%m/%d %H:%M')
                end
            end
        else
            if print_years
                value=Time.at(value).strftime('%m/%d/%y')
            else
                value=Time.at(value).strftime('%m/%d')
            end
        end
    end

    value
end

.to_octet(perm) ⇒ String

Convert u=rwx,g=rx,o=r to octet

Parameters:

  • perm (String)

    Permissions in human readbale format

Returns:

  • (String)

    Permissions in octet format



2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
# File 'lib/one_helper.rb', line 2405

def self.to_octet(perm)
    begin
        Integer(perm)
        perm
    rescue StandardError
        perm = perm.split(',')
        ret  = 0

        perm.each do |p|
            p = p.split('=')

            next unless p.size == 2

            r = p[1].count('r')
            w = p[1].count('w')
            x = p[1].count('x')

            rwx = (2 ** 0) * x + (2 ** 1) * w + (2 ** 2) * r

            case p[0]
            when 'u'
                ret += rwx * 100
            when 'g'
                ret += rwx * 10
            else
                ret += rwx * 1
            end
        end

        if ret == 0
            STDERR.puts 'Error in permissions format'
            exit(-1)
        else
            ret = ret.to_s

            if ret.size == 1
                "00#{ret}"
            elsif ret.size == 2
                "0#{ret}"
            else
                ret
            end
        end
    end
end

.unit_to_str(value, options, unit = 'K') ⇒ Object



1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
# File 'lib/one_helper.rb', line 1684

def self.unit_to_str(value, options, unit = 'K')
    if options[:kilobytes]
        value
    else
        i = BINARY_SUFFIX.index(unit).to_i

        while value > 1024 && i < 3
            value /= 1024.0
            i += 1
        end

        value = (value * 10).round / 10.0

        value = value.to_i if value - value.round == 0
        value.to_s + BINARY_SUFFIX[i]
    end
end

.update_obj(obj, file, plain = false) ⇒ Object



1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
# File 'lib/one_helper.rb', line 1765

def self.update_obj(obj, file, plain = false)
    rc = obj.info(true)

    return rc if OpenNebula.is_error?(rc)

    if file
        path = file
    else
        tmp  = Tempfile.new(obj['ID'])
        path = tmp.path

        tmp.write(yield(obj)) if block_given?
        tmp.flush

        if ENV['EDITOR']
            editor_path = ENV['EDITOR']
        else
            editor_path = EDITOR_PATH
        end

        system("#{editor_path} #{path}")

        unless $CHILD_STATUS.exitstatus.zero?
            STDERR.puts 'Editor not defined'
            exit(-1)
        end

        tmp.close
    end

    if plain
        obj.update(File.read(path), plain)
    else
        obj.update(File.read(path))
    end
end

.update_template(id, resource, path = nil, xpath = 'TEMPLATE') ⇒ Object



1734
1735
1736
# File 'lib/one_helper.rb', line 1734

def self.update_template(id, resource, path = nil, xpath = 'TEMPLATE')
    update_template_helper(false, id, resource, path, xpath)
end

.update_template_helper(append, _id, resource, path, xpath, update = true) ⇒ Object

rubocop:disable Metrics/ParameterLists



1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
# File 'lib/one_helper.rb', line 1743

def self.update_template_helper(append, _id, resource, path, xpath, update = true)
    # rubocop:enable Metrics/ParameterLists
    if path
        File.read(path)
    elsif !(stdin = read_stdin).empty?
        stdin
    elsif append
        editor_input
    else
        if update
            rc = resource.info

            if OpenNebula.is_error?(rc)
                puts rc.message
                exit(-1)
            end
        end

        editor_input(resource.template_like_str(xpath))
    end
end