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



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

def initialize
  @created_files = []
  @cleanup_on_exit = true
  @global_temp = Etc.systmpdir
end

Instance Attribute Details

#cleanup_on_exitObject

Returns the value of attribute cleanup_on_exit.



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

def cleanup_on_exit
  @cleanup_on_exit
end

#global_tempObject

Returns the value of attribute global_temp.



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

def global_temp
  @global_temp
end

Instance Method Details

#cleanupObject

Call this on process exit



43
44
45
46
47
48
# File 'lib/aspera/temp_file_manager.rb', line 43

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

#cleanup_expired(temp_folder) ⇒ Object

Garbage collect undeleted files



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/aspera/temp_file_manager.rb', line 72

def cleanup_expired(temp_folder)
  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



36
37
38
39
40
# File 'lib/aspera/temp_file_manager.rb', line 36

def delete_file(filepath)
  File.delete(filepath) if @cleanup_on_exit
rescue => e
  Log.log.warn{"Problem deleting file: #{filepath}: #{e.message}"}
end

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

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



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

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(@global_temp, 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



52
53
54
55
56
57
# File 'lib/aspera/temp_file_manager.rb', line 52

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