SyncManager.java revision aa7edda4719dc0accbc29ff917b4280f6b600675
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 this sync aborted because the internal sync loop retried too many times then
923        //   don't reschedule. Otherwise we risk getting into a retry loop.
924        // If the operation succeeded to some extent then retry immediately.
925        // If this was a two-way sync then retry soft errors with an exponential backoff.
926        // If this was an upward sync then schedule a two-way sync immediately.
927        // Otherwise do not reschedule.
928        if (syncResult.tooManyRetries) {
929            Log.d(TAG, "not retrying sync operation because it retried too many times: "
930                    + previousSyncOperation);
931        } else if (syncResult.madeSomeProgress()) {
932            if (isLoggable) {
933                Log.d(TAG, "retrying sync operation immediately because "
934                        + "even though it had an error it achieved some success");
935            }
936            rescheduleImmediately(previousSyncOperation);
937        } else if (previousSyncOperation.extras.getBoolean(
938                ContentResolver.SYNC_EXTRAS_UPLOAD, false)) {
939            final SyncOperation newSyncOperation = new SyncOperation(previousSyncOperation);
940            newSyncOperation.extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
941            newSyncOperation.setDelay(0);
942            if (Config.LOGD) {
943                Log.d(TAG, "retrying sync operation as a two-way sync because an upload-only sync "
944                        + "encountered an error: " + previousSyncOperation);
945            }
946            scheduleSyncOperation(newSyncOperation);
947        } else if (syncResult.hasSoftError()) {
948            long delay = rescheduleWithDelay(previousSyncOperation);
949            if (delay >= 0) {
950                if (isLoggable) {
951                    Log.d(TAG, "retrying sync operation in " + delay + " ms because "
952                            + "it encountered a soft error: " + previousSyncOperation);
953                }
954            }
955        } else {
956            if (Config.LOGD) {
957                Log.d(TAG, "not retrying sync operation because the error is a hard error: "
958                        + previousSyncOperation);
959            }
960        }
961    }
962
963    /**
964     * Value type that represents a sync operation.
965     */
966    static class SyncOperation implements Comparable {
967        final Account account;
968        int syncSource;
969        String authority;
970        Bundle extras;
971        final String key;
972        long earliestRunTime;
973        long delay;
974        SyncStorageEngine.PendingOperation pendingOperation;
975
976        SyncOperation(Account account, int source, String authority, Bundle extras, long delay) {
977            this.account = account;
978            this.syncSource = source;
979            this.authority = authority;
980            this.extras = new Bundle(extras);
981            this.setDelay(delay);
982            this.key = toKey();
983        }
984
985        SyncOperation(SyncOperation other) {
986            this.account = other.account;
987            this.syncSource = other.syncSource;
988            this.authority = other.authority;
989            this.extras = new Bundle(other.extras);
990            this.delay = other.delay;
991            this.earliestRunTime = other.earliestRunTime;
992            this.key = toKey();
993        }
994
995        public void setDelay(long delay) {
996            this.delay = delay;
997            if (delay >= 0) {
998                this.earliestRunTime = SystemClock.elapsedRealtime() + delay;
999            } else {
1000                this.earliestRunTime = 0;
1001            }
1002        }
1003
1004        public String toString() {
1005            StringBuilder sb = new StringBuilder();
1006            sb.append("authority: ").append(authority);
1007            sb.append(" account: ").append(account);
1008            sb.append(" extras: ");
1009            extrasToStringBuilder(extras, sb);
1010            sb.append(" syncSource: ").append(syncSource);
1011            sb.append(" when: ").append(earliestRunTime);
1012            sb.append(" delay: ").append(delay);
1013            sb.append(" key: {").append(key).append("}");
1014            if (pendingOperation != null) sb.append(" pendingOperation: ").append(pendingOperation);
1015            return sb.toString();
1016        }
1017
1018        private String toKey() {
1019            StringBuilder sb = new StringBuilder();
1020            sb.append("authority: ").append(authority);
1021            sb.append(" account: ").append(account);
1022            sb.append(" extras: ");
1023            extrasToStringBuilder(extras, sb);
1024            return sb.toString();
1025        }
1026
1027        private static void extrasToStringBuilder(Bundle bundle, StringBuilder sb) {
1028            sb.append("[");
1029            for (String key : bundle.keySet()) {
1030                sb.append(key).append("=").append(bundle.get(key)).append(" ");
1031            }
1032            sb.append("]");
1033        }
1034
1035        public int compareTo(Object o) {
1036            SyncOperation other = (SyncOperation)o;
1037            if (earliestRunTime == other.earliestRunTime) {
1038                return 0;
1039            }
1040            return (earliestRunTime < other.earliestRunTime) ? -1 : 1;
1041        }
1042    }
1043
1044    /**
1045     * @hide
1046     */
1047    class ActiveSyncContext extends ISyncContext.Stub implements ServiceConnection {
1048        final SyncOperation mSyncOperation;
1049        final long mHistoryRowId;
1050        ISyncAdapter mSyncAdapter;
1051        final long mStartTime;
1052        long mTimeoutStartTime;
1053
1054        public ActiveSyncContext(SyncOperation syncOperation,
1055                long historyRowId) {
1056            super();
1057            mSyncOperation = syncOperation;
1058            mHistoryRowId = historyRowId;
1059            mSyncAdapter = null;
1060            mStartTime = SystemClock.elapsedRealtime();
1061            mTimeoutStartTime = mStartTime;
1062        }
1063
1064        public void sendHeartbeat() {
1065            // ignore this call if it corresponds to an old sync session
1066            if (mActiveSyncContext == this) {
1067                SyncManager.this.updateHeartbeatTime();
1068            }
1069        }
1070
1071        public void onFinished(SyncResult result) {
1072            // include "this" in the message so that the handler can ignore it if this
1073            // ActiveSyncContext is no longer the mActiveSyncContext at message handling
1074            // time
1075            sendSyncFinishedOrCanceledMessage(this, result);
1076        }
1077
1078        public void toString(StringBuilder sb) {
1079            sb.append("startTime ").append(mStartTime)
1080                    .append(", mTimeoutStartTime ").append(mTimeoutStartTime)
1081                    .append(", mHistoryRowId ").append(mHistoryRowId)
1082                    .append(", syncOperation ").append(mSyncOperation);
1083        }
1084
1085        public void onServiceConnected(ComponentName name, IBinder service) {
1086            Message msg = mSyncHandler.obtainMessage();
1087            msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
1088            msg.obj = new ServiceConnectionData(this, ISyncAdapter.Stub.asInterface(service));
1089            mSyncHandler.sendMessage(msg);
1090        }
1091
1092        public void onServiceDisconnected(ComponentName name) {
1093            Message msg = mSyncHandler.obtainMessage();
1094            msg.what = SyncHandler.MESSAGE_SERVICE_DISCONNECTED;
1095            msg.obj = new ServiceConnectionData(this, null);
1096            mSyncHandler.sendMessage(msg);
1097        }
1098
1099        boolean bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info) {
1100            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1101                Log.d(TAG, "bindToSyncAdapter: " + info.componentName + ", connection " + this);
1102            }
1103            Intent intent = new Intent();
1104            intent.setAction("android.content.SyncAdapter");
1105            intent.setComponent(info.componentName);
1106            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1107                    com.android.internal.R.string.sync_binding_label);
1108            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1109                    mContext, 0, new Intent(Settings.ACTION_SYNC_SETTINGS), 0));
1110            return mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
1111        }
1112
1113        void unBindFromSyncAdapter() {
1114            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1115                Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
1116            }
1117            mContext.unbindService(this);
1118        }
1119
1120        @Override
1121        public String toString() {
1122            StringBuilder sb = new StringBuilder();
1123            toString(sb);
1124            return sb.toString();
1125        }
1126    }
1127
1128    protected void dump(FileDescriptor fd, PrintWriter pw) {
1129        StringBuilder sb = new StringBuilder();
1130        dumpSyncState(pw, sb);
1131        if (isSyncEnabled()) {
1132            dumpSyncHistory(pw, sb);
1133        }
1134
1135        pw.println();
1136        pw.println("SyncAdapters:");
1137        for (RegisteredServicesCache.ServiceInfo info : mSyncAdapters.getAllServices()) {
1138            pw.println("  " + info);
1139        }
1140    }
1141
1142    static String formatTime(long time) {
1143        Time tobj = new Time();
1144        tobj.set(time);
1145        return tobj.format("%Y-%m-%d %H:%M:%S");
1146    }
1147
1148    protected void dumpSyncState(PrintWriter pw, StringBuilder sb) {
1149        pw.print("sync enabled: "); pw.println(isSyncEnabled());
1150        pw.print("data connected: "); pw.println(mDataConnectionIsConnected);
1151        pw.print("memory low: "); pw.println(mStorageIsLow);
1152
1153        final Account[] accounts = mAccounts;
1154        pw.print("accounts: ");
1155        if (accounts != null) {
1156            pw.println(accounts.length);
1157        } else {
1158            pw.println("none");
1159        }
1160        final long now = SystemClock.elapsedRealtime();
1161        pw.print("now: "); pw.println(now);
1162        pw.print("uptime: "); pw.print(DateUtils.formatElapsedTime(now/1000));
1163                pw.println(" (HH:MM:SS)");
1164        pw.print("time spent syncing: ");
1165                pw.print(DateUtils.formatElapsedTime(
1166                        mSyncHandler.mSyncTimeTracker.timeSpentSyncing() / 1000));
1167                pw.print(" (HH:MM:SS), sync ");
1168                pw.print(mSyncHandler.mSyncTimeTracker.mLastWasSyncing ? "" : "not ");
1169                pw.println("in progress");
1170        if (mSyncHandler.mAlarmScheduleTime != null) {
1171            pw.print("next alarm time: "); pw.print(mSyncHandler.mAlarmScheduleTime);
1172                    pw.print(" (");
1173                    pw.print(DateUtils.formatElapsedTime((mSyncHandler.mAlarmScheduleTime-now)/1000));
1174                    pw.println(" (HH:MM:SS) from now)");
1175        } else {
1176            pw.println("no alarm is scheduled (there had better not be any pending syncs)");
1177        }
1178
1179        pw.print("active sync: "); pw.println(mActiveSyncContext);
1180
1181        pw.print("notification info: ");
1182        sb.setLength(0);
1183        mSyncHandler.mSyncNotificationInfo.toString(sb);
1184        pw.println(sb.toString());
1185
1186        synchronized (mSyncQueue) {
1187            pw.print("sync queue: ");
1188            sb.setLength(0);
1189            mSyncQueue.dump(sb);
1190            pw.println(sb.toString());
1191        }
1192
1193        ActiveSyncInfo active = mSyncStorageEngine.getActiveSync();
1194        if (active != null) {
1195            SyncStorageEngine.AuthorityInfo authority
1196                    = mSyncStorageEngine.getAuthority(active.authorityId);
1197            final long durationInSeconds = (now - active.startTime) / 1000;
1198            pw.print("Active sync: ");
1199                    pw.print(authority != null ? authority.account : "<no account>");
1200                    pw.print(" ");
1201                    pw.print(authority != null ? authority.authority : "<no account>");
1202                    pw.print(", duration is ");
1203                    pw.println(DateUtils.formatElapsedTime(durationInSeconds));
1204        } else {
1205            pw.println("No sync is in progress.");
1206        }
1207
1208        ArrayList<SyncStorageEngine.PendingOperation> ops
1209                = mSyncStorageEngine.getPendingOperations();
1210        if (ops != null && ops.size() > 0) {
1211            pw.println();
1212            pw.println("Pending Syncs");
1213            final int N = ops.size();
1214            for (int i=0; i<N; i++) {
1215                SyncStorageEngine.PendingOperation op = ops.get(i);
1216                pw.print("  #"); pw.print(i); pw.print(": account=");
1217                pw.print(op.account.name); pw.print(":");
1218                pw.print(op.account.type); pw.print(" authority=");
1219                pw.println(op.authority);
1220                if (op.extras != null && op.extras.size() > 0) {
1221                    sb.setLength(0);
1222                    SyncOperation.extrasToStringBuilder(op.extras, sb);
1223                    pw.print("    extras: "); pw.println(sb.toString());
1224                }
1225            }
1226        }
1227
1228        HashSet<Account> processedAccounts = new HashSet<Account>();
1229        ArrayList<SyncStatusInfo> statuses
1230                = mSyncStorageEngine.getSyncStatus();
1231        if (statuses != null && statuses.size() > 0) {
1232            pw.println();
1233            pw.println("Sync Status");
1234            final int N = statuses.size();
1235            for (int i=0; i<N; i++) {
1236                SyncStatusInfo status = statuses.get(i);
1237                SyncStorageEngine.AuthorityInfo authority
1238                        = mSyncStorageEngine.getAuthority(status.authorityId);
1239                if (authority != null) {
1240                    Account curAccount = authority.account;
1241
1242                    if (processedAccounts.contains(curAccount)) {
1243                        continue;
1244                    }
1245
1246                    processedAccounts.add(curAccount);
1247
1248                    pw.print("  Account "); pw.print(authority.account.name);
1249                            pw.print(" "); pw.print(authority.account.type);
1250                            pw.println(":");
1251                    for (int j=i; j<N; j++) {
1252                        status = statuses.get(j);
1253                        authority = mSyncStorageEngine.getAuthority(status.authorityId);
1254                        if (!curAccount.equals(authority.account)) {
1255                            continue;
1256                        }
1257                        pw.print("    "); pw.print(authority.authority);
1258                        pw.println(":");
1259                        pw.print("      count: local="); pw.print(status.numSourceLocal);
1260                                pw.print(" poll="); pw.print(status.numSourcePoll);
1261                                pw.print(" server="); pw.print(status.numSourceServer);
1262                                pw.print(" user="); pw.print(status.numSourceUser);
1263                                pw.print(" total="); pw.println(status.numSyncs);
1264                        pw.print("      total duration: ");
1265                                pw.println(DateUtils.formatElapsedTime(
1266                                        status.totalElapsedTime/1000));
1267                        if (status.lastSuccessTime != 0) {
1268                            pw.print("      SUCCESS: source=");
1269                                    pw.print(SyncStorageEngine.SOURCES[
1270                                            status.lastSuccessSource]);
1271                                    pw.print(" time=");
1272                                    pw.println(formatTime(status.lastSuccessTime));
1273                        } else {
1274                            pw.print("      FAILURE: source=");
1275                                    pw.print(SyncStorageEngine.SOURCES[
1276                                            status.lastFailureSource]);
1277                                    pw.print(" initialTime=");
1278                                    pw.print(formatTime(status.initialFailureTime));
1279                                    pw.print(" lastTime=");
1280                                    pw.println(formatTime(status.lastFailureTime));
1281                            pw.print("      message: "); pw.println(status.lastFailureMesg);
1282                        }
1283                    }
1284                }
1285            }
1286        }
1287    }
1288
1289    private void dumpTimeSec(PrintWriter pw, long time) {
1290        pw.print(time/1000); pw.print('.'); pw.print((time/100)%10);
1291        pw.print('s');
1292    }
1293
1294    private void dumpDayStatistic(PrintWriter pw, SyncStorageEngine.DayStats ds) {
1295        pw.print("Success ("); pw.print(ds.successCount);
1296        if (ds.successCount > 0) {
1297            pw.print(" for "); dumpTimeSec(pw, ds.successTime);
1298            pw.print(" avg="); dumpTimeSec(pw, ds.successTime/ds.successCount);
1299        }
1300        pw.print(") Failure ("); pw.print(ds.failureCount);
1301        if (ds.failureCount > 0) {
1302            pw.print(" for "); dumpTimeSec(pw, ds.failureTime);
1303            pw.print(" avg="); dumpTimeSec(pw, ds.failureTime/ds.failureCount);
1304        }
1305        pw.println(")");
1306    }
1307
1308    protected void dumpSyncHistory(PrintWriter pw, StringBuilder sb) {
1309        SyncStorageEngine.DayStats dses[] = mSyncStorageEngine.getDayStatistics();
1310        if (dses != null && dses[0] != null) {
1311            pw.println();
1312            pw.println("Sync Statistics");
1313            pw.print("  Today:  "); dumpDayStatistic(pw, dses[0]);
1314            int today = dses[0].day;
1315            int i;
1316            SyncStorageEngine.DayStats ds;
1317
1318            // Print each day in the current week.
1319            for (i=1; i<=6 && i < dses.length; i++) {
1320                ds = dses[i];
1321                if (ds == null) break;
1322                int delta = today-ds.day;
1323                if (delta > 6) break;
1324
1325                pw.print("  Day-"); pw.print(delta); pw.print(":  ");
1326                dumpDayStatistic(pw, ds);
1327            }
1328
1329            // Aggregate all following days into weeks and print totals.
1330            int weekDay = today;
1331            while (i < dses.length) {
1332                SyncStorageEngine.DayStats aggr = null;
1333                weekDay -= 7;
1334                while (i < dses.length) {
1335                    ds = dses[i];
1336                    if (ds == null) {
1337                        i = dses.length;
1338                        break;
1339                    }
1340                    int delta = weekDay-ds.day;
1341                    if (delta > 6) break;
1342                    i++;
1343
1344                    if (aggr == null) {
1345                        aggr = new SyncStorageEngine.DayStats(weekDay);
1346                    }
1347                    aggr.successCount += ds.successCount;
1348                    aggr.successTime += ds.successTime;
1349                    aggr.failureCount += ds.failureCount;
1350                    aggr.failureTime += ds.failureTime;
1351                }
1352                if (aggr != null) {
1353                    pw.print("  Week-"); pw.print((today-weekDay)/7); pw.print(": ");
1354                    dumpDayStatistic(pw, aggr);
1355                }
1356            }
1357        }
1358
1359        ArrayList<SyncStorageEngine.SyncHistoryItem> items
1360                = mSyncStorageEngine.getSyncHistory();
1361        if (items != null && items.size() > 0) {
1362            pw.println();
1363            pw.println("Recent Sync History");
1364            final int N = items.size();
1365            for (int i=0; i<N; i++) {
1366                SyncStorageEngine.SyncHistoryItem item = items.get(i);
1367                SyncStorageEngine.AuthorityInfo authority
1368                        = mSyncStorageEngine.getAuthority(item.authorityId);
1369                pw.print("  #"); pw.print(i+1); pw.print(": ");
1370                        if (authority != null) {
1371                            pw.print(authority.account.name);
1372                            pw.print(":");
1373                            pw.print(authority.account.type);
1374                            pw.print(" ");
1375                            pw.print(authority.authority);
1376                        } else {
1377                            pw.print("<no account>");
1378                        }
1379                Time time = new Time();
1380                time.set(item.eventTime);
1381                pw.print(" "); pw.print(SyncStorageEngine.SOURCES[item.source]);
1382                        pw.print(" @ ");
1383                        pw.print(formatTime(item.eventTime));
1384                        pw.print(" for ");
1385                        dumpTimeSec(pw, item.elapsedTime);
1386                        pw.println();
1387                if (item.event != SyncStorageEngine.EVENT_STOP
1388                        || item.upstreamActivity !=0
1389                        || item.downstreamActivity != 0) {
1390                    pw.print("    event="); pw.print(item.event);
1391                            pw.print(" upstreamActivity="); pw.print(item.upstreamActivity);
1392                            pw.print(" downstreamActivity="); pw.println(item.downstreamActivity);
1393                }
1394                if (item.mesg != null
1395                        && !SyncStorageEngine.MESG_SUCCESS.equals(item.mesg)) {
1396                    pw.print("    mesg="); pw.println(item.mesg);
1397                }
1398            }
1399        }
1400    }
1401
1402    /**
1403     * A helper object to keep track of the time we have spent syncing since the last boot
1404     */
1405    private class SyncTimeTracker {
1406        /** True if a sync was in progress on the most recent call to update() */
1407        boolean mLastWasSyncing = false;
1408        /** Used to track when lastWasSyncing was last set */
1409        long mWhenSyncStarted = 0;
1410        /** The cumulative time we have spent syncing */
1411        private long mTimeSpentSyncing;
1412
1413        /** Call to let the tracker know that the sync state may have changed */
1414        public synchronized void update() {
1415            final boolean isSyncInProgress = mActiveSyncContext != null;
1416            if (isSyncInProgress == mLastWasSyncing) return;
1417            final long now = SystemClock.elapsedRealtime();
1418            if (isSyncInProgress) {
1419                mWhenSyncStarted = now;
1420            } else {
1421                mTimeSpentSyncing += now - mWhenSyncStarted;
1422            }
1423            mLastWasSyncing = isSyncInProgress;
1424        }
1425
1426        /** Get how long we have been syncing, in ms */
1427        public synchronized long timeSpentSyncing() {
1428            if (!mLastWasSyncing) return mTimeSpentSyncing;
1429
1430            final long now = SystemClock.elapsedRealtime();
1431            return mTimeSpentSyncing + (now - mWhenSyncStarted);
1432        }
1433    }
1434
1435    class ServiceConnectionData {
1436        public final ActiveSyncContext activeSyncContext;
1437        public final ISyncAdapter syncAdapter;
1438        ServiceConnectionData(ActiveSyncContext activeSyncContext, ISyncAdapter syncAdapter) {
1439            this.activeSyncContext = activeSyncContext;
1440            this.syncAdapter = syncAdapter;
1441        }
1442    }
1443
1444    /**
1445     * Handles SyncOperation Messages that are posted to the associated
1446     * HandlerThread.
1447     */
1448    class SyncHandler extends Handler {
1449        // Messages that can be sent on mHandler
1450        private static final int MESSAGE_SYNC_FINISHED = 1;
1451        private static final int MESSAGE_SYNC_ALARM = 2;
1452        private static final int MESSAGE_CHECK_ALARMS = 3;
1453        private static final int MESSAGE_SERVICE_CONNECTED = 4;
1454        private static final int MESSAGE_SERVICE_DISCONNECTED = 5;
1455
1456        public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo();
1457        private Long mAlarmScheduleTime = null;
1458        public final SyncTimeTracker mSyncTimeTracker = new SyncTimeTracker();
1459
1460        // used to track if we have installed the error notification so that we don't reinstall
1461        // it if sync is still failing
1462        private boolean mErrorNotificationInstalled = false;
1463        private volatile CountDownLatch mReadyToRunLatch = new CountDownLatch(1);
1464
1465        public void onBootCompleted() {
1466            mBootCompleted = true;
1467            if (mReadyToRunLatch != null) {
1468                mReadyToRunLatch.countDown();
1469            }
1470        }
1471
1472        private void waitUntilReadyToRun() {
1473            CountDownLatch latch = mReadyToRunLatch;
1474            if (latch != null) {
1475                while (true) {
1476                    try {
1477                        latch.await();
1478                        mReadyToRunLatch = null;
1479                        return;
1480                    } catch (InterruptedException e) {
1481                        Thread.currentThread().interrupt();
1482                    }
1483                }
1484            }
1485        }
1486        /**
1487         * Used to keep track of whether a sync notification is active and who it is for.
1488         */
1489        class SyncNotificationInfo {
1490            // only valid if isActive is true
1491            public Account account;
1492
1493            // only valid if isActive is true
1494            public String authority;
1495
1496            // true iff the notification manager has been asked to send the notification
1497            public boolean isActive = false;
1498
1499            // Set when we transition from not running a sync to running a sync, and cleared on
1500            // the opposite transition.
1501            public Long startTime = null;
1502
1503            public void toString(StringBuilder sb) {
1504                sb.append("account ").append(account)
1505                        .append(", authority ").append(authority)
1506                        .append(", isActive ").append(isActive)
1507                        .append(", startTime ").append(startTime);
1508            }
1509
1510            @Override
1511            public String toString() {
1512                StringBuilder sb = new StringBuilder();
1513                toString(sb);
1514                return sb.toString();
1515            }
1516        }
1517
1518        public SyncHandler(Looper looper) {
1519            super(looper);
1520        }
1521
1522        public void handleMessage(Message msg) {
1523            try {
1524                waitUntilReadyToRun();
1525                switch (msg.what) {
1526                    case SyncHandler.MESSAGE_SYNC_FINISHED:
1527                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1528                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_FINISHED");
1529                        }
1530                        SyncHandlerMessagePayload payload = (SyncHandlerMessagePayload)msg.obj;
1531                        if (mActiveSyncContext != payload.activeSyncContext) {
1532                            if (Config.LOGD) {
1533                                Log.d(TAG, "handleSyncHandlerMessage: sync context doesn't match, "
1534                                        + "dropping: mActiveSyncContext " + mActiveSyncContext
1535                                        + " != " + payload.activeSyncContext);
1536                            }
1537                            return;
1538                        }
1539                        runSyncFinishedOrCanceled(payload.syncResult);
1540
1541                        // since we are no longer syncing, check if it is time to start a new sync
1542                        runStateIdle();
1543                        break;
1544
1545                    case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
1546                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
1547                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1548                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
1549                                    + msgData.activeSyncContext
1550                                    + " active is " + mActiveSyncContext);
1551                        }
1552                        // check that this isn't an old message
1553                        if (mActiveSyncContext == msgData.activeSyncContext) {
1554                            runBoundToSyncAdapter(msgData.syncAdapter);
1555                        }
1556                        break;
1557                    }
1558
1559                    case SyncHandler.MESSAGE_SERVICE_DISCONNECTED: {
1560                        ServiceConnectionData msgData = (ServiceConnectionData)msg.obj;
1561                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1562                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_DISCONNECTED: "
1563                                    + msgData.activeSyncContext
1564                                    + " active is " + mActiveSyncContext);
1565                        }
1566                        // check that this isn't an old message
1567                        if (mActiveSyncContext == msgData.activeSyncContext) {
1568                            // cancel the sync if we have a syncadapter, which means one is
1569                            // outstanding
1570                            if (mActiveSyncContext.mSyncAdapter != null) {
1571                                try {
1572                                    mActiveSyncContext.mSyncAdapter.cancelSync(mActiveSyncContext);
1573                                } catch (RemoteException e) {
1574                                    // we don't need to retry this in this case
1575                                }
1576                            }
1577
1578                            // pretend that the sync failed with an IOException,
1579                            // which is a soft error
1580                            SyncResult syncResult = new SyncResult();
1581                            syncResult.stats.numIoExceptions++;
1582                            runSyncFinishedOrCanceled(syncResult);
1583
1584                            // since we are no longer syncing, check if it is time to start a new
1585                            // sync
1586                            runStateIdle();
1587                        }
1588
1589                        break;
1590                    }
1591
1592                    case SyncHandler.MESSAGE_SYNC_ALARM: {
1593                        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1594                        if (isLoggable) {
1595                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_ALARM");
1596                        }
1597                        mAlarmScheduleTime = null;
1598                        try {
1599                            if (mActiveSyncContext != null) {
1600                                if (isLoggable) {
1601                                    Log.v(TAG, "handleSyncHandlerMessage: sync context is active");
1602                                }
1603                                runStateSyncing();
1604                            }
1605
1606                            // if the above call to runStateSyncing() resulted in the end of a sync,
1607                            // check if it is time to start a new sync
1608                            if (mActiveSyncContext == null) {
1609                                if (isLoggable) {
1610                                    Log.v(TAG, "handleSyncHandlerMessage: "
1611                                            + "sync context is not active");
1612                                }
1613                                runStateIdle();
1614                            }
1615                        } finally {
1616                            mHandleAlarmWakeLock.release();
1617                        }
1618                        break;
1619                    }
1620
1621                    case SyncHandler.MESSAGE_CHECK_ALARMS:
1622                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1623                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_CHECK_ALARMS");
1624                        }
1625                        // we do all the work for this case in the finally block
1626                        break;
1627                }
1628            } finally {
1629                final boolean isSyncInProgress = mActiveSyncContext != null;
1630                if (!isSyncInProgress) {
1631                    mSyncWakeLock.release();
1632                }
1633                manageSyncNotification();
1634                manageErrorNotification();
1635                manageSyncAlarm();
1636                mSyncTimeTracker.update();
1637            }
1638        }
1639
1640        private void runStateSyncing() {
1641            // if the sync timeout has been reached then cancel it
1642
1643            ActiveSyncContext activeSyncContext = mActiveSyncContext;
1644
1645            final long now = SystemClock.elapsedRealtime();
1646            if (now > activeSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC) {
1647                SyncOperation nextSyncOperation;
1648                synchronized (mSyncQueue) {
1649                    nextSyncOperation = mSyncQueue.head();
1650                }
1651                if (nextSyncOperation != null && nextSyncOperation.earliestRunTime <= now) {
1652                    if (Config.LOGD) {
1653                        Log.d(TAG, "canceling and rescheduling sync because it ran too long: "
1654                                + activeSyncContext.mSyncOperation);
1655                    }
1656                    rescheduleImmediately(activeSyncContext.mSyncOperation);
1657                    sendSyncFinishedOrCanceledMessage(activeSyncContext,
1658                            null /* no result since this is a cancel */);
1659                } else {
1660                    activeSyncContext.mTimeoutStartTime = now + MAX_TIME_PER_SYNC;
1661                }
1662            }
1663
1664            // no need to schedule an alarm, as that will be done by our caller.
1665        }
1666
1667        private void runStateIdle() {
1668            boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1669            if (isLoggable) Log.v(TAG, "runStateIdle");
1670
1671            // If we aren't ready to run (e.g. the data connection is down), get out.
1672            if (!mDataConnectionIsConnected) {
1673                if (isLoggable) {
1674                    Log.v(TAG, "runStateIdle: no data connection, skipping");
1675                }
1676                setStatusText("No data connection");
1677                return;
1678            }
1679
1680            if (mStorageIsLow) {
1681                if (isLoggable) {
1682                    Log.v(TAG, "runStateIdle: memory low, skipping");
1683                }
1684                setStatusText("Memory low");
1685                return;
1686            }
1687
1688            // If the accounts aren't known yet then we aren't ready to run. We will be kicked
1689            // when the account lookup request does complete.
1690            Account[] accounts = mAccounts;
1691            if (accounts == null) {
1692                if (isLoggable) {
1693                    Log.v(TAG, "runStateIdle: accounts not known, skipping");
1694                }
1695                setStatusText("Accounts not known yet");
1696                return;
1697            }
1698
1699            // Otherwise consume SyncOperations from the head of the SyncQueue until one is
1700            // found that is runnable (not disabled, etc). If that one is ready to run then
1701            // start it, otherwise just get out.
1702            SyncOperation op;
1703            final boolean backgroundDataUsageAllowed =
1704                    getConnectivityManager().getBackgroundDataSetting();
1705            synchronized (mSyncQueue) {
1706                while (true) {
1707                    op = mSyncQueue.head();
1708                    if (op == null) {
1709                        if (isLoggable) {
1710                            Log.v(TAG, "runStateIdle: no more sync operations, returning");
1711                        }
1712                        return;
1713                    }
1714
1715                    // Sync is disabled, drop this operation.
1716                    if (!isSyncEnabled()) {
1717                        if (isLoggable) {
1718                            Log.v(TAG, "runStateIdle: sync disabled, dropping " + op);
1719                        }
1720                        mSyncQueue.popHead();
1721                        continue;
1722                    }
1723
1724                    // skip the sync if it isn't manual and auto sync is disabled
1725                    final boolean manualSync = op.extras.getBoolean(
1726                            ContentResolver.SYNC_EXTRAS_MANUAL, false);
1727                    final boolean syncAutomatically =
1728                            mSyncStorageEngine.getSyncAutomatically(op.account, op.authority)
1729                                    && mSyncStorageEngine.getMasterSyncAutomatically();
1730                    boolean syncAllowed =
1731                            manualSync || (backgroundDataUsageAllowed && syncAutomatically);
1732                    int isSyncable = mSyncStorageEngine.getIsSyncable(op.account, op.authority);
1733                    if (isSyncable == 0) {
1734                        // if not syncable, don't allow
1735                        syncAllowed = false;
1736                    } else if (isSyncable < 0) {
1737                        // if the syncable state is unknown, only allow initialization syncs
1738                        syncAllowed =
1739                                op.extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
1740                    }
1741                    if (!syncAllowed) {
1742                        if (isLoggable) {
1743                            Log.v(TAG, "runStateIdle: sync off, dropping " + op);
1744                        }
1745                        mSyncQueue.popHead();
1746                        continue;
1747                    }
1748
1749                    // skip the sync if the account of this operation no longer exists
1750                    if (!ArrayUtils.contains(accounts, op.account)) {
1751                        mSyncQueue.popHead();
1752                        if (isLoggable) {
1753                            Log.v(TAG, "runStateIdle: account not present, dropping " + op);
1754                        }
1755                        continue;
1756                    }
1757
1758                    // go ahead and try to sync this syncOperation
1759                    if (isLoggable) {
1760                        Log.v(TAG, "runStateIdle: found sync candidate: " + op);
1761                    }
1762                    break;
1763                }
1764
1765                // If the first SyncOperation isn't ready to run schedule a wakeup and
1766                // get out.
1767                final long now = SystemClock.elapsedRealtime();
1768                if (op.earliestRunTime > now) {
1769                    if (Log.isLoggable(TAG, Log.DEBUG)) {
1770                        Log.d(TAG, "runStateIdle: the time is " + now + " yet the next "
1771                                + "sync operation is for " + op.earliestRunTime + ": " + op);
1772                    }
1773                    return;
1774                }
1775
1776                // We will do this sync. Remove it from the queue and run it outside of the
1777                // synchronized block.
1778                if (isLoggable) {
1779                    Log.v(TAG, "runStateIdle: we are going to sync " + op);
1780                }
1781                mSyncQueue.popHead();
1782            }
1783
1784            // connect to the sync adapter
1785            SyncAdapterType syncAdapterType = SyncAdapterType.newKey(op.authority, op.account.type);
1786            RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
1787                    mSyncAdapters.getServiceInfo(syncAdapterType);
1788            if (syncAdapterInfo == null) {
1789                if (Config.LOGD) {
1790                    Log.d(TAG, "can't find a sync adapter for " + syncAdapterType);
1791                }
1792                runStateIdle();
1793                return;
1794            }
1795
1796            ActiveSyncContext activeSyncContext =
1797                    new ActiveSyncContext(op, insertStartSyncEvent(op));
1798            mActiveSyncContext = activeSyncContext;
1799            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1800                Log.v(TAG, "runStateIdle: setting mActiveSyncContext to " + mActiveSyncContext);
1801            }
1802            mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1803            if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo)) {
1804                Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
1805                mActiveSyncContext = null;
1806                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1807                runStateIdle();
1808                return;
1809            }
1810
1811            mSyncWakeLock.acquire();
1812            // no need to schedule an alarm, as that will be done by our caller.
1813
1814            // the next step will occur when we get either a timeout or a
1815            // MESSAGE_SERVICE_CONNECTED or MESSAGE_SERVICE_DISCONNECTED message
1816        }
1817
1818        private void runBoundToSyncAdapter(ISyncAdapter syncAdapter) {
1819            mActiveSyncContext.mSyncAdapter = syncAdapter;
1820            final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1821            try {
1822                syncAdapter.startSync(mActiveSyncContext, syncOperation.authority,
1823                        syncOperation.account, syncOperation.extras);
1824            } catch (RemoteException remoteExc) {
1825                if (Config.LOGD) {
1826                    Log.d(TAG, "runStateIdle: caught a RemoteException, rescheduling", remoteExc);
1827                }
1828                mActiveSyncContext.unBindFromSyncAdapter();
1829                mActiveSyncContext = null;
1830                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1831                rescheduleWithDelay(syncOperation);
1832            } catch (RuntimeException exc) {
1833                mActiveSyncContext.unBindFromSyncAdapter();
1834                mActiveSyncContext = null;
1835                mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1836                Log.e(TAG, "Caught a RuntimeException while starting the sync " + syncOperation,
1837                        exc);
1838            }
1839        }
1840
1841        private void runSyncFinishedOrCanceled(SyncResult syncResult) {
1842            boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
1843            if (isLoggable) Log.v(TAG, "runSyncFinishedOrCanceled");
1844            final ActiveSyncContext activeSyncContext = mActiveSyncContext;
1845            mActiveSyncContext = null;
1846            mSyncStorageEngine.setActiveSync(mActiveSyncContext);
1847
1848            final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
1849
1850            final long elapsedTime = SystemClock.elapsedRealtime() - activeSyncContext.mStartTime;
1851
1852            String historyMessage;
1853            int downstreamActivity;
1854            int upstreamActivity;
1855            if (syncResult != null) {
1856                if (isLoggable) {
1857                    Log.v(TAG, "runSyncFinishedOrCanceled: is a finished: operation "
1858                            + syncOperation + ", result " + syncResult);
1859                }
1860
1861                if (!syncResult.hasError()) {
1862                    if (isLoggable) {
1863                        Log.v(TAG, "finished sync operation " + syncOperation);
1864                    }
1865                    historyMessage = SyncStorageEngine.MESG_SUCCESS;
1866                    // TODO: set these correctly when the SyncResult is extended to include it
1867                    downstreamActivity = 0;
1868                    upstreamActivity = 0;
1869                } else {
1870                    maybeRescheduleSync(syncResult, syncOperation);
1871                    if (Config.LOGD) {
1872                        Log.d(TAG, "failed sync operation " + syncOperation);
1873                    }
1874                    historyMessage = Integer.toString(syncResultToErrorNumber(syncResult));
1875                    // TODO: set these correctly when the SyncResult is extended to include it
1876                    downstreamActivity = 0;
1877                    upstreamActivity = 0;
1878                }
1879            } else {
1880                if (isLoggable) {
1881                    Log.v(TAG, "runSyncFinishedOrCanceled: is a cancel: operation "
1882                            + syncOperation);
1883                }
1884                if (activeSyncContext.mSyncAdapter != null) {
1885                    try {
1886                        activeSyncContext.mSyncAdapter.cancelSync(activeSyncContext);
1887                    } catch (RemoteException e) {
1888                        // we don't need to retry this in this case
1889                    }
1890                }
1891                historyMessage = SyncStorageEngine.MESG_CANCELED;
1892                downstreamActivity = 0;
1893                upstreamActivity = 0;
1894            }
1895
1896            stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
1897                    upstreamActivity, downstreamActivity, elapsedTime);
1898
1899            activeSyncContext.unBindFromSyncAdapter();
1900
1901            if (syncResult != null && syncResult.tooManyDeletions) {
1902                installHandleTooManyDeletesNotification(syncOperation.account,
1903                        syncOperation.authority, syncResult.stats.numDeletes);
1904            } else {
1905                mNotificationMgr.cancel(
1906                        syncOperation.account.hashCode() ^ syncOperation.authority.hashCode());
1907            }
1908
1909            if (syncResult != null && syncResult.fullSyncRequested) {
1910                scheduleSyncOperation(new SyncOperation(syncOperation.account,
1911                        syncOperation.syncSource, syncOperation.authority, new Bundle(), 0));
1912            }
1913            // no need to schedule an alarm, as that will be done by our caller.
1914        }
1915
1916        /**
1917         * Convert the error-containing SyncResult into the Sync.History error number. Since
1918         * the SyncResult may indicate multiple errors at once, this method just returns the
1919         * most "serious" error.
1920         * @param syncResult the SyncResult from which to read
1921         * @return the most "serious" error set in the SyncResult
1922         * @throws IllegalStateException if the SyncResult does not indicate any errors.
1923         *   If SyncResult.error() is true then it is safe to call this.
1924         */
1925        private int syncResultToErrorNumber(SyncResult syncResult) {
1926            if (syncResult.syncAlreadyInProgress)
1927                return ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
1928            if (syncResult.stats.numAuthExceptions > 0)
1929                return ContentResolver.SYNC_ERROR_AUTHENTICATION;
1930            if (syncResult.stats.numIoExceptions > 0)
1931                return ContentResolver.SYNC_ERROR_IO;
1932            if (syncResult.stats.numParseExceptions > 0)
1933                return ContentResolver.SYNC_ERROR_PARSE;
1934            if (syncResult.stats.numConflictDetectedExceptions > 0)
1935                return ContentResolver.SYNC_ERROR_CONFLICT;
1936            if (syncResult.tooManyDeletions)
1937                return ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS;
1938            if (syncResult.tooManyRetries)
1939                return ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES;
1940            if (syncResult.databaseError)
1941                return ContentResolver.SYNC_ERROR_INTERNAL;
1942            throw new IllegalStateException("we are not in an error state, " + syncResult);
1943        }
1944
1945        private void manageSyncNotification() {
1946            boolean shouldCancel;
1947            boolean shouldInstall;
1948
1949            if (mActiveSyncContext == null) {
1950                mSyncNotificationInfo.startTime = null;
1951
1952                // we aren't syncing. if the notification is active then remember that we need
1953                // to cancel it and then clear out the info
1954                shouldCancel = mSyncNotificationInfo.isActive;
1955                shouldInstall = false;
1956            } else {
1957                // we are syncing
1958                final SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1959
1960                final long now = SystemClock.elapsedRealtime();
1961                if (mSyncNotificationInfo.startTime == null) {
1962                    mSyncNotificationInfo.startTime = now;
1963                }
1964
1965                // cancel the notification if it is up and the authority or account is wrong
1966                shouldCancel = mSyncNotificationInfo.isActive &&
1967                        (!syncOperation.authority.equals(mSyncNotificationInfo.authority)
1968                        || !syncOperation.account.equals(mSyncNotificationInfo.account));
1969
1970                // there are four cases:
1971                // - the notification is up and there is no change: do nothing
1972                // - the notification is up but we should cancel since it is stale:
1973                //   need to install
1974                // - the notification is not up but it isn't time yet: don't install
1975                // - the notification is not up and it is time: need to install
1976
1977                if (mSyncNotificationInfo.isActive) {
1978                    shouldInstall = shouldCancel;
1979                } else {
1980                    final boolean timeToShowNotification =
1981                            now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
1982                    // show the notification immediately if this is a manual sync
1983                    final boolean manualSync = syncOperation.extras
1984                            .getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
1985                    shouldInstall = timeToShowNotification || manualSync;
1986                }
1987            }
1988
1989            if (shouldCancel && !shouldInstall) {
1990                mNeedSyncActiveNotification = false;
1991                sendSyncStateIntent();
1992                mSyncNotificationInfo.isActive = false;
1993            }
1994
1995            if (shouldInstall) {
1996                SyncOperation syncOperation = mActiveSyncContext.mSyncOperation;
1997                mNeedSyncActiveNotification = true;
1998                sendSyncStateIntent();
1999                mSyncNotificationInfo.isActive = true;
2000                mSyncNotificationInfo.account = syncOperation.account;
2001                mSyncNotificationInfo.authority = syncOperation.authority;
2002            }
2003        }
2004
2005        /**
2006         * Check if there were any long-lasting errors, if so install the error notification,
2007         * otherwise cancel the error notification.
2008         */
2009        private void manageErrorNotification() {
2010            //
2011            long when = mSyncStorageEngine.getInitialSyncFailureTime();
2012            if ((when > 0) && (when + ERROR_NOTIFICATION_DELAY_MS < System.currentTimeMillis())) {
2013                if (!mErrorNotificationInstalled) {
2014                    mNeedSyncErrorNotification = true;
2015                    sendSyncStateIntent();
2016                }
2017                mErrorNotificationInstalled = true;
2018            } else {
2019                if (mErrorNotificationInstalled) {
2020                    mNeedSyncErrorNotification = false;
2021                    sendSyncStateIntent();
2022                }
2023                mErrorNotificationInstalled = false;
2024            }
2025        }
2026
2027        private void manageSyncAlarm() {
2028            // in each of these cases the sync loop will be kicked, which will cause this
2029            // method to be called again
2030            if (!mDataConnectionIsConnected) return;
2031            if (mAccounts == null) return;
2032            if (mStorageIsLow) return;
2033
2034            // Compute the alarm fire time:
2035            // - not syncing: time of the next sync operation
2036            // - syncing, no notification: time from sync start to notification create time
2037            // - syncing, with notification: time till timeout of the active sync operation
2038            Long alarmTime = null;
2039            ActiveSyncContext activeSyncContext = mActiveSyncContext;
2040            if (activeSyncContext == null) {
2041                SyncOperation syncOperation;
2042                synchronized (mSyncQueue) {
2043                    syncOperation = mSyncQueue.head();
2044                }
2045                if (syncOperation != null) {
2046                    alarmTime = syncOperation.earliestRunTime;
2047                }
2048            } else {
2049                final long notificationTime =
2050                        mSyncHandler.mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
2051                final long timeoutTime =
2052                        mActiveSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC;
2053                if (mSyncHandler.mSyncNotificationInfo.isActive) {
2054                    alarmTime = timeoutTime;
2055                } else {
2056                    alarmTime = Math.min(notificationTime, timeoutTime);
2057                }
2058            }
2059
2060            // adjust the alarmTime so that we will wake up when it is time to
2061            // install the error notification
2062            if (!mErrorNotificationInstalled) {
2063                long when = mSyncStorageEngine.getInitialSyncFailureTime();
2064                if (when > 0) {
2065                    when += ERROR_NOTIFICATION_DELAY_MS;
2066                    // convert when fron absolute time to elapsed run time
2067                    long delay = when - System.currentTimeMillis();
2068                    when = SystemClock.elapsedRealtime() + delay;
2069                    alarmTime = alarmTime != null ? Math.min(alarmTime, when) : when;
2070                }
2071            }
2072
2073            // determine if we need to set or cancel the alarm
2074            boolean shouldSet = false;
2075            boolean shouldCancel = false;
2076            final boolean alarmIsActive = mAlarmScheduleTime != null;
2077            final boolean needAlarm = alarmTime != null;
2078            if (needAlarm) {
2079                if (!alarmIsActive || alarmTime < mAlarmScheduleTime) {
2080                    shouldSet = true;
2081                }
2082            } else {
2083                shouldCancel = alarmIsActive;
2084            }
2085
2086            // set or cancel the alarm as directed
2087            ensureAlarmService();
2088            if (shouldSet) {
2089                mAlarmScheduleTime = alarmTime;
2090                mAlarmService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime,
2091                        mSyncAlarmIntent);
2092            } else if (shouldCancel) {
2093                mAlarmScheduleTime = null;
2094                mAlarmService.cancel(mSyncAlarmIntent);
2095            }
2096        }
2097
2098        private void sendSyncStateIntent() {
2099            Intent syncStateIntent = new Intent(Intent.ACTION_SYNC_STATE_CHANGED);
2100            syncStateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2101            syncStateIntent.putExtra("active", mNeedSyncActiveNotification);
2102            syncStateIntent.putExtra("failing", mNeedSyncErrorNotification);
2103            mContext.sendBroadcast(syncStateIntent);
2104        }
2105
2106        private void installHandleTooManyDeletesNotification(Account account, String authority,
2107                long numDeletes) {
2108            if (mNotificationMgr == null) return;
2109
2110            final ProviderInfo providerInfo = mContext.getPackageManager().resolveContentProvider(
2111                    authority, 0 /* flags */);
2112            if (providerInfo == null) {
2113                return;
2114            }
2115            CharSequence authorityName = providerInfo.loadLabel(mContext.getPackageManager());
2116
2117            Intent clickIntent = new Intent();
2118            clickIntent.setClassName("com.android.providers.subscribedfeeds",
2119                    "com.android.settings.SyncActivityTooManyDeletes");
2120            clickIntent.putExtra("account", account);
2121            clickIntent.putExtra("authority", authority);
2122            clickIntent.putExtra("provider", authorityName.toString());
2123            clickIntent.putExtra("numDeletes", numDeletes);
2124
2125            if (!isActivityAvailable(clickIntent)) {
2126                Log.w(TAG, "No activity found to handle too many deletes.");
2127                return;
2128            }
2129
2130            final PendingIntent pendingIntent = PendingIntent
2131                    .getActivity(mContext, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);
2132
2133            CharSequence tooManyDeletesDescFormat = mContext.getResources().getText(
2134                    R.string.contentServiceTooManyDeletesNotificationDesc);
2135
2136            Notification notification =
2137                new Notification(R.drawable.stat_notify_sync_error,
2138                        mContext.getString(R.string.contentServiceSync),
2139                        System.currentTimeMillis());
2140            notification.setLatestEventInfo(mContext,
2141                    mContext.getString(R.string.contentServiceSyncNotificationTitle),
2142                    String.format(tooManyDeletesDescFormat.toString(), authorityName),
2143                    pendingIntent);
2144            notification.flags |= Notification.FLAG_ONGOING_EVENT;
2145            mNotificationMgr.notify(account.hashCode() ^ authority.hashCode(), notification);
2146        }
2147
2148        /**
2149         * Checks whether an activity exists on the system image for the given intent.
2150         *
2151         * @param intent The intent for an activity.
2152         * @return Whether or not an activity exists.
2153         */
2154        private boolean isActivityAvailable(Intent intent) {
2155            PackageManager pm = mContext.getPackageManager();
2156            List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
2157            int listSize = list.size();
2158            for (int i = 0; i < listSize; i++) {
2159                ResolveInfo resolveInfo = list.get(i);
2160                if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
2161                        != 0) {
2162                    return true;
2163                }
2164            }
2165
2166            return false;
2167        }
2168
2169        public long insertStartSyncEvent(SyncOperation syncOperation) {
2170            final int source = syncOperation.syncSource;
2171            final long now = System.currentTimeMillis();
2172
2173            EventLog.writeEvent(2720, syncOperation.authority,
2174                                SyncStorageEngine.EVENT_START, source,
2175                                syncOperation.account.name.hashCode());
2176
2177            return mSyncStorageEngine.insertStartSyncEvent(
2178                    syncOperation.account, syncOperation.authority, now, source);
2179        }
2180
2181        public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage,
2182                int upstreamActivity, int downstreamActivity, long elapsedTime) {
2183            EventLog.writeEvent(2720, syncOperation.authority,
2184                                SyncStorageEngine.EVENT_STOP, syncOperation.syncSource,
2185                                syncOperation.account.name.hashCode());
2186
2187            mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime, resultMessage,
2188                    downstreamActivity, upstreamActivity);
2189        }
2190    }
2191
2192    static class SyncQueue {
2193        private SyncStorageEngine mSyncStorageEngine;
2194
2195        private static final boolean DEBUG_CHECK_DATA_CONSISTENCY = false;
2196
2197        // A priority queue of scheduled SyncOperations that is designed to make it quick
2198        // to find the next SyncOperation that should be considered for running.
2199        private final PriorityQueue<SyncOperation> mOpsByWhen = new PriorityQueue<SyncOperation>();
2200
2201        // A Map of SyncOperations operationKey -> SyncOperation that is designed for
2202        // quick lookup of an enqueued SyncOperation.
2203        private final HashMap<String, SyncOperation> mOpsByKey = Maps.newHashMap();
2204
2205        public SyncQueue(SyncStorageEngine syncStorageEngine) {
2206            mSyncStorageEngine = syncStorageEngine;
2207            ArrayList<SyncStorageEngine.PendingOperation> ops
2208                    = mSyncStorageEngine.getPendingOperations();
2209            final int N = ops.size();
2210            for (int i=0; i<N; i++) {
2211                SyncStorageEngine.PendingOperation op = ops.get(i);
2212                SyncOperation syncOperation = new SyncOperation(
2213                        op.account, op.syncSource, op.authority, op.extras, 0);
2214                syncOperation.pendingOperation = op;
2215                add(syncOperation, op);
2216            }
2217
2218            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2219        }
2220
2221        public boolean add(SyncOperation operation) {
2222            return add(new SyncOperation(operation),
2223                    null /* this is not coming from the database */);
2224        }
2225
2226        private boolean add(SyncOperation operation,
2227                SyncStorageEngine.PendingOperation pop) {
2228            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2229
2230            // If this operation is expedited then set its earliestRunTime to be immediately
2231            // before the head of the list, or not if none are in the list.
2232            if (operation.delay < 0) {
2233                SyncOperation headOperation = head();
2234                if (headOperation != null) {
2235                    operation.earliestRunTime = Math.min(SystemClock.elapsedRealtime(),
2236                            headOperation.earliestRunTime - 1);
2237                } else {
2238                    operation.earliestRunTime = SystemClock.elapsedRealtime();
2239                }
2240            }
2241
2242            // - if an operation with the same key exists and this one should run earlier,
2243            //   delete the old one and add the new one
2244            // - if an operation with the same key exists and if this one should run
2245            //   later, ignore it
2246            // - if no operation exists then add the new one
2247            final String operationKey = operation.key;
2248            SyncOperation existingOperation = mOpsByKey.get(operationKey);
2249
2250            // if this operation matches an existing operation that is being retried (delay > 0)
2251            // and this isn't a manual sync operation, ignore this operation
2252            if (existingOperation != null && existingOperation.delay > 0) {
2253                if (!operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)) {
2254                    return false;
2255                }
2256            }
2257
2258            if (existingOperation != null
2259                    && operation.earliestRunTime >= existingOperation.earliestRunTime) {
2260                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2261                return false;
2262            }
2263
2264            if (existingOperation != null) {
2265                removeByKey(operationKey);
2266            }
2267
2268            operation.pendingOperation = pop;
2269            if (operation.pendingOperation == null) {
2270                pop = new SyncStorageEngine.PendingOperation(
2271                                operation.account, operation.syncSource,
2272                                operation.authority, operation.extras);
2273                pop = mSyncStorageEngine.insertIntoPending(pop);
2274                if (pop == null) {
2275                    throw new IllegalStateException("error adding pending sync operation "
2276                            + operation);
2277                }
2278                operation.pendingOperation = pop;
2279            }
2280
2281            if (DEBUG_CHECK_DATA_CONSISTENCY) {
2282                debugCheckDataStructures(
2283                        false /* don't compare with the DB, since we know
2284                               it is inconsistent right now */ );
2285            }
2286            mOpsByKey.put(operationKey, operation);
2287            mOpsByWhen.add(operation);
2288            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(pop == null);
2289            return true;
2290        }
2291
2292        public void removeByKey(String operationKey) {
2293            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2294            SyncOperation operationToRemove = mOpsByKey.remove(operationKey);
2295            if (!mOpsByWhen.remove(operationToRemove)) {
2296                throw new IllegalStateException(
2297                        "unable to find " + operationToRemove + " in mOpsByWhen");
2298            }
2299
2300            if (!mSyncStorageEngine.deleteFromPending(operationToRemove.pendingOperation)) {
2301                final String errorMessage = "unable to find pending row for " + operationToRemove;
2302                Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
2303            }
2304
2305            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2306        }
2307
2308        public SyncOperation head() {
2309            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2310            return mOpsByWhen.peek();
2311        }
2312
2313        public void popHead() {
2314            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2315            SyncOperation operation = mOpsByWhen.remove();
2316            if (mOpsByKey.remove(operation.key) == null) {
2317                throw new IllegalStateException("unable to find " + operation + " in mOpsByKey");
2318            }
2319
2320            if (!mSyncStorageEngine.deleteFromPending(operation.pendingOperation)) {
2321                final String errorMessage = "unable to find pending row for " + operation;
2322                Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
2323            }
2324
2325            if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2326        }
2327
2328        public void clear(Account account, String authority) {
2329            Iterator<Map.Entry<String, SyncOperation>> entries = mOpsByKey.entrySet().iterator();
2330            while (entries.hasNext()) {
2331                Map.Entry<String, SyncOperation> entry = entries.next();
2332                SyncOperation syncOperation = entry.getValue();
2333                if (account != null && !syncOperation.account.equals(account)) continue;
2334                if (authority != null && !syncOperation.authority.equals(authority)) continue;
2335
2336                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2337                entries.remove();
2338                if (!mOpsByWhen.remove(syncOperation)) {
2339                    throw new IllegalStateException(
2340                            "unable to find " + syncOperation + " in mOpsByWhen");
2341                }
2342
2343                if (!mSyncStorageEngine.deleteFromPending(syncOperation.pendingOperation)) {
2344                    final String errorMessage = "unable to find pending row for " + syncOperation;
2345                    Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
2346                }
2347
2348                if (DEBUG_CHECK_DATA_CONSISTENCY) debugCheckDataStructures(true /* check the DB */);
2349            }
2350        }
2351
2352        public void dump(StringBuilder sb) {
2353            sb.append("SyncQueue: ").append(mOpsByWhen.size()).append(" operation(s)\n");
2354            for (SyncOperation operation : mOpsByWhen) {
2355                sb.append(operation).append("\n");
2356            }
2357        }
2358
2359        private void debugCheckDataStructures(boolean checkDatabase) {
2360            if (mOpsByKey.size() != mOpsByWhen.size()) {
2361                throw new IllegalStateException("size mismatch: "
2362                        + mOpsByKey .size() + " != " + mOpsByWhen.size());
2363            }
2364            for (SyncOperation operation : mOpsByWhen) {
2365                if (!mOpsByKey.containsKey(operation.key)) {
2366                    throw new IllegalStateException(
2367                        "operation " + operation + " is in mOpsByWhen but not mOpsByKey");
2368                }
2369            }
2370            for (Map.Entry<String, SyncOperation> entry : mOpsByKey.entrySet()) {
2371                final SyncOperation operation = entry.getValue();
2372                final String key = entry.getKey();
2373                if (!key.equals(operation.key)) {
2374                    throw new IllegalStateException(
2375                        "operation " + operation + " in mOpsByKey doesn't match key " + key);
2376                }
2377                if (!mOpsByWhen.contains(operation)) {
2378                    throw new IllegalStateException(
2379                        "operation " + operation + " is in mOpsByKey but not mOpsByWhen");
2380                }
2381            }
2382
2383            if (checkDatabase) {
2384                final int N = mSyncStorageEngine.getPendingOperationCount();
2385                if (mOpsByKey.size() != N) {
2386                    ArrayList<SyncStorageEngine.PendingOperation> ops
2387                            = mSyncStorageEngine.getPendingOperations();
2388                    StringBuilder sb = new StringBuilder();
2389                    for (int i=0; i<N; i++) {
2390                        SyncStorageEngine.PendingOperation op = ops.get(i);
2391                        sb.append("#");
2392                        sb.append(i);
2393                        sb.append(": account=");
2394                        sb.append(op.account);
2395                        sb.append(" syncSource=");
2396                        sb.append(op.syncSource);
2397                        sb.append(" authority=");
2398                        sb.append(op.authority);
2399                        sb.append("\n");
2400                    }
2401                    dump(sb);
2402                    throw new IllegalStateException("DB size mismatch: "
2403                            + mOpsByKey.size() + " != " + N + "\n"
2404                            + sb.toString());
2405                }
2406            }
2407        }
2408    }
2409}
2410