Class: Morpheus::Cli::ApplianceSettingsCommand

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand
Defined in:
lib/morpheus/cli/commands/appliance_settings_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from AccountsHelper

#account_column_definitions, #account_users_interface, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Instance Method Details

#connect(opts) ⇒ Object



13
14
15
16
17
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 13

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @appliance_settings_interface = @api_client.appliance_settings
  @roles_interface = @api_client.roles
end

#get(args) ⇒ Object



23
24
25
26
27
28
29
30
31
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
111
112
113
114
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 23

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get appliance settings."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end
  
  begin
    @appliance_settings_interface.setopts(options)

    if options[:dry_run]
      print_dry_run @appliance_settings_interface.dry.get()
      return
    end
    json_response = @appliance_settings_interface.get()
    if options[:json]
      puts as_json(json_response, options, "applianceSettings")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "applianceSettings")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['applianceSettings']], options)
      return 0
    end

    appliance_settings = json_response['applianceSettings']

    print_h1 "Appliance Settings"
    print cyan
    description_cols = {
      "Appliance URL" => lambda {|it| it['applianceUrl'] },
      "Internal Appliance URL (PXE)" => lambda {|it| it['internalApplianceUrl'] },
      "API Allowed Origins" => lambda {|it| it['apiAllowedOrigins'] },
      # Tenant Management Settings
      "Registration Enabled" => lambda {|it| format_boolean(it['registrationEnabled']) },
      "Default Tenant Role" => lambda {|it| it['defaultRoleId'] },
      "Default User Role" => lambda {|it| it['defaultUserRoleId'] },
      "Docker Privileged Mode" => lambda {|it| format_boolean(it['dockerPrivilegedMode']) },
      # User Management Settings
      "Expire Password After" => lambda {|it| format_days(it['expirePwdDays']) },
      "Disable User After Attempts" => lambda {|it| it['disableAfterAttempts'] == 0 ? 'Disabled' : it['disableAfterAttempts']},
      "Disable User if Inactive For" => lambda {|it| format_days(it['disableAfterDaysInactive']) },
      "Send warning email before deactivating" => lambda {|it| format_days(it['warnUserDaysBefore']) },
      # Email Settings
      "SMTP From Address" => lambda {|it| it['smtpMailFrom'] },
      "SMTP Server" => lambda {|it| it['smtpServer'] },
      "SMTP Port" => lambda {|it| it['smtpPort'] },
      "SMTP SSL Enabled" => lambda {|it| format_boolean(it['smtpSSL']) },
      "SMTP TLS Encryption" => lambda {|it| format_boolean(it['smtpTLS']) },
      "SMTP User" => lambda {|it| it['smtpUser'] },
      "SMTP Password" => lambda {|it| it['smtpPassword'] },
      # Proxy Settings
      "Proxy Host" => lambda {|it| it['proxyHost'] },
      "Proxy Port" => lambda {|it| it['proxyPort'] },
      "Proxy User" => lambda {|it| it['proxyUser'] },
      "Proxy Password" => lambda {|it| it['proxyPassword'] },
      "Proxy Domain" => lambda {|it| it['proxyDomain'] },
      "Proxy Workstation" => lambda {|it| it['proxyWorkstation'] },
      # Currency Settings
      "Currency Provider" => lambda {|it| it['currencyProvider'] },
      "Currency Provider API Key" => lambda {|it| it['currencyKey'] },
      # Retention Settings
      "Stats Retainment Period" => lambda {|it| it['statsRetainmentPeriod'] ? it['statsRetainmentPeriod'].to_s + ' days' : '' },
    }
    print_description_list(description_cols, appliance_settings)

    enabled_zone_types = appliance_settings['enabledZoneTypes']

    if enabled_zone_types.nil? || enabled_zone_types.empty?
      print_h2 "Enabled Clouds"
      print cyan
      print yellow "No Clouds Enabled"
    else
      print_h2 "Enabled Clouds"
      print cyan
      print enabled_zone_types.collect {|it| it['name']}.join(', ')
    end
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#handle(args) ⇒ Object



19
20
21
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 19

def handle(args)
  handle_subcommand(args)
end

#reindex(args) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 334

