Class: Morpheus::Cli::CloudDatastoresCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, InfrastructureHelper
Defined in:
lib/morpheus/cli/cloud_datastores_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from InfrastructureHelper

#cloud_type_for_id, #cloud_type_for_name, #cloud_type_for_name_or_id, #clouds_interface, #find_cloud_by_id, #find_cloud_by_name, #find_cloud_by_name_or_id, #find_group_by_id, #find_group_by_name, #find_group_by_name_or_id, #get_available_cloud_types, #groups_interface, included

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeCloudDatastoresCommand

Returns a new instance of CloudDatastoresCommand.



17
18
19
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 17

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#connect(opts) ⇒ Object



21
22
23
24
25
26
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 21

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @cloud_datastores_interface = @api_client.cloud_datastores
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
end

#get(args) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 112

def get(args)
  cloud_id = nil
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[datastore]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a datastore." + "\n" +
                  "[datastore] is required. This is the name or id of a datastore." + "\n" +
                  "-c [cloud] is required. This is the name or id of the cloud."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [datastore]\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @cloud_datastores_interface.dry.get(cloud['id'], args[0].to_i)
      else
        print_dry_run @cloud_datastores_interface.dry.list(cloud['id'], {name:args[0]})
      end
      return
    end
    datastore = find_datastore_by_name_or_id(cloud['id'], args[0])
    return 1 if datastore.nil?
    json_response = {'datastore' => datastore}  # skip redundant request
    # json_response = @datastores_interface.get(datastore['id'])
    datastore = json_response['datastore']
    if options[:json]
      puts as_json(json_response, options, "datastore")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "datastore")
      return 0
    elsif options[:csv]
      puts records_as_csv([datastore], options)
      return 0
    end
    print_h1 "Datastore Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Type" => lambda {|it| it['type'].to_s.capitalize },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "Capacity" => lambda {|it| it['freeSpace'] ? Filesize.from("#{it['freeSpace']} B").pretty.strip : "Unknown" },
      "Online" => lambda {|it| format_boolean(it['online']) },
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
      # "Owner" => lambda {|it| it['owner'] ? it['owner']['name'] : '' },
    }
    print_description_list(description_cols, datastore)

    if datastore['resourcePermission'].nil?
      print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if datastore['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if datastore['resourcePermission']['sites']
        datastore['resourcePermission']['sites'].each do |site|
          rows.push(site)
        end
      end
      rows = rows.collect do |site|
        # {group: site['name'], default: site['default'] ? 'Yes' : ''}
        {group: site['name']}
      end
      # columns = [:group, :default]
      columns = [:group]
      print cyan
      print as_pretty_table(rows, columns)
    end

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#handle(args) ⇒ Object



28
29
30
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 28

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 32

def list(args)
  cloud_id = nil
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("-c [cloud]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :json, :dry_run, :remote])
    opts.footer = "List datastores for a cloud." + "\n" +
                  "-c [cloud] is required. This is the name or id of the cloud."
  end
  optparse.parse!(args)
  connect(options)
  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    params.merge!(parse_list_options(options))
    if options[:dry_run]
      print_dry_run @cloud_datastores_interface.dry.list(cloud['id'], params)
      return
    end
    json_response = @cloud_datastores_interface.list(cloud['id'], params)
    datastores = json_response["datastores"]
    if options[:json]
      puts as_json(json_response, options, "datastores")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "datastores")
      return 0
    elsif options[:csv]
      puts records_as_csv(datastores, options)
      return 0
    end
    title = "Morpheus Datastores - Cloud: #{cloud['name']}"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if datastores.empty?
      print cyan,"No datastores found.",reset,"\n"
    else
      rows = datastores.collect {|datastore| 
        row = {
          id: datastore['id'],
          name: datastore['name'],
          type: datastore['type'].to_s.capitalize,
          #cloud: datastore['zone'] ? datastore['zone']['name'] : '',
          capacity: datastore['freeSpace'] ? Filesize.from("#{datastore['freeSpace']} B").pretty.strip : "Unknown",
          online: format_boolean(datastore['online']),
          active: format_boolean(datastore['active']),
          visibility: datastore['visibility'].to_s.capitalize,
          tenants: datastore['tenants'] ? datastore['tenants'].collect {|it| it['name'] }.uniq.join(', ') : ''
          # owner: datastore['owner'] ? datastore['owner']['name'] : ''
        }
        row
      }
      columns = [:id, :name, :type, :capacity, :online, :active, :visibility, :tenants]
      if options[:include_fields]
        columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      print_results_pagination(json_response, {:label => "datastore", :n_label => "datastores"})
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/morpheus/cli/cloud_datastores_command.rb', line 211

def update(args)
  options = {}
  cloud_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[datastore] -c [cloud] [options]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    # opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
    #   if list.size == 1 && list[0] == 'null' # hacky way to clear it
    #     group_defaults_list = []
    #   else
    #     group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    #   end
    # end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a datastore") do |val|
      options['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a datastore." + "\n" +
                  "[datastore] is required. This is the id of a datstore."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)

  begin
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    datastore = find_datastore_by_name_or_id(cloud['id'], args[0])
    return 1 if datastore.nil?
    
    # merge -O options into normally parsed options
    options.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # prompt for datastore options
      payload = {
        'datastore' => {
        }
      }
      
      # allow arbitrary -O options
      payload['datastore'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    
      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = options['tenants']
      end

      # Active
      if options['active'] != nil
        payload['datastore']['active'] = options['active']
      end
      
      # Visibility
      if options['visibility'] != nil
        payload['datastore']['visibility'] = options['visibility']
      end

    end

    if options[:dry_run]
      print_dry_run @cloud_datastores_interface.dry.update(cloud['id'], datastore["id"], payload)
      return
    end
    json_response = @cloud_datastores_interface.update(cloud['id'], datastore["id"], payload)
    if options[:json]
      puts as_json(json_response)
    else
      datastore = json_response['datastore']
      print_green_success "Updated datastore #{datastore['name']}"
      get([datastore['id'], "-c", cloud['id'].to_s]) # argh, to_s needed on option values..
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end