summaryrefslogtreecommitdiff
path: root/java/com/google/android/libraries/mobiledatadownload/internal/downloader/DownloaderCallbackImpl.java
blob: bd784b39e93c958029a6eea6709f6702d4e4509a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
197
198
199
200
201
202
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.libraries.mobiledatadownload.internal.downloader;

import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.immediateVoidFuture;

import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import androidx.annotation.VisibleForTesting;
import com.google.android.libraries.mobiledatadownload.DownloadException;
import com.google.android.libraries.mobiledatadownload.DownloadException.DownloadResultCode;
import com.google.android.libraries.mobiledatadownload.Flags;
import com.google.android.libraries.mobiledatadownload.file.SynchronousFileStorage;
import com.google.android.libraries.mobiledatadownload.file.openers.ReadStreamOpener;
import com.google.android.libraries.mobiledatadownload.file.openers.RecursiveSizeOpener;
import com.google.android.libraries.mobiledatadownload.file.openers.WriteStreamOpener;
import com.google.android.libraries.mobiledatadownload.file.transforms.TransformProtos;
import com.google.android.libraries.mobiledatadownload.internal.SharedFilesMetadata;
import com.google.android.libraries.mobiledatadownload.internal.downloader.MddFileDownloader.DownloaderCallback;
import com.google.android.libraries.mobiledatadownload.internal.logging.EventLogger;
import com.google.android.libraries.mobiledatadownload.internal.logging.LogUtil;
import com.google.android.libraries.mobiledatadownload.internal.util.FileGroupUtil;
import com.google.android.libraries.mobiledatadownload.tracing.PropagatedFluentFuture;
import com.google.android.libraries.mobiledatadownload.tracing.PropagatedFutures;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.mobiledatadownload.LogEnumsProto.MddClientEvent;
import com.google.mobiledatadownload.LogProto.DataDownloadFileGroupStats;
import com.google.mobiledatadownload.internal.MetadataProto.DataFile;
import com.google.mobiledatadownload.internal.MetadataProto.DataFileGroupInternal.AllowedReaders;
import com.google.mobiledatadownload.internal.MetadataProto.FileStatus;
import com.google.mobiledatadownload.internal.MetadataProto.GroupKey;
import com.google.mobiledatadownload.internal.MetadataProto.NewFileKey;
import com.google.mobiledatadownload.internal.MetadataProto.SharedFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executor;

/**
 * Impl for {@link DownloaderCallback}, that is called by the file downloader on download complete
 * or failed events
 */
public class DownloaderCallbackImpl implements DownloaderCallback {

  private static final String TAG = "DownloaderCallbackImpl";

  private final SharedFilesMetadata sharedFilesMetadata;
  private final SynchronousFileStorage fileStorage;
  private final DataFile dataFile;
  private final AllowedReaders allowedReaders;
  private final String checksum;
  private final EventLogger eventLogger;
  private final GroupKey groupKey;
  private final int fileGroupVersionNumber;
  private final long buildId;
  private final String variantId;
  private final Flags flags;
  private final Executor sequentialControlExecutor;

  public DownloaderCallbackImpl(
      SharedFilesMetadata sharedFilesMetadata,
      SynchronousFileStorage fileStorage,
      DataFile dataFile,
      AllowedReaders allowedReaders,
      EventLogger eventLogger,
      GroupKey groupKey,
      int fileGroupVersionNumber,
      long buildId,
      String variantId,
      Flags flags,
      Executor sequentialControlExecutor) {
    this.sharedFilesMetadata = sharedFilesMetadata;
    this.fileStorage = fileStorage;
    this.dataFile = dataFile;
    this.allowedReaders = allowedReaders;
    checksum = FileGroupUtil.getFileChecksum(dataFile);
    this.eventLogger = eventLogger;
    this.groupKey = groupKey;
    this.fileGroupVersionNumber = fileGroupVersionNumber;
    this.buildId = buildId;
    this.variantId = variantId;
    this.flags = flags;
    this.sequentialControlExecutor = sequentialControlExecutor;
  }

