Class: Morpheus::Cli::License

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_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, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #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

Constructor Details

#initializeLicense

alias_subcommand :details, :get



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

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

Instance Method Details

#apply(args) ⇒ Object



121
122
123
124
# File 'lib/morpheus/cli/license.rb', line 121

def apply(args)
  print_error "#{yellow}DEPRECATION WARNING: `license apply` has been deprecated and replaced with `license install`. Please use `license install` instead.#{reset}\n"
  install(args)
end

#connect(opts) ⇒ Object



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

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)		
  @license_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).license
end

#decode(args) ⇒ Object



165
166
167
168
# File 'lib/morpheus/cli/license.rb', line 165

def decode(args)
  print_error "#{yellow}DEPRECATION WARNING: `license decode` has been deprecated and replaced with `license test`. Please use `license test` instead.#{reset}\n"
  test(args)
end

#format_product_tier(license) ⇒ Object



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/morpheus/cli/license.rb', line 289

def format_product_tier(license)
  product_tier = license['productTier'] || 'capacity'
  if product_tier == 'capacity'
    'Capacity'
  elsif product_tier == 'essentials'
    'Essentials'
  elsif product_tier == 'pro'
    'Pro'
  elsif product_tier == 'enterprise'
    'Enterprise'
  elsif product_tier == 'msp'
    'Service Provider'
  else
    product_tier.to_s.capitalize
  end
end

#get(args) ⇒ Object



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
115
116
117
118
119
# File 'lib/morpheus/cli/license.rb', line 31

def get(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json, :yaml, :fields, :dry_run, :remote])
    opts.footer = "Get details about the currently installed license.\n" +
                  "This information includes license features and limits.\n" +
                  "The actual secret license key value will never be returned."
  end
  optparse.parse!(args)
  if args.count > 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    # make api request
    @license_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @license_interface.dry.get()
      return 0, nil
    end
    json_response = @license_interface.get()
    # 200 OK, parse results
    license = json_response['license']
    current_usage = json_response['currentUsage'] || {}
    used_memory = json_response['licenseUsedMemory'] || current_usage['memory']
    used_storage = current_usage['storage']
    used_workloads = current_usage['workloads']
    
    # Determine exit status and any error conditions for the command
    exit_code = 0
    err = nil
    if license.nil?
      exit_code = 1
      err = "No license currently installed."
    end

    # render common formats like dry run, curl, json , yaml , etc.
    render_result = render_with_format(json_response, options)
    return exit_code, err if render_result

    if options[:quiet]
      return exit_code, err
    end
    
    if exit_code != 0 
      print_error red, err.to_s, reset, "\n"
      return exit_code, err
    end
    
    # render output

    print_h1 "License"
    max_memory = "Unlimited"
    max_storage = "Unlimited"
    max_memory = Filesize.from("#{license['maxMemory']} B").pretty  if license['maxMemory'].to_i != 0
    max_storage = Filesize.from("#{license['maxStorage']} B").pretty  if license['maxStorage'].to_i != 0
    used_memory = Filesize.from("#{used_memory} B").pretty if used_memory.to_i != 0
    used_storage = Filesize.from("#{used_storage} B").pretty if used_storage.to_i != 0
    #used_workloads = "n/a" if used_workloads.nil?
    max_workloads = license["maxInstances"].to_i == 0 ? 'Unlimited' : license["maxInstances"]
    print cyan
    description_cols = {
      "Account" => 'accountName',
      "Product Tier" => lambda {|it| format_product_tier(it) },
      "Start Date" => lambda {|it| format_local_dt(it['startDate']) },
      "End Date" => lambda {|it| 
        if it['endDate']
          format_local_dt(it['endDate']).to_s + ' (' + format_duration(Time.now, it['endDate']).to_s + ')' 
        else
          'Never'
        end
        },
      "Memory" => lambda {|it| "#{used_memory} / #{max_memory}" },
      "Storage" => lambda {|it| "#{used_storage} / #{max_storage}" },
      "Workloads" => lambda {|it| "#{used_workloads} / #{max_workloads}" },
      "Hard Limit" => lambda {|it| it[""] == false ? 'Yes' : 'No' },
    }
    print_description_list(description_cols, license)
    print reset,"\n"
  
  return exit_code, err
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return false
  end
