Class: Morpheus::Cli::Remote

Inherits:
Object
  • Object
show all
Extended by:
Term::ANSIColor
Includes:
CliCommand
Defined in:
lib/morpheus/cli/remote.rb

Constant Summary collapse

@@appliance_config =

for caching the the contents of YAML file $home/appliances it is structured like :appliance_name => => “htt[://api.gomorpheus.com”, :active => true not named @@appliances to avoid confusion with the instance variable . This is also a command class…

nil

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #handle_subcommand, included, #interactive?, #noninteractive, #print_usage, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeRemote

Returns a new instance of Remote.



15
16
17
# File 'lib/morpheus/cli/remote.rb', line 15

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

Class Method Details

.active_applianceObject

Returns two things, the remote appliance name and url



424
425
426
427
428
429
430
431
432
433
434
# File 'lib/morpheus/cli/remote.rb', line 424

def active_appliance
  if self.appliances.empty?
    return nil, nil
  end
  app_name, app_map = self.appliances.find {|k,v| v[:active] == true }
  if app_name
    return app_name, app_map[:host]
  else
    return app_name, nil
  end
end

.appliance_configObject



419
420
421
# File 'lib/morpheus/cli/remote.rb', line 419

def appliance_config
  @@appliance_config ||= load_appliance_file || {}
end

.appliancesObject



415
416
417
# File 'lib/morpheus/cli/remote.rb', line 415

def appliances
  self.appliance_config
end

.appliances_file_pathObject



473
474
475
# File 'lib/morpheus/cli/remote.rb', line 473

def appliances_file_path
  File.join(Morpheus::Cli.home_directory,"appliances")
end

.clear_active_applianceObject



449
450
451
452
453
454
455
# File 'lib/morpheus/cli/remote.rb', line 449

def clear_active_appliance
  new_appliances = self.appliances
  new_appliances.each do |k,v|
    v[:active] = false
  end
  save_appliances(new_appliances)
end

.load_appliance_fileObject



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/morpheus/cli/remote.rb', line 457

def load_appliance_file
  fn = appliances_file_path
  if File.exist? fn
    print "#{dark} #=> loading appliances file #{fn}#{reset}\n" if Morpheus::Logging.debug?
    return YAML.load_file(fn)
  else
    return {}
    # return {
    #   morpheus: {
    #     host: 'https://api.gomorpheus.com',
    #     active: true
    #   }
    # }
  end
end

.save_appliances(new_config) ⇒ Object



477
478
479
480
481
482
# File 'lib/morpheus/cli/remote.rb', line 477

def save_appliances(new_config)
  File.open(appliances_file_path, 'w') {|f| f.write new_config.to_yaml } #Store
  FileUtils.chmod(0600, appliances_file_path)
  #@@appliance_config = load_appliance_file
  @@appliance_config = new_config
end

.set_active_appliance(name) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/morpheus/cli/remote.rb', line 436

def set_active_appliance(name)
  new_appliances = self.appliances
  new_appliances.each do |k,v|
    is_match = (name ? (k == name.to_sym) : false)
    if is_match
      v[:active] = true
    else
      v[:active] = false
    end
  end
  save_appliances(new_appliances)
end

Instance Method Details

#add(args) ⇒ Object



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
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
# File 'lib/morpheus/cli/remote.rb', line 63

def add(args)
  options = {}
  use_it = false
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [url]")
    opts.on( '--use', '--use', "Make this the current remote appliance" ) do
      use_it = true
    end
    # let's free up the -d switch for global options, maybe?
    opts.on( '-d', '--default', "Does the same thing as --use" ) do
      use_it = true
    end
    # todo: use Morpheus::Cli::OptionParser < OptionParser
    # opts.on('-h', '--help', "Prints this help" ) do
    #   hidden_switches = ["--default"]
    #   good_opts = opts.to_s.split("\n").delete_if { |line| hidden_switches.find {|it| line =~ /#{Regexp.escape(it)}/ } }.join("\n") 
    #   puts good_opts
    #   exit
    # end
    build_common_options(opts, options, [:quiet])
    opts.footer = "This will add a new appliance to your list.\n" + 
                  "If it's first one, it will be made the current active appliance."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    exit 1
  end
  
  new_appliance_name = args[0].to_sym
  url = args[1]
  if url !~ /^https?\:\/\//
    print red, "The specified appliance url is invalid: '#{args[1]}'", reset, "\n"
    puts optparse
    exit 1
  end
  # maybe a ping here would be cool
  @appliances = ::Morpheus::Cli::Remote.appliances
  if @appliances.keys.empty?
    use_it = true
  end
  if @appliances[new_appliance_name] != nil
    print red, "Remote appliance already configured with the name '#{args[0]}'", reset, "\n"
    return false
  else
    @appliances[new_appliance_name] = {
      host: url,
      active: use_it
    }
    ::Morpheus::Cli::Remote.save_appliances(@appliances)
    if use_it
      Morpheus::Cli::Remote.set_active_appliance(new_appliance_name)
      @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
    end
  end
  
  if options[:quiet] || options[:no_prompt]
    return true
  end
  
  # check to see if this is a fresh appliance. 
  # GET /api/setup only returns 200 if it can still be initialized, else 400
  @setup_interface = Morpheus::SetupInterface.new(@appliance_url)
  appliance_status_json = nil
  begin
    appliance_status_json = @setup_interface.get()
    if appliance_status_json['success'] == true
      return setup([new_appliance_name])
    end
    # should not get here
  rescue RestClient::Exception => e
    #print_rest_exception(e, options)
    # laff, treating any non - 200 as meaning it is good ...is bad.. could be at the wrong site.. sending credentials..
    print cyan,"Appliance is ready.\n", reset
  end

  if use_it
    if ::Morpheus::Cli::OptionTypes::confirm("Would you like to login now?", options.merge({default: true}))
      return ::Morpheus::Cli::Login.new.handle([new_appliance_name])
    end
  end

  return true
end

#handle(args) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/morpheus/cli/remote.rb', line 19

def handle(args)
  if args.count == 0
    list(args)
  else
    handle_subcommand(args)
  end
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/remote.rb', line 27

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [])
    opts.footer = "This outputs a list of the remote appliances.\n" + 
                  "It also displays the current active appliance.\n" + 
                  "The shortcut `remote` can be used instead of `remote list`."
  end
  optparse.parse!(args)
  @appliances = ::Morpheus::Cli::Remote.appliances
  if @appliances == nil || @appliances.empty?
    print yellow,"No remote appliances configured, see `remote add`",reset,"\n"
  else
    rows = @appliances.collect do |app_name, v|
      {
        active: (v[:active] ? "=>" : ""),
        name: app_name,
        host: v[:host]
      }
    end
    print "\n" ,cyan, bold, "Morpheus Appliances\n","==================", reset, "\n\n"
    print cyan
    tp rows, {:active => {:display_name => ""}}, {:name => {:width => 16}}, {:host => {:width => 40}}
    print reset
    if @appliance_name
      #unless @appliances.keys.size == 1
        print cyan, "\n# => Currently using #{@appliance_name}\n", reset
      #end
    else
      print "\n# => No active remote appliance, see `remote use`\n", reset
    end
    print "\n" # meh
  end