  @Override
  public ListenableFuture<Void> onDownloadComplete(Uri fileUri) {
    LogUtil.d("%s: Successfully downloaded file %s", TAG, checksum);

    // Use DownloadedFileChecksum to verify downloaded file integrity if the file has Download
    // Transforms
    String downloadedFileChecksum =
        dataFile.hasDownloadTransforms()
            ? dataFile.getDownloadedFileChecksum()
            : dataFile.getChecksum();

    try {
      FileValidator.validateDownloadedFile(fileStorage, dataFile, fileUri, downloadedFileChecksum);

      if (dataFile.hasDownloadTransforms()) {
        handleDownloadTransform(fileUri);
      }
    } catch (DownloadException exception) {
      if (exception
          .getDownloadResultCode()
          .equals(DownloadResultCode.DOWNLOADED_FILE_CHECKSUM_MISMATCH_ERROR)) {
        // File was downloaded successfully, but failed checksum mismatch error. Attempt to delete
        // the file, then fail with the given exception.
        return PropagatedFluentFuture.from(
                maybeDeleteFileOnChecksumMismatch(
                    sharedFilesMetadata,
                    dataFile,
                    allowedReaders,
                    fileStorage,
                    fileUri,
                    checksum,
                    eventLogger,
                    flags,
                    sequentialControlExecutor))
            .catchingAsync(
                IOException.class,
                ioException -> {
                  // Delete on checksum failed, add it as a suppressed exception if supported (API
                  // level 19 or higher).
                  if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
                    exception.addSuppressed(ioException);
                  }
                  return immediateVoidFuture();
                },
                sequentialControlExecutor)
            .transformAsync(unused -> immediateFailedFuture(exception), sequentialControlExecutor);
      }
      return immediateFailedFuture(exception);
    }

