Statistics
| Branch: | Tag: | Revision:

one / src / cli / one_helper.rb @ 2447e7d9

History | View | Annotate | Download (10.3 KB)

1
# -------------------------------------------------------------------------- #
2
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
3
#                                                                            #
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
5
# not use this file except in compliance with the License. You may obtain    #
6
# a copy of the License at                                                   #
7
#                                                                            #
8
# http://www.apache.org/licenses/LICENSE-2.0                                 #
9
#                                                                            #
10
# Unless required by applicable law or agreed to in writing, software        #
11
# distributed under the License is distributed on an "AS IS" BASIS,          #
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
13
# See the License for the specific language governing permissions and        #
14
# limitations under the License.                                             #
15
#--------------------------------------------------------------------------- #
16

    
17
require 'cli_helper'
18

    
19
require 'OpenNebula'
20
include OpenNebula
21

    
22
module OpenNebulaHelper
23
    ONE_VERSION=<<-EOT
24
OpenNebula 2.3.0
25
Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)
26

27
Licensed under the Apache License, Version 2.0 (the "License"); you may
28
not use this file except in compliance with the License. You may obtain
29
a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
30
EOT
31

    
32
    if ONE_LOCATION
33
        TABLE_CONF_PATH=ONE_LOCATION+"/etc/cli"
34
    else
35
        TABLE_CONF_PATH="/etc/one/cli"
36
    end
37

    
38
    EDITOR_PATH='/usr/bin/vi'
39

    
40
    ########################################################################
41
    # Options
42
    ########################################################################
43
    XML={
44
        :name  => "xml",
45
        :short => "-x",
46
        :large => "--xml",
47
        :description => "Show the resource in xml format"
48
    }
49

    
50
    NUMERIC={
51
        :name  => "numeric",
52
        :short => "-n",
53
        :large => "--numeric",
54
        :description => "Do not translate user and group IDs"
55
    }
56

    
57
    KILOBYTES={
58
        :name  => "kilobytes",
59
        :short => "-k",
60
        :large => "--kilobytes",
61
        :description => "Show units in kilobytes"
62
    }
63

    
64
    OPTIONS = XML, NUMERIC, KILOBYTES
65

    
66
    class OneHelper
67
        def initialize(secret=nil, endpoint=nil)
68
            @client = OpenNebula::Client.new(secret,endpoint)
69
            @translation_hash = nil
70
        end
71

    
72
        def create_resource(options, &block)
73
            resource = factory
74

    
75
            rc = block.call(resource)
76
            if OpenNebula.is_error?(rc)
77
                return -1, rc.message
78
            else
79
                puts "ID: #{resource.id.to_s}" if options[:verbose]
80
                return 0
81
            end
82
        end
83

    
84
        def list_pool(options, top=false)
85
            user_flag = options[:filter_flag] ? options[:filter_flag] : -2
86
            pool = factory_pool(user_flag)
87

    
88
            rc = pool.info
89
            return -1, rc.message if OpenNebula.is_error?(rc)
90

    
91
            if options[:xml]
92
                return 0, pool.to_xml(true)
93
            else
94
                format_pool(pool, options, top)
95
                return 0
96
            end
97
        end
98

    
99
        def show_resource(id, options)
100
            resource = retrieve_resource(id)
101
            return -1, resource.message if OpenNebula.is_error?(resource)
102

    
103
            if options[:xml]
104
                return 0, resource.to_xml(true)
105
            else
106
                format_resource(resource)
107
                return 0
108
            end
109
        end
110

    
111
        def perform_action(id, options, verbose, &block)
112
            resource = retrieve_resource(id)
113
            return -1, resource.message if OpenNebula.is_error?(resource)
114

    
115
            rc = block.call(resource)
116
            if OpenNebula.is_error?(rc)
117
                return -1, rc.message
118
            else
119
                puts "#{self.class.rname} #{id}: #{verbose}" if options[:verbose]
120
                return 0
121
            end
122
        end
123

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

    
129
                unless rc[0]==0
130
                    puts rc[1]
131
                    exit_code=rc[0]
132
                end
133
            end
134

    
135
            exit_code
136
        end
137

    
138
        ########################################################################
139
        # Id translation
140
        ########################################################################
141
        def uid_to_str(uid, options)
142
            rid_to_str(:users, uid, options)
143
        end
144

    
145
        def gid_to_str(gid, options)
146
            rid_to_str(:groups, gid, options)
147
        end
148

    
149
        ########################################################################
150
        # Formatters for arguments
151
        ########################################################################
152
        def to_id(name)
153
            return 0, name if name.match(/^[0123456789]+$/)
154

    
155
            user_flag = -2
156
            pool = factory_pool(user_flag)
157
            poolname = self.class.rname
158

    
159
            self.class.id_to_name(name, pool, poolname)
160
        end
161

    
162
        def self.to_id_desc
163
            "OpenNebula #{self.rname} name or id"
164
        end
165

    
166
        def list_to_id(names)
167
            user_flag = -2
168
            pool = factory_pool(user_flag)
169

    
170
            rc = pool.info
171
            return -1, rc.message if OpenNebula.is_error?(rc)