end


234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/morpheus/cli/remote.rb', line 234

def print_current(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json])
    opts.footer = "Prints the name of the current remote appliance"
  end
  optparse.parse!(args)

  if @appliance_name
    print cyan, @appliance_name,"\n",reset
  else
    print yellow, "No active appliance, see `remote use`\n", reset
    return false
  end
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/remote.rb', line 148

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-d', '--default', "Make this the default remote appliance" ) do
      options[:default] = true
    end
    opts.footer = "This will delete an appliance from your list."
    build_common_options(opts, options, [:auto_confirm])
  end
  optparse.parse!(args)
  if args.empty?
    puts optparse
    exit 1
  end
  @appliances = ::Morpheus::Cli::Remote.appliances
  appliance_name = args[0].to_sym
  if @appliances[appliance_name] == nil
    print red, "Remote appliance not found by the name '#{args[0]}'", reset, "\n"
  else
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove this remote appliance '#{appliance_name}'?", options)
      exit 1
    end
    @appliances.delete(appliance_name)
    ::Morpheus::Cli::Remote.save_appliances(@appliances)
    # todo: also delete credentials and groups[appliance_name]
    ::Morpheus::Cli::Groups.clear_active_group(appliance_name) # rescue nil
    # this should be a class method too
    #::Morpheus::Cli::Credentials.clear_saved_credentials(appliance_name)
    ::Morpheus::Cli::Credentials.new(appliance_name, nil).clear_saved_credentials(appliance_name) # rescue nil
    #list([])
  end
