OSDN Git Service

Introduce BackupManagerServiceInteface in remaining parts of the code.
authorArtem Iglikov <artikz@google.com>
Wed, 5 Apr 2017 12:43:10 +0000 (13:43 +0100)
committerArtem Iglikov <artikz@google.com>
Wed, 5 Apr 2017 13:54:07 +0000 (14:54 +0100)
Use it in Trampoline, KeyValueAdbBackupEngine, KeyValueAdbRestoreEngine
where it wasn't used automatically, because of using package-private
methods and fields. To be able to do this, also make couple of methods
public and move them to the interface and add getBackupManagerBinder()
method to use instead of directly accessing the field.

Test: not required as behaviour is not modified.

Bug: 36850431

Change-Id: Ia7a26f93f8dba37ece87305979c922acb58a271f

services/backup/java/com/android/server/backup/BackupManagerService.java
services/backup/java/com/android/server/backup/BackupManagerServiceInterface.java
services/backup/java/com/android/server/backup/BackupRestoreTask.java [new file with mode: 0644]
services/backup/java/com/android/server/backup/FileMetadata.java [new file with mode: 0644]
services/backup/java/com/android/server/backup/KeyValueAdbBackupEngine.java
services/backup/java/com/android/server/backup/KeyValueAdbRestoreEngine.java
services/backup/java/com/android/server/backup/Trampoline.java

index f3e59f3..4057857 100644 (file)
@@ -306,6 +306,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
     private PowerManager mPowerManager;
     private AlarmManager mAlarmManager;
     private IStorageManager mStorageManager;
+
     IBackupManager mBackupManagerBinder;
 
     private final TransportManager mTransportManager;
@@ -763,7 +764,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
     ArrayList<FullBackupEntry> mFullBackupQueue;
 
     // Utility: build a new random integer token
