Class: S3Inventory

Inherits:
Object
  • Object
show all
Defined in:
lib/s3_inventory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(s3_helper, type, preloaded_inventory_file: nil, preloaded_inventory_date: nil) ⇒ S3Inventory

Returns a new instance of S3Inventory.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/s3_inventory.rb', line 15

def initialize(s3_helper, type, preloaded_inventory_file: nil, preloaded_inventory_date: nil)
  @s3_helper = s3_helper

  if preloaded_inventory_file && preloaded_inventory_date
    # Data preloaded, so we don't need to fetch it again
    @preloaded_inventory_file = preloaded_inventory_file
    @inventory_date = preloaded_inventory_date
  end

  if type == :upload
    @type = "original"
    @model = Upload
  elsif type == :optimized
    @type = "optimized"
    @model = OptimizedImage
  end
end

Instance Attribute Details

#inventory_dateObject (readonly)

Returns the value of attribute inventory_date.



7
8
9
# File 'lib/s3_inventory.rb', line 7

def inventory_date
  @inventory_date
end

#modelObject (readonly)

Returns the value of attribute model.



7
8
9
# File 'lib/s3_inventory.rb', line 7

def model
  @model
end

#typeObject (readonly)

Returns the value of attribute type.



7
8
9
# File 'lib/s3_inventory.rb', line 7

def type
  @type
end

Instance Method Details

#backfill_etags_and_list_missingObject



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

def backfill_etags_and_list_missing
  if !@preloaded_inventory_file && files.blank?
    error("Failed to list inventory from S3")
    return
  end

  DistributedMutex.synchronize("s3_inventory_list_missing_#{type}", validity: 30.minutes) do
    begin
      download_and_decompress_files if !@preloaded_inventory_file

      multisite_prefix = Discourse.store.upload_path
      ActiveRecord::Base.transaction do
        begin
          connection.exec(
            "CREATE TEMP TABLE #{table_name}(url text UNIQUE, etag text, PRIMARY KEY(etag, url))",
          )
          connection.copy_data("COPY #{table_name} FROM STDIN CSV") do
            for_each_inventory_row do |row|
              key = row[CSV_KEY_INDEX]

              next if Rails.configuration.multisite && key.exclude?(multisite_prefix)
              next if key.exclude?("#{type}/")

              url = File.join(Discourse.store.absolute_base_url, key)
              connection.put_copy_data("#{url},#{row[CSV_ETAG_INDEX]}\n")
            end
          end

          # backfilling etags
          connection.async_exec(
            "UPDATE #{model.table_name}
            SET etag = #{table_name}.etag
            FROM #{table_name}
            WHERE #{model.table_name}.etag IS NULL AND
              #{model.table_name}.url = #{table_name}.url",
          )

          uploads = model.where("updated_at < ?", inventory_date)
          uploads = uploads.by_users if model == Upload

          missing_uploads =
            uploads.joins(
              "LEFT JOIN #{table_name} ON #{table_name}.etag = #{model.table_name}.etag",
            ).where("#{table_name}.etag IS NULL")

          exists_with_different_etag =
            missing_uploads
              .joins(
                "LEFT JOIN #{table_name} inventory2 ON inventory2.url = #{model.table_name}.url",
              )
              .where("inventory2.etag IS NOT NULL")
              .pluck(:id)

          # marking as verified/not verified
          if model == Upload
            sql_params = {
              inventory_date: inventory_date,
              invalid_etag: Upload.verification_statuses[:invalid_etag],
              verified: Upload.verification_statuses[:verified],
              seeded_id_threshold: model::SEEDED_ID_THRESHOLD,
            }

            DB.exec(<<~SQL, sql_params)
              UPDATE #{model.table_name}
              SET verification_status = :verified
              WHERE etag IS NOT NULL
                AND verification_status <> :verified
                AND updated_at < :inventory_date
                AND id > :seeded_id_threshold
                AND EXISTS
                  (
                      SELECT 1
                      FROM #{table_name}
                      WHERE #{table_name}.etag = #{model.table_name}.etag
                  )
            SQL

            DB.exec(<<~SQL, sql_params)
              UPDATE #{model.table_name}
              SET verification_status = :invalid_etag
              WHERE verification_status <> :invalid_etag
                AND updated_at < :inventory_date
                AND id > :seeded_id_threshold
                AND NOT EXISTS
                  (
                      SELECT 1
                      FROM #{table_name}
                      WHERE #{table_name}.etag = #{model.table_name}.etag
                  )
            SQL
          end

          if (missing_count = missing_uploads.count) > 0
            missing_uploads
              .select(:id, :url)
              .find_each do |upload|
                if exists_with_different_etag.include?(upload.id)
                  log "#{upload.url} has different etag"
                else
                  log upload.url
                end
              end

            log "#{missing_count} of #{uploads.count} #{model.name.underscore.pluralize} are missing"
            if exists_with_different_etag.present?
              log "#{exists_with_different_etag.count} of these are caused by differing etags"
              log "Null the etag column and re-run for automatic backfill"
            end
          end

          Discourse.stats.set("missing_s3_#{model.table_name}", missing_count)
        ensure
          connection.exec("DROP TABLE #{table_name}") unless connection.nil?
        end
      end
    ensure
      cleanup!
    end
  end
