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