Class: Cli

Inherits:
Object show all
Extended by:
GLI::App
Defined in:
lib/cli.rb

Overview

Copyright © 2013-2016 SUSE LLC

This program is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, contact SUSE LLC.

To contact SUSE about this file by physical or electronic mail, you may find current contact information at www.suse.com

Constant Summary collapse

AVAILABLE_SCOPE_LIST =
Machinery::Ui.internal_scope_list_to_string(
  Inspector.all_scopes
)

Class Method Summary collapse

Class Method Details

.check_container_name!(image, name) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
# File 'lib/cli.rb', line 147

def self.check_container_name!(image, name)
  if image == name && !SystemDescription.valid_name?(name)
    raise Machinery::Errors::InvalidCommandLine.new(
      "Error: System description name '#{name}' is invalid. By default Machinery" \
        " uses the image name as description name if the parameter `--name` is not" \
        " provided.\nIf the image name contains a slash the `--name=NAME` parameter" \
        " is mandatory. Valid characters are 'a-zA-Z0-9_:.-'.\n\nFor example run:\n" \
        "#{Hint.program_name} #{ARGV.join(" ")} --name='#{image.tr("/", "_")}'"
    )
  end
end

.check_port_validity(port) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/cli.rb', line 258

def self.check_port_validity(port)
  if port < 2 || port > 65535
    raise Machinery::Errors::ServerPortError.new("The specified port '#{port}' is not " \
      "valid. A valid port can be in a range between 2 and 65535.")
  else
    if port >= 2 && port <= 1023 && !CurrentUser.new.is_root?
      raise Machinery::Errors::ServerPortError.new("The specified port '#{port}' needs " \
        "root privileges. Otherwise, the server cannot be started. All ports in a range " \
        "of 2-1023 need root privileges.")
    end
  end
end

.define_inspect_command_options(c) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/cli.rb', line 539

def self.define_inspect_command_options(c)
  c.flag [:name, :n], type: String, required: false, arg_name: "NAME",
    desc: "Store system description under the specified name"
  c.flag [:scope, :s], type: String, required: false,
    desc: "Inspect specified scopes", arg_name: "SCOPE_LIST"
  c.flag ["ignore-scope", :e], type: String, required: false,
    desc: "Exclude specified scopes", arg_name: "SCOPE_LIST"
  c.flag "skip-files", required: false, negatable: false,
    desc: "Do not consider given files or directories during inspection. " \
      "Either provide one file or directory name or a list of names separated by commas."
  c.switch ["extract-files", :x], required: false, negatable: false,
    desc: "Extract changed configuration files and unmanaged files from inspected system"
  if @config.experimental_features
    c.switch ["extract-metadata", :m], required: false, negatable: false,
      desc: "Extract unmanaged files metadata without extracting the files."
  end
  c.switch "extract-changed-config-files", required: false, negatable: false,
    desc: "Extract changed configuration files from inspected system"
  c.switch "extract-unmanaged-files", required: false, negatable: false,
    desc: "Extract unmanaged files from inspected system"
  c.switch "extract-changed-managed-files", required: false, negatable: false,
    desc: "Extract changed managed files from inspected system"
  c.switch :show, required: false, negatable: false,
    desc: "Print inspection result"
  c.switch :verbose, required: false, negatable: false,
    desc: "Display the filters which are used during inspection"
end

.handle_error(e) ⇒ Object



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

