Class: OpenNebulaHelper::OneHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/one_helper.rb

Overview

rubocop:disable Style/ClassVars Base class for all OpenNebula CLI helper classes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_secret = nil, _endpoint = nil) ⇒ OneHelper

Returns a new instance of OneHelper.



699
700
701
702
703
# File 'lib/one_helper.rb', line 699

def initialize(_secret = nil, _endpoint = nil)
    @client=nil

    @translation_hash = nil
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



600
601
602
# File 'lib/one_helper.rb', line 600

def client
  @client
end

Class Method Details

.clientObject



641
642
643
644
645
646
647
# File 'lib/one_helper.rb', line 641

def self.client
    if defined?(@@client)
        @@client
    else
        get_client
    end
end

.filterflag_to_i_descObject



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
# File 'lib/one_helper.rb', line 1280

def self.filterflag_to_i_desc
    <<~EOT
        a, all            all the known #{rname}s
        m, mine           the #{rname} belonging to the user in ONE_AUTH
        g, group          'mine' plus the #{rname} belonging to the groups
                          the user is member of
        G, primary group  the #{rname} owned the user's primary group
        uid               #{rname} of the user identified by this uid
        user              #{rname} of the user identified by the username
    EOT
end

.get_client(options = {}, force = false) ⇒ Object



602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/one_helper.rb', line 602

def self.get_client(options = {}, force = false)
    if !force && defined?(@@client)
        @@client
    else

        secret=nil
        password=nil

        if defined?(@@user)
            user=@@user
            password=@@password if defined?(@@password)
        else
            user=options[:user]
        end

        if user
            password=password||options[:password]||get_password
            secret="#{user}:#{password}"
        end

        if defined?(@@endpoint)
            endpoint=@@endpoint
        else
            endpoint=options[:endpoint]
        end

        # This breaks the CLI SSL support for Ruby 1.8.7, but is necessary
        # in order to do template updates, otherwise you get the broken pipe
        # error (bug #3341)
        if RUBY_VERSION < '1.9'
            sync = false
        else
            sync = true
        end
        options[:sync] = sync
        @@client=OpenNebula::Client.new(secret, endpoint, options)
    end
end

.get_passwordObject

This function is copied from ruby net/imap.rb



676
677
678
679
680
681
682
683
684
685
# File 'lib/one_helper.rb', line 676

def self.get_password
    print 'Password: '
    pass=nil
    STDIN.noecho {|io| pass=io.gets }
    puts

    pass.chop! if pass
    @@password=pass
    pass
end

.list_layout_helpObject

rubocop:enable Naming/AccessorMethodName rubocop:enable Style/ClassVars



691
692
693
# File 'lib/one_helper.rb', line 691

def self.list_layout_help
    "The default columns and their layout can be configured in #{conf_file}"
end

.list_to_id_descObject



1240
1241
1242
# File 'lib/one_helper.rb', line 1240

def self.list_to_id_desc
    "Comma-separated list of OpenNebula #{rname} names or ids"
end

.name_to_id(name, pool, ename) ⇒ Object



1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
# File 'lib/one_helper.rb', line 1244

def self.name_to_id(name, pool, ename)
    if ename == 'CLUSTER' && name.upcase == 'ALL'
        return 0, 'ALL'
    end

    objects = pool.select {|object| object.name == name }

    return -1, "#{ename} named #{name} not found." if objects.empty?
    return -1, "There are multiple #{ename}s with name #{name}." if objects.length > 1

    result = objects.first.id

    [0, result]
end

.set_endpoint(endpoint) ⇒ Object



658
659
660
# File 'lib/one_helper.rb', line 658

def self.set_endpoint(endpoint)
    @@endpoint=endpoint
end

.set_password(password) ⇒ Object



654
655
656
# File 'lib/one_helper.rb', line 654

def self.set_password(password)
    @@password=password
end

.set_user(user) ⇒ Object

rubocop:disable Naming/AccessorMethodName



650
651
652
# File 'lib/one_helper.rb', line 650

def self.set_user(user)
    @@user=user
end

.table_conf(conf_file = self.conf_file) ⇒ Object



1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/one_helper.rb', line 1292

def self.table_conf(conf_file = self.conf_file)
    path = "#{Dir.home}/.one/cli/#{conf_file}"

    if File.exist?(path)
        path
    else
        "#{TABLE_CONF_PATH}/#{conf_file}"
    end
end

.template_input_help(object_name) ⇒ Object



695
696
697
# File 'lib/one_helper.rb', line 695

def self.template_input_help(object_name)
    "#{TEMPLATE_INPUT}\nWhen using a template add only one #{object_name} instance."
end

.to_id_descObject



