Module: OpenNebulaHelper

Defined in:
lib/one_helper.rb

Defined Under Namespace

Classes: OneHelper

Constant Summary collapse

ONE_VERSION =
<<-EOT
OpenNebula #{OpenNebula::VERSION}
Copyright 2002-2022, 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'
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"
}
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 xmlrpc frontend',
        :format => String,
        :proc => lambda do |o, options|
            OneHelper.set_endpoint(o)
            [0, o]
        end
    }
]
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 => String
    }
]
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 => 'Lines to add to the context section'
    },
    {
        :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   => 'vcenter_vm_folder',
        :large  => '--vcenter_vm_folder path',
        :format => String,
        :description => "In a vCenter environment sets the the VMs and Template folder where the VM will be placed in." \
        " The path uses slashes to separate folders. For example: --vcenter_vm_folder \"/Management/VMs\""
    },
    {
        :name   => 'user_inputs',
        :large  => '--user-inputs ui1,ui2,ui3',
        :format => Array,
        :description => 'Specify the user inputs values when instantiating',
        :proc => lambda do |o, options|
            # Store user inputs that has been already processed
            options[:user_inputs_keys] = []

            # escape values
            options[:user_inputs].map! do |user_input|
                user_input_split = user_input.split('=')

                options[:user_inputs_keys] << user_input_split[0]

                "#{user_input_split[0]}=\"#{user_input_split[1]}\""
            end

            options[:user_inputs] = o.join("\n")
        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'
}
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
BinarySufix =
["K", "M", "G", "T" ]

Class Method Summary collapse

Class Method Details

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



1557
1558
1559
# File 'lib/one_helper.rb', line 1557

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

.boolean_to_str(str) ⇒ Object



1433
1434
1435
1436
1437
1438
1439
# File 'lib/one_helper.rb', line 1433

def OpenNebulaHelper.boolean_to_str(str)
    if str.to_i == 1
        "Yes"
    else
        "No"
    end
end

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



1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/one_helper.rb', line 1520

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

    while j < i do
        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



1536
1537
1538
1539
1540
1541
1542
# File 'lib/one_helper.rb', line 1536

def OpenNebulaHelper.cluster_str(str)
    if str != nil && !str.empty?
        str
    else
        "-"
    end
end

.clusters_str(clusters) ⇒ Object



1544
1545
1546
1547
1548
1549
1550
1551
# File 'lib/one_helper.rb', line 1544

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

end

.create_ar(options) ⇒ Object



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
1894
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
# File 'lib/one_helper.rb', line 1857

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(options) ⇒ Object



1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
# File 'lib/one_helper.rb', line 1710

def self.create_context(options)
    context_options = [:ssh, :net_context, :context, :init, :files_ds, :startscript, :report_ready]
    if !(options.keys & context_options).empty?
        lines=[]

        if options[:ssh]
            if options[:ssh]==true
                lines<<"SSH_PUBLIC_KEY=\"$USER[SSH_PUBLIC_KEY]\""
            else
                begin
                    key=File.read(options[:ssh]).strip
                rescue Exception => e
                    STDERR.puts e.message
                    exit(-1)
                end
                lines<<"SSH_PUBLIC_KEY=\"#{key}\""
            end
        end

        if options[:net_context]
            lines << "NETWORK = \"YES\""
        end

        lines+=options[:context] if options[:context]

        if options[:files_ds]
            text='FILES_DS="'
            text << options[:files_ds].map do |file|
                %Q<$FILE[IMAGE=\\"#{file}\\"]>
            end.join(' ')
            text << '"'

            lines << text
        end

        if options[:init]
            lines << %Q<INIT_SCRIPTS="#{options[:init].join(' ')}">
        end

        if options[:startscript]
            script = nil
            begin
                script = File.read(options[:startscript]).strip
            rescue Exception => e
                STDERR.puts e.message
                exit(-1)
            end
            script = Base64::strict_encode64(script)
            lines<<"START_SCRIPT_BASE64=\"#{script}\""
        end

        if options[:report_ready]
            lines << "REPORT_READY = \"YES\""
        end

        if !lines.empty?
            "CONTEXT=[\n" << lines.map{|l| "  " << l }.join(",\n") << "\n]\n"
        else
            nil
        end
    else
        nil
    end
end

.create_disk_net(objects, section, name) ⇒ Object



