session-ios/Signal/src/util/OWSBackupImportJob.m

491 lines
20 KiB
Mathematica
Raw Normal View History

2018-03-08 19:38:42 +01:00
//
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
//
#import "OWSBackupImportJob.h"
#import "OWSBackupIO.h"
2018-03-13 13:44:49 +01:00
#import "OWSDatabaseMigration.h"
#import "OWSDatabaseMigrationRunner.h"
2018-03-08 19:38:42 +01:00
#import "Signal-Swift.h"
#import <SignalServiceKit/NSData+Base64.h>
#import <SignalServiceKit/OWSBackgroundTask.h>
#import <SignalServiceKit/OWSFileSystem.h>
2018-03-12 20:28:55 +01:00
#import <SignalServiceKit/TSAttachment.h>
2018-03-08 19:38:42 +01:00
#import <SignalServiceKit/TSMessage.h>
#import <SignalServiceKit/TSThread.h>
NS_ASSUME_NONNULL_BEGIN
NSString *const kOWSBackup_ImportDatabaseKeySpec = @"kOWSBackup_ImportDatabaseKeySpec";
#pragma mark -
@interface OWSBackupImportJob ()
@property (nonatomic, nullable) OWSBackgroundTask *backgroundTask;
2018-03-08 19:38:42 +01:00
@property (nonatomic) OWSBackupIO *backupIO;
2018-03-08 20:02:39 +01:00
@property (nonatomic) NSArray<OWSBackupFragment *> *databaseItems;
@property (nonatomic) NSArray<OWSBackupFragment *> *attachmentsItems;
2018-03-08 20:02:39 +01:00
2018-03-08 19:38:42 +01:00
@end
#pragma mark -
@implementation OWSBackupImportJob
- (void)startAsync
{
OWSAssertIsOnMainThread();
DDLogInfo(@"%@ %s", self.logTag, __PRETTY_FUNCTION__);
self.backgroundTask = [OWSBackgroundTask backgroundTaskWithLabelStr:__PRETTY_FUNCTION__];
[self updateProgressWithDescription:nil progress:nil];
__weak OWSBackupImportJob *weakSelf = self;
[OWSBackupAPI checkCloudKitAccessWithCompletion:^(BOOL hasAccess) {
2018-03-17 21:44:54 +01:00
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (hasAccess) {
2018-03-08 19:38:42 +01:00
[weakSelf start];
2018-03-17 21:44:54 +01:00
} else {
[weakSelf failWithErrorDescription:
NSLocalizedString(@"BACKUP_IMPORT_ERROR_COULD_NOT_IMPORT",
@"Error indicating the backup import could not import the user's data.")];
2018-03-17 21:44:54 +01:00
}
});
2018-03-08 19:38:42 +01:00
}];
}
- (void)start
{
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_CONFIGURATION",
@"Indicates that the backup import is being configured.")
progress:nil];
2018-03-12 20:28:55 +01:00
if (![self configureImport]) {
[self failWithErrorDescription:NSLocalizedString(@"BACKUP_IMPORT_ERROR_COULD_NOT_IMPORT",
@"Error indicating the backup import could not import the user's data.")];
2018-03-12 20:28:55 +01:00
return;
}
if (self.isComplete) {
return;
}
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_IMPORT",
@"Indicates that the backup import data is being imported.")
progress:nil];
2018-03-08 19:38:42 +01:00
__weak OWSBackupImportJob *weakSelf = self;
2018-03-17 21:29:57 +01:00
[weakSelf downloadAndProcessManifestWithSuccess:^(OWSBackupManifestContents *manifest) {
OWSBackupImportJob *strongSelf = weakSelf;
if (!strongSelf) {
2018-03-08 19:38:42 +01:00
return;
}
if (self.isComplete) {
return;
}
OWSCAssert(manifest.databaseItems.count > 0);
OWSCAssert(manifest.attachmentsItems);
strongSelf.databaseItems = manifest.databaseItems;
strongSelf.attachmentsItems = manifest.attachmentsItems;
[strongSelf downloadAndProcessImport];
}
failure:^(NSError *manifestError) {
2018-03-17 21:29:57 +01:00
[weakSelf failWithError:manifestError];
}
backupIO:self.backupIO];
}
2018-03-12 20:10:37 +01:00
- (void)downloadAndProcessImport
{
OWSAssert(self.databaseItems);
OWSAssert(self.attachmentsItems);
2018-03-12 20:28:55 +01:00
NSMutableArray<OWSBackupFragment *> *allItems = [NSMutableArray new];
[allItems addObjectsFromArray:self.databaseItems];
[allItems addObjectsFromArray:self.attachmentsItems];
// Record metadata for all items, so that we can re-use them in incremental backups after the restore.
[self.primaryStorage.newDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
for (OWSBackupFragment *item in allItems) {
[item saveWithTransaction:transaction];
}
}];
__weak OWSBackupImportJob *weakSelf = self;
[weakSelf
downloadFilesFromCloud:allItems
completion:^(NSError *_Nullable fileDownloadError) {
if (fileDownloadError) {
[weakSelf failWithError:fileDownloadError];
return;
}
if (weakSelf.isComplete) {
return;
}
[weakSelf restoreDatabaseWithCompletion:^(BOOL restoreDatabaseSuccess) {
if (!restoreDatabaseSuccess) {
[weakSelf
failWithErrorDescription:NSLocalizedString(@"BACKUP_IMPORT_ERROR_COULD_NOT_IMPORT",
@"Error indicating the backup import "
@"could not import the user's data.")];
2018-03-12 20:28:55 +01:00
return;
}
if (weakSelf.isComplete) {
return;
}
[weakSelf ensureMigrationsWithCompletion:^(BOOL ensureMigrationsSuccess) {
if (!ensureMigrationsSuccess) {
2018-03-12 20:28:55 +01:00
[weakSelf failWithErrorDescription:NSLocalizedString(
@"BACKUP_IMPORT_ERROR_COULD_NOT_IMPORT",
@"Error indicating the backup import "
2018-03-12 20:28:55 +01:00
@"could not import the user's data.")];
2018-03-12 20:10:37 +01:00
return;
}
if (weakSelf.isComplete) {
return;
}
2018-03-22 18:48:22 +01:00
[weakSelf restoreAttachmentFiles];
if (weakSelf.isComplete) {
return;
}
// Kick off lazy restore.
2018-04-02 15:39:13 +02:00
[OWSBackupLazyRestoreJob runAsync];
2018-03-22 18:48:22 +01:00
[weakSelf succeed];
2018-03-12 20:10:37 +01:00
}];
2018-03-12 20:28:55 +01:00
}];
}];
2018-03-08 19:38:42 +01:00
}
2018-03-12 20:28:55 +01:00
- (BOOL)configureImport
2018-03-08 19:38:42 +01:00
{
DDLogVerbose(@"%@ %s", self.logTag, __PRETTY_FUNCTION__);
if (![self ensureJobTempDir]) {
OWSProdLogAndFail(@"%@ Could not create jobTempDirPath.", self.logTag);
2018-03-12 20:28:55 +01:00
return NO;
2018-03-08 19:38:42 +01:00
}
self.backupIO = [[OWSBackupIO alloc] initWithJobTempDirPath:self.jobTempDirPath];
2018-03-12 20:28:55 +01:00
return YES;
2018-03-08 19:38:42 +01:00
}
- (void)downloadFilesFromCloud:(NSMutableArray<OWSBackupFragment *> *)items
completion:(OWSBackupJobCompletion)completion
2018-03-08 20:02:39 +01:00
{
OWSAssert(items.count > 0);
2018-03-08 20:02:39 +01:00
OWSAssert(completion);
DDLogVerbose(@"%@ %s", self.logTag, __PRETTY_FUNCTION__);
[self downloadNextItemFromCloud:items recordCount:items.count completion:completion];
2018-03-08 20:02:39 +01:00
}
- (void)downloadNextItemFromCloud:(NSMutableArray<OWSBackupFragment *> *)items
2018-03-13 17:01:44 +01:00
recordCount:(NSUInteger)recordCount
2018-03-08 20:02:39 +01:00
completion:(OWSBackupJobCompletion)completion
{
OWSAssert(items);
2018-03-08 20:02:39 +01:00
OWSAssert(completion);
2018-03-12 20:10:37 +01:00
if (self.isComplete) {
// Job was aborted.
return completion(nil);
}
if (items.count < 1) {
2018-03-08 20:02:39 +01:00
// All downloads are complete; exit.
return completion(nil);
}
OWSBackupFragment *item = items.lastObject;
[items removeLastObject];
2018-03-08 20:02:39 +01:00
CGFloat progress = (recordCount > 0 ? ((recordCount - items.count) / (CGFloat)recordCount) : 0.f);
2018-03-13 17:01:44 +01:00
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_DOWNLOAD",
@"Indicates that the backup import data is being downloaded.")
progress:@(progress)];
2018-03-08 20:02:39 +01:00
2018-03-22 19:12:29 +01:00
// TODO: Use a predictable file path so that multiple "import backup" attempts
2018-03-12 20:10:37 +01:00
// will leverage successful file downloads from previous attempts.
//
// TODO: This will also require imports using a predictable jobTempDirPath.
NSString *tempFilePath = [self.jobTempDirPath stringByAppendingPathComponent:item.recordName];
2018-03-12 20:10:37 +01:00
// Skip redundant file download.
if ([NSFileManager.defaultManager fileExistsAtPath:tempFilePath]) {
[OWSFileSystem protectFileOrFolderAtPath:tempFilePath];
item.downloadFilePath = tempFilePath;
[self downloadNextItemFromCloud:items recordCount:recordCount completion:completion];
2018-03-12 20:10:37 +01:00
return;
}
2018-03-08 20:02:39 +01:00
__weak OWSBackupImportJob *weakSelf = self;
[OWSBackupAPI downloadFileFromCloudWithRecordName:item.recordName
2018-03-12 20:10:37 +01:00
toFileUrl:[NSURL fileURLWithPath:tempFilePath]
2018-03-08 20:02:39 +01:00
success:^{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[OWSFileSystem protectFileOrFolderAtPath:tempFilePath];
item.downloadFilePath = tempFilePath;
[weakSelf downloadNextItemFromCloud:items recordCount:recordCount completion:completion];
2018-03-08 20:02:39 +01:00
});
}
failure:^(NSError *error) {
2018-03-17 21:44:54 +01:00
// Ensure that we continue to work off the main thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
completion(error);
});
2018-03-08 20:02:39 +01:00
}];
}
2018-03-12 20:10:37 +01:00
- (void)restoreAttachmentFiles
{
DDLogVerbose(@"%@ %s: %zd", self.logTag, __PRETTY_FUNCTION__, self.attachmentsItems.count);
2018-03-12 20:10:37 +01:00
2018-03-22 18:33:34 +01:00
__block NSUInteger count = 0;
2018-03-22 19:05:12 +01:00
YapDatabaseConnection *dbConnection = self.primaryStorage.newDatabaseConnection;
[dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
2018-03-22 18:33:34 +01:00
for (OWSBackupFragment *item in self.attachmentsItems) {
if (self.isComplete) {
return;
}
if (item.recordName.length < 1) {
DDLogError(@"%@ attachment was not downloaded.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
2018-03-22 14:32:22 +01:00
continue;
}
2018-03-22 18:33:34 +01:00
if (item.attachmentId.length < 1) {
DDLogError(@"%@ attachment missing attachment id.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
continue;
}
if (item.relativeFilePath.length < 1) {
DDLogError(@"%@ attachment missing relative file path.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
continue;
}
2018-03-22 18:33:34 +01:00
TSAttachmentStream *_Nullable attachment =
[TSAttachmentStream fetchObjectWithUniqueID:item.attachmentId transaction:transaction];
if (!attachment) {
DDLogError(@"%@ attachment to restore could not be found.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
continue;
}
2018-03-22 19:12:29 +01:00
[attachment markForLazyRestoreWithFragment:item transaction:transaction];
2018-03-22 18:33:34 +01:00
count++;
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_RESTORING_FILES",
@"Indicates that the backup import data is being restored.")
progress:@(count / (CGFloat)self.attachmentsItems.count)];
2018-03-12 20:10:37 +01:00
}
2018-03-22 18:33:34 +01:00
}];
2018-03-12 20:10:37 +01:00
2018-03-22 18:33:34 +01:00
DDLogError(@"%@ enqueued lazy restore of %zd files.", self.logTag, count);
2018-03-08 20:02:39 +01:00
}
2018-03-17 13:37:42 +01:00
- (void)restoreDatabaseWithCompletion:(OWSBackupJobBoolCompletion)completion
2018-03-12 20:10:37 +01:00
{
OWSAssert(completion);
DDLogVerbose(@"%@ %s", self.logTag, __PRETTY_FUNCTION__);
if (self.isComplete) {
return completion(NO);
}
YapDatabaseConnection *_Nullable dbConnection = self.primaryStorage.newDatabaseConnection;
if (!dbConnection) {
OWSProdLogAndFail(@"%@ Could not create dbConnection.", self.logTag);
2018-03-12 20:10:37 +01:00
return completion(NO);
}
2018-03-13 14:51:57 +01:00
// Order matters here.
NSArray<NSString *> *collectionsToRestore = @[
[TSThread collection],
[TSAttachment collection],
// Interactions refer to threads and attachments,
// so copy them afterward.
[TSInteraction collection],
[OWSDatabaseMigration collection],
];
NSMutableDictionary<NSString *, NSNumber *> *restoredEntityCounts = [NSMutableDictionary new];
2018-03-12 20:10:37 +01:00
__block unsigned long long copiedEntities = 0;
2018-03-13 14:51:57 +01:00
__block BOOL aborted = NO;
[dbConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
for (NSString *collection in collectionsToRestore) {
if ([collection isEqualToString:[OWSDatabaseMigration collection]]) {
// It's okay if there are existing migrations; we'll clear those
// before restoring.
continue;
}
if ([transaction numberOfKeysInCollection:collection] > 0) {
DDLogError(@"%@ unexpected contents in database (%@).", self.logTag, collection);
}
}
// Clear existing database contents.
//
// This should be safe since we only ever import into an empty database.
//
// Note that if the app receives a message after registering and before restoring
// backup, it will be lost.
//
// Note that this will clear all migrations.
for (NSString *collection in collectionsToRestore) {
[transaction removeAllObjectsInCollection:collection];
}
NSUInteger count = 0;
for (OWSBackupFragment *item in self.databaseItems) {
if (self.isComplete) {
return;
}
if (item.recordName.length < 1) {
DDLogError(@"%@ database snapshot was not downloaded.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
// Database-related errors are unrecoverable.
2018-03-13 16:30:38 +01:00
aborted = YES;
return completion(NO);
}
if (!item.uncompressedDataLength || item.uncompressedDataLength.unsignedIntValue < 1) {
DDLogError(@"%@ database snapshot missing size.", self.logTag);
// Attachment-related errors are recoverable and can be ignored.
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
2018-03-13 14:51:57 +01:00
}
2018-03-13 13:44:49 +01:00
count++;
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_RESTORING_DATABASE",
@"Indicates that the backup database is being restored.")
progress:@(count / (CGFloat)self.databaseItems.count)];
@autoreleasepool {
NSData *_Nullable compressedData =
[self.backupIO decryptFileAsData:item.downloadFilePath encryptionKey:item.encryptionKey];
if (!compressedData) {
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
NSData *_Nullable uncompressedData =
[self.backupIO decompressData:compressedData
uncompressedDataLength:item.uncompressedDataLength.unsignedIntValue];
if (!uncompressedData) {
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
2018-08-06 16:05:21 +02:00
SignalIOSProtoBackupSnapshot *_Nullable entities;
2018-04-16 20:48:29 +02:00
@try {
2018-08-06 16:05:21 +02:00
NSError *error;
entities = [SignalIOSProtoBackupSnapshot parseData:uncompressedData error:&error];
if (!entities || error) {
DDLogError(@"%@ could not parse proto: %@.", self.logTag, error);
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
2018-04-16 20:48:29 +02:00
} @catch (NSException *exception) {
OWSProdLogAndFail(@"%@ Could not parse proto: %@", self.logTag, exception.debugDescription);
// TODO: Add analytics.
2018-08-06 16:05:21 +02:00
aborted = YES;
return completion(NO);
2018-04-16 20:48:29 +02:00
}
if (!entities || entities.entity.count < 1) {
DDLogError(@"%@ missing entities.", self.logTag);
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
2018-08-06 16:05:21 +02:00
for (SignalIOSProtoBackupSnapshotBackupEntity *entity in entities.entity) {
NSData *_Nullable entityData = entity.entityData;
if (entityData.length < 1) {
DDLogError(@"%@ missing entity data.", self.logTag);
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
2018-03-13 13:44:49 +01:00
__block TSYapDatabaseObject *object = nil;
@try {
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:entityData];
object = [unarchiver decodeObjectForKey:@"root"];
if (![object isKindOfClass:[object class]]) {
DDLogError(@"%@ invalid decoded entity: %@.", self.logTag, [object class]);
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
} @catch (NSException *exception) {
DDLogError(@"%@ could not decode entity.", self.logTag);
// Database-related errors are unrecoverable.
aborted = YES;
return completion(NO);
}
[object saveWithTransaction:transaction];
copiedEntities++;
NSString *collection = [object.class collection];
NSUInteger restoredEntityCount = restoredEntityCounts[collection].unsignedIntValue;
restoredEntityCounts[collection] = @(restoredEntityCount + 1);
}
2018-03-13 14:51:57 +01:00
}
}
2018-03-12 20:10:37 +01:00
}];
if (self.isComplete || aborted) {
2018-03-13 14:51:57 +01:00
return;
}
for (NSString *collection in restoredEntityCounts) {
DDLogInfo(@"%@ copied %@: %@", self.logTag, collection, restoredEntityCounts[collection]);
2018-03-13 14:51:57 +01:00
}
2018-03-12 20:10:37 +01:00
DDLogInfo(@"%@ copiedEntities: %llu", self.logTag, copiedEntities);
[self.primaryStorage logFileSizes];
2018-03-12 20:10:37 +01:00
completion(YES);
2018-03-12 20:10:37 +01:00
}
2018-03-17 13:37:42 +01:00
- (void)ensureMigrationsWithCompletion:(OWSBackupJobBoolCompletion)completion
2018-03-13 13:44:49 +01:00
{
OWSAssert(completion);
DDLogVerbose(@"%@ %s", self.logTag, __PRETTY_FUNCTION__);
2018-03-13 17:01:44 +01:00
[self updateProgressWithDescription:NSLocalizedString(@"BACKUP_IMPORT_PHASE_FINALIZING",
@"Indicates that the backup import data is being finalized.")
progress:nil];
2018-03-13 14:51:57 +01:00
// It's okay that we do this in a separate transaction from the
// restoration of backup contents. If some of migrations don't
// complete, they'll be run the next time the app launches.
dispatch_async(dispatch_get_main_queue(), ^{
[[[OWSDatabaseMigrationRunner alloc] initWithPrimaryStorage:self.primaryStorage]
runAllOutstandingWithCompletion:^{
completion(YES);
}];
});
2018-03-13 13:44:49 +01:00
}
2018-03-08 19:38:42 +01:00
@end
NS_ASSUME_NONNULL_END