def reindex(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = opts.banner = subcommand_usage()
    build_standard_update_options(opts, options, [:auto_confirm], [:payload, :options])
    opts.footer = "Reindex all search data."
  end
  optparse.parse!(args)
  connect(options)
  verify_args!(args:args, optparse:optparse, count:0)
  confirm!("Are you sure you would like reindex all search data?", options)
  @appliance_settings_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @appliance_settings_interface.dry.reindex(params)
    return
  end
  json_response = @appliance_settings_interface.reindex(params)
  render_response(json_response, options) do
    print_green_success "Reindexing all search data..."
  end
  return 0, nil
end

#toggle_maintenance(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 303

def toggle_maintenance(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = opts.banner = subcommand_usage()
    opts.on("--enabled [on|off]", String, "Enabled (on) or Disabled (off)") do |val|
      params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    build_standard_update_options(opts, options, [:auto_confirm], [:payload, :options])
    opts.footer = "Toggle maintenance mode."
  end
  optparse.parse!(args)
  connect(options)
  verify_args!(args:args, optparse:optparse, count:0)
  if params['enabled'].nil?
    confirm!("Are you sure you would like to toggle maintenance mode?", options)
  else
    confirm!("Are you sure you would like to toggle maintenance mode: #{params['enabled'] ? 'on' : 'off'}?", options)
  end
  @appliance_settings_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @appliance_settings_interface.dry.maintenance(params)
    return
  end
  json_response = @appliance_settings_interface.maintenance(params)
  render_response(json_response, options) do
    print_green_success "Toggled maintenance mode: '#{params['enabled'] ? 'on' : 'off'}'"
  end
  return 0, nil
end

#update(args) ⇒ Object



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
210
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
# File 'lib/morpheus/cli/commands/appliance_settings_command.rb', line 116

def update(args)
  options = {}
  params = {}

  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = opts.banner = subcommand_usage()
    opts.on("--appliance-url STRING", String, "Appliance URL") do |val|
      params['applianceUrl'] = val == 'null' ? nil : val
    end
    opts.on("--internal-appliance-url STRING", String, "Internal appliance URL (PXE)") do |val|
      params['internalApplianceUrl'] = val == 'null' ? nil : val
    end
    opts.on("--api-allowed-origins STRING", String, "API allowed origins") do |val|
      params['corsAllowed'] = val == 'null' ? nil : val
    end
    opts.on("--registration-enabled [on|off]", ['on','off'], "Tenant registration enabled") do |val|
      params['registrationEnabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--default-tenant-role ROLE", String, "Default tenant role authority or ID") do |val|
      if val == 'null'
        params['defaultRoleId'] = nil
      else
        options[:defaultTenantRole] = val
      end
    end
    opts.on("--default-user-role ROLE", String, "Default user role authority or ID") do |val|
      if val == 'null'
        params['defaultUserRoleId'] = nil
      else
        options[:defaultUserRole] = val
      end
    end
    opts.on("--docker-privileged-mode [on|off]", ['on','off'], "Docker privileged mode") do |val|
      params['dockerPrivilegedMode'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--expire-pwd-days NUMBER", Integer, "Expire password after specified days. Set to 0 to disable this feature") do |val|
      params['expirePwdDays'] = val.to_i
    end
    opts.on("--disable-after-attempts NUMBER", Integer, "Disable user after attempts. Set to 0 to disable this feature") do |val|
      params['disableAfterAttempts'] = val.to_i
    end
    opts.on("--disable-after-days-inactive NUMBER", Integer, "Disable user if inactive for specified days. Set to 0 to disable this feature") do |val|
      params['disableAfterDaysInactive'] = val.to_i
    end
    opts.on("--warn-user-days-before NUMBER", Integer, "Send warning email before deactivating. Set to 0 to disable this feature") do |val|
      params['warnUserDaysBefore'] = val.to_i
    end
    opts.on("--smtp-from-email STRING", String, "From email address") do |val|
      params['smtpMailFrom'] = val == 'null' ? nil : val
    end
    opts.on("--smtp-server STRING", String, "SMTP server / host") do |val|
      params['smtpServer'] = val == 'null' ? nil : val
    end
    opts.on("--smtp-port NUMBER", String, "SMTP port") do |val|
      params['smtpPort'] = val == 'null' ? nil : val.to_i
    end
    opts.on("--smtp-ssl [on|off]", ['on','off'], "Use SSL for SMTP connections") do |val|
      params['smtpSSL'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--smtp-tls [on|off]", ['on','off'], "Use TLS for SMTP connections") do |val|
      params['smtpTLS'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--smtp-user STRING", String, "SMTP user") do |val|
      params['smtpUser'] = val == 'null' ? nil : val
    end
    opts.on("--smtp-password STRING", String, "SMTP password") do |val|
      params['smtpPassword'] = val == 'null' ? nil : val
    end
    opts.on("--proxy-host STRING", String, "Proxy host") do |val|
      params['proxyHost'] = val == 'null' ? nil : val
    end
    opts.on("--proxy-port NUMBER", String, "Proxy port") do |val|
      params['proxyPort'] = val == 'null' ? nil : val.to_i
    end
    opts.on("--proxy-user STRING", String, "Proxy user") do |val|
      params['proxyUser'] = val == 'null' ? nil : val
    end
    opts.on("--proxy-password STRING", String, "Proxy password") do |val|
      params['proxyPassword'] = val == 'null' ? nil : val
    end
    opts.on("--proxy-domain STRING", String, "Proxy domain") do |val|
      params['proxyDomain'] = val == 'null' ? nil : val
    end
    opts.on("--proxy-workstation STRING", String, "Proxy workstation") do |val|
      params['proxyWorkstation'] = val == 'null' ? nil : val
    end
    opts.on("--currency-provider STRING", String, "Currency provider") do |val|
      params['currencyProvider'] = val == 'null' ? nil : val
    end
    opts.on("--currency-key STRING", String, "Currency provider API key") do |val|
      params['currencyKey'] = val == 'null' ? nil : val
    end
    opts.on("--enable-all-clouds", "Set all cloud types enabled status on, can be used in conjunction with --disable-clouds") do
      params['enableAllZoneTypes'] = true
    end
    opts.on("--enable-clouds LIST", Array, "List of cloud types to set enabled status on, each item can be either name or ID") do |list|
      options[:enableZoneTypes] = list
    end
    opts.on("--disable-clouds LIST", Array, "List of cloud types to set enabled status off, each item can be either name or ID") do |list|
      options[:disableZoneTypes] = list
    end
    opts.on("--disable-all-clouds", "Set all cloud types enabled status off, can be used in conjunction with --enable-clouds options") do
      params['disableAllZoneTypes'] = true
    end
    opts.on("--stats-retainment-period DAYS", Integer, "Stats retainment period. The number of days stats should be available. Can be 30, 60, or 90.") do |val|
      params['statsRetainmentPeriod'] = val.to_i
    end
    build_common_options(opts, options, [:json, :payload, :dry_run, :quiet, :remote])
  end

  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    parse_payload(options) do |payload|
      available_zone_types = @appliance_settings_interface.cloud_types['zoneTypes']

      if options[:enableZoneTypes]
        params['enableZoneTypes'] = options[:enableZoneTypes].collect do |zone_type_id|
          zone_type = available_zone_types.find { |it| it['id'] == zone_type_id || it['id'].to_s == zone_type_id || it['name'] == zone_type_id }
          if zone_type.nil?
            print_red_alert "Cloud type #{zone_type_id} not found"
            exit 1
          end
          zone_type['id']
        end
      end
      if options[:disableZoneTypes]
        params['disableZoneTypes'] = options[:disableZoneTypes].collect do |zone_type_id|
          zone_type = available_zone_types.find { |it| it['id'] == zone_type_id || it['id'].to_s == zone_type_id || it['name'] == zone_type_id }
          if zone_type.nil?
            print_red_alert "Cloud type #{zone_type_id} not found"
            exit 1
          end
          zone_type['id']
        end
      end

      if options[:defaultTenantRole]
        role = find_role_by_name_or_id(nil, options[:defaultTenantRole])
        if role.nil?
          exit 1
        end
        params['defaultRoleId'] = role['id']
      end

      if options[:defaultUserRole]
        role = find_role_by_name_or_id(nil, options[:defaultUserRole])
        if role.nil?
          print_red_alert "Default user role #{options[:defaultUserRole]} not found"
          exit 1
        end
        params['defaultUserRoleId'] = role['id']
      end

      if params['currencyProvider']
        currency_providers = @api_client.options.options_for_source('currencyProviders')['data']
        currency_provider = currency_providers.find {|it| it['name'] == params['currencyProvider'] || it['value'] == params['currencyProvider']}

        if currency_provider.nil?
          print_red_alert "Invalid currency provider #{params['currencyProvider']}, valid options: #{currency_providers.collect {|it| it['value']}.join('|')}"
          exit 1
        end
      end
      payload['applianceSettings'] = params
    end
    execute_api(@appliance_settings_interface, :update, nil, options, "applianceSettings") do |json_response|
      if json_response['success']
        print_green_success  "Updated appliance settings"
        get([] + (options[:remote] ? ["-r",options[:remote]] : []))
      else
        #todo: API should return 400 on error and then this is not needed
        #print_red_alert "Error updating appliance settings"
        print_rest_errors(json_response)
        [1, "Error updating appliance settings"]
      end
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end