• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 
17 package android.content;
18 
19 import android.accounts.Account;
20 import android.accounts.AccountAndUser;
21 import android.accounts.AccountManager;
22 import android.accounts.AccountManagerService;
23 import android.app.ActivityManager;
24 import android.app.AlarmManager;
25 import android.app.Notification;
26 import android.app.NotificationManager;
27 import android.app.PendingIntent;
28 import android.content.SyncStorageEngine.OnSyncRequestListener;
29 import android.content.pm.ApplicationInfo;
30 import android.content.pm.PackageManager;
31 import android.content.pm.ProviderInfo;
32 import android.content.pm.RegisteredServicesCache;
33 import android.content.pm.RegisteredServicesCacheListener;
34 import android.content.pm.ResolveInfo;
35 import android.content.pm.UserInfo;
36 import android.net.ConnectivityManager;
37 import android.net.NetworkInfo;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.HandlerThread;
41 import android.os.IBinder;
42 import android.os.Looper;
43 import android.os.Message;
44 import android.os.PowerManager;
45 import android.os.Process;
46 import android.os.RemoteException;
47 import android.os.SystemClock;
48 import android.os.SystemProperties;
49 import android.os.UserHandle;
50 import android.os.UserManager;
51 import android.os.WorkSource;
52 import android.provider.Settings;
53 import android.text.format.DateUtils;
54 import android.text.format.Time;
55 import android.util.EventLog;
56 import android.util.Log;
57 import android.util.Pair;
58 import android.util.Slog;
59 
60 import com.android.internal.R;
61 import com.android.internal.annotations.GuardedBy;
62 import com.android.internal.util.IndentingPrintWriter;
63 import com.google.android.collect.Lists;
64 import com.google.android.collect.Maps;
65 import com.google.android.collect.Sets;
66 
67 import java.io.FileDescriptor;
68 import java.io.PrintWriter;
69 import java.util.ArrayList;
70 import java.util.Arrays;
71 import java.util.Collection;
72 import java.util.Collections;
73 import java.util.Comparator;
74 import java.util.HashMap;
75 import java.util.HashSet;
76 import java.util.Iterator;
77 import java.util.List;
78 import java.util.Map;
79 import java.util.Random;
80 import java.util.Set;
81 import java.util.concurrent.CountDownLatch;
82 
83 /**
84  * @hide
85  */
86 public class SyncManager {
87     private static final String TAG = "SyncManager";
88 
89     /** Delay a sync due to local changes this long. In milliseconds */
90     private static final long LOCAL_SYNC_DELAY;
91 
92     /**
93      * If a sync takes longer than this and the sync queue is not empty then we will
94      * cancel it and add it back to the end of the sync queue. In milliseconds.
95      */
96     private static final long MAX_TIME_PER_SYNC;
97 
98     static {
99         final boolean isLargeRAM = ActivityManager.isLargeRAM();
100         int defaultMaxInitSyncs = isLargeRAM ? 5 : 2;
101         int defaultMaxRegularSyncs = isLargeRAM ? 2 : 1;
102         MAX_SIMULTANEOUS_INITIALIZATION_SYNCS =
103                 SystemProperties.getInt("sync.max_init_syncs", defaultMaxInitSyncs);
104         MAX_SIMULTANEOUS_REGULAR_SYNCS =
105                 SystemProperties.getInt("sync.max_regular_syncs", defaultMaxRegularSyncs);
106         LOCAL_SYNC_DELAY =
107                 SystemProperties.getLong("sync.local_sync_delay", 30 * 1000 /* 30 seconds */);
108         MAX_TIME_PER_SYNC =
109                 SystemProperties.getLong("sync.max_time_per_sync", 5 * 60 * 1000 /* 5 minutes */);
110         SYNC_NOTIFICATION_DELAY =
111                 SystemProperties.getLong("sync.notification_delay", 30 * 1000 /* 30 seconds */);
112     }
113 
114     private static final long SYNC_NOTIFICATION_DELAY;
115 
116     /**
117      * When retrying a sync for the first time use this delay. After that
118      * the retry time will double until it reached MAX_SYNC_RETRY_TIME.
119      * In milliseconds.
120      */
121     private static final long INITIAL_SYNC_RETRY_TIME_IN_MS = 30 * 1000; // 30 seconds
122 
123     /**
124      * Default the max sync retry time to this value.
125      */
126     private static final long DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS = 60 * 60; // one hour
127 
128     /**
129      * How long to wait before retrying a sync that failed due to one already being in progress.
130      */
131     private static final int DELAY_RETRY_SYNC_IN_PROGRESS_IN_SECONDS = 10;
132 
133     private static final int INITIALIZATION_UNBIND_DELAY_MS = 5000;
134 
135     private static final String SYNC_WAKE_LOCK_PREFIX = "*sync*";
136     private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarm";
137     private static final String SYNC_LOOP_WAKE_LOCK = "SyncLoopWakeLock";
138 
139     private static final int MAX_SIMULTANEOUS_REGULAR_SYNCS;
140     private static final int MAX_SIMULTANEOUS_INITIALIZATION_SYNCS;
141 
142     private Context mContext;
143 
144     private static final AccountAndUser[] INITIAL_ACCOUNTS_ARRAY = new AccountAndUser[0];
145 
146     // TODO: add better locking around mRunningAccounts
147     private volatile AccountAndUser[] mRunningAccounts = INITIAL_ACCOUNTS_ARRAY;
148 
149     volatile private PowerManager.WakeLock mHandleAlarmWakeLock;
150     volatile private PowerManager.WakeLock mSyncManagerWakeLock;
151     volatile private boolean mDataConnectionIsConnected = false;
152     volatile private boolean mStorageIsLow = false;
153 
154     private final NotificationManager mNotificationMgr;
155     private AlarmManager mAlarmService = null;
156 
157     private SyncStorageEngine mSyncStorageEngine;
158 
159     @GuardedBy("mSyncQueue")
160     private final SyncQueue mSyncQueue;
161 
162     protected final ArrayList<ActiveSyncContext> mActiveSyncContexts = Lists.newArrayList();
163 
164     // set if the sync active indicator should be reported
165     private boolean mNeedSyncActiveNotification = false;
166 
167     private final PendingIntent mSyncAlarmIntent;
168     // Synchronized on "this". Instead of using this directly one should instead call
169     // its accessor, getConnManager().
170     private ConnectivityManager mConnManagerDoNotUseDirectly;
171 
172     protected SyncAdaptersCache mSyncAdapters;
173 
174     private BroadcastReceiver mStorageIntentReceiver =
175             new BroadcastReceiver() {
176                 public void onReceive(Context context, Intent intent) {
177                     String action = intent.getAction();
178                     if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
179                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
180                             Log.v(TAG, "Internal storage is low.");
181                         }
182                         mStorageIsLow = true;
183                         cancelActiveSync(null /* any account */, UserHandle.USER_ALL,
184                                 null /* any authority */);
185                     } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
186                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
187                             Log.v(TAG, "Internal storage is ok.");
188                         }
189                         mStorageIsLow = false;
190                         sendCheckAlarmsMessage();
191                     }
192                 }
193             };
194 
195     private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
196         public void onReceive(Context context, Intent intent) {
197             mSyncHandler.onBootCompleted();
198         }
199     };
200 
201     private BroadcastReceiver mBackgroundDataSettingChanged = new BroadcastReceiver() {
202         public void onReceive(Context context, Intent intent) {
203             if (getConnectivityManager().getBackgroundDataSetting()) {
204                 scheduleSync(null /* account */, UserHandle.USER_ALL, null /* authority */,
205                         new Bundle(), 0 /* delay */,
206                         false /* onlyThoseWithUnknownSyncableState */);
207             }
208         }
209     };
210 
211     private BroadcastReceiver mAccountsUpdatedReceiver = new BroadcastReceiver() {
212         public void onReceive(Context context, Intent intent) {
213             updateRunningAccounts();
214 
215             // Kick off sync for everyone, since this was a radical account change
216             scheduleSync(null, UserHandle.USER_ALL, null, null, 0 /* no delay */, false);
217         }
218     };
219 
220     private final PowerManager mPowerManager;
221 
222     // Use this as a random offset to seed all periodic syncs
223     private int mSyncRandomOffsetMillis;
224 
225     private final UserManager mUserManager;
226 
227     private static final long SYNC_ALARM_TIMEOUT_MIN = 30 * 1000; // 30 seconds
228     private static final long SYNC_ALARM_TIMEOUT_MAX = 2 * 60 * 60 * 1000; // two hours
229 
getAllUsers()230     private List<UserInfo> getAllUsers() {
231         return mUserManager.getUsers();
232     }
233 
containsAccountAndUser(AccountAndUser[] accounts, Account account, int userId)234     private boolean containsAccountAndUser(AccountAndUser[] accounts, Account account, int userId) {
235         boolean found = false;
236         for (int i = 0; i < accounts.length; i++) {
237             if (accounts[i].userId == userId
238                     && accounts[i].account.equals(account)) {
239                 found = true;
240                 break;
241             }
242         }
243         return found;
244     }
245 
updateRunningAccounts()246     public void updateRunningAccounts() {
247         mRunningAccounts = AccountManagerService.getSingleton().getRunningAccounts();
248 
249         if (mBootCompleted) {
250             doDatabaseCleanup();
251         }
252 
253         for (ActiveSyncContext currentSyncContext : mActiveSyncContexts) {
254             if (!containsAccountAndUser(mRunningAccounts,
255                     currentSyncContext.mSyncOperation.account,
256                     currentSyncContext.mSyncOperation.userId)) {
257                 Log.d(TAG, "canceling sync since the account is no longer running");
258                 sendSyncFinishedOrCanceledMessage(currentSyncContext,
259                         null /* no result since this is a cancel */);
260             }
261         }
262 
263         // we must do this since we don't bother scheduling alarms when
264         // the accounts are not set yet
265         sendCheckAlarmsMessage();
266     }
267 
doDatabaseCleanup()268     private void doDatabaseCleanup() {
269         for (UserInfo user : mUserManager.getUsers(true)) {
270             // Skip any partially created/removed users
271             if (user.partial) continue;
272             Account[] accountsForUser = AccountManagerService.getSingleton().getAccounts(user.id);
273             mSyncStorageEngine.doDatabaseCleanup(accountsForUser, user.id);
274         }
275     }
276 
277     private BroadcastReceiver mConnectivityIntentReceiver =
278             new BroadcastReceiver() {
279         public void onReceive(Context context, Intent intent) {
280             final boolean wasConnected = mDataConnectionIsConnected;
281 
282             // don't use the intent to figure out if network is connected, just check
283             // ConnectivityManager directly.
284             mDataConnectionIsConnected = readDataConnectionState();
285             if (mDataConnectionIsConnected) {
286                 if (!wasConnected) {
287                     if (Log.isLoggable(TAG, Log.VERBOSE)) {
288                         Log.v(TAG, "Reconnection detected: clearing all backoffs");
289                     }
290                     mSyncStorageEngine.clearAllBackoffs(mSyncQueue);
291                 }
292                 sendCheckAlarmsMessage();
293             }
294         }
295     };
296 
readDataConnectionState()297     private boolean readDataConnectionState() {
298         NetworkInfo networkInfo = getConnectivityManager().getActiveNetworkInfo();
299         return (networkInfo != null) && networkInfo.isConnected();
300     }
301 
302     private BroadcastReceiver mShutdownIntentReceiver =
303             new BroadcastReceiver() {
304         public void onReceive(Context context, Intent intent) {
305             Log.w(TAG, "Writing sync state before shutdown...");
306             getSyncStorageEngine().writeAllState();
307         }
308     };
309 
310     private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
311         @Override
312         public void onReceive(Context context, Intent intent) {
313             String action = intent.getAction();
314             final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
315             if (userId == UserHandle.USER_NULL) return;
316 
317             if (Intent.ACTION_USER_REMOVED.equals(action)) {
318                 onUserRemoved(userId);
319             } else if (Intent.ACTION_USER_STARTING.equals(action)) {
320                 onUserStarting(userId);
321             } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
322                 onUserStopping(userId);
323             }
324         }
325     };
326 
327     private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM";
328     private final SyncHandler mSyncHandler;
329 
330     private volatile boolean mBootCompleted = false;
331 
getConnectivityManager()332     private ConnectivityManager getConnectivityManager() {
333         synchronized (this) {
334             if (mConnManagerDoNotUseDirectly == null) {
335                 mConnManagerDoNotUseDirectly = (ConnectivityManager)mContext.getSystemService(
336                         Context.CONNECTIVITY_SERVICE);
337             }
338             return mConnManagerDoNotUseDirectly;
339         }
340     }
341 
342     /**
343      * Should only be created after {@link ContentService#systemReady()} so that
344      * {@link PackageManager} is ready to query.
345      */
SyncManager(Context context, boolean factoryTest)346     public SyncManager(Context context, boolean factoryTest) {
347         // Initialize the SyncStorageEngine first, before registering observers
348         // and creating threads and so on; it may fail if the disk is full.
349         mContext = context;
350 
351         SyncStorageEngine.init(context);
352         mSyncStorageEngine = SyncStorageEngine.getSingleton();
353         mSyncStorageEngine.setOnSyncRequestListener(new OnSyncRequestListener() {
354             public void onSyncRequest(Account account, int userId, String authority,
355                     Bundle extras) {
356                 scheduleSync(account, userId, authority, extras, 0, false);
357             }
358         });
359 
360         mSyncAdapters = new SyncAdaptersCache(mContext);
361         mSyncQueue = new SyncQueue(mSyncStorageEngine, mSyncAdapters);
362 
363         HandlerThread syncThread = new HandlerThread("SyncHandlerThread",
364                 Process.THREAD_PRIORITY_BACKGROUND);
365         syncThread.start();
366         mSyncHandler = new SyncHandler(syncThread.getLooper());
367 
368         mSyncAdapters.setListener(new RegisteredServicesCacheListener<SyncAdapterType>() {
369             @Override
370             public void onServiceChanged(SyncAdapterType type, int userId, boolean removed) {
371                 if (!removed) {
372                     scheduleSync(null, UserHandle.USER_ALL, type.authority, null, 0 /* no delay */,
373                             false /* onlyThoseWithUnkownSyncableState */);
374                 }
375             }
376         }, mSyncHandler);
377 
378         mSyncAlarmIntent = PendingIntent.getBroadcast(
379                 mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0);
380 
381         IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
382         context.registerReceiver(mConnectivityIntentReceiver, intentFilter);
383 
384         if (!factoryTest) {
385             intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
386             context.registerReceiver(mBootCompletedReceiver, intentFilter);
387         }
388 
389         intentFilter = new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
390         context.registerReceiver(mBackgroundDataSettingChanged, intentFilter);
391 
392         intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
393         intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
394         context.registerReceiver(mStorageIntentReceiver, intentFilter);
395 
396         intentFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
397         intentFilter.setPriority(100);
398         context.registerReceiver(mShutdownIntentReceiver, intentFilter);
399 
400         intentFilter = new IntentFilter();
401         intentFilter.addAction(Intent.ACTION_USER_REMOVED);
402         intentFilter.addAction(Intent.ACTION_USER_STARTING);
403         intentFilter.addAction(Intent.ACTION_USER_STOPPING);
404         mContext.registerReceiverAsUser(
405                 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
406 
407         if (!factoryTest) {
408             mNotificationMgr = (NotificationManager)
409                 context.getSystemService(Context.NOTIFICATION_SERVICE);
410             context.registerReceiver(new SyncAlarmIntentReceiver(),
411                     new IntentFilter(ACTION_SYNC_ALARM));
412         } else {
413             mNotificationMgr = null;
414         }
415         mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
416         mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
417 
418         // This WakeLock is used to ensure that we stay awake between the time that we receive
419         // a sync alarm notification and when we finish processing it. We need to do this
420         // because we don't do the work in the alarm handler, rather we do it in a message
421         // handler.
422         mHandleAlarmWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
423                 HANDLE_SYNC_ALARM_WAKE_LOCK);
424         mHandleAlarmWakeLock.setReferenceCounted(false);
425 
426         // This WakeLock is used to ensure that we stay awake while running the sync loop
427         // message handler. Normally we will hold a sync adapter wake lock while it is being
428         // synced but during the execution of the sync loop it might finish a sync for
429         // one sync adapter before starting the sync for the other sync adapter and we
430         // don't want the device to go to sleep during that window.
431         mSyncManagerWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
432                 SYNC_LOOP_WAKE_LOCK);
433         mSyncManagerWakeLock.setReferenceCounted(false);
434 
435         mSyncStorageEngine.addStatusChangeListener(
436                 ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, new ISyncStatusObserver.Stub() {
437             public void onStatusChanged(int which) {
438                 // force the sync loop to run if the settings change
439                 sendCheckAlarmsMessage();
440             }
441         });
442 
443         if (!factoryTest) {
444             // Register for account list updates for all users
445             mContext.registerReceiverAsUser(mAccountsUpdatedReceiver,
446                     UserHandle.ALL,
447                     new IntentFilter(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION),
448                     null, null);
449         }
450 
451         // Pick a random second in a day to seed all periodic syncs
452         mSyncRandomOffsetMillis = mSyncStorageEngine.getSyncRandomOffset() * 1000;
453     }
454 
455     /**
456      * Return a random value v that satisfies minValue <= v < maxValue. The difference between
457      * maxValue and minValue must be less than Integer.MAX_VALUE.
458      */
jitterize(long minValue, long maxValue)459     private long jitterize(long minValue, long maxValue) {
460         Random random = new Random(SystemClock.elapsedRealtime());
461         long spread = maxValue - minValue;
462         if (spread > Integer.MAX_VALUE) {
463             throw new IllegalArgumentException("the difference between the maxValue and the "
464                     + "minValue must be less than " + Integer.MAX_VALUE);
465         }
466         return minValue + random.nextInt((int)spread);
467     }
468 
getSyncStorageEngine()469     public SyncStorageEngine getSyncStorageEngine() {
470         return mSyncStorageEngine;
471     }
472 
ensureAlarmService()473     private void ensureAlarmService() {
474         if (mAlarmService == null) {
475             mAlarmService = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
476         }
477     }
478 
479     /**
480      * Initiate a sync. This can start a sync for all providers
481      * (pass null to url, set onlyTicklable to false), only those
482      * providers that are marked as ticklable (pass null to url,
483      * set onlyTicklable to true), or a specific provider (set url
484      * to the content url of the provider).
485      *
486      * <p>If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is
487      * true then initiate a sync that just checks for local changes to send
488      * to the server, otherwise initiate a sync that first gets any
489      * changes from the server before sending local changes back to
490      * the server.
491      *
492      * <p>If a specific provider is being synced (the url is non-null)
493      * then the extras can contain SyncAdapter-specific information
494      * to control what gets synced (e.g. which specific feed to sync).
495      *
496      * <p>You'll start getting callbacks after this.
497      *
498      * @param requestedAccount the account to sync, may be null to signify all accounts
499      * @param userId the id of the user whose accounts are to be synced. If userId is USER_ALL,
500      *          then all users' accounts are considered.
501      * @param requestedAuthority the authority to sync, may be null to indicate all authorities
502      * @param extras a Map of SyncAdapter-specific information to control
503      *          syncs of a specific provider. Can be null. Is ignored
504      *          if the url is null.
505      * @param delay how many milliseconds in the future to wait before performing this
506      * @param onlyThoseWithUnkownSyncableState
507      */
scheduleSync(Account requestedAccount, int userId, String requestedAuthority, Bundle extras, long delay, boolean onlyThoseWithUnkownSyncableState)508     public void scheduleSync(Account requestedAccount, int userId, String requestedAuthority,
509             Bundle extras, long delay, boolean onlyThoseWithUnkownSyncableState) {
510         boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
511 
512         final boolean backgroundDataUsageAllowed = !mBootCompleted ||
513                 getConnectivityManager().getBackgroundDataSetting();
514 
515         if (extras == null) extras = new Bundle();
516 
517         Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
518         if (expedited) {
519             delay = -1; // this means schedule at the front of the queue
520         }
521 
522         AccountAndUser[] accounts;
523         if (requestedAccount != null && userId != UserHandle.USER_ALL) {
524             accounts = new AccountAndUser[] { new AccountAndUser(requestedAccount, userId) };
525         } else {
526             // if the accounts aren't configured yet then we can't support an account-less
527             // sync request
528             accounts = mRunningAccounts;
529             if (accounts.length == 0) {
530                 if (isLoggable) {
531                     Log.v(TAG, "scheduleSync: no accounts configured, dropping");
532                 }
533                 return;
534             }
535         }
536 
537         final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
538         final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
539         if (manualSync) {
540             extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, true);
541             extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, true);
542         }
543         final boolean ignoreSettings =
544                 extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false);
545 
546         int source;
547         if (uploadOnly) {
548             source = SyncStorageEngine.SOURCE_LOCAL;
549         } else if (manualSync) {
550             source = SyncStorageEngine.SOURCE_USER;
551         } else if (requestedAuthority == null) {
552             source = SyncStorageEngine.SOURCE_POLL;
553         } else {
554             // this isn't strictly server, since arbitrary callers can (and do) request
555             // a non-forced two-way sync on a specific url
556             source = SyncStorageEngine.SOURCE_SERVER;
557         }
558 
559         for (AccountAndUser account : accounts) {
560             // Compile a list of authorities that have sync adapters.
561             // For each authority sync each account that matches a sync adapter.
562             final HashSet<String> syncableAuthorities = new HashSet<String>();
563             for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
564                     mSyncAdapters.getAllServices(account.userId)) {
565                 syncableAuthorities.add(syncAdapter.type.authority);
566             }
567 
568             // if the url was specified then replace the list of authorities
569             // with just this authority or clear it if this authority isn't
570             // syncable
571             if (requestedAuthority != null) {
572                 final boolean hasSyncAdapter = syncableAuthorities.contains(requestedAuthority);
573                 syncableAuthorities.clear();
574                 if (hasSyncAdapter) syncableAuthorities.add(requestedAuthority);
575             }
576 
577             for (String authority : syncableAuthorities) {
578                 int isSyncable = mSyncStorageEngine.getIsSyncable(account.account, account.userId,
579                         authority);
580                 if (isSyncable == 0) {
581                     continue;
582                 }
583                 final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
584                 syncAdapterInfo = mSyncAdapters.getServiceInfo(
585                         SyncAdapterType.newKey(authority, account.account.type), account.userId);
586                 if (syncAdapterInfo == null) {
587                     continue;
588                 }
589                 final boolean allowParallelSyncs = syncAdapterInfo.type.allowParallelSyncs();
590                 final boolean isAlwaysSyncable = syncAdapterInfo.type.isAlwaysSyncable();
591                 if (isSyncable < 0 && isAlwaysSyncable) {
592                     mSyncStorageEngine.setIsSyncable(account.account, account.userId, authority, 1);
593                     isSyncable = 1;
594                 }
595                 if (onlyThoseWithUnkownSyncableState && isSyncable >= 0) {
596                     continue;
597                 }
598                 if (!syncAdapterInfo.type.supportsUploading() && uploadOnly) {
599                     continue;
600                 }
601 
602                 // always allow if the isSyncable state is unknown
603                 boolean syncAllowed =
604                         (isSyncable < 0)
605                         || ignoreSettings
606                         || (backgroundDataUsageAllowed
607                                 && mSyncStorageEngine.getMasterSyncAutomatically(account.userId)
608                                 && mSyncStorageEngine.getSyncAutomatically(account.account,
609                                         account.userId, authority));
610                 if (!syncAllowed) {
611                     if (isLoggable) {
612                         Log.d(TAG, "scheduleSync: sync of " + account + ", " + authority
613                                 + " is not allowed, dropping request");
614                     }
615                     continue;
616                 }
617 
618                 Pair<Long, Long> backoff = mSyncStorageEngine
619                         .getBackoff(account.account, account.userId, authority);
620                 long delayUntil = mSyncStorageEngine.getDelayUntilTime(account.account,
621                         account.userId, authority);
622                 final long backoffTime = backoff != null ? backoff.first : 0;
623                 if (isSyncable < 0) {
624                     Bundle newExtras = new Bundle();
625                     newExtras.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
626                     if (isLoggable) {
627                         Log.v(TAG, "scheduleSync:"
628                                 + " delay " + delay
629                                 + ", source " + source
630                                 + ", account " + account
631                                 + ", authority " + authority
632                                 + ", extras " + newExtras);
633                     }
634                     scheduleSyncOperation(
635                             new SyncOperation(account.account, account.userId, source, authority,
636                                     newExtras, 0, backoffTime, delayUntil, allowParallelSyncs));
637                 }
638                 if (!onlyThoseWithUnkownSyncableState) {
639                     if (isLoggable) {
640                         Log.v(TAG, "scheduleSync:"
641                                 + " delay " + delay
642                                 + ", source " + source
643                                 + ", account " + account
644                                 + ", authority " + authority
645                                 + ", extras " + extras);
646                     }
647                     scheduleSyncOperation(
648                             new SyncOperation(account.account, account.userId, source, authority,
649                                     extras, delay, backoffTime, delayUntil, allowParallelSyncs));
650                 }
651             }
652         }
653     }
654 
scheduleLocalSync(Account account, int userId, String authority)655     public void scheduleLocalSync(Account account, int userId, String authority) {
656         final Bundle extras = new Bundle();
657         extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
658         scheduleSync(account, userId, authority, extras, LOCAL_SYNC_DELAY,
659                 false /* onlyThoseWithUnkownSyncableState */);
660     }
661 
getSyncAdapterTypes(int userId)662     public SyncAdapterType[] getSyncAdapterTypes(int userId) {
663         final Collection<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> serviceInfos;
664         serviceInfos = mSyncAdapters.getAllServices(userId);
665         SyncAdapterType[] types = new SyncAdapterType[serviceInfos.size()];
666         int i = 0;
667         for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> serviceInfo : serviceInfos) {
668             types[i] = serviceInfo.type;
669             ++i;
670         }
671         return types;
672     }
673 
sendSyncAlarmMessage()674     private void sendSyncAlarmMessage() {
675         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_ALARM");
676         mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_SYNC_ALARM);
677     }
678 
sendCheckAlarmsMessage()679     private void sendCheckAlarmsMessage() {
680         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CHECK_ALARMS");
681         mSyncHandler.removeMessages(SyncHandler.MESSAGE_CHECK_ALARMS);
682         mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS);
683     }
684 
sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext, SyncResult syncResult)685     private void sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext,
686             SyncResult syncResult) {
687         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_FINISHED");
688         Message msg = mSyncHandler.obtainMessage();
689         msg.what = SyncHandler.MESSAGE_SYNC_FINISHED;
690         msg.obj = new SyncHandlerMessagePayload(syncContext, syncResult);
691         mSyncHandler.sendMessage(msg);
692     }
693 
sendCancelSyncsMessage(final Account account, final int userId, final String authority)694     private void sendCancelSyncsMessage(final Account account, final int userId,
695             final String authority) {
696         if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CANCEL");
697         Message msg = mSyncHandler.obtainMessage();
698         msg.what = SyncHandler.MESSAGE_CANCEL;
699         msg.obj = Pair.create(account, authority);
700         msg.arg1 = userId;
701         mSyncHandler.sendMessage(msg);
702     }
703 
704     class SyncHandlerMessagePayload {
705         public final ActiveSyncContext activeSyncContext;
706         public final SyncResult syncResult;
707 
SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult)708         SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) {
709             this.activeSyncContext = syncContext;
710             this.syncResult = syncResult;
711         }
712     }
713 
714     class SyncAlarmIntentReceiver extends BroadcastReceiver {
onReceive(Context context, Intent intent)715         public void onReceive(Context context, Intent intent) {
716             mHandleAlarmWakeLock.acquire();
717             sendSyncAlarmMessage();
718         }
719     }
720 
clearBackoffSetting(SyncOperation op)721     private void clearBackoffSetting(SyncOperation op) {
722         mSyncStorageEngine.setBackoff(op.account, op.userId, op.authority,
723                 SyncStorageEngine.NOT_IN_BACKOFF_MODE, SyncStorageEngine.NOT_IN_BACKOFF_MODE);
724         synchronized (mSyncQueue) {
725             mSyncQueue.onBackoffChanged(op.account, op.userId, op.authority, 0);
726         }
727     }
728 
increaseBackoffSetting(SyncOperation op)729     private void increaseBackoffSetting(SyncOperation op) {
730         // TODO: Use this function to align it to an already scheduled sync
731         //       operation in the specified window
732         final long now = SystemClock.elapsedRealtime();
733 
734         final Pair<Long, Long> previousSettings =
735                 mSyncStorageEngine.getBackoff(op.account, op.userId, op.authority);
736         long newDelayInMs = -1;
737         if (previousSettings != null) {
738             // don't increase backoff before current backoff is expired. This will happen for op's
739             // with ignoreBackoff set.
740             if (now < previousSettings.first) {
741                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
742                     Log.v(TAG, "Still in backoff, do not increase it. "
743                         + "Remaining: " + ((previousSettings.first - now) / 1000) + " seconds.");
744                 }
745                 return;
746             }
747             // Subsequent delays are the double of the previous delay
748             newDelayInMs = previousSettings.second * 2;
749         }
750         if (newDelayInMs <= 0) {
751             // The initial delay is the jitterized INITIAL_SYNC_RETRY_TIME_IN_MS
752             newDelayInMs = jitterize(INITIAL_SYNC_RETRY_TIME_IN_MS,
753                     (long)(INITIAL_SYNC_RETRY_TIME_IN_MS * 1.1));
754         }
755 
756         // Cap the delay
757         long maxSyncRetryTimeInSeconds = Settings.Global.getLong(mContext.getContentResolver(),
758                 Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
759                 DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS);
760         if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) {
761             newDelayInMs = maxSyncRetryTimeInSeconds * 1000;
762         }
763 
764         final long backoff = now + newDelayInMs;
765 
766         mSyncStorageEngine.setBackoff(op.account, op.userId, op.authority,
767                 backoff, newDelayInMs);
768 
769         op.backoff = backoff;
770         op.updateEffectiveRunTime();
771 
772         synchronized (mSyncQueue) {
773             mSyncQueue.onBackoffChanged(op.account, op.userId, op.authority, backoff);
774         }
775     }
776 
setDelayUntilTime(SyncOperation op, long delayUntilSeconds)777     private void setDelayUntilTime(SyncOperation op, long delayUntilSeconds) {
778         final long delayUntil = delayUntilSeconds * 1000;
779         final long absoluteNow = System.currentTimeMillis();
780         long newDelayUntilTime;
781         if (delayUntil > absoluteNow) {
782             newDelayUntilTime = SystemClock.elapsedRealtime() + (delayUntil - absoluteNow);
783         } else {
784             newDelayUntilTime = 0;
785         }
786         mSyncStorageEngine
787                 .setDelayUntilTime(op.account, op.userId, op.authority, newDelayUntilTime);
788         synchronized (mSyncQueue) {
789             mSyncQueue.onDelayUntilTimeChanged(op.account, op.authority, newDelayUntilTime);
790         }
791     }
792 
793     /**
794      * Cancel the active sync if it matches the authority and account.
795      * @param account limit the cancelations to syncs with this account, if non-null
796      * @param authority limit the cancelations to syncs with this authority, if non-null
797      */
cancelActiveSync(Account account, int userId, String authority)798     public void cancelActiveSync(Account account, int userId, String authority) {
799         sendCancelSyncsMessage(account, userId, authority);
800     }
801 
802     /**
803      * Create and schedule a SyncOperation.
804      *
805      * @param syncOperation the SyncOperation to schedule
806      */
scheduleSyncOperation(SyncOperation syncOperation)807     public void scheduleSyncOperation(SyncOperation syncOperation) {
808         boolean queueChanged;
809         synchronized (mSyncQueue) {
810             queueChanged = mSyncQueue.add(syncOperation);
811         }
812 
813         if (queueChanged) {
814             if (Log.isLoggable(TAG, Log.VERBOSE)) {
815                 Log.v(TAG, "scheduleSyncOperation: enqueued " + syncOperation);
816             }
817             sendCheckAlarmsMessage();
818         } else {
819             if (Log.isLoggable(TAG, Log.VERBOSE)) {
820                 Log.v(TAG, "scheduleSyncOperation: dropping duplicate sync operation "
821                         + syncOperation);
822             }
823         }
824     }
825 
826     /**
827      * Remove scheduled sync operations.
828      * @param account limit the removals to operations with this account, if non-null
829      * @param authority limit the removals to operations with this authority, if non-null
830      */
clearScheduledSyncOperations(Account account, int userId, String authority)831     public void clearScheduledSyncOperations(Account account, int userId, String authority) {
832         synchronized (mSyncQueue) {
833             mSyncQueue.remove(account, userId, authority);
834         }
835         mSyncStorageEngine.setBackoff(account, userId, authority,
836                 SyncStorageEngine.NOT_IN_BACKOFF_MODE, SyncStorageEngine.NOT_IN_BACKOFF_MODE);
837     }
838 
maybeRescheduleSync(SyncResult syncResult, SyncOperation operation)839     void maybeRescheduleSync(SyncResult syncResult, SyncOperation operation) {
840         boolean isLoggable = Log.isLoggable(TAG, Log.DEBUG);
841         if (isLoggable) {
842             Log.d(TAG, "encountered error(s) during the sync: " + syncResult + ", " + operation);
843         }
844 
845         operation = new SyncOperation(operation);
846 
847         // The SYNC_EXTRAS_IGNORE_BACKOFF only applies to the first attempt to sync a given
848         // request. Retries of the request will always honor the backoff, so clear the
849         // flag in case we retry this request.
850         if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, false)) {
851             operation.extras.remove(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF);
852         }
853 
854         // If this sync aborted because the internal sync loop retried too many times then
855         //   don't reschedule. Otherwise we risk getting into a retry loop.
856         // If the operation succeeded to some extent then retry immediately.
857         // If this was a two-way sync then retry soft errors with an exponential backoff.
858         // If this was an upward sync then schedule a two-way sync immediately.
859         // Otherwise do not reschedule.
860         if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, false)) {
861             Log.d(TAG, "not retrying sync operation because SYNC_EXTRAS_DO_NOT_RETRY was specified "
862                     + operation);
863         } else if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false)
864                 && !syncResult.syncAlreadyInProgress) {
865             operation.extras.remove(ContentResolver.SYNC_EXTRAS_UPLOAD);
866             Log.d(TAG, "retrying sync operation as a two-way sync because an upload-only sync "
867                     + "encountered an error: " + operation);
868             scheduleSyncOperation(operation);
869         } else if (syncResult.tooManyRetries) {
870             Log.d(TAG, "not retrying sync operation because it retried too many times: "
871                     + operation);
872         } else if (syncResult.madeSomeProgress()) {
873             if (isLoggable) {
874                 Log.d(TAG, "retrying sync operation because even though it had an error "
875                         + "it achieved some success");
876             }
877             scheduleSyncOperation(operation);
878         } else if (syncResult.syncAlreadyInProgress) {
879             if (isLoggable) {
880                 Log.d(TAG, "retrying sync operation that failed because there was already a "
881                         + "sync in progress: " + operation);
882             }
883             scheduleSyncOperation(new SyncOperation(operation.account, operation.userId,
884                     operation.syncSource,
885                     operation.authority, operation.extras,
886                     DELAY_RETRY_SYNC_IN_PROGRESS_IN_SECONDS * 1000,
887                     operation.backoff, operation.delayUntil, operation.allowParallelSyncs));
888         } else if (syncResult.hasSoftError()) {
889             if (isLoggable) {
890                 Log.d(TAG, "retrying sync operation because it encountered a soft error: "
891                         + operation);
892             }
893             scheduleSyncOperation(operation);
894         } else {
895             Log.d(TAG, "not retrying sync operation because the error is a hard error: "
896                     + operation);
897         }
898     }
899 
onUserStarting(int userId)900     private void onUserStarting(int userId) {
901         // Make sure that accounts we're about to use are valid
902         AccountManagerService.getSingleton().validateAccounts(userId);
903 
904         mSyncAdapters.invalidateCache(userId);
905 
906         updateRunningAccounts();
907 
908         synchronized (mSyncQueue) {
909             mSyncQueue.addPendingOperations(userId);
910         }
911 
912         // Schedule sync for any accounts under started user
913         final Account[] accounts = AccountManagerService.getSingleton().getAccounts(userId);
914         for (Account account : accounts) {
915             scheduleSync(account, userId, null, null, 0 /* no delay */,
916                     true /* onlyThoseWithUnknownSyncableState */);
917         }
918 
919         sendCheckAlarmsMessage();
920     }
921 
onUserStopping(int userId)922     private void onUserStopping(int userId) {
923         updateRunningAccounts();
924 
925         cancelActiveSync(
926                 null /* any account */,
927                 userId,
928                 null /* any authority */);
929     }
930 
onUserRemoved(int userId)931     private void onUserRemoved(int userId) {
932         updateRunningAccounts();
933 
934         // Clean up the storage engine database
935         mSyncStorageEngine.doDatabaseCleanup(new Account[0], userId);
936         synchronized (mSyncQueue) {
937             mSyncQueue.removeUser(userId);
938         }
939     }
940 
941     /**
942      * @hide
943      */
944     class ActiveSyncContext extends ISyncContext.Stub
945             implements ServiceConnection, IBinder.DeathRecipient {
946         final SyncOperation mSyncOperation;
947         final long mHistoryRowId;
948         ISyncAdapter mSyncAdapter;
949         final long mStartTime;
950         long mTimeoutStartTime;
951         boolean mBound;
952         final PowerManager.WakeLock mSyncWakeLock;
953         final int mSyncAdapterUid;
954         SyncInfo mSyncInfo;
955         boolean mIsLinkedToDeath = false;
956 
957         /**
958          * Create an ActiveSyncContext for an impending sync and grab the wakelock for that
959          * sync adapter. Since this grabs the wakelock you need to be sure to call
960          * close() when you are done with this ActiveSyncContext, whether the sync succeeded
961          * or not.
962          * @param syncOperation the SyncOperation we are about to sync
963          * @param historyRowId the row in which to record the history info for this sync
964          * @param syncAdapterUid the UID of the application that contains the sync adapter
965          * for this sync. This is used to attribute the wakelock hold to that application.
966          */
ActiveSyncContext(SyncOperation syncOperation, long historyRowId, int syncAdapterUid)967         public ActiveSyncContext(SyncOperation syncOperation, long historyRowId,
968                 int syncAdapterUid) {
969             super();
970             mSyncAdapterUid = syncAdapterUid;
971             mSyncOperation = syncOperation;
972             mHistoryRowId = historyRowId;
973             mSyncAdapter = null;
974             mStartTime = SystemClock.elapsedRealtime();
975             mTimeoutStartTime = mStartTime;
976             mSyncWakeLock = mSyncHandler.getSyncWakeLock(
977                     mSyncOperation.account, mSyncOperation.authority);
978             mSyncWakeLock.setWorkSource(new WorkSource(syncAdapterUid));
979             mSyncWakeLock.acquire();
980         }
981 
sendHeartbeat()982         public void sendHeartbeat() {
983             // heartbeats are no longer used
984         }
985 
onFinished(SyncResult result)986         public void onFinished(SyncResult result) {
987             if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "onFinished: " + this);
988             // include "this" in the message so that the handler can ignore it if this
989             // ActiveSyncContext is no longer the mActiveSyncContext at message handling
990             // time
991             sendSyncFinishedOrCanceledMessage(this, result);
992         }
993 
toString(StringBuilder sb)994         public void toString(StringBuilder sb) {
995             sb.append("startTime ").append(mStartTime)
996                     .append(", mTimeoutStartTime ").append(mTimeoutStartTime)
997                     .append(", mHistoryRowId ").append(mHistoryRowId)
998                     .append(", syncOperation ").append(mSyncOperation);
999         }
1000 
onServiceConnected(ComponentName name, IBinder service)1001         public void onServiceConnected(ComponentName name, IBinder service) {
1002             Message msg = mSyncHandler.obtainMessage();
1003             msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
1004             msg.obj = new ServiceConnectionData(this, ISyncAdapter.Stub.asInterface(service));
1005             mSyncHandler.sendMessage(msg);
1006         }
1007 
onServiceDisconnected(ComponentName name)1008         public void onServiceDisconnected(ComponentName name) {
1009             Message msg = mSyncHandler.obtainMessage();
1010             msg.what = SyncHandler.MESSAGE_SERVICE_DISCONNECTED;
1011             msg.obj = new ServiceConnectionData(this, null);
1012             mSyncHandler.sendMessage(msg);
1013         }
1014 
bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info, int userId)1015         boolean bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info, int userId) {
1016             if (Log.isLoggable(TAG, Log.VERBOSE)) {
1017                 Log.d(TAG, "bindToSyncAdapter: " + info.componentName + ", connection " + this);
1018             }
1019             Intent intent = new Intent();
1020             intent.setAction("android.content.SyncAdapter");
1021             intent.setComponent(info.componentName);
1022             intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1023                     com.android.internal.R.string.sync_binding_label);
1024             intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivityAsUser(
1025                     mContext, 0, new Intent(Settings.ACTION_SYNC_SETTINGS), 0,
1026                     null, new UserHandle(userId)));
1027             mBound = true;
1028             final boolean bindResult = mContext.bindService(intent, this,
1029                     Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND
1030                     | Context.BIND_ALLOW_OOM_MANAGEMENT,
1031                     mSyncOperation.userId);
1032             if (!bindResult) {
1033                 mBound = false;
1034             }
1035             return bindResult;
1036         }
1037 
1038         /**
1039          * Performs the required cleanup, which is the releasing of the wakelock and
1040          * unbinding from the sync adapter (if actually bound).
1041          */
close()1042         protected void close() {
1043             if (Log.isLoggable(TAG, Log.VERBOSE)) {
1044                 Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
1045             }
1046             if (mBound) {
1047                 mBound = false;
1048                 mContext.unbindService(this);
1049             }
1050             mSyncWakeLock.release();
1051             mSyncWakeLock.setWorkSource(null);
1052         }
1053 
1054         @Override
toString()1055         public String toString() {
1056             StringBuilder sb = new StringBuilder();
1057             toString(sb);
1058             return sb.toString();
1059         }
1060 
1061         @Override
binderDied()1062         public void binderDied() {
1063             sendSyncFinishedOrCanceledMessage(this, null);
1064         }
1065     }
1066 
dump(FileDescriptor fd, PrintWriter pw)1067     protected void dump(FileDescriptor fd, PrintWriter pw) {
1068         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
1069         dumpSyncState(ipw);
1070         dumpSyncHistory(ipw);
1071         dumpSyncAdapters(ipw);
1072     }
1073 
formatTime(long time)1074     static String formatTime(long time) {
1075         Time tobj = new Time();
1076         tobj.set(time);
1077         return tobj.format("%Y-%m-%d %H:%M:%S");
1078     }
1079 
dumpSyncState(PrintWriter pw)1080     protected void dumpSyncState(PrintWriter pw) {
1081         pw.print("data connected: "); pw.println(mDataConnectionIsConnected);
1082         pw.print("auto sync: ");
1083         List<UserInfo> users = getAllUsers();
1084         if (users != null) {
1085             for (UserInfo user : users) {
1086                 pw.print("u" + user.id + "="
1087                         + mSyncStorageEngine.getMasterSyncAutomatically(user.id) + " ");
1088             }
1089             pw.println();
1090         }
1091         pw.print("memory low: "); pw.println(mStorageIsLow);
1092 
1093         final AccountAndUser[] accounts = AccountManagerService.getSingleton().getAllAccounts();
1094 
1095         pw.print("accounts: ");
1096         if (accounts != INITIAL_ACCOUNTS_ARRAY) {
1097             pw.println(accounts.length);
1098         } else {
1099             pw.println("not known yet");
1100         }
1101         final long now = SystemClock.elapsedRealtime();
1102         pw.print("now: "); pw.print(now);
1103         pw.println(" (" + formatTime(System.currentTimeMillis()) + ")");
1104         pw.print("offset: "); pw.print(DateUtils.formatElapsedTime(mSyncRandomOffsetMillis/1000));
1105         pw.println(" (HH:MM:SS)");
1106         pw.print("uptime: "); pw.print(DateUtils.formatElapsedTime(now/1000));
1107                 pw.println(" (HH:MM:SS)");
1108         pw.print("time spent syncing: ");
1109                 pw.print(DateUtils.formatElapsedTime(
1110                         mSyncHandler.mSyncTimeTracker.timeSpentSyncing() / 1000));
1111                 pw.print(" (HH:MM:SS), sync ");
1112                 pw.print(mSyncHandler.mSyncTimeTracker.mLastWasSyncing ? "" : "not ");
1113                 pw.println("in progress");
1114         if (mSyncHandler.mAlarmScheduleTime != null) {
1115             pw.print("next alarm time: "); pw.print(mSyncHandler.mAlarmScheduleTime);
1116                     pw.print(" (");
1117                     pw.print(DateUtils.formatElapsedTime((mSyncHandler.mAlarmScheduleTime-now)/1000));
1118                     pw.println(" (HH:MM:SS) from now)");
1119         } else {
1120             pw.println("no alarm is scheduled (there had better not be any pending syncs)");
1121         }
1122 
1123         pw.print("notification info: ");
1124         final StringBuilder sb = new StringBuilder();
1125         mSyncHandler.mSyncNotificationInfo.toString(sb);
1126         pw.println(sb.toString());
1127 
1128         pw.println();
1129         pw.println("Active Syncs: " + mActiveSyncContexts.size());
1130         for (SyncManager.ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
1131             final long durationInSeconds = (now - activeSyncContext.mStartTime) / 1000;
1132             pw.print("  ");
1133             pw.print(DateUtils.formatElapsedTime(durationInSeconds));
1134             pw.print(" - ");
1135             pw.print(activeSyncContext.mSyncOperation.dump(false));
1136             pw.println();
1137         }
1138 
1139         synchronized (mSyncQueue) {
1140             sb.setLength(0);
1141             mSyncQueue.dump(sb);
1142         }
1143         pw.println();
1144         pw.print(sb.toString());
1145 
1146         // join the installed sync adapter with the accounts list and emit for everything
1147         pw.println();
1148         pw.println("Sync Status");
1149         for (AccountAndUser account : accounts) {
1150             pw.print("  Account "); pw.print(account.account.name);
1151                     pw.print(" u"); pw.print(account.userId);
1152                     pw.print(" "); pw.print(account.account.type);
1153                     pw.println(":");
1154             for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterType :
1155                     mSyncAdapters.getAllServices(account.userId)) {
1156                 if (!syncAdapterType.type.accountType.equals(account.account.type)) {
1157                     continue;
1158                 }
1159 
1160                 SyncStorageEngine.AuthorityInfo settings =
1161                         mSyncStorageEngine.getOrCreateAuthority(
1162                                 account.account, account.userId, syncAdapterType.type.authority);
1163                 SyncStatusInfo status = mSyncStorageEngine.getOrCreateSyncStatus(settings);
1164                 pw.print("    "); pw.print(settings.authority);
1165                 pw.println(":");
1166                 pw.print("      settings:");
1167                 pw.print(" " + (settings.syncable > 0
1168                         ? "syncable"
1169                         : (settings.syncable == 0 ? "not syncable" : "not initialized")));
1170                 pw.print(", " + (settings.enabled ? "enabled" : "disabled"));
1171                 if (settings.delayUntil > now) {
1172                     pw.print(", delay for "
1173                             + ((settings.delayUntil - now) / 1000) + " sec");
1174                 }
1175                 if (settings.backoffTime > now) {
1176                     pw.print(", backoff for "
1177                             + ((settings.backoffTime - now) / 1000) + " sec");
1178                 }
1179                 if (settings.backoffDelay > 0) {
1180                     pw.print(", the backoff increment is " + settings.backoffDelay / 1000
1181                                 + " sec");
1182                 }
1183                 pw.println();
1184                 for (int periodicIndex = 0;
1185                         periodicIndex < settings.periodicSyncs.size();
1186                         periodicIndex++) {
1187                     Pair<Bundle, Long> info = settings.periodicSyncs.get(periodicIndex);
1188                     long lastPeriodicTime = status.getPeriodicSyncTime(periodicIndex);
1189                     long nextPeriodicTime = lastPeriodicTime + info.second * 1000;
1190                     pw.println("      periodic period=" + info.second
1191                             + ", extras=" + info.first
1192                             + ", next=" + formatTime(nextPeriodicTime));
1193                 }
1194                 pw.print("      count: local="); pw.print(status.numSourceLocal);
1195                 pw.print(" poll="); pw.print(status.numSourcePoll);
1196                 pw.print(" periodic="); pw.print(status.numSourcePeriodic);
1197                 pw.print(" server="); pw.print(status.numSourceServer);
1198                 pw.print(" user="); pw.print(status.numSourceUser);
1199                 pw.print(" total="); pw.print(status.numSyncs);
1200                 pw.println();
1201                 pw.print("      total duration: ");
1202                 pw.println(DateUtils.formatElapsedTime(status.totalElapsedTime/1000));
1203                 if (status.lastSuccessTime != 0) {
1204                     pw.print("      SUCCESS: source=");
1205                     pw.print(SyncStorageEngine.SOURCES[status.lastSuccessSource]);
1206                     pw.print(" time=");
1207                     pw.println(formatTime(status.lastSuccessTime));
1208                 }
1209                 if (status.lastFailureTime != 0) {
1210                     pw.print("      FAILURE: source=");
1211                     pw.print(SyncStorageEngine.SOURCES[
1212                             status.lastFailureSource]);
1213                     pw.print(" initialTime=");
1214                     pw.print(formatTime(status.initialFailureTime));
1215                     pw.print(" lastTime=");
1216                     pw.println(formatTime(status.lastFailureTime));
1217                     int errCode = status.getLastFailureMesgAsInt(0);
1218                     pw.print("      message: "); pw.println(
1219                             getLastFailureMessage(errCode) + " (" + errCode + ")");
1220                 }
1221             }
1222         }
1223     }
1224 
getLastFailureMessage(int code)1225     private String getLastFailureMessage(int code) {
1226         switch (code) {
1227             case ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS:
1228                 return "sync already in progress";
1229 
1230             case ContentResolver.SYNC_ERROR_AUTHENTICATION:
1231                 return "authentication error";
1232 
1233             case ContentResolver.SYNC_ERROR_IO:
1234                 return "I/O error";
1235 
1236             case ContentResolver.SYNC_ERROR_PARSE:
1237                 return "parse error";
1238 
1239             case ContentResolver.SYNC_ERROR_CONFLICT:
1240                 return "conflict error";
1241 
1242             case ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS:
1243                 return "too many deletions error";
1244 
1245             case ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES:
1246                 return "too many retries error";
1247 
1248             case ContentResolver.SYNC_ERROR_INTERNAL:
1249                 return "internal error";
1250 
1251             default:
1252                 return "unknown";
1253         }
1254     }
1255 
dumpTimeSec(PrintWriter pw, long time)1256     private void dumpTimeSec(PrintWriter pw, long time) {
1257         pw.print(time/1000); pw.print('.'); pw.print((time/100)%10);
1258         pw.print('s');
1259     }
1260 
dumpDayStatistic(PrintWriter pw, SyncStorageEngine.DayStats ds)1261     private void dumpDayStatistic(PrintWriter pw, SyncStorageEngine.DayStats ds) {
1262         pw.print("Success ("); pw.print(ds.successCount);
1263         if (ds.successCount > 0) {
1264             pw.print(" for "); dumpTimeSec(pw, ds.successTime);
1265             pw.print(" avg="); dumpTimeSec(pw, ds.successTime/ds.successCount);
1266         }
1267         pw.print(") Failure ("); pw.print(ds.failureCount);
1268         if (ds.failureCount > 0) {
1269             pw.print(" for "); dumpTimeSec(pw, ds.failureTime);
1270             pw.print(" avg="); dumpTimeSec(pw, ds.failureTime/ds.failureCount);
1271         }
1272         pw.println(")");
1273     }
1274 
dumpSyncHistory(PrintWriter pw)1275     protected void dumpSyncHistory(PrintWriter pw) {
1276         dumpRecentHistory(pw);
1277         dumpDayStatistics(pw);
1278     }
1279 
dumpRecentHistory(PrintWriter pw)1280     private void dumpRecentHistory(PrintWriter pw) {
1281         final ArrayList<SyncStorageEngine.SyncHistoryItem> items
1282                 = mSyncStorageEngine.getSyncHistory();
1283         if (items != null && items.size() > 0) {
1284             final Map<String, AuthoritySyncStats> authorityMap = Maps.newHashMap();
1285             long totalElapsedTime = 0;
1286             long totalTimes = 0;
1287             final int N = items.size();
1288 
1289             int maxAuthority = 0;
1290             int maxAccount = 0;
1291             for (SyncStorageEngine.SyncHistoryItem item : items) {
1292                 SyncStorageEngine.AuthorityInfo authority
1293                         = mSyncStorageEngine.getAuthority(item.authorityId);
1294                 final String authorityName;
1295                 final String accountKey;
1296                 if (authority != null) {
1297                     authorityName = authority.authority;
1298                     accountKey = authority.account.name + "/" + authority.account.type
1299                             + " u" + authority.userId;
1300                 } else {
1301                     authorityName = "Unknown";
1302                     accountKey = "Unknown";
1303                 }
1304 
1305                 int length = authorityName.length();
1306                 if (length > maxAuthority) {
1307                     maxAuthority = length;
1308                 }
1309                 length = accountKey.length();
1310                 if (length > maxAccount) {
1311                     maxAccount = length;
1312                 }
1313 
1314                 final long elapsedTime = item.elapsedTime;
1315                 totalElapsedTime += elapsedTime;
1316                 totalTimes++;
1317                 AuthoritySyncStats authoritySyncStats = authorityMap.get(authorityName);
1318                 if (authoritySyncStats == null) {
1319                     authoritySyncStats = new AuthoritySyncStats(authorityName);
1320                     authorityMap.put(authorityName, authoritySyncStats);
1321                 }
1322                 authoritySyncStats.elapsedTime += elapsedTime;
1323                 authoritySyncStats.times++;
1324                 final Map<String, AccountSyncStats> accountMap = authoritySyncStats.accountMap;
1325                 AccountSyncStats accountSyncStats = accountMap.get(accountKey);
1326                 if (accountSyncStats == null) {
1327                     accountSyncStats = new AccountSyncStats(accountKey);
1328                     accountMap.put(accountKey, accountSyncStats);
1329                 }
1330                 accountSyncStats.elapsedTime += elapsedTime;
1331                 accountSyncStats.times++;
1332 
1333             }
1334 
1335             if (totalElapsedTime > 0) {
1336                 pw.println();
1337                 pw.printf("Detailed Statistics (Recent history):  "
1338                         + "%d (# of times) %ds (sync time)\n",
1339                         totalTimes, totalElapsedTime / 1000);
1340 
1341                 final List<AuthoritySyncStats> sortedAuthorities =
1342                         new ArrayList<AuthoritySyncStats>(authorityMap.values());
1343                 Collections.sort(sortedAuthorities, new Comparator<AuthoritySyncStats>() {
1344                     @Override
1345                     public int compare(AuthoritySyncStats lhs, AuthoritySyncStats rhs) {
1346                         // reverse order
1347                         int compare = Integer.compare(rhs.times, lhs.times);
1348                         if (compare == 0) {
1349                             compare = Long.compare(rhs.elapsedTime, lhs.elapsedTime);
1350                         }
1351                         return compare;
1352                     }
1353                 });
1354 
1355                 final int maxLength = Math.max(maxAuthority, maxAccount + 3);
1356                 final int padLength = 2 + 2 + maxLength + 2 + 10 + 11;
1357                 final char chars[] = new char[padLength];
1358                 Arrays.fill(chars, '-');
1359                 final String separator = new String(chars);
1360 
1361                 final String authorityFormat =
1362                         String.format("  %%-%ds: %%-9s  %%-11s\n", maxLength + 2);
1363                 final String accountFormat =
1364                         String.format("    %%-%ds:   %%-9s  %%-11s\n", maxLength);
1365 
1366                 pw.println(separator);
1367                 for (AuthoritySyncStats authoritySyncStats : sortedAuthorities) {
1368                     String name = authoritySyncStats.name;
1369                     long elapsedTime;
1370                     int times;
1371                     String timeStr;
1372                     String timesStr;
1373 
1374                     elapsedTime = authoritySyncStats.elapsedTime;
1375                     times = authoritySyncStats.times;
1376                     timeStr = String.format("%ds/%d%%",
1377                             elapsedTime / 1000,
1378                             elapsedTime * 100 / totalElapsedTime);
1379                     timesStr = String.format("%d/%d%%",
1380                             times,
1381                             times * 100 / totalTimes);
1382                     pw.printf(authorityFormat, name, timesStr, timeStr);
1383 
1384                     final List<AccountSyncStats> sortedAccounts =
1385                             new ArrayList<AccountSyncStats>(
1386                                     authoritySyncStats.accountMap.values());
1387                     Collections.sort(sortedAccounts, new Comparator<AccountSyncStats>() {
1388                         @Override
1389                         public int compare(AccountSyncStats lhs, AccountSyncStats rhs) {
1390                             // reverse order
1391                             int compare = Integer.compare(rhs.times, lhs.times);
1392                             if (compare == 0) {
1393                                 compare = Long.compare(rhs.elapsedTime, lhs.elapsedTime);
1394                             }
1395                             return compare;
1396                         }
1397                     });
1398                     for (AccountSyncStats stats: sortedAccounts) {
1399                         elapsedTime = stats.elapsedTime;
1400                         times = stats.times;
1401                         timeStr = String.format("%ds/%d%%",
1402                                 elapsedTime / 1000,
1403                                 elapsedTime * 100 / totalElapsedTime);
1404                         timesStr = String.format("%d/%d%%",
1405                                 times,
1406                                 times * 100 / totalTimes);
1407                         pw.printf(accountFormat, stats.name, timesStr, timeStr);
1408                     }
1409                     pw.println(separator);
1410                 }
1411             }
1412 
1413             pw.println();
1414             pw.println("Recent Sync History");
1415             final String format = "  %-" + maxAccount + "s  %s\n";
1416             final Map<String, Long> lastTimeMap = Maps.newHashMap();
1417 
1418             for (int i = 0; i < N; i++) {
1419                 SyncStorageEngine.SyncHistoryItem item = items.get(i);
1420                 SyncStorageEngine.AuthorityInfo authority
1421                         = mSyncStorageEngine.getAuthority(item.authorityId);
1422                 final String authorityName;
1423                 final String accountKey;
1424                 if (authority != null) {
1425                     authorityName = authority.authority;
1426                     accountKey = authority.account.name + "/" + authority.account.type
1427                             + " u" + authority.userId;
1428                 } else {
1429                     authorityName = "Unknown";
1430                     accountKey = "Unknown";
1431                 }
1432                 final long elapsedTime = item.elapsedTime;
1433                 final Time time = new Time();
1434                 final long eventTime = item.eventTime;
1435                 time.set(eventTime);
1436 
1437                 final String key = authorityName + "/" + accountKey;
1438                 final Long lastEventTime = lastTimeMap.get(key);
1439                 final String diffString;
1440                 if (lastEventTime == null) {
1441                     diffString = "";
1442                 } else {
1443                     final long diff = (lastEventTime - eventTime) / 1000;
1444                     if (diff < 60) {
1445                         diffString = String.valueOf(diff);
1446                     } else if (diff < 3600) {
1447                         diffString = String.format("%02d:%02d", diff / 60, diff % 60);
1448                     } else {
1449                         final long sec = diff % 3600;
1450                         diffString = String.format("%02d:%02d:%02d",
1451                                 diff / 3600, sec / 60, sec % 60);
1452                     }
1453                 }
1454                 lastTimeMap.put(key, eventTime);
1455 
1456                 pw.printf("  #%-3d: %s %8s  %5.1fs  %8s",
1457                         i + 1,
1458                         formatTime(eventTime),
1459                         SyncStorageEngine.SOURCES[item.source],
1460                         ((float) elapsedTime) / 1000,
1461                         diffString);
1462                 pw.printf(format, accountKey, authorityName);
1463 
1464                 if (item.event != SyncStorageEngine.EVENT_STOP
1465                         || item.upstreamActivity != 0
1466                         || item.downstreamActivity != 0) {
1467                     pw.printf("    event=%d upstreamActivity=%d downstreamActivity=%d\n",
1468                             item.event,
1469                             item.upstreamActivity,
1470                             item.downstreamActivity);
1471                 }
1472                 if (item.mesg != null
1473                         && !SyncStorageEngine.MESG_SUCCESS.equals(item.mesg)) {
1474                     pw.printf("    mesg=%s\n", item.mesg);
1475                 }
1476             }
1477         }
1478     }
1479 
dumpDayStatistics(PrintWriter pw)1480     private void dumpDayStatistics(PrintWriter pw) {
1481         SyncStorageEngine.DayStats dses[] = mSyncStorageEngine.getDayStatistics();
1482         if (dses != null && dses[0] != null) {
1483             pw.println();
1484             pw.println("Sync Statistics");
1485             pw.print("  Today:  "); dumpDayStatistic(pw, dses[0]);
1486             int today = dses[0].day;
1487             int i;
1488             SyncStorageEngine.DayStats ds;
1489 
1490             // Print each day in the current week.
1491             for (i=1; i<=6 && i < dses.length; i++) {
1492                 ds = dses[i];
1493                 if (ds == null) break;
1494                 int delta = today-ds.day;
1495                 if (delta > 6) break;
1496 
1497                 pw.print("  Day-"); pw.print(delta); pw.print(":  ");
1498                 dumpDayStatistic(pw, ds);
1499             }
1500 
1501             // Aggregate all following days into weeks and print totals.
1502             int weekDay = today;
1503             while (i < dses.length) {
1504                 SyncStorageEngine.DayStats aggr = null;
1505                 weekDay -= 7;
1506                 while (i < dses.length) {
1507                     ds = dses[i];
1508                     if (ds == null) {
1509                         i = dses.length;
1510                         break;
1511                     }
1512                     int delta = weekDay-ds.day;
1513                     if (delta > 6) break;
1514                     i++;
1515 
1516                     if (aggr == null) {
1517                         aggr = new SyncStorageEngine.DayStats(weekDay);
1518                     }
1519                     aggr.successCount += ds.successCount;
1520                     aggr.successTime += ds.successTime;
1521                     aggr.failureCount += ds.failureCount;
1522                     aggr.failureTime += ds.failureTime;
1523                 }
1524                 if (aggr != null) {
1525                     pw.print("  Week-"); pw.print((today-weekDay)/7); pw.print(": ");
1526                     dumpDayStatistic(pw, aggr);
1527                 }
1528             }
1529         }
1530     }
1531 
dumpSyncAdapters(IndentingPrintWriter pw)1532     private void dumpSyncAdapters(IndentingPrintWriter pw) {
1533         pw.println();
1534         final List<UserInfo> users = getAllUsers();
1535         if (users != null) {
1536             for (UserInfo user : users) {
1537                 pw.println("Sync adapters for " + user + ":");
1538                 pw.increaseIndent();
1539                 for (RegisteredServicesCache.ServiceInfo<?> info :
1540                         mSyncAdapters.getAllServices(user.id)) {
1541                     pw.println(info);
1542                 }
1543                 pw.decreaseIndent();
1544                 pw.println();
1545             }
1546         }
1547     }
1548 
1549     private static class AuthoritySyncStats {
1550         String name;
1551         long elapsedTime;
1552         int times;
1553         Map<String, AccountSyncStats> accountMap = Maps.newHashMap();
1554 
AuthoritySyncStats(String name)1555         private AuthoritySyncStats(String name) {
1556             this.name = name;
1557         }
1558     }
1559 
1560     private static class AccountSyncStats {
1561         String name;
1562         long elapsedTime;
1563         int times;
1564 
AccountSyncStats(String name)1565         private AccountSyncStats(String name) {
1566             this.name = name;
1567         }
1568     }
1569 
1570     /**
1571      * A helper object to keep track of the time we have spent syncing since the last boot
1572      */
1573     private class SyncTimeTracker {
1574         /** True if a sync was in progress on the most recent call to update() */
1575         boolean mLastWasSyncing = false;
1576         /** Used to track when lastWasSyncing was last set */
1577         long mWhenSyncStarted = 0;
1578         /** The cumulative time we have spent syncing */
1579         private long mTimeSpentSyncing;
1580 
1581         /** Call to let the tracker know that the sync state may have changed */
update()1582         public synchronized void update() {
1583             final boolean isSyncInProgress = !mActiveSyncContexts.isEmpty();
1584             if (isSyncInProgress == mLastWasSyncing) return;
1585             final long now = SystemClock.elapsedRealtime();
1586             if (isSyncInProgress) {
1587                 mWhenSyncStarted = now;
1588             } else {
1589                 mTimeSpentSyncing += now - mWhenSyncStarted;
1590             }
1591             mLastWasSyncing = isSyncInProgress;
1592         }
1593 
1594         /** Get how long we have been syncing, in ms */
timeSpentSyncing()1595         public synchronized long timeSpentSyncing() {
1596             if (!mLastWasSyncing) return mTimeSpentSyncing;
1597 
1598             final long now = SystemClock.elapsedRealtime();
1599             return mTimeSpentSyncing + (now - mWhenSyncStarted);
1600         }
1601     }
1602 
1603     class ServiceConnectionData {
1604         public final ActiveSyncContext activeSyncContext;
1605         public final ISyncAdapter syncAdapter;
ServiceConnectionData(ActiveSyncContext activeSyncContext, ISyncAdapter syncAdapter)1606         ServiceConnectionData(ActiveSyncContext activeSyncContext, ISyncAdapter syncAdapter) {
1607             this.activeSyncContext = activeSyncContext;
1608             this.syncAdapter = syncAdapter;
1609         }
1610     }
1611 
1612     /**
1613      * Handles SyncOperation Messages that are posted to the associated
1614      * HandlerThread.
1615      */
1616     class SyncHandler extends Handler {
1617         // Messages that can be sent on mHandler
1618         private static final int MESSAGE_SYNC_FINISHED = 1;
1619         private static final int MESSAGE_SYNC_ALARM = 2;
1620         private static final int MESSAGE_CHECK_ALARMS = 3;
1621         private static final int MESSAGE_SERVICE_CONNECTED = 4;
1622         private static final int MESSAGE_SERVICE_DISCONNECTED = 5;
1623         private static final int MESSAGE_CANCEL = 6;
1624 
1625         public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo();
1626         private Long mAlarmScheduleTime = null;
1627         public final SyncTimeTracker mSyncTimeTracker = new SyncTimeTracker();
1628         private final HashMap<Pair<Account, String>, PowerManager.WakeLock> mWakeLocks =
1629                 Maps.newHashMap();
1630 
1631         private volatile CountDownLatch mReadyToRunLatch = new CountDownLatch(1);
1632 
onBootCompleted()1633         public void onBootCompleted() {
1634             mBootCompleted = true;
1635 
1636             doDatabaseCleanup();
1637 
1638             if (mReadyToRunLatch != null) {
1639                 mReadyToRunLatch.countDown();
1640             }
1641         }
1642 
getSyncWakeLock(Account account, String authority)1643         private PowerManager.WakeLock getSyncWakeLock(Account account, String authority) {
1644             final Pair<Account, String> wakeLockKey = Pair.create(account, authority);
1645             PowerManager.WakeLock wakeLock = mWakeLocks.get(wakeLockKey);
1646             if (wakeLock == null) {
1647                 final String name = SYNC_WAKE_LOCK_PREFIX + "_" + authority + "_" + account;
1648                 wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
1649                 wakeLock.setReferenceCounted(false);
1650                 mWakeLocks.put(wakeLockKey, wakeLock);
1651             }
1652             return wakeLock;
1653         }
1654 
waitUntilReadyToRun()1655         private void waitUntilReadyToRun() {
1656             CountDownLatch latch = mReadyToRunLatch;
1657             if (latch != null) {
1658                 while (true) {
1659                     try {
1660                         latch.await();
1661                         mReadyToRunLatch = null;
1662                         return;
1663                     } catch (InterruptedException e) {
1664                         Thread.currentThread().interrupt();
1665                     }
1666                 }
1667             }
1668         }
1669         /**
1670          * Used to keep track of whether a sync notification is active and who it is for.
1671          */
1672         class SyncNotificationInfo {
1673             // true iff the notification manager has been asked to send the notification
1674             public boolean isActive = false;
1675 
1676             // Set when we transition from not running a sync to running a sync, and cleared on
1677             // the opposite transition.
1678             public Long startTime = null;
1679 
toString(StringBuilder sb)1680             public void toString(StringBuilder sb) {
1681                 sb.append("isActive ").append(isActive).append(", startTime ").append(startTime);
1682             }
1683 
1684             @Override
toString()1685             public String toString() {
1686                 StringBuilder sb = new StringBuilder();
1687                 toString(sb);
1688                 return sb.toString();
1689             }
1690         }
1691 
SyncHandler(Looper looper)1692         public SyncHandler(Looper looper) {
1693             super(looper);
1694         }
1695 
handleMessage(Message msg)1696         public void handleMessage(Message msg) {
1697             long earliestFuturePollTime = Long.MAX_VALUE;
1698             long nextPendingSyncTime = Long.MAX_VALUE;
1699 
1700             // Setting the value here instead of a method because we want the dumpsys logs
1701             // to have the most recent value used.
1702             try {
1703                 waitUntilReadyToRun();
1704                 mDataConnectionIsConnected = readDataConnectionState();
1705                 mSyncManagerWakeLock.acquire();
1706                 // Always do this first so that we be sure that any periodic syncs that
1707                 // are ready to run have been converted into pending syncs. This allows the
1708                 // logic that considers the next steps to take based on the set of pending syncs
1709                 // to also take into account the periodic syncs.
1710                 earliestFuturePollTime = scheduleReadyPeriodicSyncs();
1711                 switch (msg.what) {
1712                     case SyncHandler.MESSAGE_CANCEL: {
1713                         Pair<Account, String> payload = (Pair<Account, String>)msg.obj;
1714                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
1715                             Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CANCEL: "
1716                                     + payload.first + ", " + payload.second);
1717                         }
1718                         cancelActiveSyncLocked(payload.first, msg.arg1, payload.second);
1719                         nextPendingSyncTime = maybeStartNextSyncLocked();
1720                         break;
1721                     }
1722 
1723                     case SyncHandler.MESSAGE_SYNC_FINISHED:
1724                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
1725                             Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_FINISHED");
1726                         }
1727                         SyncHandlerMessagePayload payload = (SyncHandlerMessagePayload)msg.obj;
1728                         if (!isSyncStillActive(payload.activeSyncContext)) {
1729                             Log.d(TAG, "handleSyncHandlerMessage: dropping since the "
1730                                     + "sync is no longer active: "
1731                                     + payload.activeSyncContext);
1732                             break;
1733                         }
1734                         runSyncFinishedOrCanceledLocked(payload.syncResult, payload.activeSyncContext);
1735 
1736                         // since a sync just finished check if it is time to start a new sync
1737                         nextPendingSyncTime = maybeStartNextSyncLocked();
1738                         break;
1739 
1740                     case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
1741                         ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
1742                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
1743                             Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
1744                                     + msgData.activeSyncContext);
1745                         }
1746                         // check that this isn't an old message
1747                         if (isSyncStillActive(msgData.activeSyncContext)) {
1748                             runBoundToSyncAdapter(msgData.activeSyncContext, msgData.syncAdapter);
1749                         }
1750                         break;
1751                     }
1752 
1753                     case SyncHandler.MESSAGE_SERVICE_DISCONNECTED: {
1754                         final ActiveSyncContext currentSyncContext =
1755                                 ((ServiceConnectionData)msg.obj).activeSyncContext;
1756                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
1757                             Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_DISCONNECTED: "
1758                                     + currentSyncContext);
1759                         }
1760                         // check that this isn't an old message
1761                         if (isSyncStillActive(currentSyncContext)) {
1762                             // cancel the sync if we have a syncadapter, which means one is
1763                             // outstanding
1764                             if (currentSyncContext.mSyncAdapter != null) {
1765                                 try {
1766                                     currentSyncContext.mSyncAdapter.cancelSync(currentSyncContext);
1767                                 } catch (RemoteException e) {
1768                                     // we don't need to retry this in this case
1769                                 }
1770                             }
1771 
1772                             // pretend that the sync failed with an IOException,
1773                             // which is a soft error
1774                             SyncResult syncResult = new SyncResult();
1775                             syncResult.stats.numIoExceptions++;
1776                             runSyncFinishedOrCanceledLocked(syncResult, currentSyncContext);
1777 
1778                             // since a sync just finished check if it is time to start a new sync
1779                             nextPendingSyncTime = maybeStartNextSyncLocked();
1780                         }
1781 
1782                         break;
1783                     }
1784 
1785                     case SyncHandler.MESSAGE_SYNC_ALARM: {
1786                         boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1787                         if (isLoggable) {
1788                             Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_ALARM");
1789                         }
1790                         mAlarmScheduleTime = null;
1791                         try {
1792                             nextPendingSyncTime = maybeStartNextSyncLocked();
1793                         } finally {
1794                             mHandleAlarmWakeLock.release();
1795                         }
1796                         break;
1797                     }
1798 
1799                     case SyncHandler.MESSAGE_CHECK_ALARMS:
1800                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
1801                             Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_CHECK_ALARMS");
1802                         }
1803                         nextPendingSyncTime = maybeStartNextSyncLocked();
1804                         break;
1805                 }
1806             } finally {
1807                 manageSyncNotificationLocked();
1808                 manageSyncAlarmLocked(earliestFuturePollTime, nextPendingSyncTime);
1809                 mSyncTimeTracker.update();
1810                 mSyncManagerWakeLock.release();
1811             }
1812         }
1813 
1814         /**
1815          * Turn any periodic sync operations that are ready to run into pending sync operations.
1816          * @return the desired start time of the earliest future  periodic sync operation,
1817          * in milliseconds since boot
1818          */
scheduleReadyPeriodicSyncs()1819         private long scheduleReadyPeriodicSyncs() {
1820             final boolean backgroundDataUsageAllowed =
1821                     getConnectivityManager().getBackgroundDataSetting();
1822             long earliestFuturePollTime = Long.MAX_VALUE;
1823             if (!backgroundDataUsageAllowed) {
1824                 return earliestFuturePollTime;
1825             }
1826 
1827             AccountAndUser[] accounts = mRunningAccounts;
1828 
1829             final long nowAbsolute = System.currentTimeMillis();
1830             final long shiftedNowAbsolute = (0 < nowAbsolute - mSyncRandomOffsetMillis)
1831                                                ? (nowAbsolute  - mSyncRandomOffsetMillis) : 0;
1832 
1833             ArrayList<SyncStorageEngine.AuthorityInfo> infos = mSyncStorageEngine.getAuthorities();
1834             for (SyncStorageEngine.AuthorityInfo info : infos) {
1835                 // skip the sync if the account of this operation no longer exists
1836                 if (!containsAccountAndUser(accounts, info.account, info.userId)) {
1837                     continue;
1838                 }
1839 
1840                 if (!mSyncStorageEngine.getMasterSyncAutomatically(info.userId)
1841                         || !mSyncStorageEngine.getSyncAutomatically(info.account, info.userId,
1842                                 info.authority)) {
1843                     continue;
1844                 }
1845 
1846                 if (mSyncStorageEngine.getIsSyncable(info.account, info.userId, info.authority)
1847                         == 0) {
1848                     continue;
1849                 }
1850 
1851                 SyncStatusInfo status = mSyncStorageEngine.getOrCreateSyncStatus(info);
1852                 for (int i = 0, N = info.periodicSyncs.size(); i < N; i++) {
1853                     final Bundle extras = info.periodicSyncs.get(i).first;
1854                     final Long periodInMillis = info.periodicSyncs.get(i).second * 1000;
1855                     // find when this periodic sync was last scheduled to run
1856                     final long lastPollTimeAbsolute = status.getPeriodicSyncTime(i);
1857 
1858                     long remainingMillis
1859                             = periodInMillis - (shiftedNowAbsolute % periodInMillis);
1860 
1861                     /*
1862                      * Sync scheduling strategy:
1863                      *    Set the next periodic sync based on a random offset (in seconds).
1864                      *
1865                      *    Also sync right now if any of the following cases hold
1866                      *    and mark it as having been scheduled
1867                      *
1868                      * Case 1:  This sync is ready to run now.
1869                      * Case 2:  If the lastPollTimeAbsolute is in the future,
1870                      *          sync now and reinitialize. This can happen for
1871                      *          example if the user changed the time, synced and
1872                      *          changed back.
1873                      * Case 3:  If we failed to sync at the last scheduled time
1874                      */
1875                     if (remainingMillis == periodInMillis  // Case 1
1876                             || lastPollTimeAbsolute > nowAbsolute // Case 2
1877                             || (nowAbsolute - lastPollTimeAbsolute
1878                                     >= periodInMillis)) { // Case 3
1879                         // Sync now
1880                         final Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(
1881                                 info.account, info.userId, info.authority);
1882                         final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
1883                         syncAdapterInfo = mSyncAdapters.getServiceInfo(
1884                                 SyncAdapterType.newKey(info.authority, info.account.type),
1885                                 info.userId);
1886                         if (syncAdapterInfo == null) {
1887                             continue;
1888                         }
1889                         scheduleSyncOperation(
1890                                 new SyncOperation(info.account, info.userId,
1891                                         SyncStorageEngine.SOURCE_PERIODIC,
1892                                         info.authority, extras, 0 /* delay */,
1893                                         backoff != null ? backoff.first : 0,
1894                                         mSyncStorageEngine.getDelayUntilTime(
1895                                                 info.account, info.userId, info.authority),
1896                                         syncAdapterInfo.type.allowParallelSyncs()));
1897                         status.setPeriodicSyncTime(i, nowAbsolute);
1898                     }
1899                     // Compute when this periodic sync should next run
1900                     final long nextPollTimeAbsolute = nowAbsolute + remainingMillis;
1901 
1902                     // remember this time if it is earlier than earliestFuturePollTime
1903                     if (nextPollTimeAbsolute < earliestFuturePollTime) {
1904                         earliestFuturePollTime = nextPollTimeAbsolute;
1905                     }
1906                 }
1907             }
1908 
1909             if (earliestFuturePollTime == Long.MAX_VALUE) {
1910                 return Long.MAX_VALUE;
1911             }
1912 
1913             // convert absolute time to elapsed time
1914             return SystemClock.elapsedRealtime()
1915                     + ((earliestFuturePollTime < nowAbsolute)
1916                       ? 0
1917                       : (earliestFuturePollTime - nowAbsolute));
1918         }
1919 
maybeStartNextSyncLocked()1920         private long maybeStartNextSyncLocked() {
1921             final boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1922             if (isLoggable) Log.v(TAG, "maybeStartNextSync");
1923 
1924             // If we aren't ready to run (e.g. the data connection is down), get out.
1925             if (!mDataConnectionIsConnected) {
1926                 if (isLoggable) {
1927                     Log.v(TAG, "maybeStartNextSync: no data connection, skipping");
1928                 }
1929                 return Long.MAX_VALUE;
1930             }
1931 
1932             if (mStorageIsLow) {
1933                 if (isLoggable) {
1934                     Log.v(TAG, "maybeStartNextSync: memory low, skipping");
1935                 }
1936                 return Long.MAX_VALUE;
1937             }
1938 
1939             // If the accounts aren't known yet then we aren't ready to run. We will be kicked
1940             // when the account lookup request does complete.
1941             AccountAndUser[] accounts = mRunningAccounts;
1942             if (accounts == INITIAL_ACCOUNTS_ARRAY) {
1943                 if (isLoggable) {
1944                     Log.v(TAG, "maybeStartNextSync: accounts not known, skipping");
1945                 }
1946                 return Long.MAX_VALUE;
1947             }
1948 
1949             // Otherwise consume SyncOperations from the head of the SyncQueue until one is
1950             // found that is runnable (not disabled, etc). If that one is ready to run then
1951             // start it, otherwise just get out.
1952             final boolean backgroundDataUsageAllowed =
1953                     getConnectivityManager().getBackgroundDataSetting();
1954 
1955             final long now = SystemClock.elapsedRealtime();
1956 
1957             // will be set to the next time that a sync should be considered for running
1958             long nextReadyToRunTime = Long.MAX_VALUE;
1959 
1960             // order the sync queue, dropping syncs that are not allowed
1961             ArrayList<SyncOperation> operations = new ArrayList<SyncOperation>();
1962             synchronized (mSyncQueue) {
1963                 if (isLoggable) {
1964                     Log.v(TAG, "build the operation array, syncQueue size is "
1965                         + mSyncQueue.getOperations().size());
1966                 }
1967                 final Iterator<SyncOperation> operationIterator = mSyncQueue.getOperations()
1968                         .iterator();
1969 
1970                 final ActivityManager activityManager
1971                         = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
1972                 final Set<Integer> removedUsers = Sets.newHashSet();
1973                 while (operationIterator.hasNext()) {
1974                     final SyncOperation op = operationIterator.next();
1975 
1976                     // drop the sync if the account of this operation no longer exists
1977                     if (!containsAccountAndUser(accounts, op.account, op.userId)) {
1978                         operationIterator.remove();
1979                         mSyncStorageEngine.deleteFromPending(op.pendingOperation);
1980                         continue;
1981                     }
1982 
1983                     // drop this sync request if it isn't syncable
1984                     int syncableState = mSyncStorageEngine.getIsSyncable(
1985                             op.account, op.userId, op.authority);
1986                     if (syncableState == 0) {
1987                         operationIterator.remove();
1988                         mSyncStorageEngine.deleteFromPending(op.pendingOperation);
1989                         continue;
1990                     }
1991 
1992                     // if the user in not running, drop the request
1993                     if (!activityManager.isUserRunning(op.userId)) {
1994                         final UserInfo userInfo = mUserManager.getUserInfo(op.userId);
1995                         if (userInfo == null) {
1996                             removedUsers.add(op.userId);
1997                         }
1998                         continue;
1999                     }
2000 
2001                     // if the next run time is in the future, meaning there are no syncs ready
2002                     // to run, return the time
2003                     if (op.effectiveRunTime > now) {
2004                         if (nextReadyToRunTime > op.effectiveRunTime) {
2005                             nextReadyToRunTime = op.effectiveRunTime;
2006                         }
2007                         continue;
2008                     }
2009 
2010                     final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
2011                     syncAdapterInfo = mSyncAdapters.getServiceInfo(
2012                             SyncAdapterType.newKey(op.authority, op.account.type), op.userId);
2013 
2014                     // only proceed if network is connected for requesting UID
2015                     final boolean uidNetworkConnected;
2016                     if (syncAdapterInfo != null) {
2017                         final NetworkInfo networkInfo = getConnectivityManager()
2018                                 .getActiveNetworkInfoForUid(syncAdapterInfo.uid);
2019                         uidNetworkConnected = networkInfo != null && networkInfo.isConnected();
2020                     } else {
2021                         uidNetworkConnected = false;
2022                     }
2023 
2024                     // skip the sync if it isn't manual, and auto sync or
2025                     // background data usage is disabled or network is
2026                     // disconnected for the target UID.
2027                     if (!op.extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false)
2028                             && (syncableState > 0)
2029                             && (!mSyncStorageEngine.getMasterSyncAutomatically(op.userId)
2030                                 || !backgroundDataUsageAllowed
2031                                 || !uidNetworkConnected
2032                                 || !mSyncStorageEngine.getSyncAutomatically(
2033                                        op.account, op.userId, op.authority))) {
2034                         operationIterator.remove();
2035                         mSyncStorageEngine.deleteFromPending(op.pendingOperation);
2036                         continue;
2037                     }
2038 
2039                     operations.add(op);
2040                 }
2041                 for (Integer user : removedUsers) {
2042                     // if it's still removed
2043                     if (mUserManager.getUserInfo(user) == null) {
2044                         onUserRemoved(user);
2045                     }
2046                 }
2047             }
2048 
2049             // find the next operation to dispatch, if one is ready
2050             // iterate from the top, keep issuing (while potentially cancelling existing syncs)
2051             // until the quotas are filled.
2052             // once the quotas are filled iterate once more to find when the next one would be
2053             // (also considering pre-emption reasons).
2054             if (isLoggable) Log.v(TAG, "sort the candidate operations, size " + operations.size());
2055             Collections.sort(operations);
2056             if (isLoggable) Log.v(TAG, "dispatch all ready sync operations");
2057             for (int i = 0, N = operations.size(); i < N; i++) {
2058                 final SyncOperation candidate = operations.get(i);
2059                 final boolean candidateIsInitialization = candidate.isInitialization();
2060 
2061                 int numInit = 0;
2062                 int numRegular = 0;
2063                 ActiveSyncContext conflict = null;
2064                 ActiveSyncContext longRunning = null;
2065                 ActiveSyncContext toReschedule = null;
2066                 ActiveSyncContext oldestNonExpeditedRegular = null;
2067 
2068                 for (ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
2069                     final SyncOperation activeOp = activeSyncContext.mSyncOperation;
2070                     if (activeOp.isInitialization()) {
2071                         numInit++;
2072                     } else {
2073                         numRegular++;
2074                         if (!activeOp.isExpedited()) {
2075                             if (oldestNonExpeditedRegular == null
2076                                 || (oldestNonExpeditedRegular.mStartTime
2077                                     > activeSyncContext.mStartTime)) {
2078                                 oldestNonExpeditedRegular = activeSyncContext;
2079                             }
2080                         }
2081                     }
2082                     if (activeOp.account.type.equals(candidate.account.type)
2083                             && activeOp.authority.equals(candidate.authority)
2084                             && activeOp.userId == candidate.userId
2085                             && (!activeOp.allowParallelSyncs
2086                                 || activeOp.account.name.equals(candidate.account.name))) {
2087                         conflict = activeSyncContext;
2088                         // don't break out since we want to do a full count of the varieties
2089                     } else {
2090                         if (candidateIsInitialization == activeOp.isInitialization()
2091                                 && activeSyncContext.mStartTime + MAX_TIME_PER_SYNC < now) {
2092                             longRunning = activeSyncContext;
2093                             // don't break out since we want to do a full count of the varieties
2094                         }
2095                     }
2096                 }
2097 
2098                 if (isLoggable) {
2099                     Log.v(TAG, "candidate " + (i + 1) + " of " + N + ": " + candidate);
2100                     Log.v(TAG, "  numActiveInit=" + numInit + ", numActiveRegular=" + numRegular);
2101                     Log.v(TAG, "  longRunning: " + longRunning);
2102                     Log.v(TAG, "  conflict: " + conflict);
2103                     Log.v(TAG, "  oldestNonExpeditedRegular: " + oldestNonExpeditedRegular);
2104                 }
2105 
2106                 final boolean roomAvailable = candidateIsInitialization
2107                         ? numInit < MAX_SIMULTANEOUS_INITIALIZATION_SYNCS
2108                         : numRegular < MAX_SIMULTANEOUS_REGULAR_SYNCS;
2109 
2110                 if (conflict != null) {
2111                     if (candidateIsInitialization && !conflict.mSyncOperation.isInitialization()
2112                             && numInit < MAX_SIMULTANEOUS_INITIALIZATION_SYNCS) {
2113                         toReschedule = conflict;
2114                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
2115                             Log.v(TAG, "canceling and rescheduling sync since an initialization "
2116                                     + "takes higher priority, " + conflict);
2117                         }
2118                     } else if (candidate.expedited && !conflict.mSyncOperation.expedited
2119                             && (candidateIsInitialization
2120                                 == conflict.mSyncOperation.isInitialization())) {
2121                         toReschedule = conflict;
2122                         if (Log.isLoggable(TAG, Log.VERBOSE)) {
2123                             Log.v(TAG, "canceling and rescheduling sync since an expedited "
2124                                     + "takes higher priority, " + conflict);
2125                         }
2126                     } else {
2127                         continue;
2128                     }
2129                 } else if (roomAvailable) {
2130                     // dispatch candidate
2131                 } else if (candidate.isExpedited() && oldestNonExpeditedRegular != null
2132                            && !candidateIsInitialization) {
2133                     // We found an active, non-expedited regular sync. We also know that the
2134                     // candidate doesn't conflict with this active sync since conflict
2135                     // is null. Reschedule the active sync and start the candidate.
2136                     toReschedule = oldestNonExpeditedRegular;
2137                     if (Log.isLoggable(TAG, Log.VERBOSE)) {
2138                         Log.v(TAG, "canceling and rescheduling sync since an expedited is ready to run, "
2139                                 + oldestNonExpeditedRegular);
2140                     }
2141                 } else if (longRunning != null
2142                         && (candidateIsInitialization
2143                             == longRunning.mSyncOperation.isInitialization())) {
2144                     // We found an active, long-running sync. Reschedule the active
2145                     // sync and start the candidate.
2146                     toReschedule = longRunning;
2147                     if (Log.isLoggable(TAG, Log.VERBOSE)) {
2148                         Log.v(TAG, "canceling and rescheduling sync since it ran roo long, "
2149                               + longRunning);
2150                     }
2151                 } else {
2152                     // we were unable to find or make space to run this candidate, go on to
2153                     // the next one
2154                     continue;
2155                 }
2156 
2157                 if (toReschedule != null) {
2158                     runSyncFinishedOrCanceledLocked(null, toReschedule);
2159                     scheduleSyncOperation(toReschedule.mSyncOperation);
2160                 }
2161                 synchronized (mSyncQueue) {
2162                     mSyncQueue.remove(candidate);
2163                 }
2164                 dispatchSyncOperation(candidate);
2165             }
2166 
2167             return nextReadyToRunTime;
2168      }
2169 
2170         private boolean dispatchSyncOperation(SyncOperation op) {
2171             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2172                 Log.v(TAG, "dispatchSyncOperation: we are going to sync " + op);
2173                 Log.v(TAG, "num active syncs: " + mActiveSyncContexts.size());
2174                 for (ActiveSyncContext syncContext : mActiveSyncContexts) {
2175                     Log.v(TAG, syncContext.toString());
2176                 }
2177             }
2178 
2179             // connect to the sync adapter
2180             SyncAdapterType syncAdapterType = SyncAdapterType.newKey(op.authority, op.account.type);
2181             final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
2182             syncAdapterInfo = mSyncAdapters.getServiceInfo(syncAdapterType, op.userId);
2183             if (syncAdapterInfo == null) {
2184                 Log.d(TAG, "can't find a sync adapter for " + syncAdapterType
2185                         + ", removing settings for it");
2186                 mSyncStorageEngine.removeAuthority(op.account, op.userId, op.authority);
2187                 return false;
2188             }
2189 
2190             ActiveSyncContext activeSyncContext =
2191                     new ActiveSyncContext(op, insertStartSyncEvent(op), syncAdapterInfo.uid);
2192             activeSyncContext.mSyncInfo = mSyncStorageEngine.addActiveSync(activeSyncContext);
2193             mActiveSyncContexts.add(activeSyncContext);
2194             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2195                 Log.v(TAG, "dispatchSyncOperation: starting " + activeSyncContext);
2196             }
2197             if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo, op.userId)) {
2198                 Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
2199                 closeActiveSyncContext(activeSyncContext);
2200                 return false;
2201             }
2202 
2203             return true;
2204         }
2205 
2206         private void runBoundToSyncAdapter(final ActiveSyncContext activeSyncContext,
2207               ISyncAdapter syncAdapter) {
2208             activeSyncContext.mSyncAdapter = syncAdapter;
2209             final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
2210             try {
2211                 activeSyncContext.mIsLinkedToDeath = true;
2212                 syncAdapter.asBinder().linkToDeath(activeSyncContext, 0);
2213 
2214                 syncAdapter.startSync(activeSyncContext, syncOperation.authority,
2215                         syncOperation.account, syncOperation.extras);
2216             } catch (RemoteException remoteExc) {
2217                 Log.d(TAG, "maybeStartNextSync: caught a RemoteException, rescheduling", remoteExc);
2218                 closeActiveSyncContext(activeSyncContext);
2219                 increaseBackoffSetting(syncOperation);
2220                 scheduleSyncOperation(new SyncOperation(syncOperation));
2221             } catch (RuntimeException exc) {
2222                 closeActiveSyncContext(activeSyncContext);
2223                 Log.e(TAG, "Caught RuntimeException while starting the sync " + syncOperation, exc);
2224             }
2225         }
2226 
2227         private void cancelActiveSyncLocked(Account account, int userId, String authority) {
2228             ArrayList<ActiveSyncContext> activeSyncs =
2229                     new ArrayList<ActiveSyncContext>(mActiveSyncContexts);
2230             for (ActiveSyncContext activeSyncContext : activeSyncs) {
2231                 if (activeSyncContext != null) {
2232                     // if an account was specified then only cancel the sync if it matches
2233                     if (account != null) {
2234                         if (!account.equals(activeSyncContext.mSyncOperation.account)) {
2235                             continue;
2236                         }
2237                     }
2238                     // if an authority was specified then only cancel the sync if it matches
2239                     if (authority != null) {
2240                         if (!authority.equals(activeSyncContext.mSyncOperation.authority)) {
2241                             continue;
2242                         }
2243                     }
2244                     // check if the userid matches
2245                     if (userId != UserHandle.USER_ALL
2246                             && userId != activeSyncContext.mSyncOperation.userId) {
2247                         continue;
2248                     }
2249                     runSyncFinishedOrCanceledLocked(null /* no result since this is a cancel */,
2250                             activeSyncContext);
2251                 }
2252             }
2253         }
2254 
2255         private void runSyncFinishedOrCanceledLocked(SyncResult syncResult,
2256                 ActiveSyncContext activeSyncContext) {
2257             boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2258 
2259             if (activeSyncContext.mIsLinkedToDeath) {
2260                 activeSyncContext.mSyncAdapter.asBinder().unlinkToDeath(activeSyncContext, 0);
2261                 activeSyncContext.mIsLinkedToDeath = false;
2262             }
2263             closeActiveSyncContext(activeSyncContext);
2264 
2265             final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
2266 
2267             final long elapsedTime = SystemClock.elapsedRealtime() - activeSyncContext.mStartTime;
2268 
2269             String historyMessage;
2270             int downstreamActivity;
2271             int upstreamActivity;
2272             if (syncResult != null) {
2273                 if (isLoggable) {
2274                     Log.v(TAG, "runSyncFinishedOrCanceled [finished]: "
2275                             + syncOperation + ", result " + syncResult);
2276                 }
2277 
2278                 if (!syncResult.hasError()) {
2279                     historyMessage = SyncStorageEngine.MESG_SUCCESS;
2280                     // TODO: set these correctly when the SyncResult is extended to include it
2281                     downstreamActivity = 0;
2282                     upstreamActivity = 0;
2283                     clearBackoffSetting(syncOperation);
2284                 } else {
2285                     Log.d(TAG, "failed sync operation " + syncOperation + ", " + syncResult);
2286                     // the operation failed so increase the backoff time
2287                     if (!syncResult.syncAlreadyInProgress) {
2288                         increaseBackoffSetting(syncOperation);
2289                     }
2290                     // reschedule the sync if so indicated by the syncResult
2291                     maybeRescheduleSync(syncResult, syncOperation);
2292                     historyMessage = Integer.toString(syncResultToErrorNumber(syncResult));
2293                     // TODO: set these correctly when the SyncResult is extended to include it
2294                     downstreamActivity = 0;
2295                     upstreamActivity = 0;
2296                 }
2297 
2298                 setDelayUntilTime(syncOperation, syncResult.delayUntil);
2299             } else {
2300                 if (isLoggable) {
2301                     Log.v(TAG, "runSyncFinishedOrCanceled [canceled]: " + syncOperation);
2302                 }
2303                 if (activeSyncContext.mSyncAdapter != null) {
2304                     try {
2305                         activeSyncContext.mSyncAdapter.cancelSync(activeSyncContext);
2306                     } catch (RemoteException e) {
2307                         // we don't need to retry this in this case
2308                     }
2309                 }
2310                 historyMessage = SyncStorageEngine.MESG_CANCELED;
2311                 downstreamActivity = 0;
2312                 upstreamActivity = 0;
2313             }
2314 
2315             stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
2316                     upstreamActivity, downstreamActivity, elapsedTime);
2317 
2318             if (syncResult != null && syncResult.tooManyDeletions) {
2319                 installHandleTooManyDeletesNotification(syncOperation.account,
2320                         syncOperation.authority, syncResult.stats.numDeletes,
2321                         syncOperation.userId);
2322             } else {
2323                 mNotificationMgr.cancelAsUser(null,
2324                         syncOperation.account.hashCode() ^ syncOperation.authority.hashCode(),
2325                         new UserHandle(syncOperation.userId));
2326             }
2327 
2328             if (syncResult != null && syncResult.fullSyncRequested) {
2329                 scheduleSyncOperation(new SyncOperation(syncOperation.account, syncOperation.userId,
2330                         syncOperation.syncSource, syncOperation.authority, new Bundle(), 0,
2331                         syncOperation.backoff, syncOperation.delayUntil,
2332                         syncOperation.allowParallelSyncs));
2333             }
2334             // no need to schedule an alarm, as that will be done by our caller.
2335         }
2336 
2337         private void closeActiveSyncContext(ActiveSyncContext activeSyncContext) {
2338             activeSyncContext.close();
2339             mActiveSyncContexts.remove(activeSyncContext);
2340             mSyncStorageEngine.removeActiveSync(activeSyncContext.mSyncInfo,
2341                     activeSyncContext.mSyncOperation.userId);
2342         }
2343 
2344         /**
2345          * Convert the error-containing SyncResult into the Sync.History error number. Since
2346          * the SyncResult may indicate multiple errors at once, this method just returns the
2347          * most "serious" error.
2348          * @param syncResult the SyncResult from which to read
2349          * @return the most "serious" error set in the SyncResult
2350          * @throws IllegalStateException if the SyncResult does not indicate any errors.
2351          *   If SyncResult.error() is true then it is safe to call this.
2352          */
2353         private int syncResultToErrorNumber(SyncResult syncResult) {
2354             if (syncResult.syncAlreadyInProgress)
2355                 return ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
2356             if (syncResult.stats.numAuthExceptions > 0)
2357                 return ContentResolver.SYNC_ERROR_AUTHENTICATION;
2358             if (syncResult.stats.numIoExceptions > 0)
2359                 return ContentResolver.SYNC_ERROR_IO;
2360             if (syncResult.stats.numParseExceptions > 0)
2361                 return ContentResolver.SYNC_ERROR_PARSE;
2362             if (syncResult.stats.numConflictDetectedExceptions > 0)
2363                 return ContentResolver.SYNC_ERROR_CONFLICT;
2364             if (syncResult.tooManyDeletions)
2365                 return ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS;
2366             if (syncResult.tooManyRetries)
2367                 return ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES;
2368             if (syncResult.databaseError)
2369                 return ContentResolver.SYNC_ERROR_INTERNAL;
2370             throw new IllegalStateException("we are not in an error state, " + syncResult);
2371         }
2372 
manageSyncNotificationLocked()2373         private void manageSyncNotificationLocked() {
2374             boolean shouldCancel;
2375             boolean shouldInstall;
2376 
2377             if (mActiveSyncContexts.isEmpty()) {
2378                 mSyncNotificationInfo.startTime = null;
2379 
2380                 // we aren't syncing. if the notification is active then remember that we need
2381                 // to cancel it and then clear out the info
2382                 shouldCancel = mSyncNotificationInfo.isActive;
2383                 shouldInstall = false;
2384             } else {
2385                 // we are syncing
2386                 final long now = SystemClock.elapsedRealtime();
2387                 if (mSyncNotificationInfo.startTime == null) {
2388                     mSyncNotificationInfo.startTime = now;
2389                 }
2390 
2391                 // there are three cases:
2392                 // - the notification is up: do nothing
2393                 // - the notification is not up but it isn't time yet: don't install
2394                 // - the notification is not up and it is time: need to install
2395 
2396                 if (mSyncNotificationInfo.isActive) {
2397                     shouldInstall = shouldCancel = false;
2398                 } else {
2399                     // it isn't currently up, so there is nothing to cancel
2400                     shouldCancel = false;
2401 
2402                     final boolean timeToShowNotification =
2403                             now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
2404                     if (timeToShowNotification) {
2405                         shouldInstall = true;
2406                     } else {
2407                         // show the notification immediately if this is a manual sync
2408                         shouldInstall = false;
2409                         for (ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
2410                             final boolean manualSync = activeSyncContext.mSyncOperation.extras
2411                                     .getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
2412                             if (manualSync) {
2413                                 shouldInstall = true;
2414                                 break;
2415                             }
2416                         }
2417                     }
2418                 }
2419             }
2420 
2421             if (shouldCancel && !shouldInstall) {
2422                 mNeedSyncActiveNotification = false;
2423                 sendSyncStateIntent();
2424                 mSyncNotificationInfo.isActive = false;
2425             }
2426 
2427             if (shouldInstall) {
2428                 mNeedSyncActiveNotification = true;
2429                 sendSyncStateIntent();
2430                 mSyncNotificationInfo.isActive = true;
2431             }
2432         }
2433 
manageSyncAlarmLocked(long nextPeriodicEventElapsedTime, long nextPendingEventElapsedTime)2434         private void manageSyncAlarmLocked(long nextPeriodicEventElapsedTime,
2435                 long nextPendingEventElapsedTime) {
2436             // in each of these cases the sync loop will be kicked, which will cause this
2437             // method to be called again
2438             if (!mDataConnectionIsConnected) return;
2439             if (mStorageIsLow) return;
2440 
2441             // When the status bar notification should be raised
2442             final long notificationTime =
2443                     (!mSyncHandler.mSyncNotificationInfo.isActive
2444                             && mSyncHandler.mSyncNotificationInfo.startTime != null)
2445                             ? mSyncHandler.mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY
2446                             : Long.MAX_VALUE;
2447 
2448             // When we should consider canceling an active sync
2449             long earliestTimeoutTime = Long.MAX_VALUE;
2450             for (ActiveSyncContext currentSyncContext : mActiveSyncContexts) {
2451                 final long currentSyncTimeoutTime =
2452                         currentSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC;
2453                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2454                     Log.v(TAG, "manageSyncAlarm: active sync, mTimeoutStartTime + MAX is "
2455                             + currentSyncTimeoutTime);
2456                 }
2457                 if (earliestTimeoutTime > currentSyncTimeoutTime) {
2458                     earliestTimeoutTime = currentSyncTimeoutTime;
2459                 }
2460             }
2461 
2462             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2463                 Log.v(TAG, "manageSyncAlarm: notificationTime is " + notificationTime);
2464             }
2465 
2466             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2467                 Log.v(TAG, "manageSyncAlarm: earliestTimeoutTime is " + earliestTimeoutTime);
2468             }
2469 
2470             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2471                 Log.v(TAG, "manageSyncAlarm: nextPeriodicEventElapsedTime is "
2472                         + nextPeriodicEventElapsedTime);
2473             }
2474             if (Log.isLoggable(TAG, Log.VERBOSE)) {
2475                 Log.v(TAG, "manageSyncAlarm: nextPendingEventElapsedTime is "
2476                         + nextPendingEventElapsedTime);
2477             }
2478 
2479             long alarmTime = Math.min(notificationTime, earliestTimeoutTime);
2480             alarmTime = Math.min(alarmTime, nextPeriodicEventElapsedTime);
2481             alarmTime = Math.min(alarmTime, nextPendingEventElapsedTime);
2482 
2483             // Bound the alarm time.
2484             final long now = SystemClock.elapsedRealtime();
2485             if (alarmTime < now + SYNC_ALARM_TIMEOUT_MIN) {
2486                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2487                     Log.v(TAG, "manageSyncAlarm: the alarmTime is too small, "
2488                             + alarmTime + ", setting to " + (now + SYNC_ALARM_TIMEOUT_MIN));
2489                 }
2490                 alarmTime = now + SYNC_ALARM_TIMEOUT_MIN;
2491             } else if (alarmTime > now + SYNC_ALARM_TIMEOUT_MAX) {
2492                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2493                     Log.v(TAG, "manageSyncAlarm: the alarmTime is too large, "
2494                             + alarmTime + ", setting to " + (now + SYNC_ALARM_TIMEOUT_MIN));
2495                 }
2496                 alarmTime = now + SYNC_ALARM_TIMEOUT_MAX;
2497             }
2498 
2499             // determine if we need to set or cancel the alarm
2500             boolean shouldSet = false;
2501             boolean shouldCancel = false;
2502             final boolean alarmIsActive = mAlarmScheduleTime != null;
2503             final boolean needAlarm = alarmTime != Long.MAX_VALUE;
2504             if (needAlarm) {
2505                 if (!alarmIsActive || alarmTime < mAlarmScheduleTime) {
2506                     shouldSet = true;
2507                 }
2508             } else {
2509                 shouldCancel = alarmIsActive;
2510             }
2511 
2512             // set or cancel the alarm as directed
2513             ensureAlarmService();
2514             if (shouldSet) {
2515                 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2516                     Log.v(TAG, "requesting that the alarm manager wake us up at elapsed time "
2517                             + alarmTime + ", now is " + now + ", " + ((alarmTime - now) / 1000)
2518                             + " secs from now");
2519                 }
2520                 mAlarmScheduleTime = alarmTime;
2521                 mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime,
2522                         mSyncAlarmIntent);
2523             } else if (shouldCancel) {
2524                 mAlarmScheduleTime = null;
2525                 mAlarmService.cancel(mSyncAlarmIntent);
2526             }
2527         }
2528 
sendSyncStateIntent()2529         private void sendSyncStateIntent() {
2530             Intent syncStateIntent = new Intent(Intent.ACTION_SYNC_STATE_CHANGED);
2531             syncStateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2532             syncStateIntent.putExtra("active", mNeedSyncActiveNotification);
2533             syncStateIntent.putExtra("failing", false);
2534             mContext.sendBroadcastAsUser(syncStateIntent, UserHandle.OWNER);
2535         }
2536 
installHandleTooManyDeletesNotification(Account account, String authority, long numDeletes, int userId)2537         private void installHandleTooManyDeletesNotification(Account account, String authority,
2538                 long numDeletes, int userId) {
2539             if (mNotificationMgr == null) return;
2540 
2541             final ProviderInfo providerInfo = mContext.getPackageManager().resolveContentProvider(
2542                     authority, 0 /* flags */);
2543             if (providerInfo == null) {
2544                 return;
2545             }
2546             CharSequence authorityName = providerInfo.loadLabel(mContext.getPackageManager());
2547 
2548             Intent clickIntent = new Intent(mContext, SyncActivityTooManyDeletes.class);
2549             clickIntent.putExtra("account", account);
2550             clickIntent.putExtra("authority", authority);
2551             clickIntent.putExtra("provider", authorityName.toString());
2552             clickIntent.putExtra("numDeletes", numDeletes);
2553 
2554             if (!isActivityAvailable(clickIntent)) {
2555                 Log.w(TAG, "No activity found to handle too many deletes.");
2556                 return;
2557             }
2558 
2559             final PendingIntent pendingIntent = PendingIntent
2560                     .getActivityAsUser(mContext, 0, clickIntent,
2561                             PendingIntent.FLAG_CANCEL_CURRENT, null, new UserHandle(userId));
2562 
2563             CharSequence tooManyDeletesDescFormat = mContext.getResources().getText(
2564                     R.string.contentServiceTooManyDeletesNotificationDesc);
2565 
2566             Notification notification =
2567                 new Notification(R.drawable.stat_notify_sync_error,
2568                         mContext.getString(R.string.contentServiceSync),
2569                         System.currentTimeMillis());
2570             notification.setLatestEventInfo(mContext,
2571                     mContext.getString(R.string.contentServiceSyncNotificationTitle),
2572                     String.format(tooManyDeletesDescFormat.toString(), authorityName),
2573                     pendingIntent);
2574             notification.flags |= Notification.FLAG_ONGOING_EVENT;
2575             mNotificationMgr.notifyAsUser(null, account.hashCode() ^ authority.hashCode(),
2576                     notification, new UserHandle(userId));
2577         }
2578 
2579         /**
2580          * Checks whether an activity exists on the system image for the given intent.
2581          *
2582          * @param intent The intent for an activity.
2583          * @return Whether or not an activity exists.
2584          */
isActivityAvailable(Intent intent)2585         private boolean isActivityAvailable(Intent intent) {
2586             PackageManager pm = mContext.getPackageManager();
2587             List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
2588             int listSize = list.size();
2589             for (int i = 0; i < listSize; i++) {
2590                 ResolveInfo resolveInfo = list.get(i);
2591                 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
2592                         != 0) {
2593                     return true;
2594                 }
2595             }
2596 
2597             return false;
2598         }
2599 
insertStartSyncEvent(SyncOperation syncOperation)2600         public long insertStartSyncEvent(SyncOperation syncOperation) {
2601             final int source = syncOperation.syncSource;
2602             final long now = System.currentTimeMillis();
2603 
2604             EventLog.writeEvent(2720, syncOperation.authority,
2605                                 SyncStorageEngine.EVENT_START, source,
2606                                 syncOperation.account.name.hashCode());
2607 
2608             return mSyncStorageEngine.insertStartSyncEvent(
2609                     syncOperation.account, syncOperation.userId, syncOperation.authority,
2610                     now, source, syncOperation.isInitialization());
2611         }
2612 
stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage, int upstreamActivity, int downstreamActivity, long elapsedTime)2613         public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage,
2614                 int upstreamActivity, int downstreamActivity, long elapsedTime) {
2615             EventLog.writeEvent(2720, syncOperation.authority,
2616                                 SyncStorageEngine.EVENT_STOP, syncOperation.syncSource,
2617                                 syncOperation.account.name.hashCode());
2618 
2619             mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime,
2620                     resultMessage, downstreamActivity, upstreamActivity);
2621         }
2622     }
2623 
isSyncStillActive(ActiveSyncContext activeSyncContext)2624     private boolean isSyncStillActive(ActiveSyncContext activeSyncContext) {
2625         for (ActiveSyncContext sync : mActiveSyncContexts) {
2626             if (sync == activeSyncContext) {
2627                 return true;
2628             }
2629         }
2630         return false;
2631     }
2632 }
2633