172

    
173
            result = names.split(',').collect { |name|
174
                rc = to_id(name)
175
                unless rc.first==0
176
                    return rc
177
                end
178
                rc[1]
179
            }
180

    
181
            return 0, result
182
        end
183

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

    
188
        def filterflag_to_i(str)
189
            filter_flag = case str
190
            when "a", "all" then "-2"
191
            when "m", "mine" then "-3"
192
            when "g", "group" then "-1"
193
            else
194
                if str.match(/^[0123456789]+$/)
195
                    str
196
                else
197
                    user = translation_hash[:users].select { |k,v| v==str }
198
                    user.length > 0 ? user.first.first : "-2"
199
                end
200
            end
201

    
202
            return 0, filter_flag
203
        end
204

    
205
        def self.filterflag_to_i_desc
206
            desc=<<-EOT
207
a, all       all the known #{self.rname}s
208
m, mine      the #{self.rname} belonging to the user in ONE_AUTH
209
g, group     'mine' plus the #{self.rname} belonging to the groups
210
             the user is member of
211
uid          #{self.rname} of the user identified by this uid
212
user         #{self.rname} of the user identified by the username
213
EOT
214
        end
215

    
216
        def self.table_conf
217
            path = "#{ENV["HOME"]}/.one/cli/#{self.conf_file}"
218

    
219
            if File.exists?(path)
220
                return path
221
            else
222
                return "#{TABLE_CONF_PATH}/#{self.conf_file}"
223
            end
224
        end
225

    
226
        def self.id_to_name(name, pool, ename)
227
            rc = pool.info
228
            return -1, rc.message if OpenNebula.is_error?(rc)
229

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

    
232
            if objects.length>0
233
                if objects.length>1
234
                    return -1, "There are multiple #{ename}s with name #{name}."
235
                else
236
                    result = objects.first.id
237
                end
238
            else
239
                return -1,  "#{ename} named #{name} not found."
240
            end
241

    
242
            return 0, result
243
        end
244

    
245
        private
246

    
247
        def retrieve_resource(id)
248
            resource = factory(id)
249

    
250
            rc = resource.info
251
            OpenNebula.is_error?(rc) ? rc : resource
252
        end
253

    
254
        def translation_hash
255
            @translation_hash ||= {
256
                :users => generate_resource_translation(UserPool),
257
                :groups => generate_resource_translation(GroupPool)
258
            }
259
        end
260

    
261
        def generate_resource_translation(pool)
262
            p = pool.new(@client)
263
            p.info
264

    
265
            hash = Hash.new
266
            p.each { |r| hash[r["ID"]]=r["NAME"] }
267
            hash
268
        end
269

    
270
        def rid_to_str(resource, id, options)
271
            if options[:numeric]
272
                id
273
            else
274
                if name = translation_hash[resource][id]
275
                    name
276
                else
277
                    id
278
                end
279
            end
280
        end
281
    end
282

    
283
    def OpenNebulaHelper.name_to_id(name, poolname, user_flag=-2)
284
        client = OpenNebula::Client.new
285
        # TBD user_flag
286
        pool = case poolname
287
        when "HOST"  then  OpenNebula::HostPool.new(client)
288
        when "GROUP" then OpenNebula::GroupPool.new(client)
289
        when "USER"  then OpenNebula::UserPool.new(client)
290
        end
291

    
292
        OneHelper.id_to_name(name, pool, poolname)
293
    end
294

    
295
    def OpenNebulaHelper.name_to_id_desc(poolname)
296
        "OpenNebula #{poolname} name or id"
297
    end
298
    def OpenNebulaHelper.public_to_str(str)
299
        if str.to_i == 1
300
            public_str = "Y"
301
        else
302
            public_str = "N"
303
        end
304
    end
305

    
306
    def OpenNebulaHelper.time_to_str(time)
307
        value=time.to_i
308
        if value==0
309
            value='-'
310
        else
311
            value=Time.at(value).strftime("%m/%d %H:%M:%S")
312
        end
313
    end
314

    
315
    BinarySufix = ["K", "M", "G", "T" ]
316

    
317
    def OpenNebulaHelper.unit_to_str(value, options)
318
        if options[:kilobytes]
319
            value
320
        else
321
            i=0
322

    
323
            while value > 1024 && i < 3 do
324
                value /= 1024.0
325
                i+=1
326
            end
327

    
328
            value = (value * 10).round / 10.0
329

    
330
            value = value.to_i if value - value.round == 0
331
            st = value.to_s + BinarySufix[i]
332
        end
333
    end
334

    
335
    def OpenNebulaHelper.update_template(id, resource)
336
        require 'tempfile'
337

    
338
        tmp  = Tempfile.new(id)
339
        path = tmp.path
340

    
341
        tmp << resource.template_str
342
        tmp.flush
343

    
344
        editor_path = ENV["EDITOR"] ? ENV["EDITOR"] : EDITOR_PATH
345
        system("#{editor_path} #{path}")
346
        unless $?==0
347
            puts "Editor not defined"
348
            exit -1
349
        end
350

    
351
        tmp.close
352

    
353
        str = File.read(path)
354
        str
355
    end
356
end