def self.handle_error(e)
  Machinery::Ui.kill_pager

  case e
  when GLI::MissingRequiredArgumentsException
    Machinery::Ui.error("Option --" + e.message)
    exit 1
  when GLI::UnknownCommandArgument, GLI::UnknownGlobalArgument,
    GLI::UnknownCommand, GLI::BadCommandLine,
    OptionParser::MissingArgument, OptionParser::AmbiguousOption
    Machinery::Ui.error e.to_s + "\n\n"
    command = ARGV & @commands.keys.map(&:to_s)
    Machinery::Ui.error "Run '#{Hint.program_name} #{command.first} --help' for more information."
    exit 1
  when Machinery::Errors::MachineryError
    Machinery.logger.error(e.message)
    Machinery::Ui.error e.message
    exit 1
  when SystemExit
    raise
  when SignalException
    Machinery.logger.info "Machinery was aborted with signal #{e.signo}."
    exit 1
  when Errno::ENOSPC
    Machinery::Ui.error("Error: " + e.message)
    exit 1
  else
    if LocalSystem.os.canonical_name.include? ("SUSE Linux Enterprise")
      Machinery::Ui.error "Machinery experienced an unexpected error.\n" \
      "If this impacts your business please file a service request at " \
      "https://www.suse.com/mysupport\n" \
      "so that we can assist you on this issue. An active support contract is required.\n"
    else
      Machinery::Ui.error "Machinery experienced an unexpected error. Please file a " \
        "bug report at: https://github.com/SUSE/machinery/issues/new\n"
    end

    if e.is_a?(Cheetah::ExecutionFailed)
      result = ""
      result << "#{e.message}\n"
      result << "\n"

      if e.stderr && !e.stderr.empty?
        result << "Error output:\n"
        result << "#{e.stderr}\n"
      end

      if e.stdout && !e.stdout.empty?
        result << "Standard output:\n"
        result << "#{e.stdout}\n\n"
      end

      if e.backtrace && !e.backtrace.empty?
        result << "Backtrace:\n"
        result << "#{e.backtrace.join("\n")}\n\n"
      end
      Machinery.logger.error(result)
      Machinery::Ui.error result
      exit 1
    else
      Machinery.logger.error("Machinery experienced an unexpected error:")
      Machinery.logger.error(e.message)
      Machinery.logger.error(e.backtrace.join("\n"))
      raise
    end
  end
  true
end

.parse_inspect_command_options(host, options) ⇒ Object



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/cli.rb', line 567

def self.parse_inspect_command_options(host, options)
  scope_list = process_scope_option(options[:scope], options["ignore-scope"])
  name = options[:name] || host


  unless scope_list.empty?
    inspected_scopes = " for #{Machinery::Ui.internal_scope_list_to_string(scope_list)}"
  end
  Machinery::Ui.puts "Inspecting #{host}#{inspected_scopes}..."

  inspect_options = {}
  if options["show"]
    inspect_options[:show] = true
  end
  if options["verbose"]
    inspect_options[:verbose] = true
  end
  if options["extract-files"] || options["extract-changed-config-files"]
    inspect_options[:extract_changed_changed_config_files] = true
  end
  if options["extract-files"] || options["extract-changed-managed-files"]
    inspect_options[:extract_changed_managed_files] = true
  end
  if options["extract-files"] || options["extract-unmanaged-files"]
    inspect_options[:extract_unmanaged_files] = true
  end
  if options["extract-metadata"]
    inspect_options[:extract_metadata] = true
  end

  filter = FilterOptionParser.parse("inspect", options)

  if options["verbose"] && !filter.empty?
    Machinery::Ui.puts "\nThe following filters are applied during inspection:"
    Machinery::Ui.puts filter.to_array.join("\n") + "\n\n"
  else
    show_filter_note(scope_list, filter)
  end

  [name, scope_list, inspect_options, filter]
end

.parse_scopes(scope_string) ⇒ Object



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

