Class: Chef::Knife::Xargs

Inherits:
ChefFS::Knife show all
Defined in:
lib/chef/knife/xargs.rb

Constant Summary

Constants inherited from Chef::Knife

CHEF_ORGANIZATION_MANAGEMENT, OFFICIAL_PLUGINS, OPSCODE_HOSTED_CHEF_ACCESS_CONTROL

Instance Attribute Summary

Attributes inherited from Chef::Knife

#name_args, #ui

Instance Method Summary collapse

Methods inherited from ChefFS::Knife

#chef_fs, #configure_chef, #create_chef_fs, #create_local_fs, deps, #discover_repo_dir, #format_path, inherited, #local_fs, #parallelize, #pattern_arg_from, #pattern_args, #pattern_args_from

Methods inherited from Chef::Knife

#api_key, #apply_computed_config, category, chef_config_dir, #cli_keys, common_name, #config_file_settings, config_loader, #config_source, #configure_chef, #create_object, #delete_object, dependency_loaders, deps, #format_rest_error, guess_category, #humanize_exception, #humanize_http_exception, inherited, #initialize, list_commands, load_commands, load_config, load_deps, #maybe_setup_fips, #merge_configs, msg, #noauth_rest, #parse_options, reset_config_loader!, reset_subcommands!, #rest, run, #run_with_pretty_exceptions, #server_url, #show_usage, snake_case_name, subcommand_category, subcommand_class_from, subcommand_files, subcommand_loader, subcommands, subcommands_by_category, #test_mandatory_field, ui, unnamed?, use_separate_defaults?, #username

Methods included from Mixin::ConvertToClassName

#constantize, #convert_to_class_name, #convert_to_snake_case, #filename_to_qualified_string, #normalize_snake_case_name, #snake_case_basename

Constructor Details

This class inherits a constructor from Chef::Knife

Instance Method Details

#create_command(files) ⇒ Object



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
# File 'lib/chef/knife/xargs.rb', line 169

def create_command(files)
  command = name_args.join(" ")

  # Create the (empty) tempfiles
  tempfiles = {}
  begin
    # Create the temporary files
    files.each do |file|
      tempfile = Tempfile.new(file.name)
      tempfiles[tempfile] = { file: file }
    end
  rescue
    destroy_tempfiles(files)
    raise
  end

  # Create the command
  paths = tempfiles.keys.map(&:path).join(" ")
  if config[:replace_all]
    final_command = command.gsub(config[:replace_all], paths)
  elsif config[:replace_first]
    final_command = command.sub(config[:replace_first], paths)
  else
    final_command = "#{command} #{paths}"
  end

  [final_command, tempfiles]
end

#destroy_tempfiles(tempfiles) ⇒ Object



198
199
200
201
# File 'lib/chef/knife/xargs.rb', line 198

def destroy_tempfiles(tempfiles)
  # Unlink the files now that we're done with them
  tempfiles.each_key(&:close!)
end

#get_patternsObject



158
159
160
161
162
163
164
165
166
167
# File 'lib/chef/knife/xargs.rb', line 158

def get_patterns
  if config[:patterns]
    [ config[:patterns] ].flatten
  elsif config[:null_separator]
    stdin.binmode
    stdin.read.split("\000")
  else
    stdin.read.split(/\s+/)
  end
end

#runObject



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
147
148
149
150
151
152
153
154
155
156
# File 'lib/chef/knife/xargs.rb', line 89

def run
  error = false
  # Get the matches (recursively)
  files = []
  pattern_args_from(get_patterns).each do |pattern|
    Chef::ChefFS::FileSystem.list(config[:local] ? local_fs : chef_fs, pattern).each do |result|
      if result.dir?
        # TODO option to include directories
        ui.warn "#{format_path(result)}: is a directory. Will not run #{command} on it."
      else
        files << result
        ran = false

        # If the command would be bigger than max command line, back it off a bit
        # and run a slightly smaller command (with one less arg)
        if config[:max_command_line]
          command, tempfiles = create_command(files)
          begin
            if command.length > config[:max_command_line].to_i
              if files.length > 1
                command, tempfiles_minus_one = create_command(files[0..-2])
                begin
                  error = true if xargs_files(command, tempfiles_minus_one)
                  files = [ files[-1] ]
                  ran = true
                ensure
                  destroy_tempfiles(tempfiles)
                end
              else
                error = true if xargs_files(command, tempfiles)
                files = [ ]
                ran = true
              end
            end
          ensure
            destroy_tempfiles(tempfiles)
          end
        end

        # If the command has hit the limit for the # of arguments, run it
        if !ran && config[:max_arguments_per_command] && files.size >= config[:max_arguments_per_command].to_i
          command, tempfiles = create_command(files)
          begin
            error = true if xargs_files(command, tempfiles)
            files = []
            ran = true
          ensure
            destroy_tempfiles(tempfiles)
          end
        end
      end
    end
  end

  # Any leftovers commands shall be run
  if files.size > 0
    command, tempfiles = create_command(files)
    begin
      error = true if xargs_files(command, tempfiles)
    ensure
      destroy_tempfiles(tempfiles)
    end
  end

  if error
    exit 1
  end
end

#sub_filenames(str, tempfiles) ⇒ Object



273
274
275
276
277
278
# File 'lib/chef/knife/xargs.rb', line 273

def sub_filenames(str, tempfiles)
  tempfiles.each_pair do |tempfile, file|
    str = str.gsub(tempfile.path, format_path(file[:file]))
  end
  str
end

#xargs_files(command, tempfiles) ⇒ Object



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
# File 'lib/chef/knife/xargs.rb', line 203

def xargs_files(command, tempfiles)
  error = false
  # Create the temporary files
  tempfiles.each_pair do |tempfile, file|
    begin
      value = file[:file].read
      file[:value] = value
      tempfile.open
      tempfile.write(value)
      tempfile.close
    rescue Chef::ChefFS::FileSystem::OperationNotAllowedError => e
      ui.error "#{format_path(e.entry)}: #{e.reason}."
      error = true
      tempfile.close!
      tempfiles.delete(tempfile)
      next
    rescue Chef::ChefFS::FileSystem::NotFoundError => e
      ui.error "#{format_path(e.entry)}: No such file or directory"
      error = true
      tempfile.close!
      tempfiles.delete(tempfile)
      next
    end
  end

  return error if error && tempfiles.size == 0

  # Run the command
  if config[:verbose_commands] || Chef::Config[:verbosity] && Chef::Config[:verbosity] >= 1
    output sub_filenames(command, tempfiles)
  end
  command_output = `#{command}`
  command_output = sub_filenames(command_output, tempfiles)
  stdout.write command_output

  # Check if the output is different
  tempfiles.each_pair do |tempfile, file|
    # Read the new output
    new_value = IO.binread(tempfile.path)

    # Upload the output if different
    if config[:force] || new_value != file[:value]
      if config[:dry_run]
        output "Would update #{format_path(file[:file])}"
      else
        file[:file].write(new_value)
        output "Updated #{format_path(file[:file])}"
      end
    end

    # Print a diff of what was uploaded
    if config[:diff] && new_value != file[:value]
      old_file = Tempfile.open(file[:file].name)
      begin
        old_file.write(file[:value])
        old_file.close

        diff = `diff -u #{old_file.path} #{tempfile.path}`
        diff.gsub!(old_file.path, "#{format_path(file[:file])} (old)")
        diff.gsub!(tempfile.path, "#{format_path(file[:file])} (new)")
        stdout.write diff
      ensure
        old_file.close!
      end
    end
  end

  error
end