Class: Morpheus::Cli::LibraryPackagesCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from LibraryHelper

#api_client, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #format_instance_type_technology, included, #load_balance_protocols_dropdown, #print_instance_types_table, #prompt_exposed_ports

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

#initializeLibraryPackagesCommand

Returns a new instance of LibraryPackagesCommand.



16
17
18
# File 'lib/morpheus/cli/packages_command.rb', line 16

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

Instance Method Details

#connect(opts) ⇒ Object



20
21
22
23
# File 'lib/morpheus/cli/packages_command.rb', line 20

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @packages_interface = @api_client.packages
end

#export(args) ⇒ Object

generate a new .morpkg file



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

def export(args)
  full_command_string = "#{command_name} export #{args.join(' ')}".strip
  options = {}
  params = {}
  instance_type_codes = nil
  outfile = nil
  do_overwrite = false
  do_mkdir = false
  do_unzip = false
  do_open = false
  open_prog = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[instance-type]")
    opts.on('--file FILE', String, "Destination filepath for the downloaded .morpkg file.") do |val|
      outfile = val
    end
    opts.on('--package-version VALUE', String, "Version number for package.") do |val|
      params['version'] = val
    end
    opts.on('--organization NAME', String, "Organization for package.") do |val|
      params['organization'] = val
    end
    opts.on('--code VALUE', String, "Code for package. Default comes from instance type.") do |val|
      params['code'] = val
    end
    opts.on('--name VALUE', String, "Name for package. Default comes from the instance type name") do |val|
      params['name'] = val
    end
    opts.on('--description VALUE', String, "Description of package.") do |val|
      params['description'] = val
    end
    opts.on('--instance-types LIST', String, "Can be used to export multiple instance types as a single package.") do |val|
      instance_type_codes = []
      val.split(',').collect do |it|
        if !it.strip.empty?
          instance_type_codes << it.strip
        end
      end
    end
    opts.on('--all', String, "Export entire library instead of specific instance type(s).") do
      params['all'] = true
    end
    opts.on('--all-system', String, "Export all system instance types instead of specific instance type(s).") do
      params['all'] = true
      params['systemOnly'] = true
    end
    opts.on('--all-custom', String, "Export all custom instance types instead of specific instance type(s).") do
      params['all'] = true
      params['customOnly'] = true
    end
    opts.on( '-p', '--mkdir', "Create missing directories for [filename] if they do not exist." ) do
      do_mkdir = true
    end
    opts.on( '-f', '--force', "Overwrite existing [filename] if it exists. Also creates missing directories." ) do
      do_overwrite = true
      do_mkdir = true
    end
    opts.on( '--unzip', "Unzip the package to a directory with the same name." ) do
      do_unzip = true
    end
    opts.on( '--open [PROG]', String, "Unzip the package and open the expanded directory with the specified program." ) do |val|
      do_unzip = true
      do_open = true
      if !val.to_s.empty?
        open_prog = val.to_s
      else
        if RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
          open_prog = "start"
        elsif RbConfig::CONFIG['host_os'] =~ /darwin/
          open_prog = "open"
        elsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/
          open_prog = "xdg-open"
        end
      end
    end
    build_common_options(opts, options, [:options, :dry_run, :quiet])
    opts.footer = "Export one or many instance types as a morpheus library package (.morpkg) file.\n" + 
                  "[instance-type] is required. This is the instance type code." +
                  "--instance-types can bv. This is a list of instance type codes."
  end
  optparse.parse!(args)

  if args.count != 1 && !instance_type_codes && !params['all']
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} export expects 1 argument and received #{args.count}: #{args.join(' ')}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    # construct payload
    if !params['all']
      if args[0] && !instance_type_codes
        instance_type_codes = [args[0]]
      end
      params['instanceType'] = instance_type_codes
    end
    # determine outfile
    if !outfile
      # use a default location
      do_mkdir = true
      if instance_type_codes && instance_type_codes.size == 1
        outfile = File.join(Morpheus::Cli.home_directory, "tmp", "morpheus-packages", "#{instance_type_codes[0]}.morpkg")
      else
        outfile = File.join(Morpheus::Cli.home_directory, "tmp", "morpheus-packages", "download.morpkg")
      end
    end
    outfile = File.expand_path(outfile)
    if Dir.exists?(outfile)
      puts_error "#{Morpheus::Terminal.angry_prompt}--file is invalid. It is the name of an existing directory: #{outfile}"
      return 1
    end
    # always a .morpkg
    if outfile[-7..-1] != ".morpkg"
      outfile << ".morpkg"
    end
    destination_dir = File.dirname(outfile)
    if !Dir.exists?(destination_dir)
      if do_mkdir
        print cyan,"Creating local directory #{destination_dir}",reset,"\n"
        FileUtils.mkdir_p(destination_dir)
      else
        puts_error "#{Morpheus::Terminal.angry_prompt}[filename] is invalid. Directory not found: #{destination_dir}  Use -p to create the missing directory."
        return 1
      end
    end
    if File.exists?(outfile)
      if do_overwrite
        # uhh need to be careful wih the passed filepath here..
        # don't delete, just overwrite.
        # File.delete(outfile)
      else
        print_error Morpheus::Terminal.angry_prompt
        puts_error "[filename] is invalid. File already exists: #{outfile}", "Use -f to overwrite the existing file."
        # puts_error optparse
        return 1
      end
    end

    # merge -O options into normally parsed options
    params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]

    if options[:dry_run]
      print_dry_run @packages_interface.dry.export(params, outfile), full_command_string
      return 1
    end
    if !options[:quiet]
      print cyan + "Downloading morpheus package file #{outfile} ... "
    end

    http_response, bad_body = @packages_interface.export(params, outfile)

    # FileUtils.chmod(0600, outfile)
    success = http_response.code.to_i == 200
    if success
      if !options[:quiet]
        print green + "SUCCESS" + reset + "\n"
      end

      if do_unzip
        package_dir = File.join(File.dirname(outfile), File.basename(outfile).sub(/\.morpkg\Z/, ''))
        if File.exists?(package_dir)
          print cyan,"Deleting existing directory #{package_dir}",reset,"\n"
          FileUtils.rm_rf(package_dir)
        end
        print cyan,"Unzipping to #{package_dir}",reset,"\n"
        system("unzip '#{outfile}' -d '#{package_dir}' > /dev/null 2>&1")
        if do_open
          system("#{open_prog} '#{package_dir}'")
        end
      end

      return 0
    else
      if !options[:quiet]
        print red + "ERROR" + reset + " HTTP #{http_response.code}" + "\n"
        if bad_body
          puts red + bad_body
        end
        #response_body = (http_response.body.kind_of?(Net::ReadAdapter) ? "" : http_response.body)
      end
      # F it, just remove a bad result
      if File.exists?(outfile) && File.file?(outfile)
        Morpheus::Logging::DarkPrinter.puts "Deleting bad file download: #{outfile}" if Morpheus::Logging.debug?
        File.delete(outfile)
      end
      if options[:debug]
        puts_error http_response.inspect
      end
      return 1
    end
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#get(args) ⇒ Object



