blob: 6c5953fa920401149d7b15cbba3af728ced886e2 [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 Tate043dadc2009-06-02 16:11:00 -070045import android.backup.BackupManager;
46
47import com.android.internal.backup.AdbTransport;
48import com.android.internal.backup.GoogleTransport;
49import com.android.internal.backup.IBackupTransport;
Christopher Tate487529a2009-04-29 14:03:25 -070050
Christopher Tate22b87872009-05-04 16:41:53 -070051import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070052import java.io.FileDescriptor;
Christopher Tate22b87872009-05-04 16:41:53 -070053import java.io.FileNotFoundException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070054import java.io.PrintWriter;
Christopher Tate487529a2009-04-29 14:03:25 -070055import java.lang.String;
Joe Onorato8ad02812009-05-13 01:41:44 -040056import java.util.ArrayList;
57import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070058import java.util.HashSet;
Christopher Tate181fafa2009-05-14 11:12:14 -070059import java.util.Iterator;
Christopher Tate487529a2009-04-29 14:03:25 -070060import java.util.List;
61
62class BackupManagerService extends IBackupManager.Stub {
63 private static final String TAG = "BackupManagerService";
64 private static final boolean DEBUG = true;
65
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070066 private static final long COLLECTION_INTERVAL = 1000;
67 //private static final long COLLECTION_INTERVAL = 3 * 60 * 1000;
Christopher Tate487529a2009-04-29 14:03:25 -070068
69 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -070070 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate487529a2009-04-29 14:03:25 -070071
72 private Context mContext;
73 private PackageManager mPackageManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070074 private final IActivityManager mActivityManager;
Christopher Tate487529a2009-04-29 14:03:25 -070075 private final BackupHandler mBackupHandler = new BackupHandler();
76 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate181fafa2009-05-14 11:12:14 -070077 private SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
78 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -070079 // set of backup services that have pending changes
Christopher Tate46758122009-05-06 11:22:00 -070080 private class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -070081 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -070082 public boolean fullBackup;
83
Christopher Tate181fafa2009-05-14 11:12:14 -070084 BackupRequest(ApplicationInfo app, boolean isFull) {
85 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -070086 fullBackup = isFull;
87 }
Christopher Tate181fafa2009-05-14 11:12:14 -070088
89 public String toString() {
90 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
91 }
Christopher Tate46758122009-05-06 11:22:00 -070092 }
Joe Onorato8ad02812009-05-13 01:41:44 -040093 // Backups that we haven't started yet.
Christopher Tate181fafa2009-05-14 11:12:14 -070094 private HashMap<ApplicationInfo,BackupRequest> mPendingBackups
95 = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -040096 // Backups that we have started. These are separate to prevent starvation
97 // if an app keeps re-enqueuing itself.
98 private ArrayList<BackupRequest> mBackupQueue;
Christopher Tate487529a2009-04-29 14:03:25 -070099 private final Object mQueueLock = new Object();
100
Christopher Tate043dadc2009-06-02 16:11:00 -0700101 // The thread performing the sequence of queued backups binds to each app's agent
102 // in succession. Bind notifications are asynchronously delivered through the
103 // Activity Manager; use this lock object to signal when a requested binding has
104 // completed.
105 private final Object mAgentConnectLock = new Object();
106 private IBackupAgent mConnectedAgent;
107 private volatile boolean mConnecting;
108
109 private int mTransportId;
110
Christopher Tate22b87872009-05-04 16:41:53 -0700111 private File mStateDir;
Christopher Tatef4172472009-05-05 15:50:03 -0700112 private File mDataDir;
Christopher Tate487529a2009-04-29 14:03:25 -0700113
Christopher Tate487529a2009-04-29 14:03:25 -0700114 public BackupManagerService(Context context) {
115 mContext = context;
116 mPackageManager = context.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700117 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700118
Christopher Tate22b87872009-05-04 16:41:53 -0700119 // Set up our bookkeeping
Christopher Tatef4172472009-05-05 15:50:03 -0700120 mStateDir = new File(Environment.getDataDirectory(), "backup");
Christopher Tate22b87872009-05-04 16:41:53 -0700121 mStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700122 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate043dadc2009-06-02 16:11:00 -0700123 mTransportId = BackupManager.TRANSPORT_GOOGLE;
Christopher Tate22b87872009-05-04 16:41:53 -0700124
Christopher Tate3799bc22009-05-06 16:13:56 -0700125 // Build our mapping of uid to backup client services
126 synchronized (mBackupParticipants) {
127 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700128 }
129
Christopher Tate3799bc22009-05-06 16:13:56 -0700130 // Register for broadcasts about package install, etc., so we can
131 // update the provider list.
132 IntentFilter filter = new IntentFilter();
133 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
134 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
135 filter.addDataScheme("package");
136 mContext.registerReceiver(mBroadcastReceiver, filter);
137 }
138
139 // ----- Track installation/removal of packages -----
140 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
141 public void onReceive(Context context, Intent intent) {
142 if (DEBUG) Log.d(TAG, "Received broadcast " + intent);
143
144 Uri uri = intent.getData();
145 if (uri == null) {
146 return;
Christopher Tate487529a2009-04-29 14:03:25 -0700147 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700148 String pkgName = uri.getSchemeSpecificPart();
149 if (pkgName == null) {
150 return;
151 }
152
153 String action = intent.getAction();
154 if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
155 synchronized (mBackupParticipants) {
156 Bundle extras = intent.getExtras();
157 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
158 // The package was just upgraded
159 updatePackageParticipantsLocked(pkgName);
160 } else {
161 // The package was just added
162 addPackageParticipantsLocked(pkgName);
163 }
164 }
165 }
166 else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
167 Bundle extras = intent.getExtras();
168 if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
169 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
170 } else {
171 synchronized (mBackupParticipants) {
172 removePackageParticipantsLocked(pkgName);
173 }
174 }
175 }
176 }
177 };
178
Joe Onorato8ad02812009-05-13 01:41:44 -0400179 // ----- Run the actual backup process asynchronously -----
180
Christopher Tate181fafa2009-05-14 11:12:14 -0700181 private class BackupHandler extends Handler {
Joe Onorato8ad02812009-05-13 01:41:44 -0400182 public void handleMessage(Message msg) {
183
184 switch (msg.what) {
185 case MSG_RUN_BACKUP:
186 // snapshot the pending-backup set and work on that
187 synchronized (mQueueLock) {
Joe Onoratod2110db2009-05-19 13:41:21 -0700188 if (mBackupQueue == null) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700189 mBackupQueue = new ArrayList<BackupRequest>();
Joe Onoratod2110db2009-05-19 13:41:21 -0700190 for (BackupRequest b: mPendingBackups.values()) {
191 mBackupQueue.add(b);
192 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700193 mPendingBackups = new HashMap<ApplicationInfo,BackupRequest>();
Joe Onorato8ad02812009-05-13 01:41:44 -0400194 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400195 // !!! TODO: start a new backup-queue journal file too
196 // WARNING: If we crash after this line, anything in mPendingBackups will
197 // be lost. FIX THIS.
198 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700199 (new PerformBackupThread(mTransportId, mBackupQueue)).run();
200 break;
201
202 case MSG_RUN_FULL_BACKUP:
Joe Onorato8ad02812009-05-13 01:41:44 -0400203 break;
204 }
205 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400206 }
207
Christopher Tate043dadc2009-06-02 16:11:00 -0700208 void processOneBackup(BackupRequest request, IBackupAgent agent, IBackupTransport transport) {
209 final String packageName = request.appInfo.packageName;
Christopher Tate181fafa2009-05-14 11:12:14 -0700210 Log.d(TAG, "processOneBackup doBackup() on " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400211
Christopher Tate181fafa2009-05-14 11:12:14 -0700212 try {
Christopher Tate7b881282009-06-07 13:52:37 -0700213 // Look up the package info & signatures. This is first so that if it
214 // throws an exception, there's no file setup yet that would need to
215 // be unraveled.
216 PackageInfo packInfo = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
217
Christopher Tate043dadc2009-06-02 16:11:00 -0700218 // !!! TODO: get the state file dir from the transport
219 File savedStateName = new File(mStateDir, packageName);
220 File backupDataName = new File(mDataDir, packageName + ".data");
221 File newStateName = new File(mStateDir, packageName + ".new");
Joe Onorato8ad02812009-05-13 01:41:44 -0400222
223 // In a full backup, we pass a null ParcelFileDescriptor as
224 // the saved-state "file"
225 ParcelFileDescriptor savedState = (request.fullBackup) ? null
226 : ParcelFileDescriptor.open(savedStateName,
227 ParcelFileDescriptor.MODE_READ_ONLY |
228 ParcelFileDescriptor.MODE_CREATE);
229
230 backupDataName.delete();
231 ParcelFileDescriptor backupData =
232 ParcelFileDescriptor.open(backupDataName,
233 ParcelFileDescriptor.MODE_READ_WRITE |
234 ParcelFileDescriptor.MODE_CREATE);
235
236 newStateName.delete();
237 ParcelFileDescriptor newState =
238 ParcelFileDescriptor.open(newStateName,
239 ParcelFileDescriptor.MODE_READ_WRITE |
240 ParcelFileDescriptor.MODE_CREATE);
241
242 // Run the target's backup pass
Christopher Tate043dadc2009-06-02 16:11:00 -0700243 boolean success = false;
Joe Onorato8ad02812009-05-13 01:41:44 -0400244 try {
Christopher Tate043dadc2009-06-02 16:11:00 -0700245 agent.doBackup(savedState, backupData, newState);
246 success = true;
Joe Onorato8ad02812009-05-13 01:41:44 -0400247 } finally {
248 if (savedState != null) {
249 savedState.close();
250 }
251 backupData.close();
252 newState.close();
253 }
254
Christopher Tate043dadc2009-06-02 16:11:00 -0700255 // Now propagate the newly-backed-up data to the transport
256 if (success) {
Christopher Tate1885b372009-06-04 15:00:33 -0700257 if (DEBUG) Log.v(TAG, "doBackup() success; calling transport");
Christopher Tate043dadc2009-06-02 16:11:00 -0700258 backupData =
259 ParcelFileDescriptor.open(backupDataName, ParcelFileDescriptor.MODE_READ_ONLY);
Christopher Tate7b881282009-06-07 13:52:37 -0700260 int error = transport.performBackup(packInfo, backupData);
Christopher Tate043dadc2009-06-02 16:11:00 -0700261
262 // !!! TODO: After successful transport, delete the now-stale data
263 // and juggle the files so that next time the new state is passed
264 //backupDataName.delete();
265 newStateName.renameTo(savedStateName);
266 }
Christopher Tate7b881282009-06-07 13:52:37 -0700267 } catch (NameNotFoundException e) {
268 Log.e(TAG, "Package not found on backup: " + packageName);
Joe Onorato8ad02812009-05-13 01:41:44 -0400269 } catch (FileNotFoundException fnf) {
Christopher Tate7b881282009-06-07 13:52:37 -0700270 Log.w(TAG, "File not found on backup: ");
Joe Onorato8ad02812009-05-13 01:41:44 -0400271 fnf.printStackTrace();
272 } catch (RemoteException e) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700273 Log.d(TAG, "Remote target " + request.appInfo.packageName + " threw during backup:");
Joe Onorato8ad02812009-05-13 01:41:44 -0400274 e.printStackTrace();
275 } catch (Exception e) {
276 Log.w(TAG, "Final exception guard in backup: ");
277 e.printStackTrace();
278 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400279 }
280
Christopher Tate181fafa2009-05-14 11:12:14 -0700281 // Add the backup agents in the given package to our set of known backup participants.
282 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700283 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700284 // Look for apps that define the android:backupAgent attribute
Christopher Tate043dadc2009-06-02 16:11:00 -0700285 if (DEBUG) Log.v(TAG, "addPackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700286 List<ApplicationInfo> targetApps = allAgentApps();
287 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700288 }
289
Christopher Tate181fafa2009-05-14 11:12:14 -0700290 private void addPackageParticipantsLockedInner(String packageName,
291 List<ApplicationInfo> targetApps) {
292 if (DEBUG) {
293 Log.v(TAG, "Adding " + targetApps.size() + " backup participants:");
294 for (ApplicationInfo a : targetApps) {
295 Log.v(TAG, " " + a + " agent=" + a.backupAgentName);
296 }
297 }
298
299 for (ApplicationInfo app : targetApps) {
300 if (packageName == null || app.packageName.equals(packageName)) {
301 int uid = app.uid;
302 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700303 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700304 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700305 mBackupParticipants.put(uid, set);
306 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700307 set.add(app);
Christopher Tate3799bc22009-05-06 16:13:56 -0700308 }
Christopher Tate487529a2009-04-29 14:03:25 -0700309 }
310 }
311
Christopher Tate3799bc22009-05-06 16:13:56 -0700312 // Remove the given package's backup services from our known active set. If
313 // 'packageName' is null, *all* backup services will be removed.
314 void removePackageParticipantsLocked(String packageName) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700315 if (DEBUG) Log.v(TAG, "removePackageParticipantsLocked: " + packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -0700316 List<ApplicationInfo> allApps = null;
317 if (packageName != null) {
318 allApps = new ArrayList<ApplicationInfo>();
319 try {
320 ApplicationInfo app = mPackageManager.getApplicationInfo(packageName, 0);
321 allApps.add(app);
322 } catch (Exception e) {
323 // just skip it
324 }
325 } else {
326 // all apps with agents
327 allApps = allAgentApps();
328 }
329 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700330 }
331
Joe Onorato8ad02812009-05-13 01:41:44 -0400332 private void removePackageParticipantsLockedInner(String packageName,
Christopher Tate181fafa2009-05-14 11:12:14 -0700333 List<ApplicationInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700334 if (DEBUG) {
335 Log.v(TAG, "removePackageParticipantsLockedInner (" + packageName
336 + ") removing " + agents.size() + " entries");
337 for (ApplicationInfo a : agents) {
338 Log.v(TAG, " - " + a);
339 }
340 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700341 for (ApplicationInfo app : agents) {
342 if (packageName == null || app.packageName.equals(packageName)) {
343 int uid = app.uid;
344 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700345 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700346 // Find the existing entry with the same package name, and remove it.
347 // We can't just remove(app) because the instances are different.
348 for (ApplicationInfo entry: set) {
349 if (entry.packageName.equals(app.packageName)) {
350 set.remove(entry);
351 break;
352 }
353 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700354 if (set.size() == 0) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700355 mBackupParticipants.delete(uid); }
Christopher Tate3799bc22009-05-06 16:13:56 -0700356 }
357 }
358 }
359 }
360
Christopher Tate181fafa2009-05-14 11:12:14 -0700361 // Returns the set of all applications that define an android:backupAgent attribute
362 private List<ApplicationInfo> allAgentApps() {
363 List<ApplicationInfo> allApps = mPackageManager.getInstalledApplications(0);
364 int N = allApps.size();
365 if (N > 0) {
366 for (int a = N-1; a >= 0; a--) {
367 ApplicationInfo app = allApps.get(a);
368 if (app.backupAgentName == null) {
369 allApps.remove(a);
370 }
371 }
372 }
373 return allApps;
374 }
375
Christopher Tate3799bc22009-05-06 16:13:56 -0700376 // Reset the given package's known backup participants. Unlike add/remove, the update
377 // action cannot be passed a null package name.
378 void updatePackageParticipantsLocked(String packageName) {
379 if (packageName == null) {
380 Log.e(TAG, "updatePackageParticipants called with null package name");
381 return;
382 }
Christopher Tate043dadc2009-06-02 16:11:00 -0700383 if (DEBUG) Log.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700384
385 // brute force but small code size
Christopher Tate181fafa2009-05-14 11:12:14 -0700386 List<ApplicationInfo> allApps = allAgentApps();
387 removePackageParticipantsLockedInner(packageName, allApps);
388 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700389 }
390
Christopher Tate043dadc2009-06-02 16:11:00 -0700391 // ----- Back up a set of applications via a worker thread -----
392
393 class PerformBackupThread extends Thread {
394 private static final String TAG = "PerformBackupThread";
395 int mTransport;
396 ArrayList<BackupRequest> mQueue;
397
398 public PerformBackupThread(int transportId, ArrayList<BackupRequest> queue) {
399 mTransport = transportId;
400 mQueue = queue;
401 }
402
403 @Override
404 public void run() {
405 /*
406 * 1. start up the current transport
407 * 2. for each item in the queue:
408 * 2a. bind the agent [wait for async attach]
409 * 2b. set up the files and call doBackup()
410 * 2c. unbind the agent
411 * 3. tear down the transport
412 * 4. done!
413 */
414 if (DEBUG) Log.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
415
416 // stand up the current transport
417 IBackupTransport transport = null;
418 switch (mTransport) {
419 case BackupManager.TRANSPORT_ADB:
420 if (DEBUG) Log.v(TAG, "Initializing adb transport");
421 transport = new AdbTransport();
422 break;
423
424 case BackupManager.TRANSPORT_GOOGLE:
425 if (DEBUG) Log.v(TAG, "Initializing Google transport");
426 //!!! TODO: stand up the google backup transport here
427 transport = new GoogleTransport();
428 break;
429
430 default:
431 Log.e(TAG, "Perform backup with unknown transport " + mTransport);
432 // !!! TODO: re-enqueue the backup queue for later?
433 return;
434 }
435
436 try {
437 transport.startSession();
438 } catch (Exception e) {
439 Log.e(TAG, "Error starting backup session");
440 e.printStackTrace();
441 // !!! TODO: re-enqueue the backup queue for later?
442 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 Tate043dadc2009-06-02 16:11:00 -0700615
616
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700617 @Override
618 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
619 synchronized (mQueueLock) {
620 int N = mBackupParticipants.size();
621 pw.println("Participants:");
622 for (int i=0; i<N; i++) {
623 int uid = mBackupParticipants.keyAt(i);
624 pw.print(" uid: ");
625 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -0700626 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
627 for (ApplicationInfo app: participants) {
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700628 pw.print(" ");
Christopher Tate181fafa2009-05-14 11:12:14 -0700629 pw.println(app.toString());
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700630 }
631 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700632 pw.println("Pending:");
633 Iterator<BackupRequest> br = mPendingBackups.values().iterator();
634 while (br.hasNext()) {
635 pw.print(" ");
636 pw.println(br);
637 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -0700638 }
639 }
Christopher Tate487529a2009-04-29 14:03:25 -0700640}