Class: Machinery::Cli

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

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



162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/cli.rb', line 162

def self.check_container_name!(image, name)
  if image == name && !SystemDescription.valid_name?(name)
    raise Machinery::Errors::InvalidCommandLine,
      "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" \
      "#{Ui::Hint.program_name} #{ARGV.join(" ")} "\
      "--name='#{image.tr("/", "_")}'"
  end
end

.check_port_validity(port) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/cli.rb', line 276

def self.check_port_validity(port)
  if port < 2 || port > 65_535
    raise Machinery::Errors::ServerPortError,
      "The specified port '#{port}' is not valid. " \
      "A valid port can be in a range between 2 and 65535."
  elsif port >= 2 && port <= 1_023 && !CurrentUser.new.is_root?
    raise Machinery::Errors::ServerPortError,
      "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

.define_inspect_command_options(c) ⇒ Object



619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/cli.rb', line 619

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



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
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/cli.rb', line 90

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 '#{Ui::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



675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/cli.rb', line 675

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



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

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) && Ui::Renderer.for(scope)
      scopes << scope
    else
      unknown_scopes << scope
    end
  end

  unless invalid_scopes.empty?
    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

  unless unknown_scopes.empty?
    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



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/cli.rb', line 194

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

.shift_arg(args, name) ⇒ Object



186
187
188
189
190
191
192
# File 'lib/cli.rb', line 186

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

.show_filter_note(scopes, filter) ⇒ Object



179
180
181
182
183
184
# File 'lib/cli.rb', line 179

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



268
269
270
271
272
273
274
# File 'lib/cli.rb', line 268

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



1202
1203
1204
1205
1206
1207
1208
# File 'lib/cli.rb', line 1202

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



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/cli.rb', line 70

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 = if defined.empty?
      "none"
    else
      "only: #{defined.map(&:name).join(", ")}"
    end
    message = "Too many arguments: got #{parsed_arguments}, "\
      "expected #{defined_arguments}"
    raise GLI::BadCommandLine.new(message)
  end
end