SyncManager.java revision f7ae77cd67f1a3993b8e56c1af4720a7adf4e69d
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
17package android.content;
18
19import com.google.android.collect.Maps;
20
21import com.android.internal.R;
22import com.android.internal.util.ArrayUtils;
23
24import android.accounts.Account;
25import android.accounts.AccountManager;
26import android.accounts.OnAccountsUpdateListener;
27import android.app.AlarmManager;
28import android.app.Notification;
29import android.app.NotificationManager;
30import android.app.PendingIntent;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.IPackageManager;
33import android.content.pm.PackageManager;
34import android.content.pm.ResolveInfo;
35import android.content.pm.RegisteredServicesCache;
36import android.content.pm.ProviderInfo;
37import android.net.ConnectivityManager;
38import android.net.NetworkInfo;
39import android.os.Bundle;
40import android.os.Handler;
41import android.os.HandlerThread;
42import android.os.IBinder;
43import android.os.Looper;
44import android.os.Message;
45import android.os.PowerManager;
46import android.os.Process;
47import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.provider.Settings;
52import android.text.format.DateUtils;
53import android.text.format.Time;
54import android.util.Config;
55import android.util.EventLog;
56import android.util.Log;
57
58import java.io.DataInputStream;
59import java.io.DataOutputStream;
60import java.io.File;
61import java.io.FileDescriptor;
62import java.io.FileInputStream;
63import java.io.FileNotFoundException;
64import java.io.FileOutputStream;
65import java.io.IOException;
66import java.io.PrintWriter;
67import java.util.ArrayList;
68import java.util.HashMap;
69import java.util.HashSet;
70import java.util.Iterator;
71import java.util.List;
72import java.util.Map;
73import java.util.PriorityQueue;
74import java.util.Random;
75import java.util.Collection;
76import java.util.concurrent.CountDownLatch;
77
78/**
79 * @hide
80 */
81class SyncManager implements OnAccountsUpdateListener {
82    private static final String TAG = "SyncManager";
83
84    // used during dumping of the Sync history
85    private static final long MILLIS_IN_HOUR = 1000 * 60 * 60;
86    private static final long MILLIS_IN_DAY = MILLIS_IN_HOUR * 24;
87    private static final long MILLIS_IN_WEEK = MILLIS_IN_DAY * 7;
88    private static final long MILLIS_IN_4WEEKS = MILLIS_IN_WEEK * 4;
89
90    /** Delay a sync due to local changes this long. In milliseconds */
91    private static final long LOCAL_SYNC_DELAY;
92
93    /**
94     * If a sync takes longer than this and the sync queue is not empty then we will
95     * cancel it and add it back to the end of the sync queue. In milliseconds.
96     */
97    private static final long MAX_TIME_PER_SYNC;
98
99    static {
100        String localSyncDelayString = SystemProperties.get("sync.local_sync_delay");
101        long localSyncDelay = 30 * 1000; // 30 seconds
102        if (localSyncDelayString != null) {
103            try {
104                localSyncDelay = Long.parseLong(localSyncDelayString);
105            } catch (NumberFormatException nfe) {
106                // ignore, use default
107            }
108        }
109        LOCAL_SYNC_DELAY = localSyncDelay;
110
111        String maxTimePerSyncString = SystemProperties.get("sync.max_time_per_sync");
112        long maxTimePerSync = 5 * 60 * 1000; // 5 minutes
113        if (maxTimePerSyncString != null) {
114            try {
115                maxTimePerSync = Long.parseLong(maxTimePerSyncString);
116            } catch (NumberFormatException nfe) {
117                // ignore, use default
118            }
119        }
120        MAX_TIME_PER_SYNC = maxTimePerSync;
121    }
122
123    private static final long SYNC_NOTIFICATION_DELAY = 30 * 1000; // 30 seconds
124
125    /**
126     * When retrying a sync for the first time use this delay. After that
127     * the retry time will double until it reached MAX_SYNC_RETRY_TIME.
128     * In milliseconds.
129     */
130    private static final long INITIAL_SYNC_RETRY_TIME_IN_MS = 30 * 1000; // 30 seconds
131
132    /**
133     * Default the max sync retry time to this value.
134     */
135    private static final long DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS = 60 * 60; // one hour
136
137    /**
138     * An error notification is sent if sync of any of the providers has been failing for this long.
139     */
140    private static final long ERROR_NOTIFICATION_DELAY_MS = 1000 * 60 * 10; // 10 minutes
141
142    private static final String SYNC_WAKE_LOCK = "SyncManagerSyncWakeLock";
143    private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock";
144
145    private Context mContext;
146
147    private String mStatusText = "";
148    private long mHeartbeatTime = 0;
149
150    private volatile Account[] mAccounts = null;
151
152    volatile private PowerManager.WakeLock mSyncWakeLock;
153    volatile private PowerManager.WakeLock mHandleAlarmWakeLock;
154    volatile private boolean mDataConnectionIsConnected = false;
155    volatile private boolean mStorageIsLow = false;
156
157    private final NotificationManager mNotificationMgr;
158    private AlarmManager mAlarmService = null;
159    private HandlerThread mSyncThread;
160
161    private volatile IPackageManager mPackageManager;
162
163    private final SyncStorageEngine mSyncStorageEngine;
164    private final SyncQueue mSyncQueue;
165
166    private ActiveSyncContext mActiveSyncContext = null;
167
168    // set if the sync error indicator should be reported.
169    private boolean mNeedSyncErrorNotification = false;
170    // set if the sync active indicator should be reported
171    private boolean mNeedSyncActiveNotification = false;
172
173    private volatile boolean mSyncPollInitialized;
174    private final PendingIntent mSyncAlarmIntent;
175    private final PendingIntent mSyncPollAlarmIntent;
176    // Synchronized on "this". Instead of using this directly one should instead call
177    // its accessor, getConnManager().
178    private ConnectivityManager mConnManagerDoNotUseDirectly;
179
180    private final SyncAdaptersCache mSyncAdapters;
181
182    private BroadcastReceiver mStorageIntentReceiver =
183            new BroadcastReceiver() {
184                public void onReceive(Context context, Intent intent) {
185                    String action = intent.getAction();
186                    if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
187                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
188                            Log.v(TAG, "Internal storage is low.");
189                        }
190                        mStorageIsLow = true;
191                        cancelActiveSync(null /* any account */, null /* any authority */);
192                    } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
193                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
194                            Log.v(TAG, "Internal storage is ok.");
195                        }
196                        mStorageIsLow = false;
197                        sendCheckAlarmsMessage();
198                    }
199                }
200            };
201
202    private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
203        public void onReceive(Context context, Intent intent) {
204            mSyncHandler.onBootCompleted();
205        }
206    };
207
208    private BroadcastReceiver mBackgroundDataSettingChanged = new BroadcastReceiver() {
209        public void onReceive(Context context, Intent intent) {
210            if (getConnectivityManager().getBackgroundDataSetting()) {
211                scheduleSync(null /* account */, null /* authority */, new Bundle(), 0 /* delay */,
212                        false /* onlyThoseWithUnknownSyncableState */);
213            }
214        }
215    };
216
217    public void onAccountsUpdated(Account[] accounts) {
218        // remember if this was the first time this was called after an update
219        final boolean justBootedUp = mAccounts == null;
220        mAccounts = accounts;
221
222        // if a sync is in progress yet it is no longer in the accounts list,
223        // cancel it
224        ActiveSyncContext activeSyncContext = mActiveSyncContext;
225        if (activeSyncContext != null) {
226            if (!ArrayUtils.contains(accounts, activeSyncContext.mSyncOperation.account)) {
227                Log.d(TAG, "canceling sync since the account has been removed");
228                sendSyncFinishedOrCanceledMessage(activeSyncContext,
229                        null /* no result since this is a cancel */);
230            }
231        }
232
233        // we must do this since we don't bother scheduling alarms when
234        // the accounts are not set yet
235        sendCheckAlarmsMessage();
236
237        mSyncStorageEngine.doDatabaseCleanup(accounts);
238
239        if (accounts.length > 0) {
240            // If this is the first time this was called after a bootup then
241            // the accounts haven't really changed, instead they were just loaded
242            // from the AccountManager. Otherwise at least one of the accounts
243            // has a change.
244            //
245            // If there was a real account change then force a sync of all accounts.
246            // This is a bit of overkill, but at least it will end up retrying syncs
247            // that failed due to an authentication failure and thus will recover if the
248            // account change was a password update.
249            //
250            // If this was the bootup case then don't sync everything, instead only
251            // sync those that have an unknown syncable state, which will give them
252            // a chance to set their syncable state.
253            boolean onlyThoseWithUnkownSyncableState = justBootedUp;
254            scheduleSync(null, null, null, 0 /* no delay */, onlyThoseWithUnkownSyncableState);
255        }
256    }
257
258    private BroadcastReceiver mConnectivityIntentReceiver =
259            new BroadcastReceiver() {
260        public void onReceive(Context context, Intent intent) {
261            NetworkInfo networkInfo =
262                    intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
263            NetworkInfo.State state = (networkInfo == null ? NetworkInfo.State.UNKNOWN :
264                    networkInfo.getState());
265            if (Log.isLoggable(TAG, Log.VERBOSE)) {
266                Log.v(TAG, "received connectivity action.  network info: " + networkInfo);
267            }
268
269            // only pay attention to the CONNECTED and DISCONNECTED states.
270            // if connected, we are connected.
271            // if disconnected, we may not be connected.  in some cases, we may be connected on
272            // a different network.
273            // e.g., if switching from GPRS to WiFi, we may receive the CONNECTED to WiFi and
274            // DISCONNECTED for GPRS in any order.  if we receive the CONNECTED first, and then
275            // a DISCONNECTED, we want to make sure we set mDataConnectionIsConnected to true
276            // since we still have a WiFi connection.
277            switch (state) {
278                case CONNECTED:
279                    mDataConnectionIsConnected = true;
280                    break;
281                case DISCONNECTED:
282                    if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
283                        mDataConnectionIsConnected = false;
284                    } else {
285                        mDataConnectionIsConnected = true;
286                    }
287                    break;
288                default:
289                    // ignore the rest of the states -- leave our boolean alone.
290            }
291            if (mDataConnectionIsConnected) {
292                initializeSyncPoll();
293                sendCheckAlarmsMessage();
294            }
295        }
296    };
297
298    private BroadcastReceiver mShutdownIntentReceiver =
299            new BroadcastReceiver() {
300        public void onReceive(Context context, Intent intent) {
301            Log.w(TAG, "Writing sync state before shutdown...");
302            getSyncStorageEngine().writeAllState();
303        }
304    };
305
306    private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM";
307    private static final String SYNC_POLL_ALARM = "android.content.syncmanager.SYNC_POLL_ALARM";
308    private final SyncHandler mSyncHandler;
309
310    private static final int MAX_SYNC_POLL_DELAY_SECONDS = 36 * 60 * 60; // 36 hours
311    private static final int MIN_SYNC_POLL_DELAY_SECONDS = 24 * 60 * 60; // 24 hours
312
313    private static final String SYNCMANAGER_PREFS_FILENAME = "/data/system/syncmanager.prefs";
314
315    private final boolean mFactoryTest;
316
317    private volatile boolean mBootCompleted = false;
318
319    private ConnectivityManager getConnectivityManager() {
320        synchronized (this) {
321            if (mConnManagerDoNotUseDirectly == null) {
322                mConnManagerDoNotUseDirectly = (ConnectivityManager)mContext.getSystemService(
323                        Context.CONNECTIVITY_SERVICE);
324            }
325            return mConnManagerDoNotUseDirectly;
326        }
327    }
328
329    public SyncManager(Context context, boolean factoryTest) {
330        mFactoryTest = factoryTest;
331
332        // Initialize the SyncStorageEngine first, before registering observers
333        // and creating threads and so on; it may fail if the disk is full.
334        SyncStorageEngine.init(context);
335        mSyncStorageEngine = SyncStorageEngine.getSingleton();
336        mSyncQueue = new SyncQueue(mSyncStorageEngine);
337
338        mContext = context;
339
340        mSyncThread = new HandlerThread("SyncHandlerThread", Process.THREAD_PRIORITY_BACKGROUND);
341        mSyncThread.start();
342        mSyncHandler = new SyncHandler(mSyncThread.getLooper());
343
344        mPackageManager = null;
345
346        mSyncAdapters = new SyncAdaptersCache(mContext);
347
348        mSyncAlarmIntent = PendingIntent.getBroadcast(
349                mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0);
350
351        mSyncPollAlarmIntent = PendingIntent.getBroadcast(
352                mContext, 0 /* ignored */, new Intent(SYNC_POLL_ALARM), 0);
353
354        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
355        context.registerReceiver(mConnectivityIntentReceiver, intentFilter);
356
357        if (!factoryTest) {
358            intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
359            context.registerReceiver(mBootCompletedReceiver, intentFilter);
360        }
361
362        intentFilter = new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
363        context.registerReceiver(mBackgroundDataSettingChanged, intentFilter);
364
365        intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
366        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
367        context.registerReceiver(mStorageIntentReceiver, intentFilter);
368
369        intentFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
370        intentFilter.setPriority(100);
371        context.registerReceiver(mShutdownIntentReceiver, intentFilter);
372
373        if (!factoryTest) {
374            mNotificationMgr = (NotificationManager)
375                context.getSystemService(Context.NOTIFICATION_SERVICE);
376            context.registerReceiver(new SyncAlarmIntentReceiver(),
377                    new IntentFilter(ACTION_SYNC_ALARM));
378        } else {
379            mNotificationMgr = null;
380        }
381        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
382        mSyncWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, SYNC_WAKE_LOCK);
383        mSyncWakeLock.setReferenceCounted(false);
384
385        // This WakeLock is used to ensure that we stay awake between the time that we receive
386        // a sync alarm notification and when we finish processing it. We need to do this
387        // because we don't do the work in the alarm handler, rather we do it in a message
388        // handler.
389        mHandleAlarmWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
390                HANDLE_SYNC_ALARM_WAKE_LOCK);
391        mHandleAlarmWakeLock.setReferenceCounted(false);
392
393        mSyncStorageEngine.addStatusChangeListener(
394                ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, new ISyncStatusObserver.Stub() {
395            public void onStatusChanged(int which) {
396                // force the sync loop to run if the settings change
397                sendCheckAlarmsMessage();
398            }
399        });
400
401        if (!factoryTest) {
402            AccountManager.get(mContext).addOnAccountsUpdatedListener(SyncManager.this,
403                mSyncHandler, false /* updateImmediately */);
404            // do this synchronously to ensure we have the accounts before this call returns
405            onAccountsUpdated(AccountManager.get(mContext).getAccounts());
406        }
407    }
408
409    private synchronized void initializeSyncPoll() {
410        if (mSyncPollInitialized) return;
411        mSyncPollInitialized = true;
412
413        mContext.registerReceiver(new SyncPollAlarmReceiver(), new IntentFilter(SYNC_POLL_ALARM));
414
415        // load the next poll time from shared preferences
416        long absoluteAlarmTime = readSyncPollTime();
417
418        if (Log.isLoggable(TAG, Log.VERBOSE)) {
419            Log.v(TAG, "initializeSyncPoll: absoluteAlarmTime is " + absoluteAlarmTime);
420        }
421
422        // Convert absoluteAlarmTime to elapsed realtime. If this time was in the past then
423        // schedule the poll immediately, if it is too far in the future then cap it at
424        // MAX_SYNC_POLL_DELAY_SECONDS.
425        long absoluteNow = System.currentTimeMillis();
426        long relativeNow = SystemClock.elapsedRealtime();
427        long relativeAlarmTime = relativeNow;
428        if (absoluteAlarmTime > absoluteNow) {
429            long delayInMs = absoluteAlarmTime - absoluteNow;
430            final int maxDelayInMs = MAX_SYNC_POLL_DELAY_SECONDS * 1000;
431            if (delayInMs > maxDelayInMs) {
432                delayInMs = MAX_SYNC_POLL_DELAY_SECONDS * 1000;
433            }
434            relativeAlarmTime += delayInMs;
435        }
436
437        // schedule an alarm for the next poll time
438        scheduleSyncPollAlarm(relativeAlarmTime);
439    }
440
441    private void scheduleSyncPollAlarm(long relativeAlarmTime) {
442        if (Log.isLoggable(TAG, Log.VERBOSE)) {
443            Log.v(TAG, "scheduleSyncPollAlarm: relativeAlarmTime is " + relativeAlarmTime
444                    + ", now is " + SystemClock.elapsedRealtime()
445                    + ", delay is " + (relativeAlarmTime - SystemClock.elapsedRealtime()));
446        }
447        ensureAlarmService();
448        mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, relativeAlarmTime,
449                mSyncPollAlarmIntent);
450    }
451
452    /**
453     * Return a random value v that satisfies minValue <= v < maxValue. The difference between
454     * maxValue and minValue must be less than Integer.MAX_VALUE.
455     */
456    private long jitterize(long minValue, long maxValue) {
457        Random random = new Random(SystemClock.elapsedRealtime());
458        long spread = maxValue - minValue;
459        if (spread > Integer.MAX_VALUE) {
460            throw new IllegalArgumentException("the difference between the maxValue and the "
461                    + "minValue must be less than " + Integer.MAX_VALUE);
462        }
463        return minValue + random.nextInt((int)spread);
464    }
465
466    private void handleSyncPollAlarm() {
467        // determine the next poll time
468        long delayMs = jitterize(MIN_SYNC_POLL_DELAY_SECONDS, MAX_SYNC_POLL_DELAY_SECONDS) * 1000;
469        long nextRelativePollTimeMs = SystemClock.elapsedRealtime() + delayMs;
470
471        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "handleSyncPollAlarm: delay " + delayMs);
472
473        // write the absolute time to shared preferences
474        writeSyncPollTime(System.currentTimeMillis() + delayMs);
475
476        // schedule an alarm for the next poll time
477        scheduleSyncPollAlarm(nextRelativePollTimeMs);
478
479        // perform a poll
480        scheduleSync(null /* sync all syncable accounts */, null /* sync all syncable providers */,
481                new Bundle(), 0 /* no delay */, false /* onlyThoseWithUnkownSyncableState */);
482    }
483
484    private void writeSyncPollTime(long when) {
485        File f = new File(SYNCMANAGER_PREFS_FILENAME);
486        DataOutputStream str = null;
487        try {
488            str = new DataOutputStream(new FileOutputStream(f));
489            str.writeLong(when);
490        } catch (FileNotFoundException e) {
491            Log.w(TAG, "error writing to file " + f, e);
492        } catch (IOException e) {
493            Log.w(TAG, "error writing to file " + f, e);
494        } finally {
495            if (str != null) {
496                try {
497                    str.close();
498                } catch (IOException e) {
499                    Log.w(TAG, "error closing file " + f, e);
500                }
501            }
502        }
503    }
504
505    private long readSyncPollTime() {
506        File f = new File(SYNCMANAGER_PREFS_FILENAME);
507
508        DataInputStream str = null;
509        try {
510            str = new DataInputStream(new FileInputStream(f));
511            return str.readLong();
512        } catch (FileNotFoundException e) {
513            writeSyncPollTime(0);
514        } catch (IOException e) {
515            Log.w(TAG, "error reading file " + f, e);
516        } finally {
517            if (str != null) {
518                try {
519                    str.close();
520                } catch (IOException e) {
521                    Log.w(TAG, "error closing file " + f, e);
522                }
523            }
524        }
525        return 0;
526    }
527
528    public ActiveSyncContext getActiveSyncContext() {
529        return mActiveSyncContext;
530    }
531
532    public SyncStorageEngine getSyncStorageEngine() {
533        return mSyncStorageEngine;
534    }
535
536    private void ensureAlarmService() {
537        if (mAlarmService == null) {
538            mAlarmService = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
539        }
540    }
541
542    public Account getSyncingAccount() {
543        ActiveSyncContext activeSyncContext = mActiveSyncContext;
544        return (activeSyncContext != null) ? activeSyncContext.mSyncOperation.account : null;
545    }
546
547    /**
548     * Returns whether or not sync is enabled.  Sync can be enabled by
549     * setting the system property "ro.config.sync" to the value "yes".
550     * This is normally done at boot time on builds that support sync.
551     * @return true if sync is enabled
552     */
553    private boolean isSyncEnabled() {
554        // Require the precise value "yes" to discourage accidental activation.
555        return "yes".equals(SystemProperties.get("ro.config.sync"));
556    }
557
558    /**
559     * Initiate a sync. This can start a sync for all providers
560     * (pass null to url, set onlyTicklable to false), only those
561     * providers that are marked as ticklable (pass null to url,
562     * set onlyTicklable to true), or a specific provider (set url
563     * to the content url of the provider).
564     *
565     * <p>If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is
566     * true then initiate a sync that just checks for local changes to send
567     * to the server, otherwise initiate a sync that first gets any
568     * changes from the server before sending local changes back to
569     * the server.
570     *
571     * <p>If a specific provider is being synced (the url is non-null)
572     * then the extras can contain SyncAdapter-specific information
573     * to control what gets synced (e.g. which specific feed to sync).
574     *
575     * <p>You'll start getting callbacks after this.
576     *
577     * @param requestedAccount the account to sync, may be null to signify all accounts
578     * @param requestedAuthority the authority to sync, may be null to indicate all authorities
579     * @param extras a Map of SyncAdapter-specific information to control
580*          syncs of a specific provider. Can be null. Is ignored
581*          if the url is null.
582     * @param delay how many milliseconds in the future to wait before performing this
583     * @param onlyThoseWithUnkownSyncableState
584     */
585    public void scheduleSync(Account requestedAccount, String requestedAuthority,
586            Bundle extras, long delay, boolean onlyThoseWithUnkownSyncableState) {
587        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
588
589        if (mAccounts == null) {
590            Log.e(TAG, "scheduleSync: the accounts aren't known yet, this should never happen");
591            return;
592        }
593
594        if (!isSyncEnabled()) {
595            if (isLoggable) {
596                Log.v(TAG, "not syncing because sync is disabled");
597            }
598            setStatusText("Sync is disabled.");
599            return;
600        }
601
602        final boolean backgroundDataUsageAllowed = !mBootCompleted ||
603                getConnectivityManager().getBackgroundDataSetting();
604
605        if (!mDataConnectionIsConnected) setStatusText("No data connection");
606        if (mStorageIsLow) setStatusText("Memory low");
607
608        if (extras == null) extras = new Bundle();
609
610        Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
611        if (expedited) {
612            delay = -1; // this means schedule at the front of the queue
613        }
614
615        Account[] accounts;
616        if (requestedAccount != null) {
617            accounts = new Account[]{requestedAccount};
618        } else {
619            // if the accounts aren't configured yet then we can't support an account-less
620            // sync request
621            accounts = mAccounts;
622            if (accounts == null) {
623                // not ready yet
624                if (isLoggable) {
625                    Log.v(TAG, "scheduleSync: no accounts yet, dropping");
626                }
627                return;
628            }
629            if (accounts.length == 0) {
630                if (isLoggable) {
631                    Log.v(TAG, "scheduleSync: no accounts configured, dropping");
632                }
633                setStatusText("No accounts are configured.");
634                return;
635            }
636        }
637
638        final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
639        final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
640
641        int source;
642        if (uploadOnly) {
643            source = SyncStorageEngine.SOURCE_LOCAL;
644        } else if (manualSync) {
645            source = SyncStorageEngine.SOURCE_USER;
646        } else if (requestedAuthority == null) {
647            source = SyncStorageEngine.SOURCE_POLL;
648        } else {
649            // this isn't strictly server, since arbitrary callers can (and do) request
650            // a non-forced two-way sync on a specific url
651            source = SyncStorageEngine.SOURCE_SERVER;
652        }
653
654        // Compile a list of authorities that have sync adapters.
655        // For each authority sync each account that matches a sync adapter.
656        final HashSet<String> syncableAuthorities = new HashSet<String>();
657        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
658                mSyncAdapters.getAllServices()) {
659            syncableAuthorities.add(syncAdapter.type.authority);
660        }
661
662        // if the url was specified then replace the list of authorities with just this authority
663        // or clear it if this authority isn't syncable
664        if (requestedAuthority != null) {
665            final boolean hasSyncAdapter = syncableAuthorities.contains(requestedAuthority);
666            syncableAuthorities.clear();
667            if (hasSyncAdapter) syncableAuthorities.add(requestedAuthority);
668        }
669
670        final boolean masterSyncAutomatically = mSyncStorageEngine.getMasterSyncAutomatically();
671
672        for (String authority : syncableAuthorities) {
673            for (Account account : accounts) {
674                int isSyncable = mSyncStorageEngine.getIsSyncable(account, authority);
675                if (isSyncable == 0) {
676                    continue;
677                }
678                if (onlyThoseWithUnkownSyncableState && isSyncable >= 0) {
679                    continue;
680                }
681                final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
682                        mSyncAdapters.getServiceInfo(
683                                SyncAdapterType.newKey(authority, account.type));
684                if (syncAdapterInfo != null) {
685                    if (!syncAdapterInfo.type.supportsUploading() && uploadOnly) {
686                        continue;
687                    }
688
689                    // make this an initialization sync if the isSyncable state is unknown
690                    Bundle extrasCopy = extras;
691                    long delayCopy = delay;
692                    if (isSyncable < 0) {
693                        extrasCopy = new Bundle(extras);
694                        extrasCopy.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
695                        delayCopy = -1; // expedite this
696                    } else {
697                        final boolean syncAutomatically = masterSyncAutomatically
698                                && mSyncStorageEngine.getSyncAutomatically(account, authority);
699                        boolean syncAllowed =
700                                manualSync || (backgroundDataUsageAllowed && syncAutomatically);
701                        if (!syncAllowed) {
702                            if (isLoggable) {
703                                Log.d(TAG, "scheduleSync: sync of " + account + ", " + authority
704                                        + " is not allowed, dropping request");
705                            }
706                            continue;
707                        }
708                    }
709                    if (isLoggable) {
710                        Log.v(TAG, "scheduleSync:"
711                                + " delay " + delayCopy
712                                + ", source " + source
713                                + ", account " + account
714                                + ", authority " + authority
715                                + ", extras " + extrasCopy);
716                    }
717                    scheduleSyncOperation(
718                            new SyncOperation(account, source, authority, extrasCopy, delayCopy));
719                }
720            }
721        }
722    }
723
724    private void setStatusText(String message) {
725        mStatusText = message;
726    }
727
728    public void scheduleLocalSync(Account account, String authority) {
729        final Bundle extras = new Bundle();
730        extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
731        scheduleSync(account, authority, extras, LOCAL_SYNC_DELAY,
732                false /* onlyThoseWithUnkownSyncableState */);
733    }
734
735    private IPackageManager getPackageManager() {
736        // Don't bother synchronizing on this. The worst that can happen is that two threads
737        // can try to get the package manager at the same time but only one result gets
738        // used. Since there is only one package manager in the system this doesn't matter.
739        if (mPackageManager == null) {
740            IBinder b = ServiceManager.getService("package");
741            mPackageManager = IPackageManager.Stub.asInterface(b);
742        }
743        return mPackageManager;
744    }
745
746    public SyncAdapterType[] getSyncAdapterTypes() {
747        final Collection<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> serviceInfos =
748                mSyncAdapters.getAllServices();
749        SyncAdapterType[] types = new SyncAdapterType[serviceInfos.size()];
750        int i = 0;
751        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> serviceInfo : serviceInfos) {
752            types[i] = serviceInfo.type;
753            ++i;
754        }
755        return types;
756    }
757
758    public void updateHeartbeatTime() {
759        mHeartbeatTime = SystemClock.elapsedRealtime();
760        mSyncStorageEngine.reportActiveChange();
761    }
762
763    private void sendSyncAlarmMessage() {
764        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_ALARM");
765        mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_SYNC_ALARM);
766    }
767
768    private void sendCheckAlarmsMessage() {
769        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CHECK_ALARMS");
770        mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS);
771    }
772
773    private void sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext,
774            SyncResult syncResult) {
775        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_FINISHED");
776        Message msg = mSyncHandler.obtainMessage();
777        msg.what = SyncHandler.MESSAGE_SYNC_FINISHED;
778        msg.obj = new SyncHandlerMessagePayload(syncContext, syncResult);
779        mSyncHandler.sendMessage(msg);
780    }
781
782    class SyncHandlerMessagePayload {
783        public final ActiveSyncContext activeSyncContext;
784        public final SyncResult syncResult;
785
786        SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) {
787            this.activeSyncContext = syncContext;
788            this.syncResult = syncResult;
789        }
790    }
791
792    class SyncAlarmIntentReceiver extends BroadcastReceiver {
793        public void onReceive(Context context, Intent intent) {
794            mHandleAlarmWakeLock.acquire();
795            sendSyncAlarmMessage();
796        }
797    }
798
799    class SyncPollAlarmReceiver extends BroadcastReceiver {
800        public void onReceive(Context context, Intent intent) {
801            handleSyncPollAlarm();
802        }
803    }
804
805    private void rescheduleImmediately(SyncOperation syncOperation) {
806        SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation);
807        rescheduledSyncOperation.setDelay(0);
808        scheduleSyncOperation(rescheduledSyncOperation);
809    }
810
811    private long rescheduleWithDelay(SyncOperation syncOperation) {
812        long newDelayInMs;
813
814        if (syncOperation.delay == 0) {
815            // The initial delay is the jitterized INITIAL_SYNC_RETRY_TIME_IN_MS
816            newDelayInMs = jitterize(INITIAL_SYNC_RETRY_TIME_IN_MS,
817                    (long)(INITIAL_SYNC_RETRY_TIME_IN_MS * 1.1));
818        } else {
819            // Subsequent delays are the double of the previous delay
820            newDelayInMs = syncOperation.delay * 2;
821        }
822
823        // Cap the delay
824        long maxSyncRetryTimeInSeconds = Settings.Gservices.getLong(mContext.getContentResolver(),
825                Settings.Gservices.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
826                DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS);
827        if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) {
828            newDelayInMs = maxSyncRetryTimeInSeconds * 1000;
829        }
830
831        SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation);
832        rescheduledSyncOperation.setDelay(newDelayInMs);
833        scheduleSyncOperation(rescheduledSyncOperation);
834        return newDelayInMs;
835    }
836
837    /**
838     * Cancel the active sync if it matches the authority and account.
839     * @param account limit the cancelations to syncs with this account, if non-null
840     * @param authority limit the cancelations to syncs with this authority, if non-null
841     */
842    public void cancelActiveSync(Account account, String authority) {
843        ActiveSyncContext activeSyncContext = mActiveSyncContext;
844        if (activeSyncContext != null) {
845            // if an authority was specified then only cancel the sync if it matches
846            if (account != null) {
847                if (!account.equals(activeSyncContext.mSyncOperation.account)) {
848                    return;
849                }
850            }
851            // if an account was specified then only cancel the sync if it matches
852            if (authority != null) {
853                if (!authority.equals(activeSyncContext.mSyncOperation.authority)) {
854                    return;
855                }
856            }
857            sendSyncFinishedOrCanceledMessage(activeSyncContext,
858                    null /* no result since this is a cancel */);
859        }
860    }
861
862    /**
863     * Create and schedule a SyncOperation.
864     *
865     * @param syncOperation the SyncOperation to schedule
866     */
867    public void scheduleSyncOperation(SyncOperation syncOperation) {
868        // If this operation is expedited and there is a sync in progress then
869        // reschedule the current operation and send a cancel for it.
870        final boolean expedited = syncOperation.delay < 0;
871        final ActiveSyncContext activeSyncContext = mActiveSyncContext;
872        if (expedited && activeSyncContext != null) {
873            final boolean activeIsExpedited = activeSyncContext.mSyncOperation.delay < 0;
874            final boolean hasSameKey =
875                    activeSyncContext.mSyncOperation.key.equals(syncOperation.key);
876            // This request is expedited and there is a sync in progress.
877            // Interrupt the current sync only if it is not expedited and if it has a different
878            // key than the one we are scheduling.
879            if (!activeIsExpedited && !hasSameKey) {
880                rescheduleImmediately(activeSyncContext.mSyncOperation);
881                sendSyncFinishedOrCanceledMessage(activeSyncContext,
882                        null /* no result since this is a cancel */);
883            }
884        }
885
886        boolean operationEnqueued;
887        synchronized (mSyncQueue) {
888            operationEnqueued = mSyncQueue.add(syncOperation);
889        }
890
891        if (operationEnqueued) {
892            if (Log.isLoggable(TAG, Log.VERBOSE)) {
893                Log.v(TAG, "scheduleSyncOperation: enqueued " + syncOperation);
894            }
895            sendCheckAlarmsMessage();
896        } else {
897            if (Log.isLoggable(TAG, Log.VERBOSE)) {
898                Log.v(TAG, "scheduleSyncOperation: dropping duplicate sync operation "
899                        + syncOperation);
900            }
901        }
902    }
903
904    /**
905     * Remove scheduled sync operations.
906     * @param account limit the removals to operations with this account, if non-null
907     * @param authority limit the removals to operations with this authority, if non-null
908     */
909    public void clearScheduledSyncOperations(Account account, String authority) {
910        synchronized (mSyncQueue) {
911            mSyncQueue.clear(account, authority);
912        }
913    }
914
915    void maybeRescheduleSync(SyncResult syncResult, SyncOperation previousSyncOperation) {
916        boolean isLoggable = Log.isLoggable(TAG, Log.DEBUG);
917        if (isLoggable) {
918            Log.d(TAG, "encountered error(s) during the sync: " + syncResult + ", "
919                    + previousSyncOperation);
920        }
921
922        // If the operation succeeded to some extent then retry immediately.
923        // If this was a two-way sync then retry soft errors with an exponential backoff.
924        // If this was an upward sync then schedule a two-way sync immediately.
925        // Otherwise do not reschedule.
926
927        if (syncResult.madeSomeProgress()) {
928            if (isLoggable) {
929                Log.d(TAG, "retrying sync operation immediately because "
930                        + "even though it had an error it achieved some success");
931            }
932            rescheduleImmediately(previousSyncOperation);
933        } else if (previousSyncOperation.extras.getBoolean(
934                ContentResolver.SYNC_EXTRAS_UPLOAD, false)) {
935            final SyncOperation newSyncOperation = new SyncOperation(previousSyncOperation);
936            newSyncOperation.extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
937            newSyncOperation.setDelay(0);
938            if (Config.LOGD) {
939                Log.d(TAG, "retrying sync operation as a two-way sync because an upload-only sync "
940                        + "encountered an error: " + previousSyncOperation);
941            }
942            scheduleSyncOperation(newSyncOperation);
943        } else if (syncResult.hasSoftError()) {
944            long delay = rescheduleWithDelay(previousSyncOperation);
945            if (delay >= 0) {
946                if (isLoggable) {
947                    Log.d(TAG, "retrying sync operation in " + delay + " ms because "
948                            + "it encountered a soft error: " + previousSyncOperation);
949                }
950            }
951        } else {
952            if (Config.LOGD) {
953                Log.d(TAG, "not retrying sync operation because the error is a hard error: "
954                        + previousSyncOperation);
955            }
956        }
957    }
958
959    /**
960     * Value type that represents a sync operation.
961     */
962    static class SyncOperation implements Comparable {
963        final Account account;
964        int syncSource;
965        String authority;
966        Bundle extras;
967        final String key;
968        long earliestRunTime;
969        long delay;
970        SyncStorageEngine.PendingOperation pendingOperation;
971
972        SyncOperation(Account account, int source, String authority, Bundle extras, long delay) {
973            this.account = account;
974            this.syncSource = source;
975            this.authority = authority;
976            this.extras = new Bundle(extras);
977            this.setDelay(delay);
978            this.key = toKey();
979        }
980
981        SyncOperation(SyncOperation other) {
982            this.account = other.account;
983            this.syncSource = other.syncSource;
984            this.authority = other.authority;
985            this.extras = new Bundle(other.extras);
986            this.delay = other.delay;
987            this.earliestRunTime = other.earliestRunTime;
988            this.key = toKey();
989        }
990
991        public void setDelay(long delay) {
992            this.delay = delay;
993            if (delay >= 0) {
994                this.earliestRunTime = SystemClock.elapsedRealtime() + delay;
995            } else {
996                this.earliestRunTime = 0;
997            }
998        }
999
1000        public String toString() {
1001            StringBuilder sb = new StringBuilder();
1002            sb.append("authority: ").append(authority);
1003            sb.append(" account: ").append(account);
1004            sb.append(" extras: ");
1005            extrasToStringBuilder(extras, sb);
1006            sb.append(" syncSource: ").append(syncSource);
1007            sb.append(" when: ").append(earliestRunTime);
1008            sb.append(" delay: ").append(delay);
1009            sb.append(" key: {").append(key).append("}");
1010            if (pendingOperation != null) sb.append(" pendingOperation: ").append(pendingOperation);
1011            return sb.toString();
1012        }
1013
1014        private String toKey() {
1015            StringBuilder sb = new StringBuilder();
1016            sb.append("authority: ").append(authority);
1017            sb.append(" account: ").append(account);
1018            sb.append(" extras: ");
1019            extrasToStringBuilder(extras, sb);
1020            return sb.toString();
1021        }
1022
1023        private static void extrasToStringBuilder(Bundle bundle, StringBuilder sb) {
1024            sb.append("[");
1025            for (String key : bundle.keySet()) {
1026                sb.append(key).append("=").append(bundle.get(key)).append(" ");
1027            }
1028            sb.append("]");
1029        }
1030
1031        public int compareTo(Object o) {
1032            SyncOperation other = (SyncOperation)o;
1033            if (earliestRunTime == other.earliestRunTime) {
1034                return 0;
1035            }
1036            return (earliestRunTime < other.earliestRunTime) ? -1 : 1;
1037        }
1038    }
1039
1040    /**
1041     * @hide
1042     */
1043    class ActiveSyncContext extends ISyncContext.Stub implements ServiceConnection {
1044        final SyncOperation mSyncOperation;
1045        final long mHistoryRowId;
1046        ISyncAdapter mSyncAdapter;
1047        final long mStartTime;
1048        long mTimeoutStartTime;
1049
1050        public ActiveSyncContext(SyncOperation syncOperation,
1051                long historyRowId) {
1052            super();
1053            mSyncOperation = syncOperation;
1054            mHistoryRowId = historyRowId;
1055            mSyncAdapter = null;
1056            mStartTime = SystemClock.elapsedRealtime();
1057            mTimeoutStartTime = mStartTime;
1058        }
1059
1060        public void sendHeartbeat() {
1061            // ignore this call if it corresponds to an old sync session
1062            if (mActiveSyncContext == this) {
1063                SyncManager.this.updateHeartbeatTime();
1064            }
1065        }
1066
1067        public void onFinished(SyncResult result) {
1068            // include "this" in the message so that the handler can ignore it if this
1069            // ActiveSyncContext is no longer the mActiveSyncContext at message handling
1070            // time
1071            sendSyncFinishedOrCanceledMessage(this, result);
1072        }
1073
1074        public void toString(StringBuilder sb) {
1075            sb.append("startTime ").append(mStartTime)
1076                    .append(", mTimeoutStartTime ").append(mTimeoutStartTime)
1077                    .append(", mHistoryRowId ").append(mHistoryRowId)
1078                    .append(", syncOperation ").append(mSyncOperation);
1079        }
1080
1081        public void onServiceConnected(ComponentName name, IBinder service) {
1082            Message msg = mSyncHandler.obtainMessage();
1083            msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
1084            msg.obj = new ServiceConnectionData(this, ISyncAdapter.Stub.asInterface(service));
1085            mSyncHandler.sendMessage(msg);
1086        }
1087
1088        public void onServiceDisconnected(ComponentName name) {
1089            Message msg = mSyncHandler.obtainMessage();
1090            msg.what = SyncHandler.MESSAGE_SERVICE_DISCONNECTED;
1091            msg.obj = new ServiceConnectionData(this, null);
1092            mSyncHandler.sendMessage(msg);
1093        }
1094
1095        boolean bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info) {
1096            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1097                Log.d(TAG, "bindToSyncAdapter: " + info.componentName + ", connection " + this);
1098            }
1099            Intent intent = new Intent();
1100            intent.setAction("android.content.SyncAdapter");
1101            intent.setComponent(info.componentName);
1102            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1103                    com.android.internal.R.string.sync_binding_label);
1104            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1105                    mContext, 0, new Intent(Settings.ACTION_SYNC_SETTINGS), 0));
1106            return mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
1107        }
1108
1109        void unBindFromSyncAdapter() {
1110            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1111                Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
1112            }
1113            mContext.unbindService(this);
1114        }
1115
1116        @Override
1117        public String toString() {
1118            StringBuilder sb = new StringBuilder();
1119            toString(sb);
1120            return sb.toString();
1121        }
1122    }
1123
1124    protected void dump(FileDescriptor fd, PrintWriter pw) {
1125        StringBuilder sb = new StringBuilder();
1126        dumpSyncState(pw, sb);
1127        if (isSyncEnabled()) {
1128            dumpSyncHistory(pw, sb);
1129        }
1130
1131        pw.println();
1132        pw.println("SyncAdapters:");
1133        for (RegisteredServicesCache.ServiceInfo info : mSyncAdapters.getAllServices()) {
1134            pw.println("  " + info);
1135        }
1136    }
1137
1138    static String formatTime(long time) {
1139        Time tobj = new Time();
1140        tobj.set(time);
1141        return tobj.format("%Y-%m-%d %H:%M:%S");
1142    }
1143
1144    protected void dumpSyncState(PrintWriter pw, StringBuilder sb) {
1145        pw.print("sync enabled: "); pw.println(isSyncEnabled());
1146        pw.print("data connected: "); pw.println(mDataConnectionIsConnected);
1147        pw.print("memory low: "); pw.println(mStorageIsLow);
1148
1149        final Account[] accounts = mAccounts;
1150        pw.print("accounts: ");
1151        if (accounts != null) {
1152            pw.println(accounts.length);
1153        } else {
1154            pw.println("none");
1155        }
1156        final long now = SystemClock.elapsedRealtime();
1157        pw.print("now: "); pw.println(now);
1158        pw.print("uptime: "); pw.print(DateUtils.formatElapsedTime(now/1000));
1159                pw.println(" (HH:MM:SS)");
1160        pw.print("time spent syncing: ");
1161                pw.print(DateUtils.formatElapsedTime(
1162                        mSyncHandler.mSyncTimeTracker.timeSpentSyncing() / 1000));
1163                pw.print(" (HH:MM:SS), sync ");
1164                pw.print(mSyncHandler.mSyncTimeTracker.mLastWasSyncing ? "" : "not ");
1165                pw.println("in progress");
1166        if (mSyncHandler.mAlarmScheduleTime != null) {
1167            pw.print("next alarm time: "); pw.print(mSyncHandler.mAlarmScheduleTime);
1168                    pw.print(" (");
1169                    pw.print(DateUtils.formatElapsedTime((mSyncHandler.mAlarmScheduleTime-now)/1000));
1170                    pw.println(" (HH:MM:SS) from now)");
1171        } else {
1172            pw.println("no alarm is scheduled (there had better not be any pending syncs)");
1173        }
1174
1175        pw.print("active sync: "); pw.println(mActiveSyncContext);
1176
1177        pw.print("notification info: ");
1178        sb.setLength(0);
1179        mSyncHandler.mSyncNotificationInfo.toString(sb);
1180        pw.println(sb.toString());
1181
1182        synchronized (mSyncQueue) {
1183            pw.print("sync queue: ");
1184            sb.setLength(0);
1185            mSyncQueue.dump(sb);
1186            pw.println(sb.toString());
1187        }
1188
1189        ActiveSyncInfo active = mSyncStorageEngine.getActiveSync();
1190        if (active != null) {
1191            SyncStorageEngine.AuthorityInfo authority
1192                    = mSyncStorageEngine.getAuthority(active.authorityId);
1193            final long durationInSeconds = (now - active.startTime) / 1000;
1194            pw.print("Active sync: ");
1195                    pw.print(authority != null ? authority.account : "<no account>");
1196                    pw.print(" ");
1197                    pw.print(authority != null ? authority.authority : "<no account>");
1198                    pw.print(", duration is ");
1199                    pw.println(DateUtils.formatElapsedTime(durationInSeconds));
1200        } else {
1201            pw.println("No sync is in progress.");
1202        }
1203
1204        ArrayList<SyncStorageEngine.PendingOperation> ops
1205                = mSyncStorageEngine.getPendingOperations();
1206        if (ops != null && ops.size() > 0) {
1207            pw.println();
1208            pw.println("Pending Syncs");
1209            final int N = ops.size();
1210            for (int i=0; i<N; i++) {
1211                SyncStorageEngine.PendingOperation op = ops.get(i);
1212                pw.print("  #"); pw.print(i); pw.print(": account=");
1213                pw.print(op.account.name); pw.print(":");
1214                pw.print(op.account.type); pw.print(" authority=");
1215                pw.println(op.authority);
1216                if (op.extras != null && op.extras.size() > 0) {
1217                    sb.setLength(0);
1218                    SyncOperation.extrasToStringBuilder(op.extras, sb);
1219                    pw.print("    extras: "); pw.println(sb.toString());
1220                }
1221            }
1222        }
1223
1224        HashSet<Account> processedAccounts = new HashSet<Account>();
1225        ArrayList<SyncStatusInfo> statuses
1226                = mSyncStorageEngine.getSyncStatus();
1227        if (statuses != null && statuses.size() > 0) {
1228            pw.println();
1229            pw.println("Sync Status");
1230            final int N = statuses.size();
1231            for (int i=0; i<N; i++) {
1232                SyncStatusInfo status = statuses.get(i);
1233                SyncStorageEngine.AuthorityInfo authority
1234                        = mSyncStorageEngine.getAuthority(status.authorityId);
1235                if (authority != null) {
1236                    Account curAccount = authority.account;
1237
1238                    if (processedAccounts.contains(curAccount)) {
1239                        continue;
1240                    }
1241
1242                    processedAccounts.add(curAccount);
1243
1244                    pw.print("  Account "); pw.print(authority.account.name);
1245                            pw.print(" "); pw.print(authority.account.type);
1246                            pw.println(":");
1247                    for (int j=i; j<N; j++) {
1248                        status = statuses.get(j);
1249                        authority = mSyncStorageEngine.getAuthority(status.authorityId);
1250                        if (!curAccount.equals(authority.account)) {
1251                            continue;
1252                        }
1253                        pw.print("    "); pw.print(authority.authority);
1254                        pw.println(":");
1255                        pw.print("      count: local="); pw.print(status.numSourceLocal);
1256                                pw.print(" poll="); pw.print(status.numSourcePoll);
1257                                pw.print(" server="); pw.print(status.numSourceServer);
1258                                pw.print(" user="); pw.print(status.numSourceUser);
1259                                pw.print(" total="); pw.println(status.numSyncs);
1260                        pw.print("      total duration: ");
1261                                pw.println(DateUtils.formatElapsedTime(
1262                                        status.totalElapsedTime/1000));
1263                        if (status.lastSuccessTime != 0) {
1264                            pw.print("      SUCCESS: source=");
1265                                    pw.print(SyncStorageEngine.SOURCES[
1266                                            status.lastSuccessSource]);
1267                                    pw.print(" time=");
1268                                    pw.println(formatTime(status.lastSuccessTime));
1269                        } else {
1270                            pw.print("      FAILURE: source=");
1271                                    pw.print(SyncStorageEngine.SOURCES[
1272                                            status.lastFailureSource]);
1273                                    pw.print(" initialTime=");
1274                                    pw.print(formatTime(status.initialFailureTime));
1275                                    pw.print(" lastTime=");
1276                                    pw.println(formatTime(status.lastFailureTime));
1277                            pw.print("      message: "); pw.println(status.lastFailureMesg);
1278                        }
1279                    }
1280                }
1281            }
1282        }
1283    }
1284
1285    private void dumpTimeSec(PrintWriter pw, long time) {
1286        pw.print(time/1000); pw.print('.'); pw.print((time/100)%10);
1287        pw.print('s');
1288    }
1289
1290    private void dumpDayStatistic(PrintWriter pw, SyncStorageEngine.DayStats ds) {
1291        pw.print("Success ("); pw.print(ds.successCount);
1292        if (ds.successCount > 0) {
1293            pw.print(" for "); dumpTimeSec(pw, ds.successTime);
1294            pw.print(" avg="); dumpTimeSec(pw, ds.successTime/ds.successCount);
1295        }
1296        pw.print(") Failure ("); pw.print(ds.failureCount);
1297        if (ds.failureCount > 0) {
1298            pw.print(" for "); dumpTimeSec(pw, ds.failureTime);
1299            pw.print(" avg="); dumpTimeSec(pw, ds.failureTime/ds.failureCount);
1300        }
1301        pw.println(")");
1302    }
1303
1304    protected void dumpSyncHistory(PrintWriter pw, StringBuilder sb) {
1305        SyncStorageEngine.DayStats dses[] = mSyncStorageEngine.getDayStatistics();
1306        if (dses != null && dses[0] != null) {
1307            pw.println();
1308            pw.println("Sync Statistics");
1309            pw.print("  Today:  "); dumpDayStatistic(pw, dses[0]);
1310            int today = dses[0].day;
1311            int i;
1312            SyncStorageEngine.DayStats ds;
1313
1314            // Print each day in the current week.
1315            for (i=1; i<=6 && i < dses.length; i++) {
1316                ds = dses[i];
1317                if (ds == null) break;
1318                int delta = today-ds.day;
1319                if (delta > 6) break;
1320
1321                pw.print("  Day-"); pw.print(delta); pw.print(":  ");
1322                dumpDayStatistic(pw, ds);
1323            }
1324
1325            // Aggregate all following days into weeks and print totals.
1326            int weekDay = today;
1327            while (i < dses.length) {
1328                SyncStorageEngine.DayStats aggr = null;
1329                weekDay -= 7;
1330                while (i < dses.length) {
1331                    ds = dses[i];
1332                    if (ds == null) {
1333                        i = dses.length;
1334                        break;
1335                    }
1336                    int delta = weekDay-ds.day;
1337                    if (delta > 6) break;
1338                    i++;
1339
1340                    if (aggr == null) {
1341                        aggr = new SyncStorageEngine.DayStats(weekDay);
1342                    }
1343                    aggr.successCount += ds.successCount;
1344                    aggr.successTime += ds.successTime;
1345                    aggr.failureCount += ds.failureCount;
1346                    aggr.failureTime += ds.failureTime;
1347                }
1348                if (aggr != null) {
1349                    pw.print("  Week-"); pw.print((today-weekDay)/7); pw.print(": ");
1350                    dumpDayStatistic(pw, aggr);
1351                }
1352            }
1353        }
1354
1355        ArrayList<SyncStorageEngine.SyncHistoryItem> items
1356                = mSyncStorageEngine.getSyncHistory();
1357        if (items != null && items.size() > 0) {
1358            pw.println();
1359            pw.println("Recent Sync History");
1360            final int N = items.size();
1361            for (int i=0; i<N; i++) {
1362                SyncStorageEngine.SyncHistoryItem item = items.get(i);
1363                SyncStorageEngine.AuthorityInfo authority
1364                        = mSyncStorageEngine.getAuthority(item.authorityId);
1365                pw.print("  #"); pw.print(i+1); pw.print(": ");
1366                        if (authority != null) {
1367                            pw.print(authority.account.name);
1368                            pw.print(":");
1369                            pw.print(authority.account.type);
1370                            pw.print(" ");
1371                            pw.print(authority.authority);
1372                        } else {
1373                            pw.print("<no account>");
1374                        }
1375                Time time = new Time();
1376                time.set(item.eventTime);
1377                pw.print(" "); pw.print(SyncStorageEngine.SOURCES[item.source]);
1378                        pw.print(" @ ");
1379                        pw.print(formatTime(item.eventTime));
1380                        pw.print(" for ");
1381                        dumpTimeSec(pw, item.elapsedTime);
1382                        pw.println();
1383                if (item.event != SyncStorageEngine.EVENT_STOP
1384                        || item.upstreamActivity !=0
1385                        || item.downstreamActivity != 0) {
1386                    pw.print("    event="); pw.print(item.event);
1387                            pw.print(" upstreamActivity="); pw.print(item.upstreamActivity);
1388                            pw.print(" downstreamActivity="); pw.println(item.downstreamActivity);
1389                }
1390                if (item.mesg != null
1391                        && !SyncStorageEngine.MESG_SUCCESS.equals(item.mesg)) {
1392                    pw.print("    mesg="); pw.println(item.mesg);
1393                }
1394            }
1395        }
1396    }
1397
1398    /**
1399     * A helper object to keep track of the time we have spent syncing since the last boot
1400     */
1401    private class SyncTimeTracker {
1402        /** True if a sync was in progress on the most recent call to update() */
1403        boolean mLastWasSyncing = false;
1404        /** Used to track when lastWasSyncing was last set */
1405        long mWhenSyncStarted = 0;
1406        /** The cumulative time we have spent syncing */
1407        private long mTimeSpentSyncing;
1408
1409        /** Call to let the tracker know that the sync state may have changed */
1410        public synchronized void update() {
1411            final boolean isSyncInProgress = mActiveSyncContext != null;
1412            if (isSyncInProgress == mLastWasSyncing) return;
1413            final long now = SystemClock.elapsedRealtime();
1414            if (isSyncInProgress) {
1415                mWhenSyncStarted = now;
1416            } else {
1417                mTimeSpentSyncing += now - mWhenSyncStarted;
1418            }
1419            mLastWasSyncing = isSyncInProgress;
1420        }
1421
1422        /** Get how long we have been syncing, in ms */
1423        public synchronized long timeSpentSyncing() {
1424            if (!mLastWasSyncing) return mTimeSpentSyncing;
1425
1426            final long now = SystemClock.elapsedRealtime();
1427            return mTimeSpentSyncing + (now - mWhenSyncStarted);
1428        }
1429    }
1430
1431    class ServiceConnectionData {
1432        public final ActiveSyncContext activeSyncContext;
1433        public final ISyncAdapter syncAdapter;
1434        ServiceConnectionData(ActiveSyncContext activeSyncContext, ISyncAdapter syncAdapter) {
1435            this.activeSyncContext = activeSyncContext;
1436            this.syncAdapter = syncAdapter;
1437        }
1438    }
1439
1440    /**
1441     * Handles SyncOperation Messages that are posted to the associated
1442     * HandlerThread.
1443     */
1444    class SyncHandler extends Handler {
1445        // Messages that can be sent on mHandler
1446        private static final int MESSAGE_SYNC_FINISHED = 1;
1447        private static final int MESSAGE_SYNC_ALARM = 2;
1448        private static final int MESSAGE_CHECK_ALARMS = 3;
1449        private static final int MESSAGE_SERVICE_CONNECTED = 4;
1450        private static final int MESSAGE_SERVICE_DISCONNECTED = 5;
1451
1452        public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo();
1453        private Long mAlarmScheduleTime = null;
1454        public final SyncTimeTracker mSyncTimeTracker = new SyncTimeTracker();
1455
1456        // used to track if we have installed the error notification so that we don't reinstall
1457        // it if sync is still failing
1458        private boolean mErrorNotificationInstalled = false;
1459        private volatile CountDownLatch mReadyToRunLatch = new CountDownLatch(1);
1460
1461        public void onBootCompleted() {
1462            mBootCompleted = true;
1463            if (mReadyToRunLatch != null) {
1464                mReadyToRunLatch.countDown();
1465            }
1466        }
1467
1468        private void waitUntilReadyToRun() {
1469            CountDownLatch latch = mReadyToRunLatch;
1470            if (latch != null) {
1471                while (true) {
1472                    try {
1473                        latch.await();
1474                        mReadyToRunLatch = null;
1475                        return;
1476                    } catch (InterruptedException e) {
1477                        Thread.currentThread().interrupt();
1478                    }
1479                }
1480            }
1481        }
1482        /**
1483         * Used to keep track of whether a sync notification is active and who it is for.
1484         */
1485        class SyncNotificationInfo {
1486            // only valid if isActive is true
1487            public Account account;
1488
1489            // only valid if isActive is true
1490            public String authority;
1491
1492            // true iff the notification manager has been asked to send the notification
1493            public boolean isActive = false;
1494
1495            // Set when we transition from not running a sync to running a sync, and cleared on
1496            // the opposite transition.
1497            public Long startTime = null;
1498
1499            public void toString(StringBuilder sb) {
1500                sb.append("account ").append(account)
1501                        .append(", authority ").append(authority)
1502                        .append(", isActive ").append(isActive)
1503                        .append(", startTime ").append(startTime);
1504            }
1505
1506            @Override
1507            public String toString() {
1508                StringBuilder sb = new StringBuilder();
1509                toString(sb);
1510                return sb.toString();
1511            }
1512        }
1513
1514        public SyncHandler(Looper looper) {
1515            super(looper);
1516        }
1517
1518        public void handleMessage(Message msg) {
1519            try {
1520                waitUntilReadyToRun();
1521                switch (msg.what) {
1522                    case SyncHandler.MESSAGE_SYNC_FINISHED:
1523                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1524                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_FINISHED");
1525                        }
1526                        SyncHandlerMessagePayload payload = (SyncHandlerMessagePayload)msg.obj;
1527                        if (mActiveSyncContext != payload.activeSyncContext) {
1528                            if (Config.LOGD) {
1529                                Log.d(TAG, "handleSyncHandlerMessage: sync context doesn't match, "
1530                                        + "dropping: mActiveSyncContext " + mActiveSyncContext
1531                                        + " != " + payload.activeSyncContext);
1532                            }
1533                            return;
1534                        }
1535                        runSyncFinishedOrCanceled(payload.syncResult);
1536
1537                        // since we are no longer syncing, check if it is time to start a new sync
1538                        runStateIdle();
1539                        break;
1540
1541                    case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
1542                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
1543                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1544                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
1545                                    + msgData.activeSyncContext
1546                                    + " active is " + mActiveSyncContext);
1547                        }
1548                        // check that this isn't an old message
1549                        if (mActiveSyncContext == msgData.activeSyncContext) {
1550                            runBoundToSyncAdapter(msgData.syncAdapter);
1551                        }
1552                        break;
1553                    }
1554
1555                    case SyncHandler.MESSAGE_SERVICE_DISCONNECTED: {
1556                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
1557                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1558                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_DISCONNECTED: "
1559                                    + msgData.activeSyncContext
1560                                    + " active is " + mActiveSyncContext);
1561                        }
1562                        // check that this isn't an old message
1563                        if (mActiveSyncContext == msgData.activeSyncContext) {
1564                            // cancel the sync if we have a syncadapter, which means one is
1565                            // outstanding
1566                            if (mActiveSyncContext.mSyncAdapter != null) {
1567                                try {
1568                                    mActiveSyncContext.mSyncAdapter.cancelSync(mActiveSyncContext);
1569                                } catch (RemoteException e) {
1570                                    // we don't need to retry this in this case
1571                                }
1572                            }
1573
1574                            // pretend that the sync failed with an IOException,
1575                            // which is a soft error
1576                            SyncResult syncResult = new SyncResult();
1577                            syncResult.stats.numIoExceptions++;
1578                            runSyncFinishedOrCanceled(syncResult);
1579
1580                            // since we are no longer syncing, check if it is time to start a new
1581                            // sync
1582                            runStateIdle();
1583                        }
1584
1585                        break;
1586                    }
1587
1588                    case SyncHandler.MESSAGE_SYNC_ALARM: {
1589                        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1590                        if (isLoggable) {
1591                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_ALARM");
1592                        }
1593                        mAlarmScheduleTime = null;
1594                        try {
1595                            if (mActiveSyncContext != null) {
1596                                if (isLoggable) {
1597                                    Log.v(TAG, "handleSyncHandlerMessage: sync context is active");
1598                                }
1599                                runStateSyncing();
1600                            }
1601
1602                            // if the above call to runStateSyncing() resulted in the end of a sync,
1603                            // check if it is time to start a new sync
1604                            if (mActiveSyncContext == null) {
1605                                if (isLoggable) {
1606                                    Log.v(TAG, "handleSyncHandlerMessage: "
1607                                            + "sync context is not active");
1608                                }
1609                                runStateIdle();
1610                            }
1611                        } finally {
1612                            mHandleAlarmWakeLock.release();
1613                        }
1614                        break;
1615                    }
1616
1617                    case SyncHandler.MESSAGE_CHECK_ALARMS:
1618                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1619                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_CHECK_ALARMS");
1620                        }
1621                        // we do all the work for this case in the finally block
1622                        break;
1623                }
1624            } finally {
1625                final boolean isSyncInProgress = mActiveSyncContext != null;
1626                if (!isSyncInProgress) {
1627                    mSyncWakeLock.release();
1628                }
1629                manageSyncNotification();
1630                manageErrorNotification();
1631                manageSyncAlarm();
1632                mSyncTimeTracker.update();
1633            }
1634        }
1635
1636        private void runStateSyncing() {
1637            // if the sync timeout has been reached then cancel it
1638
1639            ActiveSyncContext activeSyncContext = mActiveSyncContext;
1640
1641            final long now = SystemClock.elapsedRealtime();
1642            if (now > activeSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC) {
1643                SyncOperation nextSyncOperation;
1644                synchronized (mSyncQueue) {
1645                    nextSyncOperation = mSyncQueue.head();
1646                }
1647                if (nextSyncOperation != null && nextSyncOperation.earliestRunTime <= now) {
1648                    if (Config.LOGD) {
1649                        Log.d(TAG, "canceling and rescheduling sync because it ran too long: "
1650                                + activeSyncContext.mSyncOperation);
1651                    }
1652                    rescheduleImmediately(activeSyncContext.mSyncOperation);
1653                    sendSyncFinishedOrCanceledMessage(activeSyncContext,
1654                            null /* no result since this is a cancel */);
1655                } else {
1656                    activeSyncContext.mTimeoutStartTime = now + MAX_TIME_PER_SYNC;
1657                }
1658            }
1659
1660            // no need to schedule an alarm, as that will be done by our caller.
1661        }
1662
1663        private void runStateIdle() {
1664            boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1665            if (isLoggable) Log.v(TAG, "runStateIdle");
1666
1667            // If we aren't ready to run (e.g. the data connection is down), get out.
1668            if (!mDataConnectionIsConnected) {
1669                if (isLoggable) {
1670                    Log.v(TAG, "runStateIdle: no data connection, skipping");
1671                }
1672                setStatusText("No data connection");
1673                return;
1674            }
1675
1676            if (mStorageIsLow) {
1677                if (isLoggable) {
1678                    Log.v(TAG, "runStateIdle: memory low, skipping");
1679                }
1680                setStatusText("Memory low");
1681                return;
1682            }
1683
1684            // If the accounts aren't known yet then we aren't ready to run. We will be kicked
1685            // when the account lookup request does complete.
1686            Account[] accounts = mAccounts;
1687            if (accounts == null) {
1688                if (isLoggable) {
1689                    Log.v(TAG, "runStateIdle: accounts not known, skipping");
1690                }
1691                setStatusText("Accounts not known yet");
1692                return;
1693            }
1694
1695            // Otherwise consume SyncOperations from the head of the SyncQueue until one is
1696            // found that is runnable (not disabled, etc). If that one is ready to run then
1697            // start it, otherwise just get out.
1698            SyncOperation op;
1699            final boolean backgroundDataUsageAllowed =
1700                    getConnectivityManager().getBackgroundDataSetting();
1701            synchronized (mSyncQueue) {
1702                while (true) {
1703                    op = mSyncQueue.head();
1704                    if (op == null) {
1705                        if (isLoggable) {
1706                            Log.v(TAG, "runStateIdle: no more sync operations, returning");
1707                        }
1708                        return;
1709                    }
1710
1711                    // Sync is disabled, drop this operation.
1712                    if (!isSyncEnabled()) {
1713                        if (isLoggable) {
1714                            Log.v(TAG, "runStateIdle: sync disabled, dropping " + op);
1715                        }
1716                        mSyncQueue.popHead();
1717                        continue;
1718                    }
1719
1720                    // skip the sync if it isn't manual and auto sync is disabled
1721                    final boolean manualSync = op.extras.getBoolean(
1722                            ContentResolver.SYNC_EXTRAS_MANUAL, false);
1723                    final boolean syncAutomatically =
1724                            mSyncStorageEngine.getSyncAutomatically(op.account, op.authority)
1725                                    && mSyncStorageEngine.getMasterSyncAutomatically();
1726                    boolean syncAllowed =
1727                            manualSync || (backgroundDataUsageAllowed && syncAutomatically);
1728                    int isSyncable = mSyncStorageEngine.getIsSyncable(op.account, op.authority);
1729                    if (isSyncable == 0) {
1730                        // if not syncable, don't allow
1731                        syncAllowed = false;
1732                    } else if (isSyncable < 0) {
1733                        // if the syncable state is unknown, only allow initialization syncs
1734                        syncAllowed =
1735                                op.extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
1736                    }
1737                    if (!syncAllowed) {
1738                        if (isLoggable) {
1739                            Log.v(TAG, "runStateIdle: sync off, dropping " + op);
1740                        }
1741                        mSyncQueue.popHead();
1742                        continue;
1743                    }
1744
1745                    // skip the sync if the account of this operation no longer exists
1746                    if (!ArrayUtils.contains(accounts, op.account)) {
1747                        mSyncQueue.popHead();
1748                        if (isLoggable) {
1749                            Log.v(TAG, "runStateIdle: account not present, dropping " + op);
1750                        }
1751                        continue;
1752                    }
1753
1754                    // go ahead and try to sync this syncOperation
1755                    if (isLoggable) {
1756                        Log.v(TAG, "runStateIdle: found sync candidate: " + op);
1757                    }
1758                    break;
1759                }
1760
1761                // If the first SyncOperation isn't ready to run schedule a wakeup and
1762                // get out.
1763                final long now = SystemClock.elapsedRealtime();
1764                if (op.earliestRunTime > now) {
1765                    if (Log.isLoggable(TAG, Log.DEBUG)) {
1766                        Log.d(TAG, "runStateIdle: the time is " + now + " yet the next "
1767                                + "sync operation is for " + op.earliestRunTime + ": " + op);
1768                    }
1769                    return;
1770                }
1771
1772                // We will do this sync. Remove it from the queue and run it outside of the
1773                // synchronized block.
1774                if (isLoggable) {
1775                    Log.v(TAG, "runStateIdle: we are going to sync " + op);
1776                }
1777                mSyncQueue.popHead();
1778            }
1779
1780            // connect to the sync adapter
1781            SyncAdapterType syncAdapterType = SyncAdapterType.newKey(op.authority, op.account.type);
1782            RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
1783                    mSyncAdapters.getServiceInfo(syncAdapterType);
1784            if (syncAdapterInfo == null) {
1785                if (Config.LOGD) {
1786                    Log.d(TAG, "can't find a sync adapter for " + syncAdapterType);
1787                }
1788                runStateIdle();
1789                return;
1790            }
1791
1792            ActiveSyncContext activeSyncContext =
1793                    new ActiveSyncContext(op, insertStartSyncEvent(op));
1794            mActiveSyncContext = activeSyncContext;
1795            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1796                Log.v(TAG, "runStateIdle: setting mActiveSyncContext to " + mActiveSyncContext);
1797            }
1798            mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1799            if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo)) {
1800                Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
1801                mActiveSyncContext = null;
1802                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1803                runStateIdle();
1804                return;
1805            }
1806
1807            mSyncWakeLock.acquire();
1808            // no need to schedule an alarm, as that will be done by our caller.
1809
1810            // the next step will occur when we get either a timeout or a
1811            // MESSAGE_SERVICE_CONNECTED or MESSAGE_SERVICE_DISCONNECTED message
1812        }
1813
1814        private void runBoundToSyncAdapter(ISyncAdapter syncAdapter) {
1815            mActiveSyncContext.mSyncAdapter = syncAdapter;
1816            final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1817            try {
1818                syncAdapter.startSync(mActiveSyncContext, syncOperation.authority,
1819                        syncOperation.account, syncOperation.extras);
1820            } catch (RemoteException remoteExc) {
1821                if (Config.LOGD) {
1822                    Log.d(TAG, "runStateIdle: caught a RemoteException, rescheduling", remoteExc);
1823                }
1824                mActiveSyncContext.unBindFromSyncAdapter();
1825                mActiveSyncContext = null;
1826                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1827                rescheduleWithDelay(syncOperation);
1828            } catch (RuntimeException exc) {
1829                mActiveSyncContext.unBindFromSyncAdapter();
1830                mActiveSyncContext = null;
1831                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1832                Log.e(TAG, "Caught a RuntimeException while starting the sync " + syncOperation,
1833                        exc);
1834            }
1835        }
1836
1837        private void runSyncFinishedOrCanceled(SyncResult syncResult) {
1838            boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1839            if (isLoggable) Log.v(TAG, "runSyncFinishedOrCanceled");
1840            final ActiveSyncContext activeSyncContext = mActiveSyncContext;
1841            mActiveSyncContext = null;
1842            mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1843
1844            final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
1845
1846            final long elapsedTime = SystemClock.elapsedRealtime() - activeSyncContext.mStartTime;
1847
1848            String historyMessage;
1849            int downstreamActivity;
1850            int upstreamActivity;
1851            if (syncResult != null) {
1852                if (isLoggable) {
1853                    Log.v(TAG, "runSyncFinishedOrCanceled: is a finished: operation "
1854                            + syncOperation + ", result " + syncResult);
1855                }
1856
1857                if (!syncResult.hasError()) {
1858                    if (isLoggable) {
1859                        Log.v(TAG, "finished sync operation " + syncOperation);
1860                    }
1861                    historyMessage = SyncStorageEngine.MESG_SUCCESS;
1862                    // TODO: set these correctly when the SyncResult is extended to include it
1863                    downstreamActivity = 0;
1864                    upstreamActivity = 0;
1865                } else {
1866                    maybeRescheduleSync(syncResult, syncOperation);
1867                    if (Config.LOGD) {
1868                        Log.d(TAG, "failed sync operation " + syncOperation);
1869                    }
1870                    historyMessage = Integer.toString(syncResultToErrorNumber(syncResult));
1871                    // TODO: set these correctly when the SyncResult is extended to include it
1872                    downstreamActivity = 0;
1873                    upstreamActivity = 0;
1874                }
1875            } else {
1876                if (isLoggable) {
1877                    Log.v(TAG, "runSyncFinishedOrCanceled: is a cancel: operation "
1878                            + syncOperation);
1879                }
1880                if (activeSyncContext.mSyncAdapter != null) {
1881                    try {
1882                        activeSyncContext.mSyncAdapter.cancelSync(activeSyncContext);
1883                    } catch (RemoteException e) {
1884                        // we don't need to retry this in this case
1885                    }
1886                }
1887                historyMessage = SyncStorageEngine.MESG_CANCELED;
1888                downstreamActivity = 0;
1889                upstreamActivity = 0;
1890            }
1891
1892            stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
1893                    upstreamActivity, downstreamActivity, elapsedTime);
1894
1895            activeSyncContext.unBindFromSyncAdapter();
1896
1897            if (syncResult != null && syncResult.tooManyDeletions) {
1898                installHandleTooManyDeletesNotification(syncOperation.account,
1899                        syncOperation.authority, syncResult.stats.numDeletes);
1900            } else {
1901                mNotificationMgr.cancel(
1902                        syncOperation.account.hashCode() ^ syncOperation.authority.hashCode());
1903            }
1904
1905            if (syncResult != null && syncResult.fullSyncRequested) {
1906                scheduleSyncOperation(new SyncOperation(syncOperation.account,
1907                        syncOperation.syncSource, syncOperation.authority, new Bundle(), 0));
1908            }
1909            // no need to schedule an alarm, as that will be done by our caller.
1910        }
1911
1912        /**
1913         * Convert the error-containing SyncResult into the Sync.History error number. Since
1914         * the SyncResult may indicate multiple errors at once, this method just returns the
1915         * most "serious" error.
1916         * @param syncResult the SyncResult from which to read
1917         * @return the most "serious" error set in the SyncResult
1918         * @throws IllegalStateException if the SyncResult does not indicate any errors.
1919         *   If SyncResult.error() is true then it is safe to call this.
1920         */
1921        private int syncResultToErrorNumber(SyncResult syncResult) {
1922            if (syncResult.syncAlreadyInProgress)
1923                return ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
1924            if (syncResult.stats.numAuthExceptions > 0)
1925                return ContentResolver.SYNC_ERROR_AUTHENTICATION;
1926            if (syncResult.stats.numIoExceptions > 0)
1927                return ContentResolver.SYNC_ERROR_IO;
1928            if (syncResult.stats.numParseExceptions > 0)
1929                return ContentResolver.SYNC_ERROR_PARSE;
1930            if (syncResult.stats.numConflictDetectedExceptions > 0)
1931                return ContentResolver.SYNC_ERROR_CONFLICT;
1932            if (syncResult.tooManyDeletions)
1933                return ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS;
1934            if (syncResult.tooManyRetries)
1935                return ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES;
1936            if (syncResult.databaseError)
1937                return ContentResolver.SYNC_ERROR_INTERNAL;
1938            throw new IllegalStateException("we are not in an error state, " + syncResult);
1939        }
1940
1941        private void manageSyncNotification() {
1942            boolean shouldCancel;
1943            boolean shouldInstall;
1944
1945            if (mActiveSyncContext == null) {
1946                mSyncNotificationInfo.startTime = null;
1947
1948                // we aren't syncing. if the notification is active then remember that we need
1949                // to cancel it and then clear out the info
1950                shouldCancel = mSyncNotificationInfo.isActive;
1951                shouldInstall = false;
1952            } else {
1953                // we are syncing
1954                final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1955
1956                final long now = SystemClock.elapsedRealtime();
1957                if (mSyncNotificationInfo.startTime == null) {
1958                    mSyncNotificationInfo.startTime = now;
1959                }
1960
1961                // cancel the notification if it is up and the authority or account is wrong
1962                shouldCancel = mSyncNotificationInfo.isActive &&
1963                        (!syncOperation.authority.equals(mSyncNotificationInfo.authority)
1964                        || !syncOperation.account.equals(mSyncNotificationInfo.account));
1965
1966                // there are four cases:
1967                // - the notification is up and there is no change: do nothing
1968                // - the notification is up but we should cancel since it is stale:
1969                //   need to install
1970                // - the notification is not up but it isn't time yet: don't install
1971                // - the notification is not up and it is time: need to install
1972
1973                if (mSyncNotificationInfo.isActive) {
1974                    shouldInstall = shouldCancel;
1975                } else {
1976                    final boolean timeToShowNotification =
1977                            now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
1978                    // show the notification immediately if this is a manual sync
1979                    final boolean manualSync = syncOperation.extras
1980                            .getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
1981                    shouldInstall = timeToShowNotification || manualSync;
1982                }
1983            }
1984
1985            if (shouldCancel && !shouldInstall) {
1986                mNeedSyncActiveNotification = false;
1987                sendSyncStateIntent();
1988                mSyncNotificationInfo.isActive = false;
1989            }
1990
1991            if (shouldInstall) {
1992                SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1993                mNeedSyncActiveNotification = true;
1994                sendSyncStateIntent();
1995                mSyncNotificationInfo.isActive = true;
1996                mSyncNotificationInfo.account = syncOperation.account;
1997                mSyncNotificationInfo.authority = syncOperation.authority;
1998            }
1999        }
2000
2001        /**
2002         * Check if there were any long-lasting errors, if so install the error notification,
2003         * otherwise cancel the error notification.
2004         */
2005        private void manageErrorNotification() {
2006            //
2007            long when = mSyncStorageEngine.getInitialSyncFailureTime();
2008            if ((when > 0) && (when + ERROR_NOTIFICATION_DELAY_MS < System.currentTimeMillis())) {
2009                if (!mErrorNotificationInstalled) {
2010                    mNeedSyncErrorNotification = true;
2011                    sendSyncStateIntent();
2012                }
2013                mErrorNotificationInstalled = true;
2014            } else {
2015                if (mErrorNotificationInstalled) {
2016                    mNeedSyncErrorNotification = false;
2017                    sendSyncStateIntent();
2018                }
2019                mErrorNotificationInstalled = false;
2020            }
2021        }
2022
2023        private void manageSyncAlarm() {
2024            // in each of these cases the sync loop will be kicked, which will cause this
2025            // method to be called again
2026            if (!mDataConnectionIsConnected) return;
2027            if (mAccounts == null) return;
2028            if (mStorageIsLow) return;
2029
2030            // Compute the alarm fire time:
2031            // - not syncing: time of the next sync operation
2032            // - syncing, no notification: time from sync start to notification create time
2033            // - syncing, with notification: time till timeout of the active sync operation
2034            Long alarmTime = null;
2035            ActiveSyncContext activeSyncContext = mActiveSyncContext;
2036            if (activeSyncContext == null) {
2037                SyncOperation syncOperation;
2038                synchronized (mSyncQueue) {
2039                    syncOperation = mSyncQueue.head();
2040                }
2041                if (syncOperation != null) {
2042                    alarmTime = syncOperation.earliestRunTime;
2043                }
2044            } else {
2045                final long notificationTime =
2046                        mSyncHandler.mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
2047                final long timeoutTime =
2048                        mActiveSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC;
2049                if (mSyncHandler.mSyncNotificationInfo.isActive) {
2050                    alarmTime = timeoutTime;
2051                } else {
2052                    alarmTime = Math.min(notificationTime, timeoutTime);
2053                }
2054            }
2055
2056            // adjust the alarmTime so that we will wake up when it is time to
2057            // install the error notification
2058            if (!mErrorNotificationInstalled) {
2059                long when = mSyncStorageEngine.getInitialSyncFailureTime();
2060                if (when > 0) {
2061                    when += ERROR_NOTIFICATION_DELAY_MS;
2062                    // convert when fron absolute time to elapsed run time
2063                    long delay = when - System.currentTimeMillis();
2064                    when = SystemClock.elapsedRealtime() + delay;
2065                    alarmTime = alarmTime != null ? Math.min(alarmTime, when) : when;
2066                }
2067            }
2068
2069            // determine if we need to set or cancel the alarm
2070            boolean shouldSet = false;
2071            boolean shouldCancel = false;
2072            final boolean alarmIsActive = mAlarmScheduleTime != null;
2073            final boolean needAlarm = alarmTime != null;
2074            if (needAlarm) {
2075                if (!alarmIsActive || alarmTime < mAlarmScheduleTime) {
2076                    shouldSet = true;
2077                }
2078            } else {
2079                shouldCancel = alarmIsActive;
2080            }
2081
2082            // set or cancel the alarm as directed
2083            ensureAlarmService();
2084            if (shouldSet) {
2085                mAlarmScheduleTime = alarmTime;
2086                mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime,
2087                        mSyncAlarmIntent);
2088            } else if (shouldCancel) {
2089                mAlarmScheduleTime = null;
2090                mAlarmService.cancel(mSyncAlarmIntent);
2091            }
2092        }
2093
2094        private void sendSyncStateIntent() {
2095            Intent syncStateIntent = new Intent(Intent.ACTION_SYNC_STATE_CHANGED);
2096            syncStateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2097            syncStateIntent.putExtra("active", mNeedSyncActiveNotification);
2098            syncStateIntent.putExtra("failing", mNeedSyncErrorNotification);
2099            mContext.sendBroadcast(syncStateIntent);
2100        }
2101
2102        private void installHandleTooManyDeletesNotification(Account account, String authority,
2103                long numDeletes) {
2104            if (mNotificationMgr == null) return;
2105
2106            final ProviderInfo providerInfo = mContext.getPackageManager().resolveContentProvider(
2107                    authority, 0 /* flags */);
2108            if (providerInfo == null) {
2109                return;
2110            }
2111            CharSequence authorityName = providerInfo.loadLabel(mContext.getPackageManager());
2112
2113            Intent clickIntent = new Intent();
2114            clickIntent.setClassName("com.android.providers.subscribedfeeds",
2115                    "com.android.settings.SyncActivityTooManyDeletes");
2116            clickIntent.putExtra("account", account);
2117            clickIntent.putExtra("authority", authority);
2118            clickIntent.putExtra("provider", authorityName.toString());
2119            clickIntent.putExtra("numDeletes", numDeletes);
2120
2121            if (!isActivityAvailable(clickIntent)) {
2122                Log.w(TAG, "No activity found to handle too many deletes.");
2123                return;
2124            }
2125
2126            final PendingIntent pendingIntent = PendingIntent
2127                    .getActivity(mContext, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);
2128
2129            CharSequence tooManyDeletesDescFormat = mContext.getResources().getText(
2130                    R.string.contentServiceTooManyDeletesNotificationDesc);
2131
2132            Notification notification =
2133                new Notification(R.drawable.stat_notify_sync_error,
2134                        mContext.getString(R.string.contentServiceSync),
2135                        System.currentTimeMillis());
2136            notification.setLatestEventInfo(mContext,
2137                    mContext.getString(R.string.contentServiceSyncNotificationTitle),
2138                    String.format(tooManyDeletesDescFormat.toString(), authorityName),
2139                    pendingIntent);
2140            notification.flags |= Notification.FLAG_ONGOING_EVENT;
2141            mNotificationMgr.notify(account.hashCode() ^ authority.hashCode(), notification);
2142        }
2143
2144        /**
2145         * Checks whether an activity exists on the system image for the given intent.
2146         *
2147         * @param intent The intent for an activity.
2148         * @return Whether or not an activity exists.
2149         */
2150        private boolean isActivityAvailable(Intent intent) {
2151            PackageManager pm = mContext.getPackageManager();
2152            List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
2153            int listSize = list.size();
2154            for (int i = 0; i < listSize; i++) {
2155                ResolveInfo resolveInfo = list.get(i);
2156                if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
2157                        != 0) {
2158                    return true;
2159                }
2160            }
2161
2162            return false;
2163        }
2164
2165        public long insertStartSyncEvent(SyncOperation syncOperation) {
2166            final int source = syncOperation.syncSource;
2167            final long now = System.currentTimeMillis();
2168
2169            EventLog.writeEvent(2720, syncOperation.authority,
2170                                SyncStorageEngine.EVENT_START, source,
2171                                syncOperation.account.name.hashCode());
2172
2173            return mSyncStorageEngine.insertStartSyncEvent(
2174                    syncOperation.account, syncOperation.authority, now, source);
2175        }
2176
2177        public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage,
2178                int upstreamActivity, int downstreamActivity, long elapsedTime) {
2179            EventLog.writeEvent(2720, syncOperation.authority,
2180                                SyncStorageEngine.EVENT_STOP, syncOperation.syncSource,
2181                                syncOperation.account.name.hashCode());
2182
2183            mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime, resultMessage,
2184                    downstreamActivity, upstreamActivity);
2185        }
2186    }
2187
2188    static class SyncQueue {
2189        private SyncStorageEngine mSyncStorageEngine;
2190
2191        private static final boolean DEBUG_CHECK_DATA_CONSISTENCY = false;
2192
2193        // A priority queue of scheduled SyncOperations that is designed to make it quick
2194        // to find the next SyncOperation that should be considered for running.
2195        private final PriorityQueue<SyncOperation> mOpsByWhen = new PriorityQueue<SyncOperation>();
2196
2197        // A Map of SyncOperations operationKey -> SyncOperation that is designed for
2198        // quick lookup of an enqueued SyncOperation.
2199        private final HashMap<String, SyncOperation> mOpsByKey = Maps.newHashMap();
2200
2201        public SyncQueue(SyncStorageEngine syncStorageEngine) {
2202            mSyncStorageEngine = syncStorageEngine;
2203            ArrayList<SyncStorageEngine.PendingOperation> ops
2204                    = mSyncStorageEngine.getPendingOperations();
2205            final int N = ops.size();
2206            for (int i=0; i<N; i++) {
2207                SyncStorageEngine.PendingOperation op = ops.get(i);
2208                SyncOperation syncOperation = new SyncOperation(
2209                        op.account, op.syncSource, op.authority, op.extras, 0);
2210                syncOperation.pendingOperation = op;
2211                add(syncOperation, op);
2212            }
2213
2214            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2215        }
2216
2217        public boolean add(SyncOperation operation) {
2218            return add(new SyncOperation(operation),
2219                    null /* this is not coming from the database */);
2220        }
2221
2222        private boolean add(SyncOperation operation,
2223                SyncStorageEngine.PendingOperation pop) {
2224            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2225
2226            // If this operation is expedited then set its earliestRunTime to be immediately
2227            // before the head of the list, or not if none are in the list.
2228            if (operation.delay < 0) {
2229                SyncOperation headOperation = head();
2230                if (headOperation != null) {
2231                    operation.earliestRunTime = Math.min(SystemClock.elapsedRealtime(),
2232                            headOperation.earliestRunTime - 1);
2233                } else {
2234                    operation.earliestRunTime = SystemClock.elapsedRealtime();
2235                }
2236            }
2237
2238            // - if an operation with the same key exists and this one should run earlier,
2239            //   delete the old one and add the new one
2240            // - if an operation with the same key exists and if this one should run
2241            //   later, ignore it
2242            // - if no operation exists then add the new one
2243            final String operationKey = operation.key;
2244            SyncOperation existingOperation = mOpsByKey.get(operationKey);
2245
2246            // if this operation matches an existing operation that is being retried (delay > 0)
2247            // and this isn't a manual sync operation, ignore this operation
2248            if (existingOperation != null && existingOperation.delay > 0) {
2249                if (!operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)) {
2250                    return false;
2251                }
2252            }
2253
2254            if (existingOperation != null
2255                    && operation.earliestRunTime >= existingOperation.earliestRunTime) {
2256                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2257                return false;
2258            }
2259
2260            if (existingOperation != null) {
2261                removeByKey(operationKey);
2262            }
2263
2264            operation.pendingOperation = pop;
2265            if (operation.pendingOperation == null) {
2266                pop = new SyncStorageEngine.PendingOperation(
2267                                operation.account, operation.syncSource,
2268                                operation.authority, operation.extras);
2269                pop = mSyncStorageEngine.insertIntoPending(pop);
2270                if (pop == null) {
2271                    throw new IllegalStateException("error adding pending sync operation "
2272                            + operation);
2273                }
2274                operation.pendingOperation = pop;
2275            }
2276
2277            if (DEBUG_CHECK_DATA_CONSISTENCY) {
2278                debugCheckDataStructures(
2279                        false /* don't compare with the DB, since we know
2280                               it is inconsistent right now */ );
2281            }
2282            mOpsByKey.put(operationKey, operation);
2283            mOpsByWhen.add(operation);
2284            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2285            return true;
2286        }
2287
2288        public void removeByKey(String operationKey) {
2289            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2290            SyncOperation operationToRemove = mOpsByKey.remove(operationKey);
2291            if (!mOpsByWhen.remove(operationToRemove)) {
2292                throw new IllegalStateException(
2293                        "unable to find " + operationToRemove + " in mOpsByWhen");
2294            }
2295
2296            if (!mSyncStorageEngine.deleteFromPending(operationToRemove.pendingOperation)) {
2297                throw new IllegalStateException("unable to find pending row for "
2298                        + operationToRemove);
2299            }
2300
2301            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2302        }
2303
2304        public SyncOperation head() {
2305            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2306            return mOpsByWhen.peek();
2307        }
2308
2309        public void popHead() {
2310            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2311            SyncOperation operation = mOpsByWhen.remove();
2312            if (mOpsByKey.remove(operation.key) == null) {
2313                throw new IllegalStateException("unable to find " + operation + " in mOpsByKey");
2314            }
2315
2316            if (!mSyncStorageEngine.deleteFromPending(operation.pendingOperation)) {
2317                throw new IllegalStateException("unable to find pending row for " + operation);
2318            }
2319
2320            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2321        }
2322
2323        public void clear(Account account, String authority) {
2324            Iterator<Map.Entry<String, SyncOperation>> entries = mOpsByKey.entrySet().iterator();
2325            while (entries.hasNext()) {
2326                Map.Entry<String, SyncOperation> entry = entries.next();
2327                SyncOperation syncOperation = entry.getValue();
2328                if (account != null && !syncOperation.account.equals(account)) continue;
2329                if (authority != null && !syncOperation.authority.equals(authority)) continue;
2330
2331                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2332                entries.remove();
2333                if (!mOpsByWhen.remove(syncOperation)) {
2334                    throw new IllegalStateException(
2335                            "unable to find " + syncOperation + " in mOpsByWhen");
2336                }
2337
2338                if (!mSyncStorageEngine.deleteFromPending(syncOperation.pendingOperation)) {
2339                    throw new IllegalStateException("unable to find pending row for "
2340                            + syncOperation);
2341                }
2342
2343                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2344            }
2345        }
2346
2347        public void dump(StringBuilder sb) {
2348            sb.append("SyncQueue: ").append(mOpsByWhen.size()).append(" operation(s)\n");
2349            for (SyncOperation operation : mOpsByWhen) {
2350                sb.append(operation).append("\n");
2351            }
2352        }
2353
2354        private void debugCheckDataStructures(boolean checkDatabase) {
2355            if (mOpsByKey.size() != mOpsByWhen.size()) {
2356                throw new IllegalStateException("size mismatch: "
2357                        + mOpsByKey .size() + " != " + mOpsByWhen.size());
2358            }
2359            for (SyncOperation operation : mOpsByWhen) {
2360                if (!mOpsByKey.containsKey(operation.key)) {
2361                    throw new IllegalStateException(
2362                        "operation " + operation + " is in mOpsByWhen but not mOpsByKey");
2363                }
2364            }
2365            for (Map.Entry<String, SyncOperation> entry : mOpsByKey.entrySet()) {
2366                final SyncOperation operation = entry.getValue();
2367                final String key = entry.getKey();
2368                if (!key.equals(operation.key)) {
2369                    throw new IllegalStateException(
2370                        "operation " + operation + " in mOpsByKey doesn't match key " + key);
2371                }
2372                if (!mOpsByWhen.contains(operation)) {
2373                    throw new IllegalStateException(
2374                        "operation " + operation + " is in mOpsByKey but not mOpsByWhen");
2375                }
2376            }
2377
2378            if (checkDatabase) {
2379                final int N = mSyncStorageEngine.getPendingOperationCount();
2380                if (mOpsByKey.size() != N) {
2381                    ArrayList<SyncStorageEngine.PendingOperation> ops
2382                            = mSyncStorageEngine.getPendingOperations();
2383                    StringBuilder sb = new StringBuilder();
2384                    for (int i=0; i<N; i++) {
2385                        SyncStorageEngine.PendingOperation op = ops.get(i);
2386                        sb.append("#");
2387                        sb.append(i);
2388                        sb.append(": account=");
2389                        sb.append(op.account);
2390                        sb.append(" syncSource=");
2391                        sb.append(op.syncSource);
2392                        sb.append(" authority=");
2393                        sb.append(op.authority);
2394                        sb.append("\n");
2395                    }
2396                    dump(sb);
2397                    throw new IllegalStateException("DB size mismatch: "
2398                            + mOpsByKey.size() + " != " + N + "\n"
2399                            + sb.toString());
2400                }
2401            }
2402        }
2403    }
2404}
2405