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