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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ TempFileManager

Returns a new instance of TempFileManager.



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

def initialize
  @created_files = []
  # Number of holders of a created file: not deleted by cleanup while held
  @hold_counts = {}
  # Files are created and released by transfer threads
  @mutex = Mutex.new
  @cleanup_on_exit = true
  @expiry_sec = EXPIRY_DEFAULT_SEC
  @global_temp = Etc.systmpdir
end

Instance Attribute Details

#cleanup_on_exit ⇒ Boolean

Returns true: files created by this execution are deleted by cleanup.

Returns:

  • (Boolean) —

    true: files created by this execution are deleted by cleanup



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

def cleanup_on_exit
  @cleanup_on_exit
end

#expiry_sec ⇒ Numeric?

Returns Age in seconds of files deleted by cleanup_expired, nil: never deleted.

Returns:

  • (Numeric, nil) —

    Age in seconds of files deleted by cleanup_expired, nil: never deleted



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

def expiry_sec
  @expiry_sec
end

#global_temp ⇒ Object

Returns the value of attribute global_temp.



33
34
35
# File 'lib/aspera/temp_file_manager.rb', line 33

def global_temp
  @global_temp
end

Class Method Details

.instance ⇒ TempFileManager

Returns the singleton instance of TempFileManager

Returns:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/aspera/temp_file_manager.rb', line 21

class TempFileManager
  include Singleton

  # Assume no transfer lasts longer than this
  # (garbage collect file lists which were not deleted after transfer)
  EXPIRY_DEFAULT_SEC = 5 * 86_400
  private_constant :EXPIRY_DEFAULT_SEC

  # @return [Boolean] `true`: files created by this execution are deleted by `cleanup`
  attr_accessor :cleanup_on_exit
  # @return [Numeric, nil] Age in seconds of files deleted by `cleanup_expired`, `nil`: never deleted
  attr_reader :expiry_sec
  attr_reader :global_temp

  def initialize
    @created_files = []
    # Number of holders of a created file: not deleted by cleanup while held
    @hold_counts = {}
    # Files are created and released by transfer threads
    @mutex = Mutex.new
    @cleanup_on_exit = true
    @expiry_sec = EXPIRY_DEFAULT_SEC
    @global_temp = Etc.systmpdir
  end

  # @param value [Numeric, nil] Age in seconds, `0`: all files, `nil`: never delete
  def expiry_sec=(value)
    Aspera.assert(value.nil? || (value.is_a?(Numeric) && !value.negative?), type: ParameterError) { "Expiry must be a positive duration: #{value}" }
    @expiry_sec = value
  end

  def global_temp=(value)
    @global_temp = case value
    when '@env' then Dir.tmpdir
    when '@sys' then Etc.systmpdir
    else value
    end
  end

  def delete_file(filepath)
    remove_file(filepath) if @cleanup_on_exit
  end

  # Call this on process exit, or at the end of a command.
  # Held files are kept: they are deleted when released.
  def cleanup
    @mutex.synchronize do
      @created_files.each do |filepath|
        delete_file(filepath) if !@hold_counts.key?(filepath) && File.file?(filepath)
      end
      @created_files.select! { |filepath| @hold_counts.key?(filepath) }
    end
  end

  # Keep created files after `cleanup`, until released, for example a file list used by a transfer
  # that ends after the command (asynchronous transfer).
  # A file can be held several times (multi-session): it is deleted when the last holder releases it.
  # @param paths [Array<String>] Files created by this manager (others are ignored)
  def hold(paths)
    @mutex.synchronize do
      paths.each do |filepath|
        @hold_counts[filepath] = @hold_counts.fetch(filepath, 0) + 1 if @created_files.include?(filepath)
      end
    end
  end

  # Release files held with `hold`, and delete those that are no longer held.
  # @param paths [Array<String>] Files given to `hold`
  def release(paths)
    @mutex.synchronize do
      paths.each do |filepath|
        next unless @hold_counts.key?(filepath)
        @hold_counts[filepath] -= 1
        next if @hold_counts[filepath].positive?
        @hold_counts.delete(filepath)
        @created_files.delete(filepath)
        delete_file(filepath) if File.file?(filepath)
      end
    end
  end

  # Ensure that provided folder exists, or create it, atomically create and reserve a unique file.
  # The file is created immediately (O_EXCL) to prevent TOCTOU race conditions.
  # @return [String] path to that unique file
  def new_file_path_in_folder(temp_folder, prefix: nil, suffix: nil)
    FileUtils.mkdir_p(temp_folder)
    basename = [prefix || 'aspera', SecureRandom.uuid].join('-')
    # Create the file atomically with O_EXCL (retry with another name if it exists)
    # Note: Tempfile is not used, as its file is deleted when the object is garbage collected
    new_file = Dir::Tmpname.create([basename, suffix ? "-#{suffix}" : ''], temp_folder) do |path|
      File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { nil }
    end
    @mutex.synchronize { @created_files.push(new_file) }
    new_file
  end

  # Same as above but in global temp folder, with user's name
  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

  # Generate a unique directory path inside the global temp folder (does NOT create it).
  # Unlike new_file_path_global, the caller is expected to use the path as a directory.
  # @return [String] path to a unique (not yet existing) directory
  def new_dir_path_global(prefix = nil)
    username =
      begin
        Etc.getlogin || Etc.getpwuid(::Process.uid).name || 'unknown_user'
      rescue StandardError
        'unknown_user'
      end
    dir_name = [prefix, username, SecureRandom.uuid].compact.join('-')
    File.join(@global_temp, dir_name)
  end

  # Garbage collect files not deleted by previous executions (e.g. killed), older than `expiry_sec`.
  # Not disabled by `cleanup_on_exit`, which applies to files of this execution.
  # @param temp_folder [String] Folder that contains only temporary files
  def cleanup_expired(temp_folder)
    return if @expiry_sec.nil?
    now = Time.now
    Dir.children(temp_folder).each do |name|
      file_path = File.join(temp_folder, name)
      # check age of file, delete too old
      next unless File.file?(file_path) && (now - File.mtime(file_path)) >= @expiry_sec
      Log.log.debug { "garbage collecting #{name}" }
      remove_file(file_path)
    rescue Errno::ENOENT
      # deleted meanwhile by another execution
      nil
    end
  end

  private

  # Delete a file, a failure is logged
  def remove_file(filepath)
    File.delete(filepath)
  rescue Errno::ENOENT
    nil
  rescue => e
    Log.log.warn { "Problem deleting file: #{filepath}: #{e.message}" }
  end
