blob: b003e76c5cec365639ef81ced299d925e1290f8f [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 Tate487529a2009-04-29 14:03:25 -070028import android.content.pm.PackageManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070029import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070031import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070032import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070033import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070034import android.os.Handler;
35import android.os.IBinder;
36import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070037import android.os.ParcelFileDescriptor;
Christopher Tate043dadc2009-06-02 16:11:00 -070038import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070039import android.os.RemoteException;
40import android.util.Log;
41import android.util.SparseArray;
42
43import android.backup.IBackupManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070044import android.backup.BackupManager;
45
46import com.android.internal.backup.AdbTransport;
47import com.android.internal.backup.GoogleTransport;
48import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070049
Christopher Tate22b87872009-05-04 16:41:53 -070050import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070051import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070052import java.io.FileNotFoundException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070053import java.io.PrintWriter;
Christopher Tate487529a2009-04-29 14:03:25 -070054import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040055import java.util.ArrayList;
56import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070057import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070058import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070059import java.util.List;
60
61class BackupManagerService extends IBackupManager.Stub {
62 private static final String TAG = "BackupManagerService";
63 private static final boolean DEBUG = true;
64
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070065 private static final long COLLECTION_INTERVAL = 1000;
66 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070067
68 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070069 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate487529a2009-04-29 14:03:25 -070070
71 private Context mContext;
72 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070073 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070074 private final BackupHandler mBackupHandler = new BackupHandler();
75 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070076 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
77 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070078 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070079 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070080 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070081 public boolean fullBackup;
82
Christopher Tate181fafa2009-05-14 11:12:14 -070083 BackupRequest(ApplicationInfo app, boolean isFull) {
84 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070085 fullBackup = isFull;
86 }
Christopher Tate181fafa2009-05-14 11:12:14 -070087
88 public String toString() {
89 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
90 }
Christopher Tate46758122009-05-06 11:22:00 -070091 }
Joe Onorato8ad02812009-05-13 01:41:44 -040092 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -070093 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
94 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -040095 // Backups that we have started. These are separate to prevent starvation
96 // if an app keeps re-enqueuing itself.
97 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -070098 private final Object mQueueLock = new Object();
99
Christopher Tate043dadc2009-06-02 16:11:00 -0700100 // The thread performing the sequence of queued backups binds to each app's agent
101 // in succession. Bind notifications are asynchronously delivered through the
102 // Activity Manager; use this lock object to signal when a requested binding has
103 // completed.
104 private final Object mAgentConnectLock = new Object();
105 private IBackupAgent mConnectedAgent;
106 private volatile boolean mConnecting;
107
108 private int mTransportId;
109
Christopher Tate22b87872009-05-04 16:41:53 -0700110 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700111 private File mDataDir;
Christopher Tate487529a2009-04-29 14:03:25 -0700112
Christopher Tate487529a2009-04-29 14:03:25 -0700113 public BackupManagerService(Context context) {
114 mContext = context;
115 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700116 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700117
Christopher Tate22b87872009-05-04 16:41:53 -0700118 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700119 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700120 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700121 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate043dadc2009-06-02 16:11:00 -0700122 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Christopher Tate22b87872009-05-04 16:41:53 -0700123
Christopher Tate3799bc22009-05-06 16:13:56 -0700124 // Build our mapping of uid to backup client services
125 synchronized (mBackupParticipants) {
126 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700127 }
128
Christopher Tate3799bc22009-05-06 16:13:56 -0700129 // Register for broadcasts about package install, etc., so we can
130 // update the provider list.
131 IntentFilter filter = new IntentFilter();
132 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
133 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
134 filter.addDataScheme("package");
135 mContext.registerReceiver(mBroadcastReceiver, filter);
136 }
137
138 // ----- Track installation/removal of packages -----
139 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
140 public void onReceive(Context context, Intent intent) {
141 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
142
143 Uri uri = intent.getData();
144 if (uri == null) {
145 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700146 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700147 String pkgName = uri.getSchemeSpecificPart();
148 if (pkgName == null) {
149 return;
150 }
151
Christopher Tate043dadc2009-06-02 16:11:00 -0700152 // !!! TODO: this is buggy right now; we wind up with duplicate participant entries
153 // after using 'adb install -r' of a participating app
Christopher Tate3799bc22009-05-06 16:13:56 -0700154 String action = intent.getAction();
155 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
156 synchronized (mBackupParticipants) {
157 Bundle extras = intent.getExtras();
158 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
159 // The package was just upgraded
160 updatePackageParticipantsLocked(pkgName);
161 } else {
162 // The package was just added
163 addPackageParticipantsLocked(pkgName);
164 }
165 }
166 }
167 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
168 Bundle extras = intent.getExtras();
169 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
170 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
171 } else {
172 synchronized (mBackupParticipants) {
173 removePackageParticipantsLocked(pkgName);
174 }
175 }
176 }
177 }
178 };
179
Joe Onorato8ad02812009-05-13 01:41:44 -0400180 // ----- Run the actual backup process asynchronously -----
181
Christopher Tate181fafa2009-05-14 11:12:14 -0700182 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400183 public void handleMessage(Message msg) {
184
185 switch (msg.what) {
186 case MSG_RUN_BACKUP:
187 // snapshot the pending-backup set and work on that
188 synchronized (mQueueLock) {
Joe Onoratod2110db2009-05-19 13:41:21 -0700189 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700190 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700191 for (BackupRequest b: mPendingBackups.values()) {
192 mBackupQueue.add(b);
193 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700194 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400195 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400196 // !!! TODO: start a new backup-queue journal file too
197 // WARNING: If we crash after this line, anything in mPendingBackups will
198 // be lost. FIX THIS.
199 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700200 //startOneAgent();
201 (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 Tate181fafa2009-05-14 11:12:14 -0700210 void startOneAgent() {
Joe Onorato8ad02812009-05-13 01:41:44 -0400211 // Loop until we find someone to start or the queue empties out.
Joe Onorato8ad02812009-05-13 01:41:44 -0400212 while (true) {
213 BackupRequest request;
214 synchronized (mQueueLock) {
215 int queueSize = mBackupQueue.size();
Joe Onoratod2110db2009-05-19 13:41:21 -0700216 Log.d(TAG, "mBackupQueue.size=" + queueSize);
Joe Onorato8ad02812009-05-13 01:41:44 -0400217 if (queueSize == 0) {
218 mBackupQueue = null;
Joe Onoratod2110db2009-05-19 13:41:21 -0700219 // if there are pending backups, start those after a short delay
220 if (mPendingBackups.size() > 0) {
221 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
222 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400223 return;
224 }
225 request = mBackupQueue.get(0);
226 // Take it off the queue when we're done.
227 }
228
Christopher Tate181fafa2009-05-14 11:12:14 -0700229 Log.d(TAG, "starting agent for " + request);
230 // !!! TODO: need to handle the restore case?
231 int mode = (request.fullBackup)
232 ? IApplicationThread.BACKUP_MODE_FULL
233 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
Joe Onorato8ad02812009-05-13 01:41:44 -0400234 try {
Christopher Tate181fafa2009-05-14 11:12:14 -0700235 if (mActivityManager.bindBackupAgent(request.appInfo, mode)) {
236 Log.d(TAG, "awaiting agent for " + request);
Joe Onorato8ad02812009-05-13 01:41:44 -0400237 // success
238 return;
239 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700240 } catch (RemoteException e) {
241 // can't happen; activity manager is local
Joe Onorato8ad02812009-05-13 01:41:44 -0400242 } catch (SecurityException ex) {
243 // Try for the next one.
244 Log.d(TAG, "error in bind", ex);
245 }
246 }
247 }
248
Christopher Tate043dadc2009-06-02 16:11:00 -0700249 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
250 final String packageName = request.appInfo.packageName;
Christopher Tate181fafa2009-05-14 11:12:14 -0700251 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400252
Christopher Tate181fafa2009-05-14 11:12:14 -0700253 try {
Christopher Tate043dadc2009-06-02 16:11:00 -0700254 // !!! TODO: get the state file dir from the transport
255 File savedStateName = new File(mStateDir, packageName);
256 File backupDataName = new File(mDataDir, packageName + ".data");
257 File newStateName = new File(mStateDir, packageName + ".new");
Joe Onorato8ad02812009-05-13 01:41:44 -0400258
259 // In a full backup, we pass a null ParcelFileDescriptor as
260 // the saved-state "file"
261 ParcelFileDescriptor savedState = (request.fullBackup) ? null
262 : ParcelFileDescriptor.open(savedStateName,
263 ParcelFileDescriptor.MODE_READ_ONLY |
264 ParcelFileDescriptor.MODE_CREATE);
265
266 backupDataName.delete();
267 ParcelFileDescriptor backupData =
268 ParcelFileDescriptor.open(backupDataName,
269 ParcelFileDescriptor.MODE_READ_WRITE |
270 ParcelFileDescriptor.MODE_CREATE);
271
272 newStateName.delete();
273 ParcelFileDescriptor newState =
274 ParcelFileDescriptor.open(newStateName,
275 ParcelFileDescriptor.MODE_READ_WRITE |
276 ParcelFileDescriptor.MODE_CREATE);
277
278 // Run the target's backup pass
Christopher Tate043dadc2009-06-02 16:11:00 -0700279 boolean success = false;
Joe Onorato8ad02812009-05-13 01:41:44 -0400280 try {
Christopher Tate043dadc2009-06-02 16:11:00 -0700281 agent.doBackup(savedState, backupData, newState);
282 success = true;
Joe Onorato8ad02812009-05-13 01:41:44 -0400283 } finally {
284 if (savedState != null) {
285 savedState.close();
286 }
287 backupData.close();
288 newState.close();
289 }
290
Christopher Tate043dadc2009-06-02 16:11:00 -0700291 // Now propagate the newly-backed-up data to the transport
292 if (success) {
293 backupData =
294 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
295 int error = transport.performBackup(packageName, backupData);
296
297 // !!! TODO: After successful transport, delete the now-stale data
298 // and juggle the files so that next time the new state is passed
299 //backupDataName.delete();
300 newStateName.renameTo(savedStateName);
301 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400302 } catch (FileNotFoundException fnf) {
303 Log.d(TAG, "File not found on backup: ");
304 fnf.printStackTrace();
305 } catch (RemoteException e) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700306 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
Joe Onorato8ad02812009-05-13 01:41:44 -0400307 e.printStackTrace();
308 } catch (Exception e) {
309 Log.w(TAG, "Final exception guard in backup: ");
310 e.printStackTrace();
311 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400312 }
313
Christopher Tate181fafa2009-05-14 11:12:14 -0700314 // Add the backup agents in the given package to our set of known backup participants.
315 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700316 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700317 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700318 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700319 List<ApplicationInfo> targetApps = allAgentApps();
320 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700321 }
322
Christopher Tate181fafa2009-05-14 11:12:14 -0700323 private void addPackageParticipantsLockedInner(String packageName,
324 List<ApplicationInfo> targetApps) {
325 if (DEBUG) {
326 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
327 for (ApplicationInfo a : targetApps) {
328 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
329 }
330 }
331
332 for (ApplicationInfo app : targetApps) {
333 if (packageName == null || app.packageName.equals(packageName)) {
334 int uid = app.uid;
335 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700336 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700337 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700338 mBackupParticipants.put(uid, set);
339 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700340 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700341 }
Christopher Tate487529a2009-04-29 14:03:25 -0700342 }
343 }
344
Christopher Tate3799bc22009-05-06 16:13:56 -0700345 // Remove the given package's backup services from our known active set. If
346 // 'packageName' is null, *all* backup services will be removed.
347 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700348 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700349 List<ApplicationInfo> allApps = null;
350 if (packageName != null) {
351 allApps = new ArrayList<ApplicationInfo>();
352 try {
353 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
354 allApps.add(app);
355 } catch (Exception e) {
356 // just skip it
357 }
358 } else {
359 // all apps with agents
360 allApps = allAgentApps();
361 }
362 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700363 }
364
Joe Onorato8ad02812009-05-13 01:41:44 -0400365 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700366 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700367 if (DEBUG) {
368 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
369 + ") removing " + agents.size() + " entries");
370 for (ApplicationInfo a : agents) {
371 Log.v(TAG, " - " + a);
372 }
373 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700374 for (ApplicationInfo app : agents) {
375 if (packageName == null || app.packageName.equals(packageName)) {
376 int uid = app.uid;
377 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700378 if (set != null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700379 set.remove(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700380 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700381 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700382 }
383 }
384 }
385 }
386
Christopher Tate181fafa2009-05-14 11:12:14 -0700387 // Returns the set of all applications that define an android:backupAgent attribute
388 private List<ApplicationInfo> allAgentApps() {
389 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
390 int N = allApps.size();
391 if (N > 0) {
392 for (int a = N-1; a >= 0; a--) {
393 ApplicationInfo app = allApps.get(a);
394 if (app.backupAgentName == null) {
395 allApps.remove(a);
396 }
397 }
398 }
399 return allApps;
400 }
401
Christopher Tate3799bc22009-05-06 16:13:56 -0700402 // Reset the given package's known backup participants. Unlike add/remove, the update
403 // action cannot be passed a null package name.
404 void updatePackageParticipantsLocked(String packageName) {
405 if (packageName == null) {
406 Log.e(TAG, "updatePackageParticipants called with null package name");
407 return;
408 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700409 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700410
411 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700412 List<ApplicationInfo> allApps = allAgentApps();
413 removePackageParticipantsLockedInner(packageName, allApps);
414 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700415 }
416
Christopher Tate043dadc2009-06-02 16:11:00 -0700417 // ----- Back up a set of applications via a worker thread -----
418
419 class PerformBackupThread extends Thread {
420 private static final String TAG = "PerformBackupThread";
421 int mTransport;
422 ArrayList<BackupRequest> mQueue;
423
424 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue) {
425 mTransport = transportId;
426 mQueue = queue;
427 }
428
429 @Override
430 public void run() {
431 /*
432 * 1. start up the current transport
433 * 2. for each item in the queue:
434 * 2a. bind the agent [wait for async attach]
435 * 2b. set up the files and call doBackup()
436 * 2c. unbind the agent
437 * 3. tear down the transport
438 * 4. done!
439 */
440 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
441
442 // stand up the current transport
443 IBackupTransport transport = null;
444 switch (mTransport) {
445 case BackupManager.TRANSPORT_ADB:
446 if (DEBUG) Log.v(TAG, "Initializing adb transport");
447 transport = new AdbTransport();
448 break;
449
450 case BackupManager.TRANSPORT_GOOGLE:
451 if (DEBUG) Log.v(TAG, "Initializing Google transport");
452 //!!! TODO: stand up the google backup transport here
453 transport = new GoogleTransport();
454 break;
455
456 default:
457 Log.e(TAG, "Perform backup with unknown transport " + mTransport);
458 // !!! TODO: re-enqueue the backup queue for later?
459 return;
460 }
461
462 try {
463 transport.startSession();
464 } catch (Exception e) {
465 Log.e(TAG, "Error starting backup session");
466 e.printStackTrace();
467 // !!! TODO: re-enqueue the backup queue for later?
468 return;
469 }
470
471 // The transport is up and running; now run all the backups in our queue
472 doQueuedBackups(transport);
473
474 // Finally, tear down the transport
475 try {
476 transport.endSession();
477 } catch (Exception e) {
478 Log.e(TAG, "Error ending transport");
479 e.printStackTrace();
480 }
481 }
482
483 private void doQueuedBackups(IBackupTransport transport) {
484 for (BackupRequest request : mQueue) {
485 Log.d(TAG, "starting agent for " + request);
486 // !!! TODO: need to handle the restore case?
487
488 IBackupAgent agent = null;
489 int mode = (request.fullBackup)
490 ? IApplicationThread.BACKUP_MODE_FULL
491 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
492 try {
493 synchronized(mAgentConnectLock) {
494 mConnecting = true;
495 mConnectedAgent = null;
496 if (mActivityManager.bindBackupAgent(request.appInfo, mode)) {
497 Log.d(TAG, "awaiting agent for " + request);
498
499 // success; wait for the agent to arrive
500 while (mConnecting && mConnectedAgent == null) {
501 try {
502 mAgentConnectLock.wait(10000);
503 } catch (InterruptedException e) {
504 // just retry
505 continue;
506 }
507 }
508
509 // if we timed out with no connect, abort and move on
510 if (mConnecting == true) {
511 Log.w(TAG, "Timeout waiting for agent " + request);
512 continue;
513 }
514 agent = mConnectedAgent;
515 }
516 }
517 } catch (RemoteException e) {
518 // can't happen; activity manager is local
519 } catch (SecurityException ex) {
520 // Try for the next one.
521 Log.d(TAG, "error in bind", ex);
522 }
523
524 // successful bind? run the backup for this agent
525 if (agent != null) {
526 processOneBackup(request, agent, transport);
527 }
528
529 // send the unbind even on timeout, just in case
530 try {
531 mActivityManager.unbindBackupAgent(request.appInfo);
532 } catch (RemoteException e) {
533 // can't happen
534 }
535 }
536 }
537 }
538
Christopher Tate487529a2009-04-29 14:03:25 -0700539 // ----- IBackupManager binder interface -----
540
Christopher Tatea8bf8152009-04-30 11:36:21 -0700541 public void dataChanged(String packageName) throws RemoteException {
Christopher Tate487529a2009-04-29 14:03:25 -0700542 // Record that we need a backup pass for the caller. Since multiple callers
543 // may share a uid, we need to note all candidates within that uid and schedule
544 // a backup pass for each of them.
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700545
546 Log.d(TAG, "dataChanged packageName=" + packageName);
Christopher Tate487529a2009-04-29 14:03:25 -0700547
Christopher Tate181fafa2009-05-14 11:12:14 -0700548 HashSet<ApplicationInfo> targets = mBackupParticipants.get(Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -0700549 if (targets != null) {
550 synchronized (mQueueLock) {
551 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -0700552 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -0700553 // validate the caller-supplied package name against the known set of
554 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -0700555 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -0400556 // Add the caller to the set of pending backups. If there is
557 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 BackupRequest req = new BackupRequest(app, false);
559 mPendingBackups.put(app, req);
Joe Onorato8ad02812009-05-13 01:41:44 -0400560 // !!! TODO: write to the pending-backup journal file in case of crash
Christopher Tate487529a2009-04-29 14:03:25 -0700561 }
562 }
563
Christopher Tate181fafa2009-05-14 11:12:14 -0700564 if (DEBUG) {
565 int numKeys = mPendingBackups.size();
566 Log.d(TAG, "Scheduling backup for " + numKeys + " participants:");
567 for (BackupRequest b : mPendingBackups.values()) {
568 Log.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
569 }
570 }
Christopher Tate487529a2009-04-29 14:03:25 -0700571 // Schedule a backup pass in a few minutes. As backup-eligible data
572 // keeps changing, continue to defer the backup pass until things
573 // settle down, to avoid extra overhead.
Christopher Tate043dadc2009-06-02 16:11:00 -0700574 mBackupHandler.removeMessages(MSG_RUN_BACKUP);
Christopher Tate487529a2009-04-29 14:03:25 -0700575 mBackupHandler.sendEmptyMessageDelayed(MSG_RUN_BACKUP, COLLECTION_INTERVAL);
576 }
577 }
578 }
Christopher Tate46758122009-05-06 11:22:00 -0700579
Christopher Tate043dadc2009-06-02 16:11:00 -0700580 // Schedule a backup pass for a given package. This method will schedule a
581 // full backup even for apps that do not declare an android:backupAgent, so
582 // use with care.
Christopher Tate46758122009-05-06 11:22:00 -0700583 public void scheduleFullBackup(String packageName) throws RemoteException {
Christopher Tate043dadc2009-06-02 16:11:00 -0700584 mContext.enforceCallingPermission("android.permission.BACKUP", "scheduleFullBackup");
585
586 if (DEBUG) Log.v(TAG, "Scheduling immediate full backup for " + packageName);
Christopher Tate46758122009-05-06 11:22:00 -0700587 synchronized (mQueueLock) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700588 try {
589 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
590 mPendingBackups.put(app, new BackupRequest(app, true));
591 mBackupHandler.sendEmptyMessage(MSG_RUN_FULL_BACKUP);
592 } catch (NameNotFoundException e) {
593 Log.w(TAG, "Could not find app for " + packageName + " to schedule full backup");
Christopher Tate46758122009-05-06 11:22:00 -0700594 }
595 }
596 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700597
Christopher Tate043dadc2009-06-02 16:11:00 -0700598 // Select which transport to use for the next backup operation
599 public int selectBackupTransport(int transportId) {
600 mContext.enforceCallingPermission("android.permission.BACKUP", "selectBackupTransport");
601
602 int prevTransport = mTransportId;
603 mTransportId = transportId;
604 return prevTransport;
605 }
606
607 // Callback: a requested backup agent has been instantiated. This should only
608 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700609 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700610 synchronized(mAgentConnectLock) {
611 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
612 Log.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
613 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
614 mConnectedAgent = agent;
615 mConnecting = false;
616 } else {
617 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
618 + " claiming agent connected");
619 }
620 mAgentConnectLock.notifyAll();
621 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700622 }
623
624 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
625 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -0700626 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -0700627 public void agentDisconnected(String packageName) {
628 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -0700629 synchronized(mAgentConnectLock) {
630 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
631 mConnectedAgent = null;
632 mConnecting = false;
633 } else {
634 Log.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
635 + " claiming agent disconnected");
636 }
637 mAgentConnectLock.notifyAll();
638 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700639 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700640
Christopher Tate043dadc2009-06-02 16:11:00 -0700641
642
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700643 @Override
644 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
645 synchronized (mQueueLock) {
646 int N = mBackupParticipants.size();
647 pw.println("Participants:");
648 for (int i=0; i<N; i++) {
649 int uid = mBackupParticipants.keyAt(i);
650 pw.print(" uid: ");
651 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700652 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
653 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700654 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -0700655 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700656 }
657 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700658 pw.println("Pending:");
659 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
660 while (br.hasNext()) {
661 pw.print(" ");
662 pw.println(br);
663 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700664 }
665 }
Christopher Tate487529a2009-04-29 14:03:25 -0700666}