end

#setup(args) ⇒ Object

this is a wizard that walks through the /api/setup controller it only needs to be used once to initialize a new appliance



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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/morpheus/cli/remote.rb', line 253

def setup(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:options, :json, :dry_run])
    opts.footer = "This can be used to initialize a new appliance.\n" + 
                  "You will be prompted to create the master account.\n" + 
                  "This is only available on a new, freshly installed, remote appliance."
  end
  optparse.parse!(args)

  if !@appliance_name
    print yellow, "No active appliance, see `remote use`\n", reset
    return false
  end

  # this works without any authentication!
  # it will allow anyone to use it, if there are no users/accounts in the system.
  #@api_client = establish_remote_appliance_connection(options)
  #@setup_interface = @api_client.setup
  @setup_interface = Morpheus::SetupInterface.new(@appliance_url)
  appliance_status_json = nil
  begin
    appliance_status_json = @setup_interface.get()
    if appliance_status_json['success'] != true
      print red, "Setup not available for appliance #{@appliance_name} - #{@appliance_url}.\n", reset
      print red, "#{appliance_status_json['msg']}\n", reset
      return false
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return false
  end
  
  payload = {}

  if appliance_status_json['hubRegistrationEnabled']
    link = File.join(@appliance_url, '/setup')
    print red, "Sorry, setup with hub registration is not yet available.\n", reset
    print "You can use the UI to setup your appliance.\n"
    print "Go to #{link}\n", reset
    # if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
    #   system "start #{link}"
    # elsif RbConfig::CONFIG['host_os'] =~ /darwin/
    #   system "open #{link}"
    # elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
    #   system "xdg-open #{link}"
    # end
    return false
  else
    print "\n" ,cyan, bold, "Morpheus Appliance Setup", "\n", "==================", reset, "\n\n"

    puts "It looks like you're the first one here."
    puts "Let's initialize your remote appliance at #{@appliance_url}"


    
    # Master Account
    print "\n" ,cyan, bold, "Create Master account", "\n", "==================", reset, "\n\n"
     = [
      {'fieldName' => 'accountName', 'fieldLabel' => 'Master Account Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1},
    ]
    v_prompt = Morpheus::Cli::OptionTypes.prompt(, options[:options])
    payload.merge!(v_prompt)

    # Master User
    print "\n" ,cyan, bold, "Create Master User", "\n", "==================", reset, "\n\n"
    user_option_types = [
      {'fieldName' => 'firstName', 'fieldLabel' => 'First Name', 'type' => 'text', 'required' => false, 'displayOrder' => 1},
      {'fieldName' => 'lastName', 'fieldLabel' => 'Last Name', 'type' => 'text', 'required' => false, 'displayOrder' => 2},
      {'fieldName' => 'username', 'fieldLabel' => 'Username', 'type' => 'text', 'required' => true, 'displayOrder' => 3},
      {'fieldName' => 'email', 'fieldLabel' => 'Email', 'type' => 'text', 'required' => true, 'displayOrder' => 4},
    ]
    v_prompt = Morpheus::Cli::OptionTypes.prompt(user_option_types, options[:options])
    payload.merge!(v_prompt)

    # Password prompt with re-prompting if no match
    password_option_types = [
      {'fieldName' => 'password', 'fieldLabel' => 'Password', 'type' => 'password', 'required' => true, 'displayOrder' => 6},
      {'fieldName' => 'passwordConfirmation', 'fieldLabel' => 'Confirm Password', 'type' => 'password', 'required' => true, 'displayOrder' => 7},
    ]
    v_prompt = Morpheus::Cli::OptionTypes.prompt(password_option_types, options[:options])
    while v_prompt['passwordConfirmation'] != v_prompt['password']
      print red, "Password confirmation does not match. Re-enter your new password.", reset, "\n"
      v_prompt = Morpheus::Cli::OptionTypes.prompt(password_option_types, options[:options])
    end
    payload.merge!(v_prompt)

    # Extra settings
    print "\n" ,cyan, bold, "Initial Setup", "\n", "==================", reset, "\n\n"
    extra_option_types = [
      {'fieldName' => 'applianceName', 'fieldLabel' => 'Appliance Name', 'type' => 'text', 'required' => true, 'defaultValue' => nil},
      {'fieldName' => 'applianceUrl', 'fieldLabel' => 'Appliance URL', 'type' => 'text', 'required' => true, 'defaultValue' => appliance_status_json['applianceUrl']},
      {'fieldName' => 'backups', 'fieldLabel' => 'Enable Backups', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'off'},
      {'fieldName' => 'monitoring', 'fieldLabel' => 'Enable Monitoring', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'on'},
      {'fieldName' => 'logs', 'fieldLabel' => 'Enable Logs', 'type' => 'checkbox', 'required' => false, 'defaultValue' => 'on'}
    ]
    v_prompt = Morpheus::Cli::OptionTypes.prompt(extra_option_types, options[:options])
    payload.merge!(v_prompt)

    begin
      if options[:dry_run]
        print_dry_run @setup_interface.dry.init(payload)
        return
      end
      if !options[:json]
        print "Initializing the appliance...\n"
      end
      json_response = @setup_interface.init(payload)
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      return false
    end

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    print "\n"
    print cyan, "You have successfully setup the appliance.\n"
    #print cyan, "You may now login with the command `login`.\n"
    # uh, just use Credentials.login(username, password, {save: true})
    cmd_res = Morpheus::Cli::Login.new.(['--username', payload['username'], '--password', payload['password'], '-q'])
    # print "\n"
    print cyan, "You are now logged in as the System Admin #{payload['username']}.\n"
    print reset
    #print "\n"

    if ::Morpheus::Cli::OptionTypes::confirm("Would you like to apply your License Key now?", options.merge({:default => true}))
      cmd_res = Morpheus::Cli::License.new.apply([])
      # license_is_valid = cmd_res != false
    end

    if ::Morpheus::Cli::OptionTypes::confirm("Do you want to create the first group now?", options.merge({:default => true}))
      cmd_res = Morpheus::Cli::Groups.new.add(['--use'])

      #print "\n"

      # if cmd_res !=
        if ::Morpheus::Cli::OptionTypes::confirm("Do you want to create the first cloud now?", options.merge({:default => true}))
          cmd_res = Morpheus::Cli::Clouds.new.add([])
          #print "\n"
        end
      # end
    end
    print "\n",reset

  end
end

#unuse(args) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/morpheus/cli/remote.rb', line 213

def unuse(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage()
    opts.footer = "" +
      "This clears the current active appliance.\n" +
      "You will need to use an appliance, or pass the --remote option to your commands."
    build_common_options(opts, options, [])
  end
  optparse.parse!(args)
  @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
  if @appliance_name
    Morpheus::Cli::Remote.clear_active_appliance()
    @appliance_name, @appliance_url = nil, nil
    return true
  else
    puts "You are not using any appliance"
    return false
  end
end

#use(args) ⇒ Object



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
# File 'lib/morpheus/cli/remote.rb', line 182

def use(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [])
    opts.footer = "This sets the current active appliance.\n" +
                  "This allows you to switch between your different appliances.\n" + 
                  "You may override this with the --remote option in your commands."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  new_appliance_name = args[0].to_sym
  @appliances = ::Morpheus::Cli::Remote.appliances
  if @appliance_name && @appliance_name.to_s == new_appliance_name.to_s
    print reset,"Already using the appliance '#{args[0]}'","\n",reset
  else
    if @appliances[new_appliance_name] == nil
      print red, "Remote appliance not found by the name '#{args[0]}'", reset, "\n"
      return false
    else
      Morpheus::Cli::Remote.set_active_appliance(new_appliance_name)
      @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
      #print cyan,"Switched to using appliance #{args[0]}","\n",reset
      #list([])
    end
  end
end