blob: e90e0ad35895cdec68a3ee0933418cdc484c6fc8 [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
20import android.app.IActivityManager;
21import android.app.IApplicationThread;
22import android.app.IBackupAgent;
Christopher Tate3799bc22009-05-06 16:13:56 -070023import android.content.BroadcastReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -070024import android.content.Context;
25import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070026import android.content.IntentFilter;
Christopher Tate181fafa2009-05-14 11:12:14 -070027import android.content.pm.ApplicationInfo;
Christopher Tate7b881282009-06-07 13:52:37 -070028import android.content.pm.PackageInfo;
Christopher Tate487529a2009-04-29 14:03:25 -070029import android.content.pm.PackageManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070030import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070031import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070033import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070034import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070035import android.os.Handler;
36import android.os.IBinder;
37import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070038import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070039import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070040import android.os.RemoteException;
41import android.util.Log;
42import android.util.SparseArray;
43
44import android.backup.IBackupManager;
Christopher Tate8c850b72009-06-07 19:33:20 -070045import android.backup.IRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -070046import android.backup.BackupManager;
Christopher Tate9b3905c2009-06-08 15:24:01 -070047import android.backup.RestoreSet;
Christopher Tate043dadc2009-06-02 16:11:00 -070048
49import com.android.internal.backup.AdbTransport;
50import com.android.internal.backup.GoogleTransport;
51import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070052
Christopher Tate22b87872009-05-04 16:41:53 -070053import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070054import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070055import java.io.FileNotFoundException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070056import java.io.PrintWriter;
Christopher Tate487529a2009-04-29 14:03:25 -070057import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040058import java.util.ArrayList;
59import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070060import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070061import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070062import java.util.List;
63
64class BackupManagerService extends IBackupManager.Stub {
65 private static final String TAG = "BackupManagerService";
66 private static final boolean DEBUG = true;
67
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070068 private static final long COLLECTION_INTERVAL = 1000;
69 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070070
71 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070072 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate487529a2009-04-29 14:03:25 -070073
74 private Context mContext;
75 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070076 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070077 private final BackupHandler mBackupHandler = new BackupHandler();
78 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070079 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
80 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070081 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070082 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070083 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070084 public boolean fullBackup;
85
Christopher Tate181fafa2009-05-14 11:12:14 -070086 BackupRequest(ApplicationInfo app, boolean isFull) {
87 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070088 fullBackup = isFull;
89 }
Christopher Tate181fafa2009-05-14 11:12:14 -070090
91 public String toString() {
92 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
93 }
Christopher Tate46758122009-05-06 11:22:00 -070094 }
Joe Onorato8ad02812009-05-13 01:41:44 -040095 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -070096 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
97 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -040098 // Backups that we have started. These are separate to prevent starvation
99 // if an app keeps re-enqueuing itself.
100 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -0700101 private final Object mQueueLock = new Object();
102
Christopher Tate043dadc2009-06-02 16:11:00 -0700103 // The thread performing the sequence of queued backups binds to each app's agent
104 // in succession. Bind notifications are asynchronously delivered through the
105 // Activity Manager; use this lock object to signal when a requested binding has
106 // completed.
107 private final Object mAgentConnectLock = new Object();
108 private IBackupAgent mConnectedAgent;
109 private volatile boolean mConnecting;
110
111 private int mTransportId;
112
Christopher Tate22b87872009-05-04 16:41:53 -0700113 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700114 private File mDataDir;
Christopher Tate487529a2009-04-29 14:03:25 -0700115
Christopher Tate487529a2009-04-29 14:03:25 -0700116 public BackupManagerService(Context context) {
117 mContext = context;
118 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700119 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700120
Christopher Tate22b87872009-05-04 16:41:53 -0700121 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700122 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700123 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700124 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate043dadc2009-06-02 16:11:00 -0700125 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Christopher Tate22b87872009-05-04 16:41:53 -0700126
Christopher Tate3799bc22009-05-06 16:13:56 -0700127 // Build our mapping of uid to backup client services
128 synchronized (mBackupParticipants) {
129 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700130 }
131
Christopher Tate3799bc22009-05-06 16:13:56 -0700132 // Register for broadcasts about package install, etc., so we can
133 // update the provider list.
134 IntentFilter filter = new IntentFilter();
135 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
136 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
137 filter.addDataScheme("package");
138 mContext.registerReceiver(mBroadcastReceiver, filter);
139 }
140
141 // ----- Track installation/removal of packages -----
142 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
143 public void onReceive(Context context, Intent intent) {
144 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
145
146 Uri uri = intent.getData();
147 if (uri == null) {
148 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700149 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700150 String pkgName = uri.getSchemeSpecificPart();
151 if (pkgName == null) {
152 return;
153 }
154
155 String action = intent.getAction();
156 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
157 synchronized (mBackupParticipants) {
158 Bundle extras = intent.getExtras();
159 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
160 // The package was just upgraded
161 updatePackageParticipantsLocked(pkgName);
162 } else {
163 // The package was just added
164 addPackageParticipantsLocked(pkgName);
165 }
166 }
167 }
168 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
169 Bundle extras = intent.getExtras();
170 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
171 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
172 } else {
173 synchronized (mBackupParticipants) {
174 removePackageParticipantsLocked(pkgName);
175 }
176 }
177 }
178 }
179 };
180
Joe Onorato8ad02812009-05-13 01:41:44 -0400181 // ----- Run the actual backup process asynchronously -----
182
Christopher Tate181fafa2009-05-14 11:12:14 -0700183 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400184 public void handleMessage(Message msg) {
185
186 switch (msg.what) {
187 case MSG_RUN_BACKUP:
188 // snapshot the pending-backup set and work on that
189 synchronized (mQueueLock) {
Joe Onoratod2110db2009-05-19 13:41:21 -0700190 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700191 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700192 for (BackupRequest b: mPendingBackups.values()) {
193 mBackupQueue.add(b);
194 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700195 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400196 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400197 // !!! TODO: start a new backup-queue journal file too
198 // WARNING: If we crash after this line, anything in mPendingBackups will
199 // be lost. FIX THIS.
200 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700201 (new PerformBackupThread(mTransportId, mBackupQueue)).run();
202 break;
203
204 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400205 break;
206 }
207 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400208 }
209
Christopher Tate043dadc2009-06-02 16:11:00 -0700210 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
211 final String packageName = request.appInfo.packageName;
Christopher Tate181fafa2009-05-14 11:12:14 -0700212 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400213
Christopher Tate181fafa2009-05-14 11:12:14 -0700214 try {
Christopher Tate7b881282009-06-07 13:52:37 -0700215 // Look up the package info & signatures. This is first so that if it
216 // throws an exception, there's no file setup yet that would need to
217 // be unraveled.
218 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
219
Christopher Tate043dadc2009-06-02 16:11:00 -0700220 // !!! TODO: get the state file dir from the transport
221 File savedStateName = new File(mStateDir, packageName);
222 File backupDataName = new File(mDataDir, packageName + ".data");
223 File newStateName = new File(mStateDir, packageName + ".new");
Joe Onorato8ad02812009-05-13 01:41:44 -0400224
225 // In a full backup, we pass a null ParcelFileDescriptor as
226 // the saved-state "file"
227 ParcelFileDescriptor savedState = (request.fullBackup) ? null
228 : ParcelFileDescriptor.open(savedStateName,
229 ParcelFileDescriptor.MODE_READ_ONLY |
230 ParcelFileDescriptor.MODE_CREATE);
231
232 backupDataName.delete();
233 ParcelFileDescriptor backupData =
234 ParcelFileDescriptor.open(backupDataName,
235 ParcelFileDescriptor.MODE_READ_WRITE |
236 ParcelFileDescriptor.MODE_CREATE);
237
238 newStateName.delete();
239 ParcelFileDescriptor newState =
240 ParcelFileDescriptor.open(newStateName,
241 ParcelFileDescriptor.MODE_READ_WRITE |
242 ParcelFileDescriptor.MODE_CREATE);
243
244 // Run the target's backup pass
Christopher Tate043dadc2009-06-02 16:11:00 -0700245 boolean success = false;
Joe Onorato8ad02812009-05-13 01:41:44 -0400246 try {
Christopher Tate043dadc2009-06-02 16:11:00 -0700247 agent.doBackup(savedState, backupData, newState);
248 success = true;
Joe Onorato8ad02812009-05-13 01:41:44 -0400249 } finally {
250 if (savedState != null) {
251 savedState.close();
252 }
253 backupData.close();
254 newState.close();
255 }
256
Christopher Tate043dadc2009-06-02 16:11:00 -0700257 // Now propagate the newly-backed-up data to the transport
258 if (success) {
Christopher Tate1885b372009-06-04 15:00:33 -0700259 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
Christopher Tate043dadc2009-06-02 16:11:00 -0700260 backupData =
261 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate7b881282009-06-07 13:52:37 -0700262 int error = transport.performBackup(packInfo, backupData);
Christopher Tate043dadc2009-06-02 16:11:00 -0700263
264 // !!! TODO: After successful transport, delete the now-stale data
265 // and juggle the files so that next time the new state is passed
266 //backupDataName.delete();
267 newStateName.renameTo(savedStateName);
268 }
Christopher Tate7b881282009-06-07 13:52:37 -0700269 } catch (NameNotFoundException e) {
270 Log.e(TAG, "Package not found on backup: " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400271 } catch (FileNotFoundException fnf) {
Christopher Tate7b881282009-06-07 13:52:37 -0700272 Log.w(TAG, "File not found on backup: ");
Joe Onorato8ad02812009-05-13 01:41:44 -0400273 fnf.printStackTrace();
274 } catch (RemoteException e) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700275 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
Joe Onorato8ad02812009-05-13 01:41:44 -0400276 e.printStackTrace();
277 } catch (Exception e) {
278 Log.w(TAG, "Final exception guard in backup: ");
279 e.printStackTrace();
280 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400281 }
282
Christopher Tate181fafa2009-05-14 11:12:14 -0700283 // Add the backup agents in the given package to our set of known backup participants.
284 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700285 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700286 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700287 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700288 List<ApplicationInfo> targetApps = allAgentApps();
289 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700290 }
291
Christopher Tate181fafa2009-05-14 11:12:14 -0700292 private void addPackageParticipantsLockedInner(String packageName,
293 List<ApplicationInfo> targetApps) {
294 if (DEBUG) {
295 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
296 for (ApplicationInfo a : targetApps) {
297 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
298 }
299 }
300
301 for (ApplicationInfo app : targetApps) {
302 if (packageName == null || app.packageName.equals(packageName)) {
303 int uid = app.uid;
304 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700305 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700306 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700307 mBackupParticipants.put(uid, set);
308 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700309 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700310 }
Christopher Tate487529a2009-04-29 14:03:25 -0700311 }
312 }
313
Christopher Tate3799bc22009-05-06 16:13:56 -0700314 // Remove the given package's backup services from our known active set. If
315 // 'packageName' is null, *all* backup services will be removed.
316 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700317 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700318 List<ApplicationInfo> allApps = null;
319 if (packageName != null) {
320 allApps = new ArrayList<ApplicationInfo>();
321 try {
322 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
323 allApps.add(app);
324 } catch (Exception e) {
325 // just skip it
326 }
327 } else {
328 // all apps with agents
329 allApps = allAgentApps();
330 }
331 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700332 }
333
Joe Onorato8ad02812009-05-13 01:41:44 -0400334 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700335 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700336 if (DEBUG) {
337 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
338 + ") removing " + agents.size() + " entries");
339 for (ApplicationInfo a : agents) {
340 Log.v(TAG, " - " + a);
341 }
342 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700343 for (ApplicationInfo app : agents) {
344 if (packageName == null || app.packageName.equals(packageName)) {
345 int uid = app.uid;
346 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700347 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700348 // Find the existing entry with the same package name, and remove it.
349 // We can't just remove(app) because the instances are different.
350 for (ApplicationInfo entry: set) {
351 if (entry.packageName.equals(app.packageName)) {
352 set.remove(entry);
353 break;
354 }
355 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700356 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700357 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700358 }
359 }
360 }
361 }
362
Christopher Tate181fafa2009-05-14 11:12:14 -0700363 // Returns the set of all applications that define an android:backupAgent attribute
364 private List<ApplicationInfo> allAgentApps() {
365 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
366 int N = allApps.size();
367 if (N > 0) {
368 for (int a = N-1; a >= 0; a--) {
369 ApplicationInfo app = allApps.get(a);
370 if (app.backupAgentName == null) {
371 allApps.remove(a);
372 }
373 }
374 }
375 return allApps;
376 }
377
Christopher Tate3799bc22009-05-06 16:13:56 -0700378 // Reset the given package's known backup participants. Unlike add/remove, the update
379 // action cannot be passed a null package name.
380 void updatePackageParticipantsLocked(String packageName) {
381 if (packageName == null) {
382 Log.e(TAG, "updatePackageParticipants called with null package name");
383 return;
384 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700385 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700386
387 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700388 List<ApplicationInfo> allApps = allAgentApps();
389 removePackageParticipantsLockedInner(packageName, allApps);
390 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700391 }
392
Christopher Tate8c850b72009-06-07 19:33:20 -0700393 // Instantiate the given transport
394 private IBackupTransport createTransport(int transportID) {
395 IBackupTransport transport = null;
396 switch (transportID) {
397 case BackupManager.TRANSPORT_ADB:
398 if (DEBUG) Log.v(TAG, "Initializing adb transport");
399 transport = new AdbTransport();
400 break;
401
402 case BackupManager.TRANSPORT_GOOGLE:
403 if (DEBUG) Log.v(TAG, "Initializing Google transport");
404 //!!! TODO: stand up the google backup transport for real here
405 transport = new GoogleTransport();
406 break;
407
408 default:
409 Log.e(TAG, "creating unknown transport " + transportID);
410 }
411 return transport;
412 }
413
Christopher Tate043dadc2009-06-02 16:11:00 -0700414 // ----- Back up a set of applications via a worker thread -----
415
416 class PerformBackupThread extends Thread {
417 private static final String TAG = "PerformBackupThread";
418 int mTransport;
419 ArrayList<BackupRequest> mQueue;
420
421 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue) {
422 mTransport = transportId;
423 mQueue = queue;
424 }
425
426 @Override
427 public void run() {
428 /*
429 * 1. start up the current transport
430 * 2. for each item in the queue:
431 * 2a. bind the agent [wait for async attach]
432 * 2b. set up the files and call doBackup()
433 * 2c. unbind the agent
434 * 3. tear down the transport
435 * 4. done!
436 */
437 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
438
439 // stand up the current transport
Christopher Tate8c850b72009-06-07 19:33:20 -0700440 IBackupTransport transport = createTransport(mTransport);
441 if (transport == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700442 return;
443 }
444
445 // The transport is up and running; now run all the backups in our queue
446 doQueuedBackups(transport);
447
448 // Finally, tear down the transport
449 try {
450 transport.endSession();
451 } catch (Exception e) {
452 Log.e(TAG, "Error ending transport");
453 e.printStackTrace();
454 }
455 }
456
457 private void doQueuedBackups(IBackupTransport transport) {
458 for (BackupRequest request : mQueue) {
459 Log.d(TAG, "starting agent for " + request);
460 // !!! TODO: need to handle the restore case?
461
462 IBackupAgent agent = null;
463 int mode = (request.fullBackup)
464 ? IApplicationThread.BACKUP_MODE_FULL
465 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
466 try {
467 synchronized(mAgentConnectLock) {
468 mConnecting = true;
469 mConnectedAgent = null;
470 if (mActivityManager.bindBackupAgent(request.appInfo, mode)) {
471 Log.d(TAG, "awaiting agent for " + request);
472
473 // success; wait for the agent to arrive
474 while (mConnecting && mConnectedAgent == null) {
475 try {
476 mAgentConnectLock.wait(10000);
477 } catch (InterruptedException e) {
478 // just retry
479 continue;
480 }
481 }
482
483 // if we timed out with no connect, abort and move on
484 if (mConnecting == true) {
485 Log.w(TAG, "Timeout waiting for agent " + request);
486 continue;
487 }
488 agent = mConnectedAgent;
489 }
490 }
491 } catch (RemoteException e) {
492 // can't happen; activity manager is local
493 } catch (SecurityException ex) {
494 // Try for the next one.
495 Log.d(TAG, "error in bind", ex);
496 }
497
498 // successful bind? run the backup for this agent
499 if (agent != null) {
500 processOneBackup(request, agent, transport);
501 }
502
503 // send the unbind even on timeout, just in case
504 try {
505 mActivityManager.unbindBackupAgent(request.appInfo);
506 } catch (RemoteException e) {
507 // can't happen
508 }
509 }
510 }
511 }
512
Christopher Tate487529a2009-04-29 14:03:25 -0700513 // ----- IBackupManager binder interface -----
514
Christopher Tatea8bf8152009-04-30 11:36:21 -0700515 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700516 // Record that we need a backup pass for the caller. Since multiple callers
517 // may share a uid, we need to note all candidates within that uid and schedule
518 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700519
520 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700521
Christopher Tate181fafa2009-05-14 11:12:14 -0700522 HashSet<ApplicationInfo> targets = mBackupParticipants.get(Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -0700523 if (targets != null) {
524 synchronized (mQueueLock) {
525 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700526 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700527 // validate the caller-supplied package name against the known set of
528 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700529 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400530 // Add the caller to the set of pending backups. If there is
531 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700532 BackupRequest req = new BackupRequest(app, false);
533 mPendingBackups.put(app, req);
Joe Onorato8ad02812009-05-13 01:41:44 -0400534 // !!! TODO: write to the pending-backup journal file in case of crash
Christopher Tate487529a2009-04-29 14:03:25 -0700535 }
536 }
537
Christopher Tate181fafa2009-05-14 11:12:14 -0700538 if (DEBUG) {
539 int numKeys = mPendingBackups.size();
540 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
541 for (BackupRequest b : mPendingBackups.values()) {
542 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
543 }
544 }
Christopher Tate487529a2009-04-29 14:03:25 -0700545 // Schedule a backup pass in a few minutes. As backup-eligible data
546 // keeps changing, continue to defer the backup pass until things
547 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700548 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700549 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
550 }
551 }
552 }
Christopher Tate46758122009-05-06 11:22:00 -0700553
Christopher Tate043dadc2009-06-02 16:11:00 -0700554 // Schedule a backup pass for a given package. This method will schedule a
555 // full backup even for apps that do not declare an android:backupAgent, so
556 // use with care.
Christopher Tate46758122009-05-06 11:22:00 -0700557 public void scheduleFullBackup(String packageName) throws RemoteException {
Christopher Tate043dadc2009-06-02 16:11:00 -0700558 mContext.enforceCallingPermission("android.permission.BACKUP", "scheduleFullBackup");
559
560 if (DEBUG) Log.v(TAG, "Scheduling immediate full backup for " + packageName);
Christopher Tate46758122009-05-06 11:22:00 -0700561 synchronized (mQueueLock) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700562 try {
563 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
564 mPendingBackups.put(app, new BackupRequest(app, true));
565 mBackupHandler.sendEmptyMessage(MSG_RUN_FULL_BACKUP);
566 } catch (NameNotFoundException e) {
567 Log.w(TAG, "Could not find app for " + packageName + " to schedule full backup");
Christopher Tate46758122009-05-06 11:22:00 -0700568 }
569 }
570 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700571
Christopher Tate043dadc2009-06-02 16:11:00 -0700572 // Select which transport to use for the next backup operation
573 public int selectBackupTransport(int transportId) {
574 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
575
576 int prevTransport = mTransportId;
577 mTransportId = transportId;
578 return prevTransport;
579 }
580
581 // Callback: a requested backup agent has been instantiated. This should only
582 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700583 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700584 synchronized(mAgentConnectLock) {
585 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
586 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
587 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
588 mConnectedAgent = agent;
589 mConnecting = false;
590 } else {
591 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
592 + " claiming agent connected");
593 }
594 mAgentConnectLock.notifyAll();
595 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700596 }
597
598 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
599 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700600 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700601 public void agentDisconnected(String packageName) {
602 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700603 synchronized(mAgentConnectLock) {
604 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
605 mConnectedAgent = null;
606 mConnecting = false;
607 } else {
608 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
609 + " claiming agent disconnected");
610 }
611 mAgentConnectLock.notifyAll();
612 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700613 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700614
Christopher Tate8c850b72009-06-07 19:33:20 -0700615 // Hand off a restore session
616 public IRestoreSession beginRestoreSession(int transportID) {
617 mContext.enforceCallingPermission("android.permission.BACKUP", "beginRestoreSession");
618 return null;
619 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700620
Christopher Tate9b3905c2009-06-08 15:24:01 -0700621 // ----- Restore session -----
622
623 class RestoreSession extends IRestoreSession.Stub {
624 private IBackupTransport mRestoreTransport = null;
625 RestoreSet[] mRestoreSets = null;
626
627 RestoreSession(int transportID) {
628 mRestoreTransport = createTransport(transportID);
629 }
630
631 // --- Binder interface ---
632 public RestoreSet[] getAvailableRestoreSets() throws android.os.RemoteException {
633 synchronized(this) {
634 if (mRestoreSets == null) {
635 mRestoreSets = mRestoreTransport.getAvailableRestoreSets();
636 }
637 return mRestoreSets;
638 }
639 }
640
641 public int performRestore(int token) throws android.os.RemoteException {
642 return -1;
643 }
644
645 public void endRestoreSession() throws android.os.RemoteException {
646 mRestoreTransport.endSession();
647 mRestoreTransport = null;
648 }
649 }
650
Christopher Tate043dadc2009-06-02 16:11:00 -0700651
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700652 @Override
653 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
654 synchronized (mQueueLock) {
655 int N = mBackupParticipants.size();
656 pw.println("Participants:");
657 for (int i=0; i<N; i++) {
658 int uid = mBackupParticipants.keyAt(i);
659 pw.print(" uid: ");
660 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700661 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
662 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700663 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -0700664 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700665 }
666 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700667 pw.println("Pending:");
668 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
669 while (br.hasNext()) {
670 pw.print(" ");
671 pw.println(br);
672 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700673 }
674 }
Christopher Tate487529a2009-04-29 14:03:25 -0700675}