1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
# File 'lib/one_helper.rb', line 1659

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"] if !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



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
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
# File 'lib/one_helper.rb', line 1775

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

    template<<"VCENTER_VM_FOLDER=#{options[:vcenter_vm_folder]}\n" if options[:vcenter_vm_folder]

    context=create_context(options)
    template<<context if context

    if options[:userdata] && !template_obj.nil?
        if template_obj.has_elements?('TEMPLATE/EC2')
            template_obj.add_element(
                'TEMPLATE/EC2',
                'USERDATA' => options[:userdata])

            template << template_obj.template_like_str(
                'TEMPLATE', false, 'EC2')
        end
    end

    [0, template]
end

.create_template_options_used?(options) ⇒ Boolean

Returns:

  • (Boolean)


1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
# File 'lib/one_helper.rb', line 1935

def self.create_template_options_used?(options)
    # 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 one at least one of the template options is
    # in options hash
    (template_options-options.keys)!=template_options
end

.download_resource_sunstone(kind, id, path, force) ⇒ Object



1958
1959
1960
1961
1962
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
2044
2045
2046
# File 'lib/one_helper.rb', line 1958

def self.download_resource_sunstone(kind, id, path, force)
    client = OneHelper.client
    user, password = client.one_auth.split(":", 2)

    # Step 1: Build Session to get Cookie
    uri = URI(File.join(sunstone_url,"login"))

    req = Net::HTTP::Post.new(uri)
    req.basic_auth user, password

    begin
        res = Net::HTTP.start(uri.hostname, uri.port) do |http|
            http.request(req)
        end
    rescue
        return OpenNebula::Error.new("Error connecting to '#{uri}'.")
    end

    cookie = res.response['set-cookie'].split('; ')[0]

    if cookie.nil?
       return OpenNebula::Error.new("Unable to get Cookie. Is OpenNebula running?")
    end

    # Step 2: Open '/' to get the csrftoken
    uri = URI(sunstone_url)

    req = Net::HTTP::Get.new(uri)
    req['Cookie'] = cookie

    begin
        res = Net::HTTP.start(uri.hostname, uri.port) do |http|
            http.request(req)
        end
    rescue
        return OpenNebula::Error.new("Error connecting to '#{uri}'.")
    end

    m = res.body.match(/var csrftoken = '(.*)';/)
    csrftoken = m[1] rescue nil

    if csrftoken.nil?
       return OpenNebula::Error.new("Unable to get csrftoken.")
    end

    # Step 3: Download resource
    uri = URI(File.join(sunstone_url,
                        kind.to_s,
                        id.to_s,
                        "download?csrftoken=#{csrftoken}"))

    req = Net::HTTP::Get.new(uri)

    req['Cookie'] = cookie
    req['User-Agent'] = "OpenNebula CLI"

    begin
        File.open(path, 'wb') do |f|
            Net::HTTP.start(uri.hostname, uri.port) do |http|
                http.request(req) do |res|
                    res.read_body do |chunk|
                        f.write(chunk)
                    end
                end
            end
        end
    rescue Errno::EACCES
        return OpenNebula::Error.new("Target file not writable.")
    end

    error_message = nil

    File.open(path, 'rb') do |f|
        begin
            f.seek(-1024, IO::SEEK_END)
        rescue Errno::EINVAL
        end

        tail = f.read

        m = tail.match(/@\^_\^@ (.*) @\^_\^@/m)
        error_message = m[1] if m
    end

    if error_message
        File.unlink(path)
        return OpenNebula::Error.new("Remote server error: #{error_message}")
    end
end

.editor_input(contents = nil) ⇒ Object



1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
# File 'lib/one_helper.rb', line 1617

def OpenNebulaHelper.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 $?.exitstatus == 0
        puts "Editor not defined"
        exit -1
    end

    tmp.close

    str = File.read(tmp.path)
    return str
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



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
# File 'lib/one_helper.rb', line 2260

def OpenNebulaHelper.get_plot(x, y, attr, title)
    # Require gnuplot gem only here
    begin
        require 'gnuplot'
    rescue LoadError, Gem::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



2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
# File 'lib/one_helper.rb', line 2048

def OpenNebulaHelper.level_lock_to_str(str)
    level = str.to_i
    if level == 0
        "None"
    elsif level == 1
        "Use"
    elsif level == 2
        "Manage"
    elsif level == 3
        "Admin"
    elsif level == 4
        "All"
    else
        "-"
    end
end

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



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
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
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
# File 'lib/one_helper.rb', line 2065