end

Instance Method Details

#cleanup ⇒ Object

Call this on process exit, or at the end of a command. Held files are kept: they are deleted when released.



66
67
68
69
70
71
72
73
# File 'lib/aspera/temp_file_manager.rb', line 66

def cleanup
  @mutex.synchronize do
    @created_files.each do |filepath|
      delete_file(filepath) if !@hold_counts.key?(filepath) && File.file?(filepath)
    end
    @created_files.select! { |filepath| @hold_counts.key?(filepath) }
  end
end

#cleanup_expired(temp_folder) ⇒ Object

Garbage collect files not deleted by previous executions (e.g. killed), older than expiry_sec. Not disabled by cleanup_on_exit, which applies to files of this execution.

Parameters:

  • temp_folder (String) —

    Folder that contains only temporary files



146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/aspera/temp_file_manager.rb', line 146

def cleanup_expired(temp_folder)
  return if @expiry_sec.nil?
  now = Time.now
  Dir.children(temp_folder).each do |name|
    file_path = File.join(temp_folder, name)
    # check age of file, delete too old
    next unless File.file?(file_path) && (now - File.mtime(file_path)) >= @expiry_sec
    Log.log.debug { "garbage collecting #{name}" }
    remove_file(file_path)
  rescue Errno::ENOENT
    # deleted meanwhile by another execution
    nil
  end
end

#delete_file(filepath) ⇒ Object



60
61
62
# File 'lib/aspera/temp_file_manager.rb', line 60

def delete_file(filepath)
  remove_file(filepath) if @cleanup_on_exit
end

#hold(paths) ⇒ Object

Keep created files after cleanup, until released, for example a file list used by a transfer that ends after the command (asynchronous transfer). A file can be held several times (multi-session): it is deleted when the last holder releases it.

Parameters:

  • paths (Array<String>) —

    Files created by this manager (others are ignored)



79
80
81
82
83
84
85
# File 'lib/aspera/temp_file_manager.rb', line 79

def hold(paths)
  @mutex.synchronize do
    paths.each do |filepath|
      @hold_counts[filepath] = @hold_counts.fetch(filepath, 0) + 1 if @created_files.include?(filepath)
    end
  end
end

#new_dir_path_global(prefix = nil) ⇒ String

Generate a unique directory path inside the global temp folder (does NOT create it). Unlike new_file_path_global, the caller is expected to use the path as a directory.

Returns:

  • (String) —

    path to a unique (not yet existing) directory



132
133
134
135
136
137
138
139
140
141
# File 'lib/aspera/temp_file_manager.rb', line 132

def new_dir_path_global(prefix = nil)
  username =
    begin
      Etc.getlogin || Etc.getpwuid(::Process.uid).name || 'unknown_user'
    rescue StandardError
      'unknown_user'
    end
  dir_name = [prefix, username, SecureRandom.uuid].compact.join('-')
  File.join(@global_temp, dir_name)
end

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

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



118
119
120
121
122
123
124
125
126
127
# File 'lib/aspera/temp_file_manager.rb', line 118

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) ⇒ String

Ensure that provided folder exists, or create it, atomically create and reserve a unique file. The file is created immediately (O_EXCL) to prevent TOCTOU race conditions.

Returns:

  • (String) —

    path to that unique file



105
106
107
108
109
110
111
112
113
114
115
# File 'lib/aspera/temp_file_manager.rb', line 105

def new_file_path_in_folder(temp_folder, prefix: nil, suffix: nil)
  FileUtils.mkdir_p(temp_folder)
  basename = [prefix || 'aspera', SecureRandom.uuid].join('-')
  # Create the file atomically with O_EXCL (retry with another name if it exists)
  # Note: Tempfile is not used, as its file is deleted when the object is garbage collected
  new_file = Dir::Tmpname.create([basename, suffix ? "-#{suffix}" : ''], temp_folder) do |path|
    File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { nil }
  end
  @mutex.synchronize { @created_files.push(new_file) }
  new_file
end

#release(paths) ⇒ Object

Release files held with hold, and delete those that are no longer held.

Parameters:

  • paths (Array<String>) —

    Files given to hold



89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/aspera/temp_file_manager.rb', line 89

def release(paths)
  @mutex.synchronize do
    paths.each do |filepath|
      next unless @hold_counts.key?(filepath)
      @hold_counts[filepath] -= 1
      next if @hold_counts[filepath].positive?
      @hold_counts.delete(filepath)
      @created_files.delete(filepath)
      delete_file(filepath) if File.file?(filepath)
    end
  end
end