-    int generateToken() {
+    @Override
+    public int generateRandomIntegerToken() {
         int token;
         do {
             synchronized (mTokenGenerator) {
@@ -2274,7 +2276,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
     }
 
     // fire off a backup agent, blocking until it attaches or times out
-    IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
+    @Override
+    public IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
         IBackupAgent agent = null;
         synchronized(mAgentConnectLock) {
             mConnecting = true;
@@ -2495,22 +2498,9 @@ public class BackupManagerService implements BackupManagerServiceInterface {
         }
     }
 
-    // -----
-    // Interface and methods used by the asynchronous-with-timeout backup/restore operations
-
-    interface BackupRestoreTask {
-        // Execute one tick of whatever state machine the task implements
-        void execute();
-
-        // An operation that wanted a callback has completed
-        void operationComplete(long result);
-
-        // An operation that wanted a callback has timed out
-        void handleCancel(boolean cancelAll);
-    }
-
-    void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback,
-            int operationType) {
+    @Override
+    public void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback,
+        int operationType) {
         if (operationType != OP_TYPE_BACKUP_WAIT && operationType != OP_TYPE_RESTORE_WAIT) {
             Slog.wtf(TAG, "prepareOperationTimeout() doesn't support operation " +
                     Integer.toHexString(token) + " of type " + operationType);
@@ -2554,7 +2544,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
     }
 
     // synchronous waiter case
-    boolean waitUntilOperationComplete(int token) {
+    @Override
+    public boolean waitUntilOperationComplete(int token) {
         if (MORE_DEBUG) Slog.i(TAG, "Blocking until operation complete for "
                 + Integer.toHexString(token));
         int finalState = OP_PENDING;
@@ -2716,7 +2707,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
             mNonIncremental = nonIncremental;
 
             mStateDir = new File(mBaseStateDir, dirName);
-            mCurrentOpToken = generateToken();
+            mCurrentOpToken = generateRandomIntegerToken();
 
             mFinished = false;
 
@@ -3174,7 +3165,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
             mNewState = null;
 
             boolean callingAgent = false;
-            mEphemeralOpToken = generateToken();
+            mEphemeralOpToken = generateRandomIntegerToken();
             try {
                 // Look up the package info & signatures.  This is first so that if it
                 // throws an exception, there's no file setup yet that would need to
@@ -3671,7 +3662,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
             ParcelFileDescriptor[] pipes = null;
             try {
                 pipes = ParcelFileDescriptor.createPipe();
-                int token = generateToken();
+                int token = generateRandomIntegerToken();
                 prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL,
                         null, OP_TYPE_BACKUP_WAIT);
                 mService.backupObbs(pkg.packageName, pipes[1], token, mBackupManagerBinder);
@@ -3757,7 +3748,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
         }
     }
 
-    void tearDownAgentAndKill(ApplicationInfo app) {
+    @Override
+    public void tearDownAgentAndKill(ApplicationInfo app) {
         if (app == null) {
             // Null means the system package, so just quietly move on.  :)
             return;
@@ -4204,7 +4196,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
                 String curPassword, String encryptPassword, boolean doAllApps, boolean doSystem,
                 boolean doCompress, boolean doKeyValue, String[] packages, AtomicBoolean latch) {
             super(observer);
-            mCurrentOpToken = generateToken();
+            mCurrentOpToken = generateRandomIntegerToken();
             mLatch = latch;
 
             mOutputFile = fd;
@@ -4654,8 +4646,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
             mBackupObserver = backupObserver;
             mMonitor = monitor;
             mUserInitiated = userInitiated;
-            mCurrentOpToken = generateToken();
-            mBackupRunnerOpToken = generateToken();
+            mCurrentOpToken = generateRandomIntegerToken();
+            mBackupRunnerOpToken = generateRandomIntegerToken();
 
             if (isBackupOperationInProgress()) {
                 if (DEBUG) {
@@ -5248,7 +5240,7 @@ public class BackupManagerService implements BackupManagerServiceInterface {
                 mOutput = ParcelFileDescriptor.dup(output.getFileDescriptor());
                 mTarget = target;
                 mCurrentOpToken = currentOpToken;
-                mEphemeralToken = generateToken();
+                mEphemeralToken = generateRandomIntegerToken();
                 mPreflight = new SinglePackageBackupPreflight(transport, quota, mEphemeralToken);
                 mPreflightLatch = new CountDownLatch(1);
                 mBackupLatch = new CountDownLatch(1);
@@ -5478,7 +5470,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
      * @return Whether ongoing work will continue.  The return value here will be passed
      *         along as the return value to the scheduled job's onStartJob() callback.
      */
-    boolean beginFullBackup(FullBackupJob scheduledJob) {
+    @Override
+    public boolean beginFullBackup(FullBackupJob scheduledJob) {
         long now = System.currentTimeMillis();
         FullBackupEntry entry = null;
         long latency = MIN_FULL_BACKUP_INTERVAL;
@@ -5636,7 +5629,8 @@ public class BackupManagerService implements BackupManagerServiceInterface {
 
     // The job scheduler says our constraints don't hold any more,
     // so tear down any ongoing backup task right away.
-    void endFullBackup() {
+    @Override
+    public void endFullBackup() {
         synchronized (mQueueLock) {
             if (mRunningFullBackupTask != null) {
                 if (DEBUG_SCHEDULING) {
@@ -5694,30 +5688,6 @@ public class BackupManagerService implements BackupManagerServiceInterface {
 
     // ----- Full restore from a file/socket -----
 
-    // Description of a file in the restore datastream
-    static class FileMetadata {
-        String packageName;             // name of the owning app
-        String installerPackageName;    // name of the market-type app that installed the owner
-        int type;                       // e.g. BackupAgent.TYPE_DIRECTORY
-        String domain;                  // e.g. FullBackup.DATABASE_TREE_TOKEN
-        String path;                    // subpath within the semantic domain
-        long mode;                      // e.g. 0666 (actually int)
-        long mtime;                     // last mod time, UTC time_t (actually int)
-        long size;                      // bytes of content
-
-        @Override
-        public String toString() {
-            StringBuilder sb = new StringBuilder(128);
-            sb.append("FileMetadata{");
-            sb.append(packageName); sb.append(',');
-            sb.append(type); sb.append(',');
-            sb.append(domain); sb.append(':'); sb.append(path); sb.append(',');
-            sb.append(size);
-            sb.append('}');
-            return sb.toString();
-        }
-    }
-
     enum RestorePolicy {
         IGNORE,
         ACCEPT,
@@ -7564,7 +7534,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
                         if (okay) {
                             boolean agentSuccess = true;
                             long toCopy = info.size;
-                            final int token = generateToken();
+                            final int token = generateRandomIntegerToken();
                             try {
                                 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL, null,
                                         OP_TYPE_RESTORE_WAIT);
@@ -7708,7 +7678,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
                 try {
                     // In the adb restore case, we do restore-finished here
                     if (doRestoreFinished) {
-                        final int token = generateToken();
+                        final int token = generateRandomIntegerToken();
                         final AdbRestoreFinishedLatch latch = new AdbRestoreFinishedLatch(token);
                         prepareOperationTimeout(token, TIMEOUT_FULL_BACKUP_INTERVAL, latch,
                                 OP_TYPE_RESTORE_WAIT);
@@ -8587,7 +8557,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
         PerformUnifiedRestoreTask(IBackupTransport transport, IRestoreObserver observer,
                 IBackupManagerMonitor monitor, long restoreSetToken, PackageInfo targetPackage,
                 int pmToken, boolean isFullSystemRestore, String[] filterSet) {
-            mEphemeralOpToken = generateToken();
+            mEphemeralOpToken = generateRandomIntegerToken();
             mState = UnifiedRestoreState.INITIAL;
             mStartRealtime = SystemClock.elapsedRealtime();
 
@@ -9217,7 +9187,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
             private final int mEphemeralOpToken;
 
             public StreamFeederThread() throws IOException {
-                mEphemeralOpToken = generateToken();
+                mEphemeralOpToken = generateRandomIntegerToken();
                 mTransportPipes = ParcelFileDescriptor.createPipe();
                 mEnginePipes = ParcelFileDescriptor.createPipe();
                 setRunning(true);
@@ -10039,7 +10009,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
             AdbBackupParams params = new AdbBackupParams(fd, includeApks, includeObbs,
                     includeShared, doWidgets, doAllApps, includeSystem, compress, doKeyValue,
                     pkgList);
-            final int token = generateToken();
+            final int token = generateRandomIntegerToken();
             synchronized (mAdbBackupRestoreConfirmations) {
                 mAdbBackupRestoreConfirmations.put(token, params);
             }
@@ -10147,7 +10117,7 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
             Slog.i(TAG, "Beginning restore...");
 
             AdbRestoreParams params = new AdbRestoreParams(fd);
-            final int token = generateToken();
+            final int token = generateRandomIntegerToken();
             synchronized (mAdbBackupRestoreConfirmations) {
                 mAdbBackupRestoreConfirmations.put(token, params);
             }
@@ -11397,4 +11367,10 @@ if (MORE_DEBUG) Slog.v(TAG, "   + got " + nRead + "; now wanting " + (size - soF
         }
         return null;
     }
+
+    @Override
+    public IBackupManager getBackupManagerBinder() {
+        return mBackupManagerBinder;
+    }
+
 }
index 9f61191..e415494 100644 (file)
@@ -16,6 +16,8 @@
 
 package com.android.server.backup;
 
+import android.app.IBackupAgent;
+import android.app.backup.IBackupManager;
 import android.app.backup.IBackupManagerMonitor;
 import android.app.backup.IBackupObserver;
 import android.app.backup.IFullBackupRestoreObserver;
@@ -23,6 +25,7 @@ import android.app.backup.IRestoreSession;
 import android.app.backup.ISelectBackupTransportCallback;
 import android.content.ComponentName;
 import android.content.Intent;
+import android.content.pm.ApplicationInfo;
 import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
 import java.io.FileDescriptor;
@@ -36,10 +39,16 @@ import java.io.PrintWriter;
  */
 public interface BackupManagerServiceInterface {
 
+  // Utility: build a new random integer token
+  int generateRandomIntegerToken();
+
   boolean setBackupPassword(String currentPw, String newPw);
 
   boolean hasBackupPassword();
 
+  // fire off a backup agent, blocking until it attaches or times out
+  IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode);
+
   // Get the restore-set token for the best-available restore set for this package:
   // the active set if possible, else the ancestral one.  Returns zero if none available.
   long getAvailableRestoreToken(String packageName);
@@ -52,6 +61,20 @@ public interface BackupManagerServiceInterface {
   // Cancel all running backups.
   void cancelBackups();
 
+  void prepareOperationTimeout(int token, long interval, BackupRestoreTask callback,
+      int operationType);
+
+  // synchronous waiter case
+  boolean waitUntilOperationComplete(int token);
+
+  void tearDownAgentAndKill(ApplicationInfo app);
+
+  boolean beginFullBackup(FullBackupJob scheduledJob);
+
+  // The job scheduler says our constraints don't hold any more,
+  // so tear down any ongoing backup task right away.
+  void endFullBackup();
+
   void dataChanged(String packageName);
 
   // Clear the given package's backup data from the current transport
@@ -150,4 +173,6 @@ public interface BackupManagerServiceInterface {
   boolean isAppEligibleForBackup(String packageName);
 
   void dump(FileDescriptor fd, PrintWriter pw, String[] args);
+
+  IBackupManager getBackupManagerBinder();
 }
diff --git a/services/backup/java/com/android/server/backup/BackupRestoreTask.java b/services/backup/java/com/android/server/backup/BackupRestoreTask.java
new file mode 100644 (file)
index 0000000..eab1c76
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.backup;
+
+/**
+ * Interface and methods used by the asynchronous-with-timeout backup/restore operations.
+ */
+interface BackupRestoreTask {
+
+    // Execute one tick of whatever state machine the task implements
+    void execute();
+
+    // An operation that wanted a callback has completed
+    void operationComplete(long result);
+
+    // An operation that wanted a callback has timed out
+    void handleCancel(boolean cancelAll);
+}
diff --git a/services/backup/java/com/android/server/backup/FileMetadata.java b/services/backup/java/com/android/server/backup/FileMetadata.java
new file mode 100644 (file)
index 0000000..0f71da9
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.backup;
+
+/**
+ * Description of a file in the restore datastream.
+ */
+class FileMetadata {
+    String packageName;             // name of the owning app
+    String installerPackageName;    // name of the market-type app that installed the owner
+    int type;                       // e.g. BackupAgent.TYPE_DIRECTORY
+    String domain;                  // e.g. FullBackup.DATABASE_TREE_TOKEN
+    String path;                    // subpath within the semantic domain
+    long mode;                      // e.g. 0666 (actually int)
+    long mtime;                     // last mod time, UTC time_t (actually int)
+    long size;                      // bytes of content
+
+    @Override
+    public String toString() {
+        // TODO: Clean this up.
+        StringBuilder sb = new StringBuilder(128);
+        sb.append("FileMetadata{");
+        sb.append(packageName);
+        sb.append(',');
+        sb.append(type);
+        sb.append(',');
+        sb.append(domain);
+        sb.append(':');
+        sb.append(path);
+        sb.append(',');
+        sb.append(size);
+        sb.append('}');
+        return sb.toString();
+    }
+}
index cd13760..d3577e0 100644 (file)
@@ -44,7 +44,7 @@ class KeyValueAdbBackupEngine {
     private static final String BACKUP_KEY_VALUE_BACKUP_DATA_FILENAME_SUFFIX = ".data";
     private static final String BACKUP_KEY_VALUE_NEW_STATE_FILENAME_SUFFIX = ".new";
 
-    private BackupManagerService mBackupManagerService;
+    private BackupManagerServiceInterface mBackupManagerService;
     private final PackageManager mPackageManager;
     private final OutputStream mOutput;
     private final PackageInfo mCurrentPackage;
@@ -59,7 +59,7 @@ class KeyValueAdbBackupEngine {
     private ParcelFileDescriptor mNewState;
 
     KeyValueAdbBackupEngine(OutputStream output, PackageInfo packageInfo,
-            BackupManagerService backupManagerService, PackageManager packageManager,
+        BackupManagerServiceInterface backupManagerService, PackageManager packageManager,
             File baseStateDir, File dataDir) {
         mOutput = output;
         mCurrentPackage = packageInfo;
@@ -145,14 +145,14 @@ class KeyValueAdbBackupEngine {
 
     // Return true on backup success, false otherwise
     private boolean invokeAgentForAdbBackup(String packageName, IBackupAgent agent) {
-        int token = mBackupManagerService.generateToken();
+        int token = mBackupManagerService.generateRandomIntegerToken();
         try {
             mBackupManagerService.prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL, null,
                     OP_TYPE_BACKUP_WAIT);
 
             // Start backup and wait for BackupManagerService to get callback for success or timeout
             agent.doBackup(mSavedState, mBackupData, mNewState, Long.MAX_VALUE, token,
-                    mBackupManagerService.mBackupManagerBinder);
+                    mBackupManagerService.getBackupManagerBinder());
             if (!mBackupManagerService.waitUntilOperationComplete(token)) {
                 Slog.e(TAG, "Key-value backup failed on package " + packageName);
                 return false;
@@ -214,7 +214,7 @@ class KeyValueAdbBackupEngine {
                 }
 
                 try {
-                    mBackupManagerService.mBackupManagerBinder.opComplete(mToken, 0);
+                    mBackupManagerService.getBackupManagerBinder().opComplete(mToken, 0);
                 } catch (RemoteException e) {
                     // we'll time out anyway, so we're safe
                 }
@@ -229,7 +229,7 @@ class KeyValueAdbBackupEngine {
 
     private void writeBackupData() throws IOException {
 
-        int token = mBackupManagerService.generateToken();
+        int token = mBackupManagerService.generateRandomIntegerToken();
 
         ParcelFileDescriptor[] pipes = null;
         try {
index 6fb9355..38791c1 100644 (file)
@@ -13,7 +13,6 @@ import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.util.Slog;
 
-import com.android.server.backup.BackupManagerService.FileMetadata;
 import libcore.io.IoUtils;
 
 import java.io.File;
@@ -38,7 +37,7 @@ class KeyValueAdbRestoreEngine implements Runnable {
     private static final String TAG = "KeyValueAdbRestoreEngine";
     private static final boolean DEBUG = false;
 
-    private final BackupManagerService mBackupManagerService;
+    private final BackupManagerServiceInterface mBackupManagerService;
     private final File mDataDir;
 
     FileMetadata mInfo;
@@ -47,7 +46,7 @@ class KeyValueAdbRestoreEngine implements Runnable {
     IBackupAgent mAgent;
     int mToken;
 
-    KeyValueAdbRestoreEngine(BackupManagerService backupManagerService, File dataDir,
+    KeyValueAdbRestoreEngine(BackupManagerServiceInterface backupManagerService, File dataDir,
             FileMetadata info, ParcelFileDescriptor inFD, IBackupAgent agent, int token) {
         mBackupManagerService = backupManagerService;
         mDataDir = dataDir;
@@ -96,7 +95,7 @@ class KeyValueAdbRestoreEngine implements Runnable {
                         + versionCode);
             }
             agent.doRestore(backupData, versionCode, newState, mToken,
-                    mBackupManagerService.mBackupManagerBinder);
+                    mBackupManagerService.getBackupManagerBinder());
         } catch (IOException e) {
             Slog.e(TAG, "Exception opening file. " + e);
         } catch (RemoteException e) {
index b89bad5..2c22ef4 100644 (file)
@@ -55,7 +55,7 @@ public class Trampoline extends IBackupManager.Stub {
     final Context mContext;
     final File mSuppressFile;   // existence testing & creating synchronized on 'this'
     final boolean mGlobalDisable;
-    volatile BackupManagerService mService;
+    volatile BackupManagerServiceInterface mService;
 
     public Trampoline(Context context) {
         mContext = context;
@@ -387,12 +387,12 @@ public class Trampoline extends IBackupManager.Stub {
     // Full backup/restore entry points - non-Binder; called directly
     // by the full-backup scheduled job
     /* package */ boolean beginFullBackup(FullBackupJob scheduledJob) {
-        BackupManagerService svc = mService;
+        BackupManagerServiceInterface svc = mService;
         return (svc != null) ? svc.beginFullBackup(scheduledJob) : false;
     }
 
     /* package */ void endFullBackup() {
-        BackupManagerService svc = mService;
+        BackupManagerServiceInterface svc = mService;
         if (svc != null) {
             svc.endFullBackup();
         }