1212
1213
1214
# File 'lib/one_helper.rb', line 1212

def self.to_id_desc
    "OpenNebula #{rname} name or id"
end

Instance Method Details

#backup_mode_valid?(sus_backup_mode) ⇒ Boolean

Returns:

  • (Boolean)


725
726
727
728
729
730
731
# File 'lib/one_helper.rb', line 725

def backup_mode_valid?(sus_backup_mode)
    BACKUP_MODES.each do |backup_mode|
        return true if backup_mode.casecmp?(sus_backup_mode)
    end

    false
end

#check_orphan(pool, xpath, resource_name, attributes) ⇒ Object

Check if a resource defined by attributes is referenced in pool

and :uname

atributes => …, name => …, id => …

Parameters:

  • pool

    pool to search in

  • xpath

    xpath to search in pool

  • resource_name

    name of the resource to search (e.g IMAGE)



1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
# File 'lib/one_helper.rb', line 1106

def check_orphan(pool, xpath, resource_name, attributes)
    return false if attributes.empty?

    return false unless pool["#{xpath}[#{resource_name}_ID = "\
                             "#{attributes[:id]}]"].nil?

    return false unless pool["#{xpath}[#{resource_name} = "\
                             "'#{attributes[:name]}' and "\
                             "#{resource_name}_UNAME = "\
                             "'#{attributes[:uname]}']"].nil?

    true
end

#create_resource(_options, &block) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
# File 'lib/one_helper.rb', line 713

def create_resource(_options, &block)
    resource = factory

    rc = block.call(resource)
    if OpenNebula.is_error?(rc)
        [-1, rc.message]
    else
        puts "ID: #{resource.id}"
        0
    end
end

#filterflag_to_i(str) ⇒ Object



1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/one_helper.rb', line 1259

def filterflag_to_i(str)
    filter_flag = case str
                  when 'a', 'all'   then OpenNebula::Pool::INFO_ALL
                  when 'm', 'mine'  then OpenNebula::Pool::INFO_MINE
                  when 'g', 'group' then OpenNebula::Pool::INFO_GROUP
                  when 'G', 'primary group' then OpenNebula::Pool::INFO_PRIMARY_GROUP
                  else
                      if str.match(/^[0123456789]+$/)
                          str.to_i
                      else
                          rc = OpenNebulaHelper.rname_to_id(str, 'USER')
                          return rc if rc.first==-1

                          rc[1]

                      end
                  end

    [0, filter_flag]
end

#group_name(resource, options = {}) ⇒ Object



1189
1190
1191
1192
1193
1194
1195
# File 'lib/one_helper.rb', line 1189

def group_name(resource, options = {})
    if options[:numeric]
        resource['GID']
    else
        resource['GNAME']
    end
end

#list_pool(options, top = false, filter_flag = nil) ⇒ Object



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
# File 'lib/one_helper.rb', line 1058

def list_pool(options, top = false, filter_flag = nil)
    # Capture Broken pipe
    Signal.trap('PIPE', 'EXIT')

    table = format_pool(options)

    if options[:describe]
        table.describe_columns

        return 0
    end

    filter_flag ||= OpenNebula::Pool::INFO_ALL

    pool  = factory_pool(filter_flag)
    pname = pool.pool_name

    if top
        return list_pool_top(table, pool, options)
    elsif options[:xml]
        return list_pool_xml(pool, options, filter_flag)
    elsif options[:json]
        return list_pool_format(pool, options, filter_flag) do |p|
            hash = check_resource_xsd(p, pname)
            puts ::JSON.pretty_generate(hash)
        end
    elsif options[:yaml]
        return list_pool_format(pool, options, filter_flag) do |p|
            hash = check_resource_xsd(p, pname)
            puts hash.to_yaml(:indent => 4)
        end
    else
        return list_pool_table(table, pool, options, filter_flag)
    end
rescue SystemExit, Interrupt
    # Rescue ctrl + c when paginated
    0
end

#list_pool_format(pool, options, _filter_flag) ⇒ Object


List pool in JSON format, pagination is used in interactive output




971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# File 'lib/one_helper.rb', line 971