151
152
153
# File 'lib/morpheus/cli/packages_command.rb', line 151

def get(args)
  raise "not yet implemented"
end

#handle(args) ⇒ Object



25
26
27
# File 'lib/morpheus/cli/packages_command.rb', line 25

def handle(args)
  handle_subcommand(args)
end

#install(args) ⇒ Object



155
156
157
# File 'lib/morpheus/cli/packages_command.rb', line 155

def install(args)
  raise "not yet implemented"
end

#list(args) ⇒ Object



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

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List installed packages."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))

    if options[:dry_run]
      print_dry_run @packages_interface.dry.list(params)
      return
    end
    json_response = @packages_interface.list(params)
    if options[:json]
      puts as_json(json_response, options, "packages")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "packages")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response["packages"], options)
    else
      installed_packages = json_response["packages"]
      title = "Installed Packages"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if installed_packages.empty?
        print cyan,"No installed packages found",reset,"\n"
      else
        rows = installed_packages.collect {|package|
          {
            code: package['code'],
            name: package['name'],
            version: package['version'],
            description: package['description'],
          }
        }
        columns = [:code, :name, {:description => {:max_width => 50}}]
        # custom pretty table columns ...
        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)
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



163
164
165
# File 'lib/morpheus/cli/packages_command.rb', line 163

def remove(args)
  raise "not yet implemented"
end

#search(args) ⇒ Object



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

def search(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Search the marketplace for available packages."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))

    if options[:dry_run]
      print_dry_run @packages_interface.dry.search(params)
      return
    end
    json_response = @packages_interface.search(params)
    if options[:json]
      puts as_json(json_response, options, "packages")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "packages")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response["packages"], options)
    else
      available_packages = json_response["packages"]
      title = "Available Packages"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if available_packages.empty?
        print cyan,"No packages found",reset,"\n"
      else
        rows = available_packages.collect {|package|
          {
            code: package['code'],
            name: package['name'],
            version: package['version'],
            description: package['description']
          }
        }
        columns = [:code, :name, {:description => {:max_width => 50}}]
        # custom pretty table columns ...
        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)
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



159
160
161
# File 'lib/morpheus/cli/packages_command.rb', line 159

def update(args)
  raise "not yet implemented"
end