Class: Aspera::TempFileManager

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/aspera/temp_file_manager.rb

Overview

create a temp file name for a given folder files can be deleted on process exit by calling cleanup

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTempFileManager



19
20
21
22
# File 'lib/aspera/temp_file_manager.rb', line 19

def initialize
  @created_files = []
  @cleanup_on_exit = true
end

Instance Attribute Details

#cleanup_on_exitObject

Returns the value of attribute cleanup_on_exit.



17
18
19
# File 'lib/aspera/temp_file_manager.rb', line 17

def cleanup_on_exit
  @cleanup_on_exit
end

Instance Method Details

#cleanupObject

call this on process exit



29
30
31
32
33
34
# File 'lib/aspera/temp_file_manager.rb', line 29

def cleanup
  @created_files.each do |filepath|
    delete_file(filepath) if File.file?(filepath)
  end
  @created_files = []
end

#cleanup_expired(temp_folder) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/aspera/temp_file_manager.rb', line 57

def cleanup_expired(temp_folder)
  # garbage collect undeleted files
  Dir.entries(temp_folder).each do |name|
    file_path = File.join(temp_folder, name)
    age_sec = (Time.now - File.stat(file_path).mtime).to_i
    # check age of file, delete too old
    if File.file?(file_path) && (age_sec > FILE_LIST_AGE_MAX_SEC)
      Log.log.debug{"garbage collecting #{name}"}
      delete_file(file_path)
    end
  end
end

#delete_file(filepath) ⇒ Object



24
25
26
# File 'lib/aspera/temp_file_manager.rb', line 24

def delete_file(filepath)
  File.delete(filepath) if @cleanup_on_exit
end

#new_file_path_global(prefix = nil, suffix: nil) ⇒ Object

same as above but in global temp folder, with user’s name



46
47
48
49
50
51
52
53
54
55
# File 'lib/aspera/temp_file_manager.rb', line 46

def new_file_path_global(prefix=nil, suffix: nil)
  username =
    begin
      Etc.getlogin || Etc.getpwuid(Process.uid).name || 'unknown_user'
    rescue StandardError
      'unknown_user'
    end
  prefix = [prefix, username].compact.join('-')
  new_file_path_in_folder(Etc.systmpdir, prefix: prefix, suffix: suffix)
end

#new_file_path_in_folder(temp_folder, prefix: nil, suffix: nil) ⇒ Object

ensure that provided folder exists, or create it, generate a unique filename



38
39
40
41
42
43
# File 'lib/aspera/temp_file_manager.rb', line 38

def new_file_path_in_folder(temp_folder, prefix: nil, suffix: nil)
  FileUtils.mkdir_p(temp_folder)
  new_file = File.join(temp_folder, [prefix, SecureRandom.uuid, suffix].compact.join('-'))
  @created_files.push(new_file)
  new_file
end