def list_pool_format(pool, options, _filter_flag)
    extended = options.include?(:extended) && options[:extended]

    if $stdout.isatty && (!options.key? :no_pager)
        size = $stdout.winsize[0] - 1

        # ----------- First page, check if pager is needed -------------
        rc = pool.get_page(size, 0, extended, options[:state])

        return -1, rc.message if OpenNebula.is_error?(rc)

        elements = get_format_size(pool, options)
        ppid     = -1

        if elements >= size
            ppid = start_pager
        end

        yield(pool) if block_given?

        if elements < size
            return 0
        end

        if elements < size
            return 0
        elsif !pool.is_paginated?
            stop_pager(ppid)
            return 0
        end

        # ------- Rest of the pages in the pool, piped to pager --------
        current = size

        loop do
            rc = pool.get_page(size, current, extended, options[:state])

            return -1, rc.message if OpenNebula.is_error?(rc)

            current += size

            begin
                Process.waitpid(ppid, Process::WNOHANG)
            rescue Errno::ECHILD
                break
            end

            elements = get_format_size(pool, options)

            break if elements < size

            yield(pool) if block_given?

            $stdout.flush
        end

        stop_pager(ppid)
    else
        if pool.pool_name == 'VM_POOL' && extended
            rc = pool.info_all_extended
        else
            rc = pool.info
        end

        return -1, rc.message if OpenNebula.is_error?(rc)

        yield(pool) if block_given?
    end

    0
end

#list_pool_table(table, pool, options, _filter_flag) ⇒ Object


List the pool in table form, it uses pagination for interactive output




814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/one_helper.rb', line 814

def list_pool_table(table, pool, options, _filter_flag)
    if $stdout.isatty && (!options.key? :no_pager)
        size = $stdout.winsize[0] - 1

        # ----------- First page, check if pager is needed -------------
        rc = pool.get_page(size, 0, false, options[:state])

        return -1, rc.message if OpenNebula.is_error?(rc)

        elements, hash = print_page(pool, options)

        ppid = -1

        if elements >= size
            ppid = start_pager
        end

        table.show(hash, options)

        if elements < size
            return 0
        elsif !pool.is_paginated?
            stop_pager(ppid)
            return 0
        end

        # ------- Rest of the pages in the pool, piped to pager --------
        current = size

        options[:no_header] = true

        loop do
            rc = pool.get_page(size, current, false, options[:state])

            return -1, rc.message if OpenNebula.is_error?(rc)

            current += size

            begin
                Process.waitpid(ppid, Process::WNOHANG)
            rescue Errno::ECHILD
                break
            end

            elements, hash = print_page(pool, options)

            table.show(hash, options)

            $stdout.flush

            break if elements < size
        end

        stop_pager(ppid)
    else
        rc = pool.info

        return -1, rc.message if OpenNebula.is_error?(rc)

        elements, hash = print_page(pool, options)

        if options[:ids] && elements
            hash = [hash[pool.pool_name][pool.element_name]].flatten
            hash.select! do |element|
                options[:ids].include?(element['ID'].to_i)
            end
        end

        table.show(hash, options)
    end

    0
end

#list_pool_top(table, pool, options) ⇒ Object


List pool table in top-like form




1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
# File 'lib/one_helper.rb', line 1046

def list_pool_top(table, pool, options)
    table.top(options) do
        array = pool.get_hash

        return -1, array.message if OpenNebula.is_error?(array)

        array
    end

    0
end

#list_pool_xml(pool, options, _filter_flag) ⇒ Object


List pool in XML format, pagination is used in interactive output




891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/one_helper.rb', line 891

def list_pool_xml(pool, options, _filter_flag)
    extended = options.include?(:extended) && options[:extended]

    if $stdout.isatty && (!options.key? :no_pager)
        size = $stdout.winsize[0] - 1

        # ----------- First page, check if pager is needed -------------
        rc = pool.get_page(size, 0, extended, options[:state])

        return -1, rc.message if OpenNebula.is_error?(rc)

        pname = pool.pool_name

        elements, page = print_page(pool, options)

        ppid = -1

        if elements >= size
            ppid = start_pager
        end

        puts page

        if elements < size
            return 0
        end

        if elements < size
            return 0
        elsif !pool.is_paginated?
            stop_pager(ppid)
            return 0
        end

        # ------- Rest of the pages in the pool, piped to pager --------
        current = size

        loop do
            rc = pool.get_page(size, current, extended, options[:state])

            return -1, rc.message if OpenNebula.is_error?(rc)

            current += size

            begin
                Process.waitpid(ppid, Process::WNOHANG)
            rescue Errno::ECHILD
                break
            end

            elements, page = print_page(pool, options)

            puts page

            $stdout.flush

            break if elements < size
        end

        puts "</#{pname}>"

        stop_pager(ppid)
    else
        if pool.pool_name == 'VM_POOL' && extended
            rc = pool.info_all_extended
        else
            rc = pool.info
        end

        return -1, rc.message if OpenNebula.is_error?(rc)

        puts pool.to_xml(true)
    end

    0
end

#list_to_id(names) ⇒ Object



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/one_helper.rb', line 1216