def self.parse_scopes(scope_string)
  unknown_scopes = []
  invalid_scopes = []
  scopes = []

  scope_string.split(",").each do |scope|
    unless scope =~ /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/
      invalid_scopes << scope
      next
    end

    if scope == "config-files"
      Machinery::Ui.warn(
        "The scope name `config-files` is deprecated. The new name is `changed-config-files`."
      )
      scope = "changed-config-files"
    end

    # convert cli scope naming to internal one
    scope.tr!("-", "_")

    if Inspector.all_scopes.include?(scope) && Renderer.for(scope)
      scopes << scope
    else
      unknown_scopes << scope
    end
  end

  if invalid_scopes.length > 0
    form = invalid_scopes.length > 1 ? "scopes are" : "scope is"
    raise Machinery::Errors::UnknownScope.new(
      "The following #{form} not valid:" \
        " '#{invalid_scopes.join("', '")}'." \
        " Scope names must start with a letter and contain only lowercase" \
        " letters and digits separated by dashes ('-')."
    )
  end

  if unknown_scopes.length > 0
    form = unknown_scopes.length > 1 ? "scopes are" : "scope is"
    raise Machinery::Errors::UnknownScope.new(
      "The following #{form} not supported: " \
        "#{Machinery::Ui.internal_scope_list_to_string(unknown_scopes)}. " \
      "Valid scopes are: #{AVAILABLE_SCOPE_LIST}."
    )
  end

  Inspector.sort_scopes(scopes.uniq)
end

.process_scope_option(scopes, exclude_scopes) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/cli.rb', line 177

def self.process_scope_option(scopes, exclude_scopes)
  if scopes
    if exclude_scopes
      # scope and ignore-scope
      raise Machinery::Errors::InvalidCommandLine.new("You cannot provide the --scope and " \
        "--ignore-scope option at the same time.")
    else
      # scope only
      scope_list = parse_scopes(scopes)
    end
  else
    if exclude_scopes
      # ignore-scope only
      scope_list = Inspector.all_scopes - parse_scopes(exclude_scopes)
    else
      # neither scope nor ignore-scope
      scope_list = Inspector.all_scopes
    end
  end
  if scope_list.empty?
    raise Machinery::Errors::InvalidCommandLine.new( "No scopes to process. Nothing to do.")
  end
  scope_list
end

.shift_arg(args, name) ⇒ Object



170
171
172
173
174
175
# File 'lib/cli.rb', line 170

def self.shift_arg(args, name)
  unless res = args.shift
    raise GLI::BadCommandLine.new("You need to provide the required argument #{name}.")
  end
  res
end

.show_filter_note(scopes, filter) ⇒ Object



163
164
165
166
167
168
# File 'lib/cli.rb', line 163

def self.show_filter_note(scopes, filter)
  if scopes.any? { |scope| !filter.element_filters_for_scope(scope).empty? }
    Machinery::Ui.puts "\nNote: There are filters being applied during inspection. " \
      "(Use `--verbose` option to show the filters)\n\n"
  end
end

.supports_filtering(command) ⇒ Object



252
253
254
255
256
# File 'lib/cli.rb', line 252

def self.supports_filtering(command)
  if @config.experimental_features
    command.flag :exclude, negatable: false, desc: "Exclude elements matching the filter criteria"
  end
end

.system_description_storeObject



999
1000
1001
1002
1003
1004
1005
# File 'lib/cli.rb', line 999

def self.system_description_store
  if ENV.key?("MACHINERY_DIR")
    SystemDescriptionStore.new(ENV["MACHINERY_DIR"])
  else
    SystemDescriptionStore.new
  end
end

.validate_command_line(defined, parsed) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/cli.rb', line 66

def self.validate_command_line(defined, parsed)
  if defined.any?(&:multiple?) && !defined.any?(&:optional?) && parsed.empty?
    message = "No arguments given. Nothing to do."
    raise GLI::BadCommandLine.new(message)
  elsif !defined.any?(&:multiple?) && parsed.size > defined.size
    parsed_arguments = "#{parsed.size} #{Machinery.pluralize(parsed.size, "argument")}"
    defined_arguments = defined.empty? ? "none" : "only: #{defined.map(&:name).join(", ")}"
    message = "Too many arguments: got #{parsed_arguments}, expected #{defined_arguments}"
    raise GLI::BadCommandLine.new(message)
  end
end