end

#handle(args) ⇒ Object



27
28
29
# File 'lib/morpheus/cli/license.rb', line 27

def handle(args)
  handle_subcommand(args)
end

#install(args) ⇒ Object



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

def install(args)
  options = {}
   = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[key]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    if args[0]
      key = args[0]
    else
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'licenseKey', 'fieldLabel' => 'License Key', 'type' => 'text', 'required' => true}], options[:options])
      key = v_prompt['licenseKey'] || ''
    end
    @license_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @license_interface.dry.install(key)
      return 0
    end
    json_response = @license_interface.install(key)
    license = json_response['license']
    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      print_green_success "License installed!"
      get([] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return false
  end
end

#test(args) ⇒ Object



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

def test(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[key]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Test a license key.\n" +
                  "This is a way to decode and view a license key before installing it."
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  key = nil
  if args[0]
    key = args[0]
  else
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'licenseKey', 'fieldLabel' => 'License Key', 'type' => 'text', 'required' => true}], options[:options])
    key = v_prompt['licenseKey'] || ''
  end
  begin
    @license_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @license_interface.dry.test(key)
      return
    end
    json_response = @license_interface.test(key)
    license = json_response['license']

    exit_code, err = 0, nil
    if license.nil?
      err = "Unable to decode license."
      exit_code = 1
      #return err, exit_code
    end
    render_result = render_with_format(json_response, options)
    if render_result
      return exit_code, err
    end
    if options[:quiet]
      return exit_code, err
    end
    if exit_code != 0
      print_error red, err.to_s, reset, "\n"
      return exit_code, err
    end
    
    # all good
    print_h1 "License"
    max_memory = "Unlimited"
    max_storage = "Unlimited"
    max_memory = Filesize.from("#{license['maxMemory']} B").pretty  if license['maxMemory'].to_i != 0
    max_storage = Filesize.from("#{license['maxStorage']} B").pretty  if license['maxStorage'].to_i != 0
    print cyan
    description_cols = {
      "Account" => 'accountName',
      "Product Tier" => lambda {|it| format_product_tier(it) }, 
      "Start Date" => lambda {|it| format_local_dt(it['startDate']) },
      "End Date" => lambda {|it| format_local_dt(it['endDate']) },
      "Max Memory" => lambda {|it| max_memory },
      "Max Storage" => lambda {|it| max_storage },
      "Max Instances" => lambda {|it| it["maxInstances"].to_i == 0 ? 'Unlimited' : it["maxInstances"] },
      "Hard Limit" => lambda {|it| it[""] == false ? 'Yes' : 'No' },
    }
    print_description_list(description_cols, license)
    print reset,"\n"
    return exit_code, err
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#uninstall(args) ⇒ Object



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

def uninstall(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[key]")
    build_common_options(opts, options, [:auto_confirm, :json, :yaml, :dry_run, :remote])
    opts.footer = "Uninstall the current license key.\n" +
                  "This clears out the current license key from the appliance.\n" +
                  "The function of the remote appliance will be restricted without a license installed.\n" +
                  "Be careful using this."
  end
  optparse.parse!(args)
  if args.count > 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    @license_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @license_interface.dry.uninstall(params)
      return
    end
    
    unless options[:quiet]
      print cyan,"#{bold}WARNING!#{reset}#{cyan} You are about to uninstall your license key.",reset,"\n"
      print yellow, "Be careful using this. Make sure you have a copy of your key somewhere if you intend to use it again.",reset, "\n"
      print "\n"
    end
    
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you want to uninstall the license key for remote #{@appliance_name} - #{@appliance_url}?")
      return 9, "command aborted"
    end

    json_response = @license_interface.uninstall(params)
    render_result = render_with_format(json_response, options)
    return 0 if render_result
    return 0 if options[:quiet]
    print_green_success "License uninstalled!"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end