def OpenNebulaHelper.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 %w[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

            begin
                print header
                answer = STDIN.readline.chop

                answer = initial if answer == ''
                    noanswer = ((answer == '') && optional)
            end while !noanswer && (answer =~ exp) == nil

            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

            begin
                print header
                answer = STDIN.readline.chop

                answer = initial if answer == ''

                noanswer = (answer == '') && optional
            end while !noanswer && ((answer =~ exp) == nil ||
                      answer.to_f < min || answer.to_f > max)

            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: '

            begin
                print header
                answer = STDIN.readline.chop

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

                noanswer = ((answer == '') && optional)
            end while !noanswer && !options.include?(answer)

            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



1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
# File 'lib/one_helper.rb', line 1641

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

    m=user_object.match(reg)

    return nil if !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



1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
# File 'lib/one_helper.rb', line 1475

def OpenNebulaHelper.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
        "%3dd %02dh%02dm%02ds" % [days, hours, minutes, seconds]
    else
        "%3dd %02dh%02dm" % [days, hours, minutes]
    end
end

.rname_to_id(name, poolname) ⇒ Object



1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
# File 'lib/one_helper.rb', line 1375

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

    client=OneHelper.client

    pool = case poolname
    when "HOST"          then OpenNebula::HostPool.new(client)
    when "HOOK"          then OpenNebula::HookPool.new(client)
    when "GROUP"         then OpenNebula::GroupPool.new(client)
    when "USER"          then OpenNebula::UserPool.new(client)
    when "DATASTORE"     then OpenNebula::DatastorePool.new(client)
    when "CLUSTER"       then OpenNebula::ClusterPool.new(client)
    when "VNET"          then OpenNebula::VirtualNetworkPool.new(client)
    when "IMAGE"         then OpenNebula::ImagePool.new(client)
    when "VMTEMPLATE"    then OpenNebula::TemplatePool.new(client)
    when "VNTEMPLATES"   then OpenNebula::VNTemplatePool.new(client)
    when "VM"            then OpenNebula::VirtualMachinePool.new(client)
    when "ZONE"          then OpenNebula::ZonePool.new(client)
    when "MARKETPLACE"   then OpenNebula::MarketPlacePool.new(client)
    when "FLOWTEMPLATES" then 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



1429
1430
1431
# File 'lib/one_helper.rb', line 1429

def OpenNebulaHelper.rname_to_id_desc(poolname)
    "OpenNebula #{poolname} name or id"
end

.short_period_to_str(time, print_seconds = true) ⇒ Object



1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
# File 'lib/one_helper.rb', line 1488

def OpenNebulaHelper.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
        "%3dh%02dm%02ds" % [hours, minutes, seconds]
    else
        "%3dh%02dm" % [hours, minutes]
    end
end

.size_in_mb(size) ⇒ Object



1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
# File 'lib/one_helper.rb', line 1406

def OpenNebulaHelper.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')
        return -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
        return 0, value.ceil
    end
end

.sunstone_urlObject



1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
# File 'lib/one_helper.rb', line 1947

def self.sunstone_url
    if (one_sunstone = ENV['ONE_SUNSTONE'])
       one_sunstone
    elsif (one_xmlrpc = ENV['ONE_XMLRPC'])
        uri = URI(one_xmlrpc)
        "#{uri.scheme}://#{uri.host}:9869"
    else
        "http://localhost:9869"
    end
end

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



1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
# File 'lib/one_helper.rb', line 1441

def OpenNebulaHelper.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

    return 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



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
2346
2347
2348
2349
2350
2351
2352
2353
2354
# File 'lib/one_helper.rb', line 2310

def OpenNebulaHelper.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



1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
# File 'lib/one_helper.rb', line 1502

def OpenNebulaHelper.unit_to_str(value, options, unit="K")
    if options[:kilobytes]
        value
    else
        i=BinarySufix.index(unit).to_i

        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]
    end
end

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



1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
# File 'lib/one_helper.rb', line 1580

def OpenNebulaHelper.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



1553
1554
1555
# File 'lib/one_helper.rb', line 1553

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

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



1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'lib/one_helper.rb', line 1561

def OpenNebulaHelper.update_template_helper(append, id, resource, path, xpath, update=true)
    if path
        return File.read(path)
    elsif append
        return editor_input()
    else
        if update
            rc = resource.info

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

        return editor_input(resource.template_like_str(xpath))
    end
end