1# Accessing Backup and Restore
2
3You can use **BackupExtensionAbility** to enable an application to access the backup and restore framework.
4
5**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.
6
7## Available APIs
8
9For details about how to use the APIs, see [BackupExtensionAbility](../reference/apis-core-file-kit/js-apis-application-backupExtensionAbility.md#backupextensionability) and [Backup and Restore Extension Capability](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md).
10
11## Constraints
12
13- The path of the file or directory to be backed up or restored cannot exceed 4095 bytes. Otherwise, undefined behavior may occur.
14- 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.
15- 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.
16
17## How to Develop
18
191. Add **extensionAbilities** to the application's **module.json5** file.
20
21   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)**.
22
23   Example:
24
25   ```json
26   {
27       "extensionAbilities": [
28           {
29               "description": "$string:ServiceExtAbility",
30               "icon": "$media:icon",
31               "name": "BackupExtensionAbility",
32               "type": "backup",
33               "exported": false,
34               "metadata": [
35                   {
36                       "name": "ohos.extension.backup",
37                       "resource": "$profile:backup_config"
38                   }
39               ],
40               // In the BackupExtension.ets file, define BackupExtensionAbility in extensionAbilities and override onBackup or onBackupEx and onRestore or onRestoreEx methods. The onBackupEx and onRestoreEx methods are recommended.
41               // 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.
42               "srcEntry": "./ets/BackupExtension/BackupExtension.ets",
43           }
44       ]
45   }
46   ```
47
482. Add a metadata profile.
49
50   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.
51
52   Metadata profile example:
53
54   ```json
55   {
56       "allowToBackupRestore": true,
57       "includes": [
58           "/data/storage/el2/base/files/users/"
59       ],
60       "excludes": [
61           "/data/storage/el2/base/files/users/hidden/"
62       ],
63       "fullBackupOnly": false,
64       "restoreDeps": ""
65   }
66   ```
67
683. 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.
69
70   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.
71
72   The following example shows an empty implementation of the **BackupExtension.ets** file.
73
74    ```ts
75    //onBackup && onRestore
76    import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
77    import {hilog} from '@kit.PerformanceAnalysisKit';
78
79    const TAG = `FileBackupExtensionAbility`;
80    export default class BackupExtension extends  BackupExtensionAbility {
81      //onBackup
82      async onBackup ()   {
83        hilog.info(0x0000, TAG, `onBackup ok`);
84      }
85      //onRestore
86      async onRestore (bundleVersion : BundleVersion) {
87        hilog.info(0x0000, TAG, `onRestore ok ${JSON.stringify(bundleVersion)}`);
88        hilog.info(0x0000, TAG, `onRestore end`);
89      }
90    }
91    ```
92
93    ```ts
94    //onBackupEx && onRestoreEx
95    import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
96
97    interface ErrorInfo {
98      type: string,
99      errorCode: number,
100      errorInfo: string
101    }
102
103    class BackupExt extends BackupExtensionAbility {
104      //onBackupEx
105      async onBackupEx(backupInfo: string): Promise<string> {
106        console.log(`onBackupEx ok`);
107        let errorInfo: ErrorInfo = {
108          type: "ErrorInfo",
109          errorCode: 0,
110          errorInfo: "app diy error info"
111        }
112        return JSON.stringify(errorInfo);
113      }
114
115      // onRestoreEx
116      async onRestoreEx(bundleVersion : BundleVersion, restoreInfo: string): Promise<string> {
117        console.log(`onRestoreEx ok ${JSON.stringify(bundleVersion)}`);
118        let errorInfo: ErrorInfo = {
119          type: "ErrorInfo",
120          errorCode: 0,
121          errorInfo: "app diy error info"
122        }
123        return JSON.stringify(errorInfo);
124      }
125    }
126    ```
127
128### Description of the Metadata Profile
129
130| Field            | Type  | Mandatory| Description                                                        |
131| -------------------- | ---------- | ---- | ------------------------------------------------------------ |
132| allowToBackupRestore | Boolean    | Yes  | Whether to enable backup and restore. The default value is **false**.                             |
133| 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>If **includes** is not configured, the backup and restore framework uses the **includes** default (as listed in the code snippet below).|
134| 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>If **excludes** is not configured, the backup and restore framework uses an empty array by default.|
135| 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) in the data restore process. If it is **false** or not specified, the restored data is decompressed in **/**.|
136| restoreDeps          | String    | No  | **(Not recommended)** Dependencies for the application to restore.<br/>The default value is "". <br/>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.|
137| extraInfo            | JSON string    | No  | Additional information to be passed.                                  |
138
139> **NOTE**
140>
141> When setting **fullBackupOnly**, observe the following:
142>
143> - 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.
144> - 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**.
145>
146> You can determine the data restore mode to use based on service requirements. Assume that the temporary directory is **/data/storage/el2/base/.backup/restore/** and the data backup directory of the application is **data/storage/el2/base/files/A/**.
147>
148> 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 **/data/storage/el2/base/.backup/restore/data/storage/el2/base/files/A/** directory.
149
150**includes** defaults:
151
152```json
153{
154    "includes": [
155    "data/storage/el1/database/",
156    "data/storage/el1/base/files/",
157    "data/storage/el1/base/preferences/",
158    "data/storage/el1/base/haps/<module-name>/files/",
159    "data/storage/el1/base/haps/<module-name>/preferences/",
160    "data/storage/el2/database/",
161    "data/storage/el2/base/files/",
162    "data/storage/el2/base/preferences/",
163    "data/storage/el2/base/haps/<module-name>/files/",
164    "data/storage/el2/base/haps/<module-name>/preferences/",
165    "data/storage/el2/distributedfiles/"
166    ]
167}
168```
169