    return updateFileStatus(
        FileStatus.DOWNLOAD_COMPLETE,
        dataFile,
        allowedReaders,
        sharedFilesMetadata,
        sequentialControlExecutor);
  }

  @Override
  public ListenableFuture<Void> onDownloadFailed(DownloadException exception) {
    LogUtil.d("%s: Failed to download file %s", TAG, checksum);
    if (exception
        .getDownloadResultCode()
        .equals(DownloadResultCode.DOWNLOADED_FILE_CHECKSUM_MISMATCH_ERROR)) {
      return updateFileStatus(
          FileStatus.CORRUPTED,
          dataFile,
          allowedReaders,
          sharedFilesMetadata,
          sequentialControlExecutor);
    }
    return updateFileStatus(
        FileStatus.DOWNLOAD_FAILED,
        dataFile,
        allowedReaders,
        sharedFilesMetadata,
        sequentialControlExecutor);
  }

  private void handleDownloadTransform(Uri downloadedFileUri) throws DownloadException {
    if (!dataFile.hasDownloadTransforms()) {
      return;
    }
    Uri finalFileUri = FileNameUtil.getFinalFileUriWithTempDownloadedFile(downloadedFileUri);
    if (FileGroupUtil.hasZipDownloadTransform(dataFile)) {
      applyZipDownloadTransforms(
          eventLogger,
          fileStorage,
          downloadedFileUri,
          finalFileUri,
          groupKey,
          fileGroupVersionNumber,
          buildId,
          variantId,
          dataFile.getFileId());
    } else {
      handleNonZipDownloadTransform(downloadedFileUri, finalFileUri);
    }
  }

  private void handleNonZipDownloadTransform(Uri downloadedFileUri, Uri finalFileUri)
      throws DownloadException {
    Uri downloadFileUriWithTransform;
    try {
      downloadFileUriWithTransform =
          downloadedFileUri
              .buildUpon()
              .encodedFragment(TransformProtos.toEncodedFragment(dataFile.getDownloadTransforms()))
              .build();
    } catch (IllegalArgumentException e) {
      LogUtil.e(e, "%s: Exception while trying to serialize download transform", TAG);
      throw DownloadException.builder()
          .setDownloadResultCode(DownloadResultCode.UNABLE_TO_SERIALIZE_DOWNLOAD_TRANSFORM_ERROR)
          .setCause(e)
          .build();
    }
    applyDownloadTransforms(
        eventLogger,
        fileStorage,
        downloadFileUriWithTransform,
        finalFileUri,
        groupKey,
        fileGroupVersionNumber,
        buildId,
        variantId,
        dataFile);
    // Verify original checksum if provided.
    if (dataFile.getChecksumType() != DataFile.ChecksumType.NONE
        && !FileValidator.verifyChecksum(fileStorage, finalFileUri, checksum)) {
      LogUtil.e("%s: Final file checksum verification failed. %s.", TAG, finalFileUri);
      throw DownloadException.builder()
          .setDownloadResultCode(DownloadResultCode.FINAL_FILE_CHECKSUM_MISMATCH_ERROR)
          .build();
    }
  }

  @VisibleForTesting
  static void applyDownloadTransforms(
      EventLogger eventLogger,
      SynchronousFileStorage fileStorage,
      Uri source,
      Uri target,
      GroupKey groupKey,
      int fileGroupVersionNumber,
      long buildId,
      String variantId,
      DataFile dataFile)
      throws DownloadException {

    try (InputStream in = fileStorage.open(source, ReadStreamOpener.create());
        OutputStream out = fileStorage.open(target, WriteStreamOpener.create())) {
      ByteStreams.copy(in, out);
    } catch (IOException ioe) {
      LogUtil.e(ioe, "%s: Failed to apply download transform for file %s.", TAG, source);
      throw DownloadException.builder()
          .setDownloadResultCode(DownloadResultCode.DOWNLOAD_TRANSFORM_IO_ERROR)
          .setCause(ioe)
          .build();
    }
    try {
      if (FileGroupUtil.hasCompressDownloadTransform(dataFile)) {
        long fullFileSize = fileStorage.fileSize(target);
        long downloadedFileSize = fileStorage.fileSize(source);
        if (fullFileSize > downloadedFileSize) {
          DataDownloadFileGroupStats fileGroupStats =
              DataDownloadFileGroupStats.newBuilder()
                  .setFileGroupName(groupKey.getGroupName())
                  .setFileGroupVersionNumber(fileGroupVersionNumber)
                  .setBuildId(buildId)
                  .setVariantId(variantId)
                  .setOwnerPackage(groupKey.getOwnerPackage())
                  .build();
          eventLogger.logMddNetworkSavings(
              fileGroupStats,
              0,
              fullFileSize,
              downloadedFileSize,
              dataFile.getFileId(),
              /* deltaIndex= */ 0);
        }
      }
      fileStorage.deleteFile(source);
    } catch (IOException ioe) {
      // Ignore if fails to log file size or delete the temp compress file, as it will eventually
      // be garbage collected.
      LogUtil.d(ioe, "%s: Failed to get file size or delete compress file %s.", TAG, source);
    }
  }

  @VisibleForTesting
  static void applyZipDownloadTransforms(
      EventLogger eventLogger,
      SynchronousFileStorage fileStorage,
      Uri source,
      Uri target,
      GroupKey groupKey,
      int fileGroupVersionNumber,
      long buildId,
      String variantId,
      String fileId)
      throws DownloadException {

    try {
      fileStorage.open(source, ZipFolderOpener.create(target));
    } catch (IOException ioe) {
      LogUtil.e(ioe, "%s: Failed to apply zip download transform for file %s.", TAG, source);
      throw DownloadException.builder()
          .setDownloadResultCode(DownloadResultCode.DOWNLOAD_TRANSFORM_IO_ERROR)
          .setCause(ioe)
          .build();
    }
    try {
      DataDownloadFileGroupStats fileGroupStats =
          DataDownloadFileGroupStats.newBuilder()
              .setFileGroupName(groupKey.getGroupName())
              .setFileGroupVersionNumber(fileGroupVersionNumber)
              .setBuildId(buildId)
              .setVariantId(variantId)
              .setOwnerPackage(groupKey.getOwnerPackage())
              .build();
      eventLogger.logMddNetworkSavings(
          fileGroupStats,
          0,
          getFileOrDirectorySize(fileStorage, target),
          fileStorage.fileSize(source),
          fileId,
          0);
      // Delete the zip file only if unzip successfully to avoid re-download
      fileStorage.deleteFile(source);
    } catch (IOException ioe) {
      // Ignore if fails to log file size or delete the temp zip file, as it will eventually be
      // garbage collected.
      LogUtil.d(ioe, "%s: Failed to get file size or delete zip file %s.", TAG, source);
    }
  }

  private static long getFileOrDirectorySize(SynchronousFileStorage fileStorage, Uri uri)
      throws IOException {
    return fileStorage.open(uri, RecursiveSizeOpener.create());
  }

  /** Get {@link SharedFile} or fail with {@link DownloadException}. */
  private static ListenableFuture<SharedFile> getSharedFileOrFail(
      SharedFilesMetadata sharedFilesMetadata,
      NewFileKey newFileKey,
      Executor sequentialControlExecutor) {
    return PropagatedFutures.transformAsync(
        sharedFilesMetadata.read(newFileKey),
        sharedFile -> {
          // Cannot find the file metadata, fail to update the file status.
          if (sharedFile == null) {
            // TODO(b/131166925): MDD dump should not use lite proto toString.
            LogUtil.e("%s: Shared file not found, newFileKey = %s", TAG, newFileKey);
            return immediateFailedFuture(
                DownloadException.builder()
                    .setDownloadResultCode(DownloadResultCode.SHARED_FILE_NOT_FOUND_ERROR)
                    .build());
          }

          return immediateFuture(sharedFile);
        },
        sequentialControlExecutor);
  }

  /**
   * Maybe delete on-device file after a completed download when a checksum mismatch occurs.
   *
   * <p>When a checksum mismatch occurs after a completed download, it's possible that the data has
   * been corrupted on-disk. In this event, we should delete the on-disk file so it can be
   * redownloaded again in a non-corrupted state.
   *
   * <p>However, it's also possible that a bad config was sent with a wrong checksum. In this event,
   * the on-disk file may not be corrupted, so deleting it could lead to an increase in network
   * bandwidth usage.
   *
   * <p>In order to balance the two cases, MDD will start to delete the on-disk file, but after a
   * certain number of retries, this deletion will be skipped to prevent unnecessary network
   * bandwidth usage.
   *
   * <p>This future may return a failed future with an IOException if attempting to delete the file
   * fails.
   */
  static ListenableFuture<Void> maybeDeleteFileOnChecksumMismatch(
      SharedFilesMetadata sharedFilesMetadata,
      DataFile dataFile,
      AllowedReaders allowedReaders,
      SynchronousFileStorage fileStorage,
      Uri fileUri,
      String checksum,
      EventLogger eventLogger,
      Flags flags,
      Executor sequentialControlExecutor) {
    NewFileKey newFileKey = SharedFilesMetadata.createKeyFromDataFile(dataFile, allowedReaders);
    return PropagatedFluentFuture.from(
            getSharedFileOrFail(sharedFilesMetadata, newFileKey, sequentialControlExecutor))
        .transformAsync(
            sharedFile -> {
              if (sharedFile.getChecksumMismatchRetryDownloadCount()
                  >= flags.downloaderMaxRetryOnChecksumMismatchCount()) {
                LogUtil.d(
                    "%s: Checksum mismatch detected but the has already reached retry limit!"
                        + " Skipping removal for file %s",
                    TAG, checksum);
                eventLogger.logEventSampled(MddClientEvent.Code.EVENT_CODE_UNSPECIFIED);
              } else {
                LogUtil.d(
                    "%s: Removing file and marking as corrupted due to checksum mismatch", TAG);
                try {
                  fileStorage.deleteFile(fileUri);
                } catch (IOException e) {
                  // Deleting the corrupted file is best effort, the next time MDD attempts to
                  // download, we will try again to delete the file. For now, just log this error.
                  LogUtil.e(e, "%s: Failed to remove corrupted file %s", TAG, checksum);
                  return immediateFailedFuture(e);
                }
              }
              return immediateVoidFuture();
            },
            sequentialControlExecutor);
  }

  /**
   * Find the file metadata and update the file status. Throws {@link DownloadException} if the file
   * status failed to be updated.
   */
  static ListenableFuture<Void> updateFileStatus(
      FileStatus fileStatus,
      DataFile dataFile,
      AllowedReaders allowedReaders,
      SharedFilesMetadata sharedFilesMetadata,
      Executor sequentialControlExecutor) {
    NewFileKey newFileKey = SharedFilesMetadata.createKeyFromDataFile(dataFile, allowedReaders);

    return PropagatedFluentFuture.from(
            getSharedFileOrFail(sharedFilesMetadata, newFileKey, sequentialControlExecutor))
        .transformAsync(
            sharedFile -> {
              SharedFile.Builder sharedFileBuilder =
                  sharedFile.toBuilder().setFileStatus(fileStatus);
              if (fileStatus.equals(FileStatus.CORRUPTED)) {
                // Corrupted state indicates a checksum mismatch failure, so increment the retry
                // download count.
                sharedFileBuilder.setChecksumMismatchRetryDownloadCount(
                    sharedFile.getChecksumMismatchRetryDownloadCount() + 1);
              }
              return sharedFilesMetadata.write(newFileKey, sharedFileBuilder.build());
            },
            sequentialControlExecutor)
        .transformAsync(
            writeSuccess -> {
              if (!writeSuccess) {
                // TODO(b/131166925): MDD dump should not use lite proto toString.
                LogUtil.e(
                    "%s: Unable to write back download info for file entry with %s",
                    TAG, newFileKey);
                return immediateFailedFuture(
                    DownloadException.builder()
                        .setDownloadResultCode(DownloadResultCode.UNABLE_TO_UPDATE_FILE_STATE_ERROR)
                        .build());
              }
              return immediateVoidFuture();
            },
            sequentialControlExecutor);
  }
}