1# Accessing Backup and Restore 2<!--Kit: Core File Kit--> 3<!--Subsystem: FileManagement--> 4<!--Owner: @lvzhenjie--> 5<!--Designer: @wang_zhangjun; @chenxi0605--> 6<!--Tester: @liuhonggang123--> 7<!--Adviser: @foryourself--> 8 9You can use **BackupExtensionAbility** to enable an application to access the backup and restore framework. 10 11**BackupExtensionAbility** is a class derived from [ExtensionAbility](../application-models/extensionability-overview.md) in the [stage model](../application-models/stage-model-development-overview.md). The application that has accessed the backup and restore framework can customize the backup and restore behavior, including whether to enable backup and restore and specifying the data to be backed up, in a profile. 12 13## Available APIs 14 15The following table lists the key APIs of the backup and restore extension capability. For details about how to use the APIs, see [BackupExtensionAbility](../reference/apis-core-file-kit/js-apis-application-backupExtensionAbility.md#backupextensionability) and [BackupExtensionContext](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md). 16 17| Name | Description | 18| ------------------------------------------------------------ | ---------------- | 19| onBackup(): void | Called to back up data before backup data migration.| 20| onBackupEx(backupInfo: string): string \| Promise<string> | Called to back up data before backup data migration. It supports passing backup information and returning backup results. | 21| onRestore(bundleVersion: BundleVersion): void | Called to restore data after backup data migration.| 22| onRestoreEx(bundleVersion: BundleVersion, restoreInfo: string): string \| Promise<string> | Called to restore data after backup data migration. It supports passing restore information and returning restore results.| 23| onRelease(scenario: number): Promise<void> | Called when data backup or restore is complete.<br>**NOTE**<br>This API is supported since API version 20.| 24 25## Constraints 26 27- The path of the file or directory to be backed up or restored cannot exceed 4095 bytes. Otherwise, undefined behavior may occur. 28- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (`r` in DAC). Otherwise, the backup fails. 29- If a file needs to be backed up, the application process must have the permission to retrieve all the ancestor directories of the file (`x` in DAC). Otherwise, the backup fails. 30- The path of the file or directory to be backed up or restored does not support relative paths (**../**) and soft links. 31 32## How to Develop 33 341. Add `extensionAbilities` to the application's `module.json5` file. 35 36 In `module.json5`, add the `extensionAbilities` field, set `type` to `backup`, and add a record with `name` set to `ohos.extension. backup` under ["metadata"](../reference/apis-ability-kit/js-apis-bundleManager-metadata.md). 37 38 Example: 39 40 ```json 41 { 42 "extensionAbilities": [ 43 { 44 "description": "$string:ServiceExtAbility", 45 "icon": "$media:icon", 46 "name": "BackupExtensionAbility", 47 "type": "backup", 48 "exported": false, 49 "metadata": [ 50 { 51 "name": "ohos.extension.backup", 52 "resource": "$profile:backup_config" 53 } 54 ], 55 // In the BackupExtension.ets file, define BackupExtensionAbility in extensionAbilities and override onBackup or onBackupEx 56 // and onRestore or onRestoreEx methods. onBackupEx and onRestoreEx are recommended. 57 // Empty implementation can be used if there is no special requirement. In this case, the backup and restore service backs up or restores data based on the unified backup and restore rules. 58 "srcEntry": "./ets/BackupExtension/BackupExtension.ets" 59 } 60 ] 61 } 62 ``` 63 642. Add a metadata profile. 65 66 The metadata profile defines the files to be transferred during the backup and restore process. The profile is located in the `resources/base/profile` directory of the project, and the file name must be the same as the value of `metadata.resource, for example, backup_config.json` in the `module.json5` file. 67 68 Metadata profile example: 69 70 ```json 71 { 72 "allowToBackupRestore": true, 73 "includes": [ 74 "/data/storage/el2/base/files/users/" 75 ], 76 "excludes": [ 77 "/data/storage/el2/base/files/users/hidden/" 78 ], 79 "fullBackupOnly": false, 80 "restoreDeps": "" 81 } 82 ``` 83 843. Customize `BackupExtensionAbility` in the `BackupExtension.ets` file and override `onBackup/onBackupEx` or `onRestore/onRestoreEx` to back up preprocessed application data or process the data to be restored. 85 86 Empty implementation can be used if there is no special requirement. In this case, the backup and restore service backs up or restores data based on the unified backup and restore rules. 87 88 The following example shows an empty implementation of the `BackupExtension.ets` file. 89 90 ```ts 91 //onBackup && onRestore 92 import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; 93 import {hilog} from '@kit.PerformanceAnalysisKit'; 94 95 const TAG = `FileBackupExtensionAbility`; 96 export default class BackupExtension extends BackupExtensionAbility { 97 //onBackup 98 async onBackup () { 99 hilog.info(0x0000, TAG, `onBackup ok`); 100 } 101 //onRestore 102 async onRestore (bundleVersion : BundleVersion) { 103 hilog.info(0x0000, TAG, `onRestore end`); 104 } 105 } 106 ``` 107 108 ```ts 109 //onBackupEx && onRestoreEx 110 import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; 111 112 interface ErrorInfo { 113 type: string, 114 errorCode: number, 115 errorInfo: string 116 } 117 118 class BackupExt extends BackupExtensionAbility { 119 //onBackupEx 120 async onBackupEx(backupInfo: string): Promise<string> { 121 console.info(`onBackupEx ok`); 122 let errorInfo: ErrorInfo = { 123 type: "ErrorInfo", 124 errorCode: 0, 125 errorInfo: "app diy error info" 126 } 127 return JSON.stringify(errorInfo); 128 } 129 130 // onRestoreEx 131 async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> { 132 console.info(`onRestoreEx begin`); 133 let errorInfo: ErrorInfo = { 134 type: "ErrorInfo", 135 errorCode: 0, 136 errorInfo: "app diy error info" 137 } 138 return JSON.stringify(errorInfo); 139 } 140 } 141 ``` 142 1434. Starting from API version 20, to perform special operations after application data backup and restore, such as cleaning up temporary files created during these processes, you can customize `BackupExtensionAbility` inherited by the class in the `BackupExtension.ets` file and override the `onRelease` method for execution when the backup or restore is complete. 144 145 `onRelease` has a timeout mechanism. If the `onRelease` operation is not completed within 5 seconds, the application process exits when the backup and restoration are complete. 146 147 The following example shows how to implement `onRelease` when the temporary file directory needs to be removed. 148 149 ```ts 150 import { BackupExtensionAbility, fileIo } from '@kit.CoreFileKit'; 151 152 const SCENARIO_BACKUP: number = 1; 153 const SCENARIO_RESTORE: number = 2; 154 // Temporary directory to be removed. 155 let filePath: string = '/data/storage/el2/base/.temp/'; 156 157 class BackupExt extends BackupExtensionAbility { 158 async onRelease(scenario: number): Promise<void> { 159 try { 160 if (scenario == SCENARIO_BACKUP) { 161 // In the backup scenario, the application implements the processing. The following describes how to delete temporary files generated during backup. 162 console.info(`onRelease begin`); 163 await fileIo.rmdir(filePath); 164 console.info(`onRelease end, rmdir succeed`); 165 } 166 if (scenario == SCENARIO_RESTORE) { 167 // In the restore scenario, the application implements the processing. The following describes how to remove temporary files generated during restoration. 168 console.info(`onRelease begin`); 169 await fileIo.rmdir(filePath); 170 console.info(`onRelease end, rmdir succeed`); 171 } 172 } catch (error) { 173 console.error(`onRelease failed with error. Code: ${error.code}, message: ${error.message}`); 174 } 175 } 176 } 177 ``` 178 179### Description of the Metadata Profile 180 181| Field | Type | Mandatory| Description | 182| -------------------- | ---------- | ---- | ------------------------------------------------------------ | 183| allowToBackupRestore | Boolean | Yes | Whether to enable backup and restore. The value **true** means backup and restore are enabled; the value **false** (default) means the opposite. | 184| includes | String array| No | Files and directories to be backed up in the application sandbox directory.<br>The pattern string that does not start with a slash (/) indicates a relative path.<br>When configuring `includes`, ensure that the configured path range is included in the supported paths listed in the following code snippet.<br>If `includes` is not configured, the backup and restore framework uses the **includes** default (as listed in the code snippet below).| 185| excludes | String array| No | Items in `includes` that do not need to be backed up. The value is in the same format as `includes`.<br>When configuring `excludes`, ensure that it is within the subset of `includes`.<br>If `excludes` is not configured, the backup and restore framework uses an empty array by default.| 186| fullBackupOnly | Boolean | No | Whether to use the default restore directory of the application. The default value is **false**. If the value is **true**, data will be cached in a temporary directory obtained by [backupDir](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md#properties) in the data restore process. If it is **false** or not specified, the restored data is decompressed in **/**.| 187| restoreDeps | String | No | **(Not recommended)** Dependencies for the application to restore. The default value is "". You need to configure the names of the dependent applications. Currently, only one dependency is supported. The configured dependency takes effect only in the context of one restore task. If no dependent application is detected, the dependency description will be ignored and the restore task continues. The application restore will fail if the dependent application is not restored or fails to be restored.| 188| extraInfo | JSON string | No | Additional information to be passed. | 189 190> **NOTE** 191> 192> When setting **fullBackupOnly**, observe the following: 193> 194> - If **fullBackupOnly** is set to **false**, the restored data will be decompressed in the root directory **/**, and the file with the same name in the directory will be overwritten. 195> - If **fullBackupOnly** is set to **true**, the restored data will be decompressed in a temporary directory. You need to implement the data restoration logic in **OnRestore** or **OnRestoreEx**. 196> 197> You can determine the data restore mode to use based on service requirements. 198> 199> Example: 200> Assume that the application backup path is **data/storage/el2/base/files/A/**. If **fullBackupOnly** is **false**, the restored data will be decompressed to the **/data/storage/el2/base/files/A/** directory. If **fullBackupOnly** is **true**, data will be decompressed to the temporary directory **[backupDir](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md)/restore/data/storage/el2/base/files/A/**. 201 202The following lists the paths supported by **includes**: 203 204```json 205{ 206 "includes": [ 207 "data/storage/el1/database/", 208 "data/storage/el1/base/files/", 209 "data/storage/el1/base/preferences/", 210 "data/storage/el1/base/haps/*/files/", 211 "data/storage/el1/base/haps/*/preferences/", 212 "data/storage/el2/database/", 213 "data/storage/el2/base/files/", 214 "data/storage/el2/base/preferences/", 215 "data/storage/el2/base/haps/*/files/", 216 "data/storage/el2/base/haps/*/preferences/", 217 "data/storage/el2/distributedfiles/", 218 "data/storage/el5/database/", 219 "data/storage/el5/base/files/", 220 "data/storage/el5/base/preferences/", 221 "data/storage/el5/base/haps/*/files/", 222 "data/storage/el5/base/haps/*/preferences/" 223 ] 224} 225``` 226 227## 228 229 230 231- 232