end

#decompress_inventory_file(file) ⇒ Object



171
172
173
174
175
176
177
178
179
180
# File 'lib/s3_inventory.rb', line 171

def decompress_inventory_file(file)
  log "Decompressing inventory file '#{file[:filename]}', this may take a while..."
  Discourse::Utils.execute_command(
    "gzip",
    "--decompress",
    file[:filename],
    failure_message: "Failed to decompress inventory file '#{file[:filename]}'.",
    chdir: tmp_directory,
  )
end

#download_inventory_file_to_tmp_directory(file) ⇒ Object



162
163
164
165
166
167
168
169
# File 'lib/s3_inventory.rb', line 162

def download_inventory_file_to_tmp_directory(file)
  return if File.exist?(file[:filename])

  log "Downloading inventory file '#{file[:key]}' to tmp directory..."
  failure_message = "Failed to inventory file '#{file[:key]}' to tmp directory."

  @s3_helper.download_file(file[:key], file[:filename], failure_message)
end

#for_each_inventory_rowObject



154
155
156
157
158
159
160
# File 'lib/s3_inventory.rb', line 154

def for_each_inventory_row
  if @preloaded_inventory_file
    CSV.foreach(@preloaded_inventory_file) { |row| yield(row) }
  else
    files.each { |file| CSV.foreach(file[:filename][0...-3]) { |row| yield(row) } }
  end
end

#prepare_for_all_sitesObject



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/s3_inventory.rb', line 219

def prepare_for_all_sites
  db_names = RailsMultisite::ConnectionManagement.all_dbs
  db_files = {}

  db_names.each { |db| db_files[db] = Tempfile.new("#{db}-inventory.csv") }

  download_and_decompress_files
  for_each_inventory_row do |row|
    key = row[CSV_KEY_INDEX]
    row_db = key.match(%r{uploads/([^/]+)/})&.[](1)
    if row_db && file = db_files[row_db]
      file.write(row.to_csv)
    end
  end

  db_names.each { |db| db_files[db].rewind }

  db_files
ensure
  cleanup!
end

#update_bucket_inventory_configurationObject



210
211
212
213
214
215
216
217
# File 'lib/s3_inventory.rb', line 210

def update_bucket_inventory_configuration
  @s3_helper.s3_client.put_bucket_inventory_configuration(
    bucket: bucket_name,
    id: inventory_id,
    inventory_configuration: inventory_configuration,
    use_accelerate_endpoint: false,
  )
end

#update_bucket_policyObject



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/s3_inventory.rb', line 182

def update_bucket_policy
  @s3_helper.s3_client.put_bucket_policy(
    bucket: bucket_name,
    policy: {
      Version: "2012-10-17",
      Statement: [
        {
          Sid: "InventoryAndAnalyticsPolicy",
          Effect: "Allow",
          Principal: {
            Service: "s3.amazonaws.com",
          },
          Action: ["s3:PutObject"],
          Resource: ["#{inventory_path_arn}/*"],
          Condition: {
            ArnLike: {
              "aws:SourceArn": bucket_arn,
            },
            StringEquals: {
              "s3:x-amz-acl": "bucket-owner-full-control",
            },
          },
        },
      ],
    }.to_json,
  )
end