def list_to_id(names)
    rc = get_pool
    return rc if rc.first != 0

    pool     = rc[1]
    poolname = self.class.rname

    result = names.split(',').collect do |name|
        if name.match(/^[0123456789]+$/)
            name.to_i
        else
            rc = OneHelper.name_to_id(name, pool, poolname)

            if rc.first == -1
                return rc[0], rc[1]
            end

            rc[1]
        end
    end

    [0, result]
end

#perform_action(id, options, verbose, &block) ⇒ Object



1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
# File 'lib/one_helper.rb', line 1150

def perform_action(id, options, verbose, &block)
    resource = retrieve_resource(id)

    rc = block.call(resource)
    if OpenNebula.is_error?(rc)
        [-1, rc.message]
    else
        if options[:verbose]
            puts "#{self.class.rname} #{id}: #{verbose}"
        end
        0
    end
end

#perform_actions(ids, options, verbose, &block) ⇒ Object



1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
# File 'lib/one_helper.rb', line 1164

def perform_actions(ids, options, verbose, &block)
    exit_code = 0
    ids.each do |id|
        rc = perform_action(id, options, verbose, &block)

        unless rc[0]==0
            STDERR.puts rc[1]
            exit_code=rc[0]
        end
    end

    exit_code
end


778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'lib/one_helper.rb', line 778

def print_page(pool, options)
    elements = 0
    page     = ''

    if options[:xml]
        elements += 1

        page << pool.to_xml(true)
    else
        pname = pool.pool_name
        ename = pool.element_name

        if options[:decrypt]
            page = pool.map do |element|
                element.info(true)
                element.to_hash[ename]
            end
        else
            page  = pool.to_hash
            elems = page[pname][ename]
        end

        if elems.class == Array
            elements = elems.length
        else
            elements = 1
        end
    end

    [elements, page]
end

#retrieve_resource(id) ⇒ Object



1302
1303
1304
# File 'lib/one_helper.rb', line 1302

def retrieve_resource(id)
    factory(id)
end

#set_client(options, client = nil) ⇒ Object



705
706
707
708
709
710
711
# File 'lib/one_helper.rb', line 705

def set_client(options, client = nil)
    if client.nil?
        @client=OpenNebulaHelper::OneHelper.get_client(options, true)
    else
        @client = client
    end
end

#show_resource(id, options) ⇒ Object



1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'lib/one_helper.rb', line 1120

def show_resource(id, options)
    resource = retrieve_resource(id)

    if !options.key? :decrypt
        rc = resource.info
    else
        rc = resource.info(true)
    end

    return -1, rc.message if OpenNebula.is_error?(rc)

    if options[:xml]
        [0, resource.to_xml(true)]
    elsif options[:json]
        # If body is set, the resource contains a JSON inside
        if options[:body]
            [0, check_resource_xsd(resource)]
        else
            [0, ::JSON.pretty_generate(
                check_resource_xsd(resource)
            )]
        end
    elsif options[:yaml]
        [0, check_resource_xsd(resource).to_yaml(:indent => 4)]
    else
        format_resource(resource, options)
        0
    end
end

#start_pagerObject


List pool functions



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
# File 'lib/one_helper.rb', line 736

def start_pager
    pager = ENV['ONE_PAGER'] || 'more'

    # Start pager, defaults to less
    p_r, p_w = IO.pipe

    Signal.trap('PIPE', 'SIG_IGN')
    Signal.trap('PIPE', 'EXIT')

    lpid = fork do
        $stdin.reopen(p_r)

        p_r.close
        p_w.close

        Kernel.select [$stdin]

        exec([pager, pager])
    end

    # Send listing to pager pipe
    $stdout.close
    $stdout = p_w.dup

    p_w.close
    p_r.close

    lpid
end

#stop_pager(lpid) ⇒ Object



766
767
768
769
770
771
772
773
774
775
776
# File 'lib/one_helper.rb', line 766

def stop_pager(lpid)
    $stdout.close

    begin
        Process.wait(lpid)
    rescue Interrupt
        Process.kill('TERM', lpid)
        Process.wait(lpid)
    rescue Errno::ECHILD
    end
end

#to_id(name) ⇒ Object

Formatters for arguments



1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# File 'lib/one_helper.rb', line 1200

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

    rc = get_pool
    return rc if rc.first != 0

    pool     = rc[1]
    poolname = self.class.rname

    OneHelper.name_to_id(name, pool, poolname)
end

#user_name(resource, options = {}) ⇒ Object

Id translation



1181
1182
1183
1184
1185
1186
1187
# File 'lib/one_helper.rb', line 1181

def user_name(resource, options = {})
    if options[:numeric]
        resource['UID']
    else
        resource['UNAME']
    end
end