SyncManager.java revision 07ad8dc2087aa02da48353acc19ba82e62d99f82
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 com.android.server.content;
18
19import android.accounts.Account;
20import android.accounts.AccountAndUser;
21import android.accounts.AccountManager;
22import android.app.ActivityManager;
23import android.app.AlarmManager;
24import android.app.AppGlobals;
25import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.content.BroadcastReceiver;
29import android.content.ComponentName;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.ISyncAdapter;
33import android.content.ISyncContext;
34import android.content.ISyncServiceAdapter;
35import android.content.ISyncStatusObserver;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.PeriodicSync;
39import android.content.ServiceConnection;
40import android.content.SyncActivityTooManyDeletes;
41import android.content.SyncAdapterType;
42import android.content.SyncAdaptersCache;
43import android.content.SyncInfo;
44import android.content.SyncResult;
45import android.content.SyncStatusInfo;
46import android.content.pm.ApplicationInfo;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.PackageManager.NameNotFoundException;
50import android.content.pm.ProviderInfo;
51import android.content.pm.RegisteredServicesCache;
52import android.content.pm.RegisteredServicesCacheListener;
53import android.content.pm.ResolveInfo;
54import android.content.pm.UserInfo;
55import android.net.ConnectivityManager;
56import android.net.NetworkInfo;
57import android.os.BatteryStats;
58import android.os.Bundle;
59import android.os.Handler;
60import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
63import android.os.PowerManager;
64import android.os.RemoteException;
65import android.os.ServiceManager;
66import android.os.SystemClock;
67import android.os.SystemProperties;
68import android.os.UserHandle;
69import android.os.UserManager;
70import android.os.WorkSource;
71import android.provider.Settings;
72import android.text.format.DateUtils;
73import android.text.format.Time;
74import android.text.TextUtils;
75import android.util.EventLog;
76import android.util.Log;
77import android.util.Pair;
78
79import com.android.internal.R;
80import com.android.internal.annotations.GuardedBy;
81import com.android.internal.app.IBatteryStats;
82import com.android.internal.os.BackgroundThread;
83import com.android.internal.util.IndentingPrintWriter;
84import com.android.server.accounts.AccountManagerService;
85import com.android.server.content.SyncStorageEngine.AuthorityInfo;
86import com.android.server.content.SyncStorageEngine.OnSyncRequestListener;
87import com.google.android.collect.Lists;
88import com.google.android.collect.Maps;
89import com.google.android.collect.Sets;
90
91import java.io.FileDescriptor;
92import java.io.PrintWriter;
93import java.util.ArrayList;
94import java.util.Arrays;
95import java.util.Collection;
96import java.util.Collections;
97import java.util.Comparator;
98import java.util.HashMap;
99import java.util.HashSet;
100import java.util.Iterator;
101import java.util.List;
102import java.util.Map;
103import java.util.Random;
104import java.util.Set;
105
106/**
107 * @hide
108 */
109public class SyncManager {
110    private static final String TAG = "SyncManager";
111
112    /** Delay a sync due to local changes this long. In milliseconds */
113    private static final long LOCAL_SYNC_DELAY;
114
115    /**
116     * If a sync takes longer than this and the sync queue is not empty then we will
117     * cancel it and add it back to the end of the sync queue. In milliseconds.
118     */
119    private static final long MAX_TIME_PER_SYNC;
120
121    static {
122        final boolean isLargeRAM = !ActivityManager.isLowRamDeviceStatic();
123        int defaultMaxInitSyncs = isLargeRAM ? 5 : 2;
124        int defaultMaxRegularSyncs = isLargeRAM ? 2 : 1;
125        MAX_SIMULTANEOUS_INITIALIZATION_SYNCS =
126                SystemProperties.getInt("sync.max_init_syncs", defaultMaxInitSyncs);
127        MAX_SIMULTANEOUS_REGULAR_SYNCS =
128                SystemProperties.getInt("sync.max_regular_syncs", defaultMaxRegularSyncs);
129        LOCAL_SYNC_DELAY =
130                SystemProperties.getLong("sync.local_sync_delay", 30 * 1000 /* 30 seconds */);
131        MAX_TIME_PER_SYNC =
132                SystemProperties.getLong("sync.max_time_per_sync", 5 * 60 * 1000 /* 5 minutes */);
133        SYNC_NOTIFICATION_DELAY =
134                SystemProperties.getLong("sync.notification_delay", 30 * 1000 /* 30 seconds */);
135    }
136
137    private static final long SYNC_NOTIFICATION_DELAY;
138
139    /**
140     * When retrying a sync for the first time use this delay. After that
141     * the retry time will double until it reached MAX_SYNC_RETRY_TIME.
142     * In milliseconds.
143     */
144    private static final long INITIAL_SYNC_RETRY_TIME_IN_MS = 30 * 1000; // 30 seconds
145
146    /**
147     * Default the max sync retry time to this value.
148     */
149    private static final long DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS = 60 * 60; // one hour
150
151    /**
152     * How long to wait before retrying a sync that failed due to one already being in progress.
153     */
154    private static final int DELAY_RETRY_SYNC_IN_PROGRESS_IN_SECONDS = 10;
155
156    /**
157     * How long to wait before considering an active sync to have timed-out, and cancelling it.
158     */
159    private static final long ACTIVE_SYNC_TIMEOUT_MILLIS = 30L * 60 * 1000;  // 30 mins.
160
161    private static final String SYNC_WAKE_LOCK_PREFIX = "*sync*/";
162    private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarm";
163    private static final String SYNC_LOOP_WAKE_LOCK = "SyncLoopWakeLock";
164
165    private static final int MAX_SIMULTANEOUS_REGULAR_SYNCS;
166    private static final int MAX_SIMULTANEOUS_INITIALIZATION_SYNCS;
167
168    private Context mContext;
169
170    private static final AccountAndUser[] INITIAL_ACCOUNTS_ARRAY = new AccountAndUser[0];
171
172    // TODO: add better locking around mRunningAccounts
173    private volatile AccountAndUser[] mRunningAccounts = INITIAL_ACCOUNTS_ARRAY;
174
175    volatile private PowerManager.WakeLock mHandleAlarmWakeLock;
176    volatile private PowerManager.WakeLock mSyncManagerWakeLock;
177    volatile private boolean mDataConnectionIsConnected = false;
178    volatile private boolean mStorageIsLow = false;
179
180    private final NotificationManager mNotificationMgr;
181    private AlarmManager mAlarmService = null;
182    private final IBatteryStats mBatteryStats;
183
184    private SyncStorageEngine mSyncStorageEngine;
185
186    @GuardedBy("mSyncQueue")
187    private final SyncQueue mSyncQueue;
188
189    protected final ArrayList<ActiveSyncContext> mActiveSyncContexts = Lists.newArrayList();
190
191    // set if the sync active indicator should be reported
192    private boolean mNeedSyncActiveNotification = false;
193
194    private final PendingIntent mSyncAlarmIntent;
195    // Synchronized on "this". Instead of using this directly one should instead call
196    // its accessor, getConnManager().
197    private ConnectivityManager mConnManagerDoNotUseDirectly;
198
199    protected SyncAdaptersCache mSyncAdapters;
200
201    private BroadcastReceiver mStorageIntentReceiver =
202            new BroadcastReceiver() {
203                @Override
204                public void onReceive(Context context, Intent intent) {
205                    String action = intent.getAction();
206                    if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
207                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
208                            Log.v(TAG, "Internal storage is low.");
209                        }
210                        mStorageIsLow = true;
211                        cancelActiveSync(
212                                SyncStorageEngine.EndPoint.USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL,
213                                null /* any sync */);
214                    } else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
215                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
216                            Log.v(TAG, "Internal storage is ok.");
217                        }
218                        mStorageIsLow = false;
219                        sendCheckAlarmsMessage();
220                    }
221                }
222            };
223
224    private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
225        @Override
226        public void onReceive(Context context, Intent intent) {
227            mSyncHandler.onBootCompleted();
228        }
229    };
230
231    private BroadcastReceiver mAccountsUpdatedReceiver = new BroadcastReceiver() {
232        @Override
233        public void onReceive(Context context, Intent intent) {
234            updateRunningAccounts();
235
236            // Kick off sync for everyone, since this was a radical account change
237            scheduleSync(null, UserHandle.USER_ALL, SyncOperation.REASON_ACCOUNTS_UPDATED, null,
238                    null, 0 /* no delay */, 0/* no delay */, false);
239        }
240    };
241
242    private final PowerManager mPowerManager;
243
244    // Use this as a random offset to seed all periodic syncs.
245    private int mSyncRandomOffsetMillis;
246
247    private final UserManager mUserManager;
248
249    private static final long SYNC_ALARM_TIMEOUT_MIN = 30 * 1000; // 30 seconds
250    private static final long SYNC_ALARM_TIMEOUT_MAX = 2 * 60 * 60 * 1000; // two hours
251
252    private List<UserInfo> getAllUsers() {
253        return mUserManager.getUsers();
254    }
255
256    private boolean containsAccountAndUser(AccountAndUser[] accounts, Account account, int userId) {
257        boolean found = false;
258        for (int i = 0; i < accounts.length; i++) {
259            if (accounts[i].userId == userId
260                    && accounts[i].account.equals(account)) {
261                found = true;
262                break;
263            }
264        }
265        return found;
266    }
267
268    public void updateRunningAccounts() {
269        mRunningAccounts = AccountManagerService.getSingleton().getRunningAccounts();
270
271        if (mBootCompleted) {
272            doDatabaseCleanup();
273        }
274
275        AccountAndUser[] accounts = mRunningAccounts;
276        for (ActiveSyncContext currentSyncContext : mActiveSyncContexts) {
277            if (!containsAccountAndUser(accounts,
278                    currentSyncContext.mSyncOperation.target.account,
279                    currentSyncContext.mSyncOperation.target.userId)) {
280                Log.d(TAG, "canceling sync since the account is no longer running");
281                sendSyncFinishedOrCanceledMessage(currentSyncContext,
282                        null /* no result since this is a cancel */);
283            }
284        }
285        // we must do this since we don't bother scheduling alarms when
286        // the accounts are not set yet
287        sendCheckAlarmsMessage();
288    }
289
290    private void doDatabaseCleanup() {
291        for (UserInfo user : mUserManager.getUsers(true)) {
292            // Skip any partially created/removed users
293            if (user.partial) continue;
294            Account[] accountsForUser = AccountManagerService.getSingleton().getAccounts(user.id);
295            mSyncStorageEngine.doDatabaseCleanup(accountsForUser, user.id);
296        }
297    }
298
299    private BroadcastReceiver mConnectivityIntentReceiver =
300            new BroadcastReceiver() {
301        @Override
302        public void onReceive(Context context, Intent intent) {
303            final boolean wasConnected = mDataConnectionIsConnected;
304
305            // don't use the intent to figure out if network is connected, just check
306            // ConnectivityManager directly.
307            mDataConnectionIsConnected = readDataConnectionState();
308            if (mDataConnectionIsConnected) {
309                if (!wasConnected) {
310                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
311                        Log.v(TAG, "Reconnection detected: clearing all backoffs");
312                    }
313                    mSyncStorageEngine.clearAllBackoffs(mSyncQueue);
314                }
315                sendCheckAlarmsMessage();
316            }
317        }
318    };
319
320    private boolean readDataConnectionState() {
321        NetworkInfo networkInfo = getConnectivityManager().getActiveNetworkInfo();
322        return (networkInfo != null) && networkInfo.isConnected();
323    }
324
325    private BroadcastReceiver mShutdownIntentReceiver =
326            new BroadcastReceiver() {
327        @Override
328        public void onReceive(Context context, Intent intent) {
329            Log.w(TAG, "Writing sync state before shutdown...");
330            getSyncStorageEngine().writeAllState();
331        }
332    };
333
334    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
335        @Override
336        public void onReceive(Context context, Intent intent) {
337            String action = intent.getAction();
338            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
339            if (userId == UserHandle.USER_NULL) return;
340
341            if (Intent.ACTION_USER_REMOVED.equals(action)) {
342                onUserRemoved(userId);
343            } else if (Intent.ACTION_USER_STARTING.equals(action)) {
344                onUserStarting(userId);
345            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
346                onUserStopping(userId);
347            }
348        }
349    };
350
351    private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM";
352    private final SyncHandler mSyncHandler;
353
354    private volatile boolean mBootCompleted = false;
355
356    private ConnectivityManager getConnectivityManager() {
357        synchronized (this) {
358            if (mConnManagerDoNotUseDirectly == null) {
359                mConnManagerDoNotUseDirectly = (ConnectivityManager)mContext.getSystemService(
360                        Context.CONNECTIVITY_SERVICE);
361            }
362            return mConnManagerDoNotUseDirectly;
363        }
364    }
365
366    /**
367     * Should only be created after {@link ContentService#systemReady()} so that
368     * {@link PackageManager} is ready to query.
369     */
370    public SyncManager(Context context, boolean factoryTest) {
371        // Initialize the SyncStorageEngine first, before registering observers
372        // and creating threads and so on; it may fail if the disk is full.
373        mContext = context;
374
375        SyncStorageEngine.init(context);
376        mSyncStorageEngine = SyncStorageEngine.getSingleton();
377        mSyncStorageEngine.setOnSyncRequestListener(new OnSyncRequestListener() {
378            @Override
379            public void onSyncRequest(SyncStorageEngine.EndPoint info, int reason, Bundle extras) {
380                if (info.target_provider) {
381                    scheduleSync(info.account, info.userId, reason, info.provider, extras,
382                        0 /* no flex */,
383                        0 /* run immediately */,
384                        false);
385                } else if (info.target_service) {
386                    scheduleSync(info.service, info.userId, reason, extras,
387                            0 /* no flex */,
388                            0 /* run immediately */);
389                }
390            }
391        });
392
393        mSyncAdapters = new SyncAdaptersCache(mContext);
394        mSyncQueue = new SyncQueue(mContext.getPackageManager(), mSyncStorageEngine, mSyncAdapters);
395
396        mSyncHandler = new SyncHandler(BackgroundThread.get().getLooper());
397
398        mSyncAdapters.setListener(new RegisteredServicesCacheListener<SyncAdapterType>() {
399            @Override
400            public void onServiceChanged(SyncAdapterType type, int userId, boolean removed) {
401                if (!removed) {
402                    scheduleSync(null, UserHandle.USER_ALL,
403                            SyncOperation.REASON_SERVICE_CHANGED,
404                            type.authority, null, 0 /* no delay */, 0 /* no delay */,
405                            false /* onlyThoseWithUnkownSyncableState */);
406                }
407            }
408        }, mSyncHandler);
409
410        mSyncAlarmIntent = PendingIntent.getBroadcast(
411                mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0);
412
413        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
414        context.registerReceiver(mConnectivityIntentReceiver, intentFilter);
415
416        if (!factoryTest) {
417            intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
418            intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
419            context.registerReceiver(mBootCompletedReceiver, intentFilter);
420        }
421
422        intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
423        intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
424        context.registerReceiver(mStorageIntentReceiver, intentFilter);
425
426        intentFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
427        intentFilter.setPriority(100);
428        context.registerReceiver(mShutdownIntentReceiver, intentFilter);
429
430        intentFilter = new IntentFilter();
431        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
432        intentFilter.addAction(Intent.ACTION_USER_STARTING);
433        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
434        mContext.registerReceiverAsUser(
435                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
436
437        if (!factoryTest) {
438            mNotificationMgr = (NotificationManager)
439                context.getSystemService(Context.NOTIFICATION_SERVICE);
440            context.registerReceiver(new SyncAlarmIntentReceiver(),
441                    new IntentFilter(ACTION_SYNC_ALARM));
442        } else {
443            mNotificationMgr = null;
444        }
445        mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
446        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
447        mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
448                BatteryStats.SERVICE_NAME));
449
450        // This WakeLock is used to ensure that we stay awake between the time that we receive
451        // a sync alarm notification and when we finish processing it. We need to do this
452        // because we don't do the work in the alarm handler, rather we do it in a message
453        // handler.
454        mHandleAlarmWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
455                HANDLE_SYNC_ALARM_WAKE_LOCK);
456        mHandleAlarmWakeLock.setReferenceCounted(false);
457
458        // This WakeLock is used to ensure that we stay awake while running the sync loop
459        // message handler. Normally we will hold a sync adapter wake lock while it is being
460        // synced but during the execution of the sync loop it might finish a sync for
461        // one sync adapter before starting the sync for the other sync adapter and we
462        // don't want the device to go to sleep during that window.
463        mSyncManagerWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
464                SYNC_LOOP_WAKE_LOCK);
465        mSyncManagerWakeLock.setReferenceCounted(false);
466
467        mSyncStorageEngine.addStatusChangeListener(
468                ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, new ISyncStatusObserver.Stub() {
469            @Override
470            public void onStatusChanged(int which) {
471                // force the sync loop to run if the settings change
472                sendCheckAlarmsMessage();
473            }
474        });
475
476        if (!factoryTest) {
477            // Register for account list updates for all users
478            mContext.registerReceiverAsUser(mAccountsUpdatedReceiver,
479                    UserHandle.ALL,
480                    new IntentFilter(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION),
481                    null, null);
482        }
483
484        // Pick a random second in a day to seed all periodic syncs
485        mSyncRandomOffsetMillis = mSyncStorageEngine.getSyncRandomOffset() * 1000;
486    }
487
488    /**
489     * Return a random value v that satisfies minValue <= v < maxValue. The difference between
490     * maxValue and minValue must be less than Integer.MAX_VALUE.
491     */
492    private long jitterize(long minValue, long maxValue) {
493        Random random = new Random(SystemClock.elapsedRealtime());
494        long spread = maxValue - minValue;
495        if (spread > Integer.MAX_VALUE) {
496            throw new IllegalArgumentException("the difference between the maxValue and the "
497                    + "minValue must be less than " + Integer.MAX_VALUE);
498        }
499        return minValue + random.nextInt((int)spread);
500    }
501
502    public SyncStorageEngine getSyncStorageEngine() {
503        return mSyncStorageEngine;
504    }
505
506    public int getIsSyncable(Account account, int userId, String providerName) {
507        int isSyncable = mSyncStorageEngine.getIsSyncable(account, userId, providerName);
508        UserInfo userInfo = UserManager.get(mContext).getUserInfo(userId);
509
510        // If it's not a restricted user, return isSyncable
511        if (userInfo == null || !userInfo.isRestricted()) return isSyncable;
512
513        // Else check if the sync adapter has opted-in or not
514        RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
515                mSyncAdapters.getServiceInfo(
516                SyncAdapterType.newKey(providerName, account.type), userId);
517        if (syncAdapterInfo == null) return isSyncable;
518
519        PackageInfo pInfo = null;
520        try {
521            pInfo = AppGlobals.getPackageManager().getPackageInfo(
522                syncAdapterInfo.componentName.getPackageName(), 0, userId);
523            if (pInfo == null) return isSyncable;
524        } catch (RemoteException re) {
525            // Shouldn't happen
526            return isSyncable;
527        }
528        if (pInfo.restrictedAccountType != null
529                && pInfo.restrictedAccountType.equals(account.type)) {
530            return isSyncable;
531        } else {
532            return 0;
533        }
534    }
535
536    private void ensureAlarmService() {
537        if (mAlarmService == null) {
538            mAlarmService = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
539        }
540    }
541
542    /**
543     * Initiate a sync using the new anonymous service API.
544     * @param cname SyncService component bound to in order to perform the sync.
545     * @param userId the id of the user whose accounts are to be synced. If userId is USER_ALL,
546     *          then all users' accounts are considered.
547     * @param uid Linux uid of the application that is performing the sync.
548     * @param extras a Map of SyncAdapter-specific information to control
549     *          syncs of a specific provider. Cannot be null.
550     * @param beforeRunTimeMillis milliseconds before <code>runtimeMillis</code> that this sync may
551     * be run.
552     * @param runtimeMillis milliseconds from now by which this sync must be run.
553     */
554    public void scheduleSync(ComponentName cname, int userId, int uid, Bundle extras,
555            long beforeRunTimeMillis, long runtimeMillis) {
556        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
557        if (isLoggable) {
558            Log.d(TAG, "one off sync for: " + cname + " " + extras.toString());
559        }
560
561        Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
562        if (expedited) {
563            runtimeMillis = -1; // this means schedule at the front of the queue
564        }
565
566        final boolean ignoreSettings =
567                extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false);
568        int source = SyncStorageEngine.SOURCE_SERVICE;
569        boolean isEnabled = mSyncStorageEngine.getIsTargetServiceActive(cname, userId);
570        // Only schedule this sync if
571        //   - we've explicitly been told to ignore settings.
572        //   - global sync is enabled for this user.
573        boolean syncAllowed =
574                ignoreSettings
575                || mSyncStorageEngine.getMasterSyncAutomatically(userId);
576        if (!syncAllowed) {
577            if (isLoggable) {
578                Log.d(TAG, "scheduleSync: sync of " + cname + " not allowed, dropping request.");
579            }
580            return;
581        }
582        if (!isEnabled) {
583            if (isLoggable) {
584                Log.d(TAG, "scheduleSync: " + cname + " is not enabled, dropping request");
585            }
586            return;
587        }
588        SyncStorageEngine.EndPoint info = new SyncStorageEngine.EndPoint(cname, userId);
589        Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(info);
590        long delayUntil = mSyncStorageEngine.getDelayUntilTime(info);
591        final long backoffTime = backoff != null ? backoff.first : 0;
592        if (isLoggable) {
593                Log.v(TAG, "schedule Sync:"
594                        + ", delay until " + delayUntil
595                        + ", run by " + runtimeMillis
596                        + ", flex " + beforeRunTimeMillis
597                        + ", source " + source
598                        + ", sync service " + cname
599                        + ", extras " + extras);
600        }
601        scheduleSyncOperation(
602                new SyncOperation(cname, userId, uid, source, extras,
603                        runtimeMillis /* runtime */,
604                        beforeRunTimeMillis /* flextime */,
605                        backoffTime,
606                        delayUntil));
607    }
608
609    /**
610     * Initiate a sync. This can start a sync for all providers
611     * (pass null to url, set onlyTicklable to false), only those
612     * providers that are marked as ticklable (pass null to url,
613     * set onlyTicklable to true), or a specific provider (set url
614     * to the content url of the provider).
615     *
616     * <p>If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is
617     * true then initiate a sync that just checks for local changes to send
618     * to the server, otherwise initiate a sync that first gets any
619     * changes from the server before sending local changes back to
620     * the server.
621     *
622     * <p>If a specific provider is being synced (the url is non-null)
623     * then the extras can contain SyncAdapter-specific information
624     * to control what gets synced (e.g. which specific feed to sync).
625     *
626     * <p>You'll start getting callbacks after this.
627     *
628     * @param requestedAccount the account to sync, may be null to signify all accounts
629     * @param userId the id of the user whose accounts are to be synced. If userId is USER_ALL,
630     *          then all users' accounts are considered.
631     * @param reason for sync request. If this is a positive integer, it is the Linux uid
632     * assigned to the process that requested the sync. If it's negative, the sync was requested by
633     * the SyncManager itself and could be one of the following:
634     *      {@link SyncOperation#REASON_BACKGROUND_DATA_SETTINGS_CHANGED}
635     *      {@link SyncOperation#REASON_ACCOUNTS_UPDATED}
636     *      {@link SyncOperation#REASON_SERVICE_CHANGED}
637     *      {@link SyncOperation#REASON_PERIODIC}
638     *      {@link SyncOperation#REASON_IS_SYNCABLE}
639     *      {@link SyncOperation#REASON_SYNC_AUTO}
640     *      {@link SyncOperation#REASON_MASTER_SYNC_AUTO}
641     *      {@link SyncOperation#REASON_USER_START}
642     * @param requestedAuthority the authority to sync, may be null to indicate all authorities
643     * @param extras a Map of SyncAdapter-specific information to control
644     *          syncs of a specific provider. Can be null. Is ignored
645     *          if the url is null.
646     * @param beforeRuntimeMillis milliseconds before runtimeMillis that this sync can run.
647     * @param runtimeMillis maximum milliseconds in the future to wait before performing sync.
648     * @param onlyThoseWithUnkownSyncableState Only sync authorities that have unknown state.
649     */
650    public void scheduleSync(Account requestedAccount, int userId, int reason,
651            String requestedAuthority, Bundle extras, long beforeRuntimeMillis,
652            long runtimeMillis, boolean onlyThoseWithUnkownSyncableState) {
653        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
654
655        if (extras == null) {
656            extras = new Bundle();
657        }
658        if (isLoggable) {
659            Log.d(TAG, "one-time sync for: " + requestedAccount + " " + extras.toString() + " "
660                    + requestedAuthority);
661        }
662        Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
663        if (expedited) {
664            runtimeMillis = -1; // this means schedule at the front of the queue
665        }
666
667        AccountAndUser[] accounts;
668        if (requestedAccount != null && userId != UserHandle.USER_ALL) {
669            accounts = new AccountAndUser[] { new AccountAndUser(requestedAccount, userId) };
670        } else {
671            accounts = mRunningAccounts;
672            if (accounts.length == 0) {
673                if (isLoggable) {
674                    Log.v(TAG, "scheduleSync: no accounts configured, dropping");
675                }
676                return;
677            }
678        }
679
680        final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
681        final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
682        if (manualSync) {
683            extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, true);
684            extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, true);
685        }
686        final boolean ignoreSettings =
687                extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false);
688
689        int source;
690        if (uploadOnly) {
691            source = SyncStorageEngine.SOURCE_LOCAL;
692        } else if (manualSync) {
693            source = SyncStorageEngine.SOURCE_USER;
694        } else if (requestedAuthority == null) {
695            source = SyncStorageEngine.SOURCE_POLL;
696        } else {
697            // this isn't strictly server, since arbitrary callers can (and do) request
698            // a non-forced two-way sync on a specific url
699            source = SyncStorageEngine.SOURCE_SERVER;
700        }
701
702        for (AccountAndUser account : accounts) {
703            // Compile a list of authorities that have sync adapters.
704            // For each authority sync each account that matches a sync adapter.
705            final HashSet<String> syncableAuthorities = new HashSet<String>();
706            for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
707                    mSyncAdapters.getAllServices(account.userId)) {
708                syncableAuthorities.add(syncAdapter.type.authority);
709            }
710
711            // if the url was specified then replace the list of authorities
712            // with just this authority or clear it if this authority isn't
713            // syncable
714            if (requestedAuthority != null) {
715                final boolean hasSyncAdapter = syncableAuthorities.contains(requestedAuthority);
716                syncableAuthorities.clear();
717                if (hasSyncAdapter) syncableAuthorities.add(requestedAuthority);
718            }
719
720            for (String authority : syncableAuthorities) {
721                int isSyncable = getIsSyncable(account.account, account.userId,
722                        authority);
723                if (isSyncable == 0) {
724                    continue;
725                }
726                final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
727                syncAdapterInfo = mSyncAdapters.getServiceInfo(
728                        SyncAdapterType.newKey(authority, account.account.type), account.userId);
729                if (syncAdapterInfo == null) {
730                    continue;
731                }
732                final boolean allowParallelSyncs = syncAdapterInfo.type.allowParallelSyncs();
733                final boolean isAlwaysSyncable = syncAdapterInfo.type.isAlwaysSyncable();
734                if (isSyncable < 0 && isAlwaysSyncable) {
735                    mSyncStorageEngine.setIsSyncable(account.account, account.userId, authority, 1);
736                    isSyncable = 1;
737                }
738                if (onlyThoseWithUnkownSyncableState && isSyncable >= 0) {
739                    continue;
740                }
741                if (!syncAdapterInfo.type.supportsUploading() && uploadOnly) {
742                    continue;
743                }
744
745                boolean syncAllowed =
746                        (isSyncable < 0) // always allow if the isSyncable state is unknown
747                        || ignoreSettings
748                        || (mSyncStorageEngine.getMasterSyncAutomatically(account.userId)
749                                && mSyncStorageEngine.getSyncAutomatically(account.account,
750                                        account.userId, authority));
751                if (!syncAllowed) {
752                    if (isLoggable) {
753                        Log.d(TAG, "scheduleSync: sync of " + account + ", " + authority
754                                + " is not allowed, dropping request");
755                    }
756                    continue;
757                }
758                SyncStorageEngine.EndPoint info =
759                        new SyncStorageEngine.EndPoint(
760                                account.account, authority, account.userId);
761                Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(info);
762                long delayUntil =
763                        mSyncStorageEngine.getDelayUntilTime(info);
764                final long backoffTime = backoff != null ? backoff.first : 0;
765                if (isSyncable < 0) {
766                    // Initialisation sync.
767                    Bundle newExtras = new Bundle();
768                    newExtras.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
769                    if (isLoggable) {
770                        Log.v(TAG, "schedule initialisation Sync:"
771                                + ", delay until " + delayUntil
772                                + ", run by " + 0
773                                + ", flex " + 0
774                                + ", source " + source
775                                + ", account " + account
776                                + ", authority " + authority
777                                + ", extras " + newExtras);
778                    }
779                    scheduleSyncOperation(
780                            new SyncOperation(account.account, account.userId, reason, source,
781                                    authority, newExtras, 0 /* immediate */, 0 /* No flex time*/,
782                                    backoffTime, delayUntil, allowParallelSyncs));
783                }
784                if (!onlyThoseWithUnkownSyncableState) {
785                    if (isLoggable) {
786                        Log.v(TAG, "scheduleSync:"
787                                + " delay until " + delayUntil
788                                + " run by " + runtimeMillis
789                                + " flex " + beforeRuntimeMillis
790                                + ", source " + source
791                                + ", account " + account
792                                + ", authority " + authority
793                                + ", extras " + extras);
794                    }
795                    scheduleSyncOperation(
796                            new SyncOperation(account.account, account.userId, reason, source,
797                                    authority, extras, runtimeMillis, beforeRuntimeMillis,
798                                    backoffTime, delayUntil, allowParallelSyncs));
799                }
800            }
801        }
802    }
803
804    /**
805     * Schedule sync based on local changes to a provider. Occurs within interval
806     * [LOCAL_SYNC_DELAY, 2*LOCAL_SYNC_DELAY].
807     */
808    public void scheduleLocalSync(Account account, int userId, int reason, String authority) {
809        final Bundle extras = new Bundle();
810        extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
811        scheduleSync(account, userId, reason, authority, extras,
812                LOCAL_SYNC_DELAY /* earliest run time */,
813                2 * LOCAL_SYNC_DELAY /* latest sync time. */,
814                false /* onlyThoseWithUnkownSyncableState */);
815    }
816
817    public SyncAdapterType[] getSyncAdapterTypes(int userId) {
818        final Collection<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> serviceInfos;
819        serviceInfos = mSyncAdapters.getAllServices(userId);
820        SyncAdapterType[] types = new SyncAdapterType[serviceInfos.size()];
821        int i = 0;
822        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> serviceInfo : serviceInfos) {
823            types[i] = serviceInfo.type;
824            ++i;
825        }
826        return types;
827    }
828
829    private void sendSyncAlarmMessage() {
830        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_ALARM");
831        mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_SYNC_ALARM);
832    }
833
834    private void sendCheckAlarmsMessage() {
835        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CHECK_ALARMS");
836        mSyncHandler.removeMessages(SyncHandler.MESSAGE_CHECK_ALARMS);
837        mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS);
838    }
839
840    private void sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext,
841            SyncResult syncResult) {
842        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_FINISHED");
843        Message msg = mSyncHandler.obtainMessage();
844        msg.what = SyncHandler.MESSAGE_SYNC_FINISHED;
845        msg.obj = new SyncHandlerMessagePayload(syncContext, syncResult);
846        mSyncHandler.sendMessage(msg);
847    }
848
849    private void sendCancelSyncsMessage(final SyncStorageEngine.EndPoint info, Bundle extras) {
850        if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CANCEL");
851        Message msg = mSyncHandler.obtainMessage();
852        msg.what = SyncHandler.MESSAGE_CANCEL;
853        msg.setData(extras);
854        msg.obj = info;
855        mSyncHandler.sendMessage(msg);
856    }
857
858    /**
859     * Post a delayed message to the handler that will result in the cancellation of the provided
860     * running sync's context.
861     */
862    private void postSyncExpiryMessage(ActiveSyncContext activeSyncContext) {
863        if (Log.isLoggable(TAG, Log.VERBOSE)) {
864            Log.v(TAG, "posting MESSAGE_SYNC_EXPIRED in " +
865                    (ACTIVE_SYNC_TIMEOUT_MILLIS/1000) + "s");
866        }
867        Message msg = mSyncHandler.obtainMessage();
868        msg.what = SyncHandler.MESSAGE_SYNC_EXPIRED;
869        msg.obj = activeSyncContext;
870        mSyncHandler.sendMessageDelayed(msg, ACTIVE_SYNC_TIMEOUT_MILLIS);
871    }
872
873    /**
874     * Remove any time-outs previously posted for the provided active sync.
875     */
876    private void removeSyncExpiryMessage(ActiveSyncContext activeSyncContext) {
877        if (Log.isLoggable(TAG, Log.VERBOSE)) {
878            Log.v(TAG, "removing all MESSAGE_SYNC_EXPIRED for " + activeSyncContext.toString());
879        }
880        mSyncHandler.removeMessages(SyncHandler.MESSAGE_SYNC_EXPIRED, activeSyncContext);
881    }
882
883    class SyncHandlerMessagePayload {
884        public final ActiveSyncContext activeSyncContext;
885        public final SyncResult syncResult;
886
887        SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) {
888            this.activeSyncContext = syncContext;
889            this.syncResult = syncResult;
890        }
891    }
892
893    class SyncAlarmIntentReceiver extends BroadcastReceiver {
894        @Override
895        public void onReceive(Context context, Intent intent) {
896            mHandleAlarmWakeLock.acquire();
897            sendSyncAlarmMessage();
898        }
899    }
900
901    private void clearBackoffSetting(SyncOperation op) {
902        mSyncStorageEngine.setBackoff(op.target,
903                SyncStorageEngine.NOT_IN_BACKOFF_MODE,
904                SyncStorageEngine.NOT_IN_BACKOFF_MODE);
905        synchronized (mSyncQueue) {
906            mSyncQueue.onBackoffChanged(op.target, 0);
907        }
908    }
909
910    private void increaseBackoffSetting(SyncOperation op) {
911        // TODO: Use this function to align it to an already scheduled sync
912        //       operation in the specified window
913        final long now = SystemClock.elapsedRealtime();
914
915        final Pair<Long, Long> previousSettings =
916                mSyncStorageEngine.getBackoff(op.target);
917        long newDelayInMs = -1;
918        if (previousSettings != null) {
919            // don't increase backoff before current backoff is expired. This will happen for op's
920            // with ignoreBackoff set.
921            if (now < previousSettings.first) {
922                if (Log.isLoggable(TAG, Log.VERBOSE)) {
923                    Log.v(TAG, "Still in backoff, do not increase it. "
924                        + "Remaining: " + ((previousSettings.first - now) / 1000) + " seconds.");
925                }
926                return;
927            }
928            // Subsequent delays are the double of the previous delay
929            newDelayInMs = previousSettings.second * 2;
930        }
931        if (newDelayInMs <= 0) {
932            // The initial delay is the jitterized INITIAL_SYNC_RETRY_TIME_IN_MS
933            newDelayInMs = jitterize(INITIAL_SYNC_RETRY_TIME_IN_MS,
934                    (long)(INITIAL_SYNC_RETRY_TIME_IN_MS * 1.1));
935        }
936
937        // Cap the delay
938        long maxSyncRetryTimeInSeconds = Settings.Global.getLong(mContext.getContentResolver(),
939                Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
940                DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS);
941        if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) {
942            newDelayInMs = maxSyncRetryTimeInSeconds * 1000;
943        }
944
945        final long backoff = now + newDelayInMs;
946
947        mSyncStorageEngine.setBackoff(op.target, backoff, newDelayInMs);
948        op.backoff = backoff;
949        op.updateEffectiveRunTime();
950
951        synchronized (mSyncQueue) {
952            mSyncQueue.onBackoffChanged(op.target, backoff);
953        }
954    }
955
956    private void setDelayUntilTime(SyncOperation op, long delayUntilSeconds) {
957        final long delayUntil = delayUntilSeconds * 1000;
958        final long absoluteNow = System.currentTimeMillis();
959        long newDelayUntilTime;
960        if (delayUntil > absoluteNow) {
961            newDelayUntilTime = SystemClock.elapsedRealtime() + (delayUntil - absoluteNow);
962        } else {
963            newDelayUntilTime = 0;
964        }
965        mSyncStorageEngine.setDelayUntilTime(op.target, newDelayUntilTime);
966        synchronized (mSyncQueue) {
967            mSyncQueue.onDelayUntilTimeChanged(op.target, newDelayUntilTime);
968        }
969    }
970
971    /**
972     * Cancel the active sync if it matches the target.
973     * @param info object containing info about which syncs to cancel. The target can
974     * have null account/provider info to specify all accounts/providers.
975     * @param extras if non-null, specifies the exact sync to remove.
976     */
977    public void cancelActiveSync(SyncStorageEngine.EndPoint info, Bundle extras) {
978        sendCancelSyncsMessage(info, extras);
979    }
980
981    /**
982     * Create and schedule a SyncOperation.
983     *
984     * @param syncOperation the SyncOperation to schedule
985     */
986    public void scheduleSyncOperation(SyncOperation syncOperation) {
987        boolean queueChanged;
988        synchronized (mSyncQueue) {
989            queueChanged = mSyncQueue.add(syncOperation);
990        }
991
992        if (queueChanged) {
993            if (Log.isLoggable(TAG, Log.VERBOSE)) {
994                Log.v(TAG, "scheduleSyncOperation: enqueued " + syncOperation);
995            }
996            sendCheckAlarmsMessage();
997        } else {
998            if (Log.isLoggable(TAG, Log.VERBOSE)) {
999                Log.v(TAG, "scheduleSyncOperation: dropping duplicate sync operation "
1000                        + syncOperation);
1001            }
1002        }
1003    }
1004
1005    /**
1006     * Remove scheduled sync operations.
1007     * @param info limit the removals to operations that match this target. The target can
1008     * have null account/provider info to specify all accounts/providers.
1009     */
1010    public void clearScheduledSyncOperations(SyncStorageEngine.EndPoint info) {
1011        synchronized (mSyncQueue) {
1012            mSyncQueue.remove(info, null /* all operations */);
1013        }
1014        mSyncStorageEngine.setBackoff(info,
1015                SyncStorageEngine.NOT_IN_BACKOFF_MODE, SyncStorageEngine.NOT_IN_BACKOFF_MODE);
1016    }
1017
1018    /**
1019     * Remove a specified sync, if it exists.
1020     * @param info Authority for which the sync is to be removed.
1021     * @param extras extras bundle to uniquely identify sync.
1022     */
1023    public void cancelScheduledSyncOperation(SyncStorageEngine.EndPoint info, Bundle extras) {
1024        synchronized (mSyncQueue) {
1025            mSyncQueue.remove(info, extras);
1026        }
1027        // Reset the back-off if there are no more syncs pending.
1028        if (!mSyncStorageEngine.isSyncPending(info)) {
1029            mSyncStorageEngine.setBackoff(info,
1030                    SyncStorageEngine.NOT_IN_BACKOFF_MODE, SyncStorageEngine.NOT_IN_BACKOFF_MODE);
1031        }
1032    }
1033
1034    void maybeRescheduleSync(SyncResult syncResult, SyncOperation operation) {
1035        boolean isLoggable = Log.isLoggable(TAG, Log.DEBUG);
1036        if (isLoggable) {
1037            Log.d(TAG, "encountered error(s) during the sync: " + syncResult + ", " + operation);
1038        }
1039
1040        operation = new SyncOperation(operation, 0L /* newRunTimeFromNow */);
1041
1042        // The SYNC_EXTRAS_IGNORE_BACKOFF only applies to the first attempt to sync a given
1043        // request. Retries of the request will always honor the backoff, so clear the
1044        // flag in case we retry this request.
1045        if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, false)) {
1046            operation.extras.remove(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF);
1047        }
1048
1049        if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY, false)) {
1050            if (isLoggable) {
1051                Log.d(TAG, "not retrying sync operation because SYNC_EXTRAS_DO_NOT_RETRY was specified "
1052                        + operation);
1053            }
1054        } else if (operation.extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false)
1055                && !syncResult.syncAlreadyInProgress) {
1056            // If this was an upward sync then schedule a two-way sync immediately.
1057            operation.extras.remove(ContentResolver.SYNC_EXTRAS_UPLOAD);
1058            if (isLoggable) {
1059                Log.d(TAG, "retrying sync operation as a two-way sync because an upload-only sync "
1060                        + "encountered an error: " + operation);
1061            }
1062            scheduleSyncOperation(operation);
1063        } else if (syncResult.tooManyRetries) {
1064            // If this sync aborted because the internal sync loop retried too many times then
1065            //   don't reschedule. Otherwise we risk getting into a retry loop.
1066            if (isLoggable) {
1067                Log.d(TAG, "not retrying sync operation because it retried too many times: "
1068                        + operation);
1069            }
1070        } else if (syncResult.madeSomeProgress()) {
1071            // If the operation succeeded to some extent then retry immediately.
1072            if (isLoggable) {
1073                Log.d(TAG, "retrying sync operation because even though it had an error "
1074                        + "it achieved some success");
1075            }
1076            scheduleSyncOperation(operation);
1077        } else if (syncResult.syncAlreadyInProgress) {
1078            if (isLoggable) {
1079                Log.d(TAG, "retrying sync operation that failed because there was already a "
1080                        + "sync in progress: " + operation);
1081            }
1082            scheduleSyncOperation(
1083                new SyncOperation(
1084                        operation,
1085                        DELAY_RETRY_SYNC_IN_PROGRESS_IN_SECONDS * 1000 /* newRunTimeFromNow */)
1086                );
1087        } else if (syncResult.hasSoftError()) {
1088            // If this was a two-way sync then retry soft errors with an exponential backoff.
1089            if (isLoggable) {
1090                Log.d(TAG, "retrying sync operation because it encountered a soft error: "
1091                        + operation);
1092            }
1093            scheduleSyncOperation(operation);
1094        } else {
1095            // Otherwise do not reschedule.
1096            Log.d(TAG, "not retrying sync operation because the error is a hard error: "
1097                    + operation);
1098        }
1099    }
1100
1101    private void onUserStarting(int userId) {
1102        // Make sure that accounts we're about to use are valid
1103        AccountManagerService.getSingleton().validateAccounts(userId);
1104
1105        mSyncAdapters.invalidateCache(userId);
1106
1107        updateRunningAccounts();
1108
1109        synchronized (mSyncQueue) {
1110            mSyncQueue.addPendingOperations(userId);
1111        }
1112
1113        // Schedule sync for any accounts under started user
1114        final Account[] accounts = AccountManagerService.getSingleton().getAccounts(userId);
1115        for (Account account : accounts) {
1116            scheduleSync(account, userId, SyncOperation.REASON_USER_START, null, null,
1117                    0 /* no delay */, 0 /* No flex */,
1118                    true /* onlyThoseWithUnknownSyncableState */);
1119        }
1120
1121        sendCheckAlarmsMessage();
1122    }
1123
1124    private void onUserStopping(int userId) {
1125        updateRunningAccounts();
1126
1127        cancelActiveSync(
1128                new SyncStorageEngine.EndPoint(
1129                        null /* any account */,
1130                        null /* any authority */,
1131                        userId),
1132                        null /* any sync. */
1133                );
1134    }
1135
1136    private void onUserRemoved(int userId) {
1137        updateRunningAccounts();
1138
1139        // Clean up the storage engine database
1140        mSyncStorageEngine.doDatabaseCleanup(new Account[0], userId);
1141        synchronized (mSyncQueue) {
1142            mSyncQueue.removeUserLocked(userId);
1143        }
1144    }
1145
1146    /**
1147     * @hide
1148     */
1149    class ActiveSyncContext extends ISyncContext.Stub
1150            implements ServiceConnection, IBinder.DeathRecipient {
1151        final SyncOperation mSyncOperation;
1152        final long mHistoryRowId;
1153        ISyncAdapter mSyncAdapter;
1154        ISyncServiceAdapter mSyncServiceAdapter;
1155        final long mStartTime;
1156        long mTimeoutStartTime;
1157        boolean mBound;
1158        final PowerManager.WakeLock mSyncWakeLock;
1159        final int mSyncAdapterUid;
1160        SyncInfo mSyncInfo;
1161        boolean mIsLinkedToDeath = false;
1162        String mEventName;
1163
1164        /**
1165         * Create an ActiveSyncContext for an impending sync and grab the wakelock for that
1166         * sync adapter. Since this grabs the wakelock you need to be sure to call
1167         * close() when you are done with this ActiveSyncContext, whether the sync succeeded
1168         * or not.
1169         * @param syncOperation the SyncOperation we are about to sync
1170         * @param historyRowId the row in which to record the history info for this sync
1171         * @param syncAdapterUid the UID of the application that contains the sync adapter
1172         * for this sync. This is used to attribute the wakelock hold to that application.
1173         */
1174        public ActiveSyncContext(SyncOperation syncOperation, long historyRowId,
1175                int syncAdapterUid) {
1176            super();
1177            mSyncAdapterUid = syncAdapterUid;
1178            mSyncOperation = syncOperation;
1179            mHistoryRowId = historyRowId;
1180            mSyncAdapter = null;
1181            mSyncServiceAdapter = null;
1182            mStartTime = SystemClock.elapsedRealtime();
1183            mTimeoutStartTime = mStartTime;
1184            mSyncWakeLock = mSyncHandler.getSyncWakeLock(mSyncOperation);
1185            mSyncWakeLock.setWorkSource(new WorkSource(syncAdapterUid));
1186            mSyncWakeLock.acquire();
1187        }
1188
1189        public void sendHeartbeat() {
1190            // heartbeats are no longer used
1191        }
1192
1193        public void onFinished(SyncResult result) {
1194            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "onFinished: " + this);
1195            // include "this" in the message so that the handler can ignore it if this
1196            // ActiveSyncContext is no longer the mActiveSyncContext at message handling
1197            // time
1198            sendSyncFinishedOrCanceledMessage(this, result);
1199        }
1200
1201        public void toString(StringBuilder sb) {
1202            sb.append("startTime ").append(mStartTime)
1203                    .append(", mTimeoutStartTime ").append(mTimeoutStartTime)
1204                    .append(", mHistoryRowId ").append(mHistoryRowId)
1205                    .append(", syncOperation ").append(mSyncOperation);
1206        }
1207
1208        public void onServiceConnected(ComponentName name, IBinder service) {
1209            Message msg = mSyncHandler.obtainMessage();
1210            msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
1211            msg.obj = new ServiceConnectionData(this, service);
1212            mSyncHandler.sendMessage(msg);
1213        }
1214
1215        public void onServiceDisconnected(ComponentName name) {
1216            Message msg = mSyncHandler.obtainMessage();
1217            msg.what = SyncHandler.MESSAGE_SERVICE_DISCONNECTED;
1218            msg.obj = new ServiceConnectionData(this, null);
1219            mSyncHandler.sendMessage(msg);
1220        }
1221
1222        boolean bindToSyncAdapter(ComponentName serviceComponent, int userId) {
1223            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1224                Log.d(TAG, "bindToSyncAdapter: " + serviceComponent + ", connection " + this);
1225            }
1226            Intent intent = new Intent();
1227            intent.setAction("android.content.SyncAdapter");
1228            intent.setComponent(serviceComponent);
1229            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1230                    com.android.internal.R.string.sync_binding_label);
1231            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivityAsUser(
1232                    mContext, 0, new Intent(Settings.ACTION_SYNC_SETTINGS), 0,
1233                    null, new UserHandle(userId)));
1234            mBound = true;
1235            final boolean bindResult = mContext.bindServiceAsUser(intent, this,
1236                    Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND
1237                    | Context.BIND_ALLOW_OOM_MANAGEMENT,
1238                    new UserHandle(mSyncOperation.target.userId));
1239            if (!bindResult) {
1240                mBound = false;
1241            } else {
1242                try {
1243                    mEventName = mSyncOperation.wakeLockName();
1244                    mBatteryStats.noteSyncStart(mEventName, mSyncAdapterUid);
1245                } catch (RemoteException e) {
1246                }
1247            }
1248            return bindResult;
1249        }
1250
1251        /**
1252         * Performs the required cleanup, which is the releasing of the wakelock and
1253         * unbinding from the sync adapter (if actually bound).
1254         */
1255        protected void close() {
1256            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1257                Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
1258            }
1259            if (mBound) {
1260                mBound = false;
1261                mContext.unbindService(this);
1262                try {
1263                    mBatteryStats.noteSyncFinish(mEventName, mSyncAdapterUid);
1264                } catch (RemoteException e) {
1265                }
1266            }
1267            mSyncWakeLock.release();
1268            mSyncWakeLock.setWorkSource(null);
1269        }
1270
1271        public String toString() {
1272            StringBuilder sb = new StringBuilder();
1273            toString(sb);
1274            return sb.toString();
1275        }
1276
1277        @Override
1278        public void binderDied() {
1279            sendSyncFinishedOrCanceledMessage(this, null);
1280        }
1281    }
1282
1283    protected void dump(FileDescriptor fd, PrintWriter pw) {
1284        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
1285        dumpSyncState(ipw);
1286        dumpSyncHistory(ipw);
1287        dumpSyncAdapters(ipw);
1288    }
1289
1290    static String formatTime(long time) {
1291        Time tobj = new Time();
1292        tobj.set(time);
1293        return tobj.format("%Y-%m-%d %H:%M:%S");
1294    }
1295
1296    protected void dumpSyncState(PrintWriter pw) {
1297        pw.print("data connected: "); pw.println(mDataConnectionIsConnected);
1298        pw.print("auto sync: ");
1299        List<UserInfo> users = getAllUsers();
1300        if (users != null) {
1301            for (UserInfo user : users) {
1302                pw.print("u" + user.id + "="
1303                        + mSyncStorageEngine.getMasterSyncAutomatically(user.id) + " ");
1304            }
1305            pw.println();
1306        }
1307        pw.print("memory low: "); pw.println(mStorageIsLow);
1308
1309        final AccountAndUser[] accounts = AccountManagerService.getSingleton().getAllAccounts();
1310
1311        pw.print("accounts: ");
1312        if (accounts != INITIAL_ACCOUNTS_ARRAY) {
1313            pw.println(accounts.length);
1314        } else {
1315            pw.println("not known yet");
1316        }
1317        final long now = SystemClock.elapsedRealtime();
1318        pw.print("now: "); pw.print(now);
1319        pw.println(" (" + formatTime(System.currentTimeMillis()) + ")");
1320        pw.print("offset: "); pw.print(DateUtils.formatElapsedTime(mSyncRandomOffsetMillis/1000));
1321        pw.println(" (HH:MM:SS)");
1322        pw.print("uptime: "); pw.print(DateUtils.formatElapsedTime(now/1000));
1323                pw.println(" (HH:MM:SS)");
1324        pw.print("time spent syncing: ");
1325                pw.print(DateUtils.formatElapsedTime(
1326                        mSyncHandler.mSyncTimeTracker.timeSpentSyncing() / 1000));
1327                pw.print(" (HH:MM:SS), sync ");
1328                pw.print(mSyncHandler.mSyncTimeTracker.mLastWasSyncing ? "" : "not ");
1329                pw.println("in progress");
1330        if (mSyncHandler.mAlarmScheduleTime != null) {
1331            pw.print("next alarm time: "); pw.print(mSyncHandler.mAlarmScheduleTime);
1332                    pw.print(" (");
1333                    pw.print(DateUtils.formatElapsedTime((mSyncHandler.mAlarmScheduleTime-now)/1000));
1334                    pw.println(" (HH:MM:SS) from now)");
1335        } else {
1336            pw.println("no alarm is scheduled (there had better not be any pending syncs)");
1337        }
1338
1339        pw.print("notification info: ");
1340        final StringBuilder sb = new StringBuilder();
1341        mSyncHandler.mSyncNotificationInfo.toString(sb);
1342        pw.println(sb.toString());
1343
1344        pw.println();
1345        pw.println("Active Syncs: " + mActiveSyncContexts.size());
1346        final PackageManager pm = mContext.getPackageManager();
1347        for (SyncManager.ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
1348            final long durationInSeconds = (now - activeSyncContext.mStartTime) / 1000;
1349            pw.print("  ");
1350            pw.print(DateUtils.formatElapsedTime(durationInSeconds));
1351            pw.print(" - ");
1352            pw.print(activeSyncContext.mSyncOperation.dump(pm, false));
1353            pw.println();
1354        }
1355
1356        synchronized (mSyncQueue) {
1357            sb.setLength(0);
1358            mSyncQueue.dump(sb);
1359            // Dump Pending Operations.
1360            getSyncStorageEngine().dumpPendingOperations(sb);
1361        }
1362
1363        pw.println();
1364        pw.print(sb.toString());
1365
1366        // join the installed sync adapter with the accounts list and emit for everything
1367        pw.println();
1368        pw.println("Sync Status");
1369        for (AccountAndUser account : accounts) {
1370            pw.printf("Account %s u%d %s\n",
1371                    account.account.name, account.userId, account.account.type);
1372
1373            pw.println("=======================================================================");
1374            final PrintTable table = new PrintTable(13);
1375            table.set(0, 0,
1376                    "Authority", // 0
1377                    "Syncable",  // 1
1378                    "Enabled",   // 2
1379                    "Delay",     // 3
1380                    "Loc",       // 4
1381                    "Poll",      // 5
1382                    "Per",       // 6
1383                    "Serv",      // 7
1384                    "User",      // 8
1385                    "Tot",       // 9
1386                    "Time",      // 10
1387                    "Last Sync", // 11
1388                    "Periodic"   // 12
1389            );
1390
1391            final List<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> sorted =
1392                    Lists.newArrayList();
1393            sorted.addAll(mSyncAdapters.getAllServices(account.userId));
1394            Collections.sort(sorted,
1395                    new Comparator<RegisteredServicesCache.ServiceInfo<SyncAdapterType>>() {
1396                @Override
1397                public int compare(RegisteredServicesCache.ServiceInfo<SyncAdapterType> lhs,
1398                        RegisteredServicesCache.ServiceInfo<SyncAdapterType> rhs) {
1399                    return lhs.type.authority.compareTo(rhs.type.authority);
1400                }
1401            });
1402            for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterType : sorted) {
1403                if (!syncAdapterType.type.accountType.equals(account.account.type)) {
1404                    continue;
1405                }
1406                int row = table.getNumRows();
1407                Pair<AuthorityInfo, SyncStatusInfo> syncAuthoritySyncStatus =
1408                        mSyncStorageEngine.getCopyOfAuthorityWithSyncStatus(
1409                                new SyncStorageEngine.EndPoint(
1410                                        account.account,
1411                                        syncAdapterType.type.authority,
1412                                        account.userId));
1413                SyncStorageEngine.AuthorityInfo settings = syncAuthoritySyncStatus.first;
1414                SyncStatusInfo status = syncAuthoritySyncStatus.second;
1415                String authority = settings.target.provider;
1416                if (authority.length() > 50) {
1417                    authority = authority.substring(authority.length() - 50);
1418                }
1419                table.set(row, 0, authority, settings.syncable, settings.enabled);
1420                table.set(row, 4,
1421                        status.numSourceLocal,
1422                        status.numSourcePoll,
1423                        status.numSourcePeriodic,
1424                        status.numSourceServer,
1425                        status.numSourceUser,
1426                        status.numSyncs,
1427                        DateUtils.formatElapsedTime(status.totalElapsedTime / 1000));
1428
1429
1430                for (int i = 0; i < settings.periodicSyncs.size(); i++) {
1431                    final PeriodicSync sync = settings.periodicSyncs.get(i);
1432                    final String period =
1433                            String.format("[p:%d s, f: %d s]", sync.period, sync.flexTime);
1434                    final String extras =
1435                            sync.extras.size() > 0 ?
1436                                    sync.extras.toString() : "Bundle[]";
1437                    final String next = "Next sync: " + formatTime(status.getPeriodicSyncTime(i)
1438                            + sync.period * 1000);
1439                    table.set(row + i * 2, 12, period + " " + extras);
1440                    table.set(row + i * 2 + 1, 12, next);
1441                }
1442
1443                int row1 = row;
1444                if (settings.delayUntil > now) {
1445                    table.set(row1++, 12, "D: " + (settings.delayUntil - now) / 1000);
1446                    if (settings.backoffTime > now) {
1447                        table.set(row1++, 12, "B: " + (settings.backoffTime - now) / 1000);
1448                        table.set(row1++, 12, settings.backoffDelay / 1000);
1449                    }
1450                }
1451
1452                if (status.lastSuccessTime != 0) {
1453                    table.set(row1++, 11, SyncStorageEngine.SOURCES[status.lastSuccessSource]
1454                            + " " + "SUCCESS");
1455                    table.set(row1++, 11, formatTime(status.lastSuccessTime));
1456                }
1457                if (status.lastFailureTime != 0) {
1458                    table.set(row1++, 11, SyncStorageEngine.SOURCES[status.lastFailureSource]
1459                            + " " + "FAILURE");
1460                    table.set(row1++, 11, formatTime(status.lastFailureTime));
1461                    //noinspection UnusedAssignment
1462                    table.set(row1++, 11, status.lastFailureMesg);
1463                }
1464            }
1465            table.writeTo(pw);
1466        }
1467    }
1468
1469    private String getLastFailureMessage(int code) {
1470        switch (code) {
1471            case ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS:
1472                return "sync already in progress";
1473
1474            case ContentResolver.SYNC_ERROR_AUTHENTICATION:
1475                return "authentication error";
1476
1477            case ContentResolver.SYNC_ERROR_IO:
1478                return "I/O error";
1479
1480            case ContentResolver.SYNC_ERROR_PARSE:
1481                return "parse error";
1482
1483            case ContentResolver.SYNC_ERROR_CONFLICT:
1484                return "conflict error";
1485
1486            case ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS:
1487                return "too many deletions error";
1488
1489            case ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES:
1490                return "too many retries error";
1491
1492            case ContentResolver.SYNC_ERROR_INTERNAL:
1493                return "internal error";
1494
1495            default:
1496                return "unknown";
1497        }
1498    }
1499
1500    private void dumpTimeSec(PrintWriter pw, long time) {
1501        pw.print(time/1000); pw.print('.'); pw.print((time/100)%10);
1502        pw.print('s');
1503    }
1504
1505    private void dumpDayStatistic(PrintWriter pw, SyncStorageEngine.DayStats ds) {
1506        pw.print("Success ("); pw.print(ds.successCount);
1507        if (ds.successCount > 0) {
1508            pw.print(" for "); dumpTimeSec(pw, ds.successTime);
1509            pw.print(" avg="); dumpTimeSec(pw, ds.successTime/ds.successCount);
1510        }
1511        pw.print(") Failure ("); pw.print(ds.failureCount);
1512        if (ds.failureCount > 0) {
1513            pw.print(" for "); dumpTimeSec(pw, ds.failureTime);
1514            pw.print(" avg="); dumpTimeSec(pw, ds.failureTime/ds.failureCount);
1515        }
1516        pw.println(")");
1517    }
1518
1519    protected void dumpSyncHistory(PrintWriter pw) {
1520        dumpRecentHistory(pw);
1521        dumpDayStatistics(pw);
1522    }
1523
1524    private void dumpRecentHistory(PrintWriter pw) {
1525        final ArrayList<SyncStorageEngine.SyncHistoryItem> items
1526                = mSyncStorageEngine.getSyncHistory();
1527        if (items != null && items.size() > 0) {
1528            final Map<String, AuthoritySyncStats> authorityMap = Maps.newHashMap();
1529            long totalElapsedTime = 0;
1530            long totalTimes = 0;
1531            final int N = items.size();
1532
1533            int maxAuthority = 0;
1534            int maxAccount = 0;
1535            for (SyncStorageEngine.SyncHistoryItem item : items) {
1536                SyncStorageEngine.AuthorityInfo authorityInfo
1537                        = mSyncStorageEngine.getAuthority(item.authorityId);
1538                final String authorityName;
1539                final String accountKey;
1540                if (authorityInfo != null) {
1541                    if (authorityInfo.target.target_provider) {
1542                        authorityName = authorityInfo.target.provider;
1543                        accountKey = authorityInfo.target.account.name + "/"
1544                                + authorityInfo.target.account.type
1545                                + " u" + authorityInfo.target.userId;
1546                    } else if (authorityInfo.target.target_service) {
1547                        authorityName = authorityInfo.target.service.getPackageName() + "/"
1548                                + authorityInfo.target.service.getClassName()
1549                                + " u" + authorityInfo.target.userId;
1550                        accountKey = "no account";
1551                    } else {
1552                        authorityName = "Unknown";
1553                        accountKey = "Unknown";
1554                    }
1555                } else {
1556                    authorityName = "Unknown";
1557                    accountKey = "Unknown";
1558                }
1559
1560                int length = authorityName.length();
1561                if (length > maxAuthority) {
1562                    maxAuthority = length;
1563                }
1564                length = accountKey.length();
1565                if (length > maxAccount) {
1566                    maxAccount = length;
1567                }
1568
1569                final long elapsedTime = item.elapsedTime;
1570                totalElapsedTime += elapsedTime;
1571                totalTimes++;
1572                AuthoritySyncStats authoritySyncStats = authorityMap.get(authorityName);
1573                if (authoritySyncStats == null) {
1574                    authoritySyncStats = new AuthoritySyncStats(authorityName);
1575                    authorityMap.put(authorityName, authoritySyncStats);
1576                }
1577                authoritySyncStats.elapsedTime += elapsedTime;
1578                authoritySyncStats.times++;
1579                final Map<String, AccountSyncStats> accountMap = authoritySyncStats.accountMap;
1580                AccountSyncStats accountSyncStats = accountMap.get(accountKey);
1581                if (accountSyncStats == null) {
1582                    accountSyncStats = new AccountSyncStats(accountKey);
1583                    accountMap.put(accountKey, accountSyncStats);
1584                }
1585                accountSyncStats.elapsedTime += elapsedTime;
1586                accountSyncStats.times++;
1587
1588            }
1589
1590            if (totalElapsedTime > 0) {
1591                pw.println();
1592                pw.printf("Detailed Statistics (Recent history):  "
1593                        + "%d (# of times) %ds (sync time)\n",
1594                        totalTimes, totalElapsedTime / 1000);
1595
1596                final List<AuthoritySyncStats> sortedAuthorities =
1597                        new ArrayList<AuthoritySyncStats>(authorityMap.values());
1598                Collections.sort(sortedAuthorities, new Comparator<AuthoritySyncStats>() {
1599                    @Override
1600                    public int compare(AuthoritySyncStats lhs, AuthoritySyncStats rhs) {
1601                        // reverse order
1602                        int compare = Integer.compare(rhs.times, lhs.times);
1603                        if (compare == 0) {
1604                            compare = Long.compare(rhs.elapsedTime, lhs.elapsedTime);
1605                        }
1606                        return compare;
1607                    }
1608                });
1609
1610                final int maxLength = Math.max(maxAuthority, maxAccount + 3);
1611                final int padLength = 2 + 2 + maxLength + 2 + 10 + 11;
1612                final char chars[] = new char[padLength];
1613                Arrays.fill(chars, '-');
1614                final String separator = new String(chars);
1615
1616                final String authorityFormat =
1617                        String.format("  %%-%ds: %%-9s  %%-11s\n", maxLength + 2);
1618                final String accountFormat =
1619                        String.format("    %%-%ds:   %%-9s  %%-11s\n", maxLength);
1620
1621                pw.println(separator);
1622                for (AuthoritySyncStats authoritySyncStats : sortedAuthorities) {
1623                    String name = authoritySyncStats.name;
1624                    long elapsedTime;
1625                    int times;
1626                    String timeStr;
1627                    String timesStr;
1628
1629                    elapsedTime = authoritySyncStats.elapsedTime;
1630                    times = authoritySyncStats.times;
1631                    timeStr = String.format("%ds/%d%%",
1632                            elapsedTime / 1000,
1633                            elapsedTime * 100 / totalElapsedTime);
1634                    timesStr = String.format("%d/%d%%",
1635                            times,
1636                            times * 100 / totalTimes);
1637                    pw.printf(authorityFormat, name, timesStr, timeStr);
1638
1639                    final List<AccountSyncStats> sortedAccounts =
1640                            new ArrayList<AccountSyncStats>(
1641                                    authoritySyncStats.accountMap.values());
1642                    Collections.sort(sortedAccounts, new Comparator<AccountSyncStats>() {
1643                        @Override
1644                        public int compare(AccountSyncStats lhs, AccountSyncStats rhs) {
1645                            // reverse order
1646                            int compare = Integer.compare(rhs.times, lhs.times);
1647                            if (compare == 0) {
1648                                compare = Long.compare(rhs.elapsedTime, lhs.elapsedTime);
1649                            }
1650                            return compare;
1651                        }
1652                    });
1653                    for (AccountSyncStats stats: sortedAccounts) {
1654                        elapsedTime = stats.elapsedTime;
1655                        times = stats.times;
1656                        timeStr = String.format("%ds/%d%%",
1657                                elapsedTime / 1000,
1658                                elapsedTime * 100 / totalElapsedTime);
1659                        timesStr = String.format("%d/%d%%",
1660                                times,
1661                                times * 100 / totalTimes);
1662                        pw.printf(accountFormat, stats.name, timesStr, timeStr);
1663                    }
1664                    pw.println(separator);
1665                }
1666            }
1667
1668            pw.println();
1669            pw.println("Recent Sync History");
1670            final String format = "  %-" + maxAccount + "s  %-" + maxAuthority + "s %s\n";
1671            final Map<String, Long> lastTimeMap = Maps.newHashMap();
1672            final PackageManager pm = mContext.getPackageManager();
1673            for (int i = 0; i < N; i++) {
1674                SyncStorageEngine.SyncHistoryItem item = items.get(i);
1675                SyncStorageEngine.AuthorityInfo authorityInfo
1676                        = mSyncStorageEngine.getAuthority(item.authorityId);
1677                final String authorityName;
1678                final String accountKey;
1679                if (authorityInfo != null) {
1680                    if (authorityInfo.target.target_provider) {
1681                        authorityName = authorityInfo.target.provider;
1682                        accountKey = authorityInfo.target.account.name + "/"
1683                                + authorityInfo.target.account.type
1684                                + " u" + authorityInfo.target.userId;
1685                    } else if (authorityInfo.target.target_service) {
1686                        authorityName = authorityInfo.target.service.getPackageName() + "/"
1687                                + authorityInfo.target.service.getClassName()
1688                                + " u" + authorityInfo.target.userId;
1689                        accountKey = "none";
1690                    } else {
1691                        authorityName = "Unknown";
1692                        accountKey = "Unknown";
1693                    }
1694                } else {
1695                    authorityName = "Unknown";
1696                    accountKey = "Unknown";
1697                }
1698                final long elapsedTime = item.elapsedTime;
1699                final Time time = new Time();
1700                final long eventTime = item.eventTime;
1701                time.set(eventTime);
1702
1703                final String key = authorityName + "/" + accountKey;
1704                final Long lastEventTime = lastTimeMap.get(key);
1705                final String diffString;
1706                if (lastEventTime == null) {
1707                    diffString = "";
1708                } else {
1709                    final long diff = (lastEventTime - eventTime) / 1000;
1710                    if (diff < 60) {
1711                        diffString = String.valueOf(diff);
1712                    } else if (diff < 3600) {
1713                        diffString = String.format("%02d:%02d", diff / 60, diff % 60);
1714                    } else {
1715                        final long sec = diff % 3600;
1716                        diffString = String.format("%02d:%02d:%02d",
1717                                diff / 3600, sec / 60, sec % 60);
1718                    }
1719                }
1720                lastTimeMap.put(key, eventTime);
1721
1722                pw.printf("  #%-3d: %s %8s  %5.1fs  %8s",
1723                        i + 1,
1724                        formatTime(eventTime),
1725                        SyncStorageEngine.SOURCES[item.source],
1726                        ((float) elapsedTime) / 1000,
1727                        diffString);
1728                pw.printf(format, accountKey, authorityName,
1729                        SyncOperation.reasonToString(pm, item.reason));
1730
1731                if (item.event != SyncStorageEngine.EVENT_STOP
1732                        || item.upstreamActivity != 0
1733                        || item.downstreamActivity != 0) {
1734                    pw.printf("    event=%d upstreamActivity=%d downstreamActivity=%d\n",
1735                            item.event,
1736                            item.upstreamActivity,
1737                            item.downstreamActivity);
1738                }
1739                if (item.mesg != null
1740                        && !SyncStorageEngine.MESG_SUCCESS.equals(item.mesg)) {
1741                    pw.printf("    mesg=%s\n", item.mesg);
1742                }
1743            }
1744            pw.println();
1745            pw.println("Recent Sync History Extras");
1746            for (int i = 0; i < N; i++) {
1747                final SyncStorageEngine.SyncHistoryItem item = items.get(i);
1748                final Bundle extras = item.extras;
1749                if (extras == null || extras.size() == 0) {
1750                    continue;
1751                }
1752                final SyncStorageEngine.AuthorityInfo authorityInfo
1753                        = mSyncStorageEngine.getAuthority(item.authorityId);
1754                final String authorityName;
1755                final String accountKey;
1756                if (authorityInfo != null) {
1757                    if (authorityInfo.target.target_provider) {
1758                        authorityName = authorityInfo.target.provider;
1759                        accountKey = authorityInfo.target.account.name + "/"
1760                                + authorityInfo.target.account.type
1761                                + " u" + authorityInfo.target.userId;
1762                    } else if (authorityInfo.target.target_service) {
1763                        authorityName = authorityInfo.target.service.getPackageName() + "/"
1764                                + authorityInfo.target.service.getClassName()
1765                                + " u" + authorityInfo.target.userId;
1766                        accountKey = "none";
1767                    } else {
1768                        authorityName = "Unknown";
1769                        accountKey = "Unknown";
1770                    }
1771                } else {
1772                    authorityName = "Unknown";
1773                    accountKey = "Unknown";
1774                }
1775                final Time time = new Time();
1776                final long eventTime = item.eventTime;
1777                time.set(eventTime);
1778
1779                pw.printf("  #%-3d: %s %8s ",
1780                        i + 1,
1781                        formatTime(eventTime),
1782                        SyncStorageEngine.SOURCES[item.source]);
1783
1784                pw.printf(format, accountKey, authorityName, extras);
1785            }
1786        }
1787    }
1788
1789    private void dumpDayStatistics(PrintWriter pw) {
1790        SyncStorageEngine.DayStats dses[] = mSyncStorageEngine.getDayStatistics();
1791        if (dses != null && dses[0] != null) {
1792            pw.println();
1793            pw.println("Sync Statistics");
1794            pw.print("  Today:  "); dumpDayStatistic(pw, dses[0]);
1795            int today = dses[0].day;
1796            int i;
1797            SyncStorageEngine.DayStats ds;
1798
1799            // Print each day in the current week.
1800            for (i=1; i<=6 && i < dses.length; i++) {
1801                ds = dses[i];
1802                if (ds == null) break;
1803                int delta = today-ds.day;
1804                if (delta > 6) break;
1805
1806                pw.print("  Day-"); pw.print(delta); pw.print(":  ");
1807                dumpDayStatistic(pw, ds);
1808            }
1809
1810            // Aggregate all following days into weeks and print totals.
1811            int weekDay = today;
1812            while (i < dses.length) {
1813                SyncStorageEngine.DayStats aggr = null;
1814                weekDay -= 7;
1815                while (i < dses.length) {
1816                    ds = dses[i];
1817                    if (ds == null) {
1818                        i = dses.length;
1819                        break;
1820                    }
1821                    int delta = weekDay-ds.day;
1822                    if (delta > 6) break;
1823                    i++;
1824
1825                    if (aggr == null) {
1826                        aggr = new SyncStorageEngine.DayStats(weekDay);
1827                    }
1828                    aggr.successCount += ds.successCount;
1829                    aggr.successTime += ds.successTime;
1830                    aggr.failureCount += ds.failureCount;
1831                    aggr.failureTime += ds.failureTime;
1832                }
1833                if (aggr != null) {
1834                    pw.print("  Week-"); pw.print((today-weekDay)/7); pw.print(": ");
1835                    dumpDayStatistic(pw, aggr);
1836                }
1837            }
1838        }
1839    }
1840
1841    private void dumpSyncAdapters(IndentingPrintWriter pw) {
1842        pw.println();
1843        final List<UserInfo> users = getAllUsers();
1844        if (users != null) {
1845            for (UserInfo user : users) {
1846                pw.println("Sync adapters for " + user + ":");
1847                pw.increaseIndent();
1848                for (RegisteredServicesCache.ServiceInfo<?> info :
1849                        mSyncAdapters.getAllServices(user.id)) {
1850                    pw.println(info);
1851                }
1852                pw.decreaseIndent();
1853                pw.println();
1854            }
1855        }
1856    }
1857
1858    private static class AuthoritySyncStats {
1859        String name;
1860        long elapsedTime;
1861        int times;
1862        Map<String, AccountSyncStats> accountMap = Maps.newHashMap();
1863
1864        private AuthoritySyncStats(String name) {
1865            this.name = name;
1866        }
1867    }
1868
1869    private static class AccountSyncStats {
1870        String name;
1871        long elapsedTime;
1872        int times;
1873
1874        private AccountSyncStats(String name) {
1875            this.name = name;
1876        }
1877    }
1878
1879    /**
1880     * A helper object to keep track of the time we have spent syncing since the last boot
1881     */
1882    private class SyncTimeTracker {
1883        /** True if a sync was in progress on the most recent call to update() */
1884        boolean mLastWasSyncing = false;
1885        /** Used to track when lastWasSyncing was last set */
1886        long mWhenSyncStarted = 0;
1887        /** The cumulative time we have spent syncing */
1888        private long mTimeSpentSyncing;
1889
1890        /** Call to let the tracker know that the sync state may have changed */
1891        public synchronized void update() {
1892            final boolean isSyncInProgress = !mActiveSyncContexts.isEmpty();
1893            if (isSyncInProgress == mLastWasSyncing) return;
1894            final long now = SystemClock.elapsedRealtime();
1895            if (isSyncInProgress) {
1896                mWhenSyncStarted = now;
1897            } else {
1898                mTimeSpentSyncing += now - mWhenSyncStarted;
1899            }
1900            mLastWasSyncing = isSyncInProgress;
1901        }
1902
1903        /** Get how long we have been syncing, in ms */
1904        public synchronized long timeSpentSyncing() {
1905            if (!mLastWasSyncing) return mTimeSpentSyncing;
1906
1907            final long now = SystemClock.elapsedRealtime();
1908            return mTimeSpentSyncing + (now - mWhenSyncStarted);
1909        }
1910    }
1911
1912    class ServiceConnectionData {
1913        public final ActiveSyncContext activeSyncContext;
1914        public final IBinder adapter;
1915
1916        ServiceConnectionData(ActiveSyncContext activeSyncContext, IBinder adapter) {
1917            this.activeSyncContext = activeSyncContext;
1918            this.adapter = adapter;
1919        }
1920    }
1921
1922    /**
1923     * Handles SyncOperation Messages that are posted to the associated
1924     * HandlerThread.
1925     */
1926    class SyncHandler extends Handler {
1927        // Messages that can be sent on mHandler
1928        private static final int MESSAGE_SYNC_FINISHED = 1;
1929        private static final int MESSAGE_SYNC_ALARM = 2;
1930        private static final int MESSAGE_CHECK_ALARMS = 3;
1931        private static final int MESSAGE_SERVICE_CONNECTED = 4;
1932        private static final int MESSAGE_SERVICE_DISCONNECTED = 5;
1933        private static final int MESSAGE_CANCEL = 6;
1934        /** Posted delayed in order to expire syncs that are long-running. */
1935        private static final int MESSAGE_SYNC_EXPIRED = 7;
1936
1937        public final SyncNotificationInfo mSyncNotificationInfo = new SyncNotificationInfo();
1938        private Long mAlarmScheduleTime = null;
1939        public final SyncTimeTracker mSyncTimeTracker = new SyncTimeTracker();
1940        private final HashMap<String, PowerManager.WakeLock> mWakeLocks = Maps.newHashMap();
1941
1942        private List<Message> mBootQueue = new ArrayList<Message>();
1943
1944      public void onBootCompleted() {
1945            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1946                Log.v(TAG, "Boot completed, clearing boot queue.");
1947            }
1948            doDatabaseCleanup();
1949            synchronized(this) {
1950                // Dispatch any stashed messages.
1951                for (Message message : mBootQueue) {
1952                    sendMessage(message);
1953                }
1954                mBootQueue = null;
1955                mBootCompleted = true;
1956            }
1957        }
1958
1959        private PowerManager.WakeLock getSyncWakeLock(SyncOperation operation) {
1960            final String wakeLockKey = operation.wakeLockName();
1961            PowerManager.WakeLock wakeLock = mWakeLocks.get(wakeLockKey);
1962            if (wakeLock == null) {
1963                final String name = SYNC_WAKE_LOCK_PREFIX + wakeLockKey;
1964                wakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
1965                wakeLock.setReferenceCounted(false);
1966                mWakeLocks.put(wakeLockKey, wakeLock);
1967            }
1968            return wakeLock;
1969        }
1970
1971        /**
1972         * Stash any messages that come to the handler before boot is complete.
1973         * {@link #onBootCompleted()} will disable this and dispatch all the messages collected.
1974         * @param msg Message to dispatch at a later point.
1975         * @return true if a message was enqueued, false otherwise. This is to avoid losing the
1976         * message if we manage to acquire the lock but by the time we do boot has completed.
1977         */
1978        private boolean tryEnqueueMessageUntilReadyToRun(Message msg) {
1979            synchronized (this) {
1980                if (!mBootCompleted) {
1981                    // Need to copy the message bc looper will recycle it.
1982                    mBootQueue.add(Message.obtain(msg));
1983                    return true;
1984                }
1985                return false;
1986            }
1987        }
1988
1989        /**
1990         * Used to keep track of whether a sync notification is active and who it is for.
1991         */
1992        class SyncNotificationInfo {
1993            // true iff the notification manager has been asked to send the notification
1994            public boolean isActive = false;
1995
1996            // Set when we transition from not running a sync to running a sync, and cleared on
1997            // the opposite transition.
1998            public Long startTime = null;
1999
2000            public void toString(StringBuilder sb) {
2001                sb.append("isActive ").append(isActive).append(", startTime ").append(startTime);
2002            }
2003
2004            @Override
2005            public String toString() {
2006                StringBuilder sb = new StringBuilder();
2007                toString(sb);
2008                return sb.toString();
2009            }
2010        }
2011
2012        public SyncHandler(Looper looper) {
2013            super(looper);
2014        }
2015
2016        public void handleMessage(Message msg) {
2017            if (tryEnqueueMessageUntilReadyToRun(msg)) {
2018                return;
2019            }
2020
2021            long earliestFuturePollTime = Long.MAX_VALUE;
2022            long nextPendingSyncTime = Long.MAX_VALUE;
2023            // Setting the value here instead of a method because we want the dumpsys logs
2024            // to have the most recent value used.
2025            try {
2026                mDataConnectionIsConnected = readDataConnectionState();
2027                mSyncManagerWakeLock.acquire();
2028                // Always do this first so that we be sure that any periodic syncs that
2029                // are ready to run have been converted into pending syncs. This allows the
2030                // logic that considers the next steps to take based on the set of pending syncs
2031                // to also take into account the periodic syncs.
2032                earliestFuturePollTime = scheduleReadyPeriodicSyncs();
2033                switch (msg.what) {
2034                    case SyncHandler.MESSAGE_SYNC_EXPIRED:
2035                        ActiveSyncContext expiredContext = (ActiveSyncContext) msg.obj;
2036                        if (Log.isLoggable(TAG, Log.DEBUG)) {
2037                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_EXPIRED: expiring "
2038                                    + expiredContext);
2039                        }
2040                        cancelActiveSync(expiredContext.mSyncOperation.target,
2041                                expiredContext.mSyncOperation.extras);
2042                        nextPendingSyncTime = maybeStartNextSyncLocked();
2043                        break;
2044
2045                    case SyncHandler.MESSAGE_CANCEL: {
2046                        SyncStorageEngine.EndPoint payload = (SyncStorageEngine.EndPoint) msg.obj;
2047                        Bundle extras = msg.peekData();
2048                        if (Log.isLoggable(TAG, Log.DEBUG)) {
2049                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CANCEL: "
2050                                    + payload + " bundle: " + extras);
2051                        }
2052                        cancelActiveSyncLocked(payload, extras);
2053                        nextPendingSyncTime = maybeStartNextSyncLocked();
2054                        break;
2055                    }
2056
2057                    case SyncHandler.MESSAGE_SYNC_FINISHED:
2058                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2059                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_FINISHED");
2060                        }
2061                        SyncHandlerMessagePayload payload = (SyncHandlerMessagePayload) msg.obj;
2062                        if (!isSyncStillActive(payload.activeSyncContext)) {
2063                            Log.d(TAG, "handleSyncHandlerMessage: dropping since the "
2064                                    + "sync is no longer active: "
2065                                    + payload.activeSyncContext);
2066                            break;
2067                        }
2068                        runSyncFinishedOrCanceledLocked(payload.syncResult,
2069                                payload.activeSyncContext);
2070
2071                        // since a sync just finished check if it is time to start a new sync
2072                        nextPendingSyncTime = maybeStartNextSyncLocked();
2073                        break;
2074
2075                    case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
2076                        ServiceConnectionData msgData = (ServiceConnectionData) msg.obj;
2077                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2078                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
2079                                    + msgData.activeSyncContext);
2080                        }
2081                        // check that this isn't an old message
2082                        if (isSyncStillActive(msgData.activeSyncContext)) {
2083                            runBoundToAdapter(
2084                                    msgData.activeSyncContext,
2085                                    msgData.adapter);
2086                        }
2087                        break;
2088                    }
2089
2090                    case SyncHandler.MESSAGE_SERVICE_DISCONNECTED: {
2091                        final ActiveSyncContext currentSyncContext =
2092                                ((ServiceConnectionData) msg.obj).activeSyncContext;
2093                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2094                            Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_DISCONNECTED: "
2095                                    + currentSyncContext);
2096                        }
2097                        // check that this isn't an old message
2098                        if (isSyncStillActive(currentSyncContext)) {
2099                            // cancel the sync if we have a syncadapter, which means one is
2100                            // outstanding
2101                            try {
2102                                if (currentSyncContext.mSyncAdapter != null) {
2103                                    currentSyncContext.mSyncAdapter.cancelSync(currentSyncContext);
2104                                } else if (currentSyncContext.mSyncServiceAdapter != null) {
2105                                    currentSyncContext.mSyncServiceAdapter
2106                                        .cancelSync(currentSyncContext);
2107                                }
2108                            } catch (RemoteException e) {
2109                                // We don't need to retry this in this case.
2110                            }
2111
2112                            // pretend that the sync failed with an IOException,
2113                            // which is a soft error
2114                            SyncResult syncResult = new SyncResult();
2115                            syncResult.stats.numIoExceptions++;
2116                            runSyncFinishedOrCanceledLocked(syncResult, currentSyncContext);
2117
2118                            // since a sync just finished check if it is time to start a new sync
2119                            nextPendingSyncTime = maybeStartNextSyncLocked();
2120                        }
2121
2122                        break;
2123                    }
2124
2125                    case SyncHandler.MESSAGE_SYNC_ALARM: {
2126                        boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2127                        if (isLoggable) {
2128                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_SYNC_ALARM");
2129                        }
2130                        mAlarmScheduleTime = null;
2131                        try {
2132                            nextPendingSyncTime = maybeStartNextSyncLocked();
2133                        } finally {
2134                            mHandleAlarmWakeLock.release();
2135                        }
2136                        break;
2137                    }
2138
2139                    case SyncHandler.MESSAGE_CHECK_ALARMS:
2140                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2141                            Log.v(TAG, "handleSyncHandlerMessage: MESSAGE_CHECK_ALARMS");
2142                        }
2143                        nextPendingSyncTime = maybeStartNextSyncLocked();
2144                        break;
2145                }
2146            } finally {
2147                manageSyncNotificationLocked();
2148                manageSyncAlarmLocked(earliestFuturePollTime, nextPendingSyncTime);
2149                mSyncTimeTracker.update();
2150                mSyncManagerWakeLock.release();
2151            }
2152        }
2153
2154        private boolean isDispatchable(SyncStorageEngine.EndPoint target) {
2155            final boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2156            if (target.target_provider) {
2157                // skip the sync if the account of this operation no longer exists
2158                AccountAndUser[] accounts = mRunningAccounts;
2159                if (!containsAccountAndUser(
2160                        accounts, target.account, target.userId)) {
2161                    return false;
2162                }
2163                if (!mSyncStorageEngine.getMasterSyncAutomatically(target.userId)
2164                        || !mSyncStorageEngine.getSyncAutomatically(
2165                                target.account,
2166                                target.userId,
2167                                target.provider)) {
2168                    if (isLoggable) {
2169                        Log.v(TAG, "    Not scheduling periodic operation: sync turned off.");
2170                    }
2171                    return false;
2172                }
2173                if (getIsSyncable(target.account, target.userId, target.provider)
2174                        == 0) {
2175                    if (isLoggable) {
2176                        Log.v(TAG, "    Not scheduling periodic operation: isSyncable == 0.");
2177                    }
2178                    return false;
2179                }
2180            } else if (target.target_service) {
2181                if (mSyncStorageEngine.getIsTargetServiceActive(target.service, target.userId)) {
2182                    if (isLoggable) {
2183                        Log.v(TAG, "   Not scheduling periodic operation: isEnabled == 0.");
2184                    }
2185                    return false;
2186                }
2187            }
2188            return true;
2189        }
2190
2191        /**
2192         * Turn any periodic sync operations that are ready to run into pending sync operations.
2193         * @return the desired start time of the earliest future periodic sync operation,
2194         * in milliseconds since boot
2195         */
2196        private long scheduleReadyPeriodicSyncs() {
2197            final boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2198            if (isLoggable) {
2199                Log.v(TAG, "scheduleReadyPeriodicSyncs");
2200            }
2201            long earliestFuturePollTime = Long.MAX_VALUE;
2202
2203            final long nowAbsolute = System.currentTimeMillis();
2204            final long shiftedNowAbsolute = (0 < nowAbsolute - mSyncRandomOffsetMillis)
2205                    ? (nowAbsolute - mSyncRandomOffsetMillis) : 0;
2206
2207            ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos = mSyncStorageEngine
2208                    .getCopyOfAllAuthoritiesWithSyncStatus();
2209            for (Pair<AuthorityInfo, SyncStatusInfo> info : infos) {
2210                final AuthorityInfo authorityInfo = info.first;
2211                final SyncStatusInfo status = info.second;
2212
2213                if (TextUtils.isEmpty(authorityInfo.target.provider)) {
2214                    Log.e(TAG, "Got an empty provider string. Skipping: "
2215                        + authorityInfo.target.provider);
2216                    continue;
2217                }
2218
2219                if (!isDispatchable(authorityInfo.target)) {
2220                    continue;
2221                }
2222
2223                for (int i = 0, N = authorityInfo.periodicSyncs.size(); i < N; i++) {
2224                    final PeriodicSync sync = authorityInfo.periodicSyncs.get(i);
2225                    final Bundle extras = sync.extras;
2226                    final Long periodInMillis = sync.period * 1000;
2227                    final Long flexInMillis = sync.flexTime * 1000;
2228                    // Skip if the period is invalid.
2229                    if (periodInMillis <= 0) {
2230                        continue;
2231                    }
2232                    // Find when this periodic sync was last scheduled to run.
2233                    final long lastPollTimeAbsolute = status.getPeriodicSyncTime(i);
2234                    final long shiftedLastPollTimeAbsolute =
2235                            (0 < lastPollTimeAbsolute - mSyncRandomOffsetMillis) ?
2236                                    (lastPollTimeAbsolute - mSyncRandomOffsetMillis) : 0;
2237                    long remainingMillis
2238                        = periodInMillis - (shiftedNowAbsolute % periodInMillis);
2239                    long timeSinceLastRunMillis
2240                        = (nowAbsolute - lastPollTimeAbsolute);
2241                    // Schedule this periodic sync to run early if it's close enough to its next
2242                    // runtime, and far enough from its last run time.
2243                    // If we are early, there will still be time remaining in this period.
2244                    boolean runEarly = remainingMillis <= flexInMillis
2245                            && timeSinceLastRunMillis > periodInMillis - flexInMillis;
2246                    if (isLoggable) {
2247                        Log.v(TAG, "sync: " + i + " for " + authorityInfo.target + "."
2248                        + " period: " + (periodInMillis)
2249                        + " flex: " + (flexInMillis)
2250                        + " remaining: " + (remainingMillis)
2251                        + " time_since_last: " + timeSinceLastRunMillis
2252                        + " last poll absol: " + lastPollTimeAbsolute
2253                        + " last poll shifed: " + shiftedLastPollTimeAbsolute
2254                        + " shifted now: " + shiftedNowAbsolute
2255                        + " run_early: " + runEarly);
2256                    }
2257                    /*
2258                     * Sync scheduling strategy: Set the next periodic sync
2259                     * based on a random offset (in seconds). Also sync right
2260                     * now if any of the following cases hold and mark it as
2261                     * having been scheduled
2262                     * Case 1: This sync is ready to run now.
2263                     * Case 2: If the lastPollTimeAbsolute is in the
2264                     * future, sync now and reinitialize. This can happen for
2265                     * example if the user changed the time, synced and changed
2266                     * back.
2267                     * Case 3: If we failed to sync at the last scheduled time.
2268                     * Case 4: This sync is close enough to the time that we can schedule it.
2269                     */
2270                    if (remainingMillis == periodInMillis // Case 1
2271                            || lastPollTimeAbsolute > nowAbsolute // Case 2
2272                            || timeSinceLastRunMillis >= periodInMillis // Case 3
2273                            || runEarly) { // Case 4
2274                        // Sync now
2275                        SyncStorageEngine.EndPoint target = authorityInfo.target;
2276                        final Pair<Long, Long> backoff =
2277                                mSyncStorageEngine.getBackoff(target);
2278                        mSyncStorageEngine.setPeriodicSyncTime(authorityInfo.ident,
2279                                authorityInfo.periodicSyncs.get(i), nowAbsolute);
2280
2281                        if (target.target_provider) {
2282                            final RegisteredServicesCache.ServiceInfo<SyncAdapterType>
2283                                syncAdapterInfo = mSyncAdapters.getServiceInfo(
2284                                    SyncAdapterType.newKey(
2285                                            target.provider, target.account.type),
2286                                    target.userId);
2287                            if (syncAdapterInfo == null) {
2288                                continue;
2289                            }
2290                            scheduleSyncOperation(
2291                                    new SyncOperation(target.account, target.userId,
2292                                            SyncOperation.REASON_PERIODIC,
2293                                            SyncStorageEngine.SOURCE_PERIODIC,
2294                                            target.provider, extras,
2295                                            0 /* runtime */, 0 /* flex */,
2296                                            backoff != null ? backoff.first : 0,
2297                                            mSyncStorageEngine.getDelayUntilTime(target),
2298                                            syncAdapterInfo.type.allowParallelSyncs()));
2299                        } else if (target.target_service) {
2300                            scheduleSyncOperation(
2301                                    new SyncOperation(target.service, target.userId,
2302                                            SyncOperation.REASON_PERIODIC,
2303                                            SyncStorageEngine.SOURCE_PERIODIC,
2304                                            extras,
2305                                            0 /* runtime */,
2306                                            0 /* flex */,
2307                                            backoff != null ? backoff.first : 0,
2308                                            mSyncStorageEngine.getDelayUntilTime(target)));
2309                        }
2310                    }
2311                    // Compute when this periodic sync should next run.
2312                    long nextPollTimeAbsolute;
2313                    if (runEarly) {
2314                        // Add the time remaining so we don't get out of phase.
2315                        nextPollTimeAbsolute = nowAbsolute + periodInMillis + remainingMillis;
2316                    } else {
2317                        nextPollTimeAbsolute = nowAbsolute + remainingMillis;
2318                    }
2319                    if (nextPollTimeAbsolute < earliestFuturePollTime) {
2320                        earliestFuturePollTime = nextPollTimeAbsolute;
2321                    }
2322                }
2323            }
2324
2325            if (earliestFuturePollTime == Long.MAX_VALUE) {
2326                return Long.MAX_VALUE;
2327            }
2328
2329            // convert absolute time to elapsed time
2330            return SystemClock.elapsedRealtime() +
2331                ((earliestFuturePollTime < nowAbsolute) ?
2332                    0 : (earliestFuturePollTime - nowAbsolute));
2333        }
2334
2335        private long maybeStartNextSyncLocked() {
2336            final boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2337            if (isLoggable) Log.v(TAG, "maybeStartNextSync");
2338
2339            // If we aren't ready to run (e.g. the data connection is down), get out.
2340            if (!mDataConnectionIsConnected) {
2341                if (isLoggable) {
2342                    Log.v(TAG, "maybeStartNextSync: no data connection, skipping");
2343                }
2344                return Long.MAX_VALUE;
2345            }
2346
2347            if (mStorageIsLow) {
2348                if (isLoggable) {
2349                    Log.v(TAG, "maybeStartNextSync: memory low, skipping");
2350                }
2351                return Long.MAX_VALUE;
2352            }
2353
2354            // If the accounts aren't known yet then we aren't ready to run. We will be kicked
2355            // when the account lookup request does complete.
2356            if (mRunningAccounts == INITIAL_ACCOUNTS_ARRAY) {
2357                if (isLoggable) {
2358                    Log.v(TAG, "maybeStartNextSync: accounts not known, skipping");
2359                }
2360                return Long.MAX_VALUE;
2361            }
2362
2363            // Otherwise consume SyncOperations from the head of the SyncQueue until one is
2364            // found that is runnable (not disabled, etc). If that one is ready to run then
2365            // start it, otherwise just get out.
2366            final long now = SystemClock.elapsedRealtime();
2367
2368            // will be set to the next time that a sync should be considered for running
2369            long nextReadyToRunTime = Long.MAX_VALUE;
2370
2371            // order the sync queue, dropping syncs that are not allowed
2372            ArrayList<SyncOperation> operations = new ArrayList<SyncOperation>();
2373            synchronized (mSyncQueue) {
2374                if (isLoggable) {
2375                    Log.v(TAG, "build the operation array, syncQueue size is "
2376                        + mSyncQueue.getOperations().size());
2377                }
2378                final Iterator<SyncOperation> operationIterator =
2379                        mSyncQueue.getOperations().iterator();
2380
2381                final ActivityManager activityManager
2382                        = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
2383                final Set<Integer> removedUsers = Sets.newHashSet();
2384                while (operationIterator.hasNext()) {
2385                    final SyncOperation op = operationIterator.next();
2386
2387                    // If the user is not running, skip the request.
2388                    if (!activityManager.isUserRunning(op.target.userId)) {
2389                        final UserInfo userInfo = mUserManager.getUserInfo(op.target.userId);
2390                        if (userInfo == null) {
2391                            removedUsers.add(op.target.userId);
2392                        }
2393                        if (isLoggable) {
2394                            Log.v(TAG, "    Dropping all sync operations for + "
2395                                    + op.target.userId + ": user not running.");
2396                        }
2397                        continue;
2398                    }
2399                    if (!isOperationValidLocked(op)) {
2400                        operationIterator.remove();
2401                        mSyncStorageEngine.deleteFromPending(op.pendingOperation);
2402                        continue;
2403                    }
2404                    // If the next run time is in the future, even given the flexible scheduling,
2405                    // return the time.
2406                    if (op.effectiveRunTime - op.flexTime > now) {
2407                        if (nextReadyToRunTime > op.effectiveRunTime) {
2408                            nextReadyToRunTime = op.effectiveRunTime;
2409                        }
2410                        if (isLoggable) {
2411                            Log.v(TAG, "    Not running sync operation: Sync too far in future."
2412                                    + "effective: " + op.effectiveRunTime + " flex: " + op.flexTime
2413                                    + " now: " + now);
2414                        }
2415                        continue;
2416                    }
2417                    // Add this sync to be run.
2418                    operations.add(op);
2419                }
2420
2421                for (Integer user : removedUsers) {
2422                    // if it's still removed
2423                    if (mUserManager.getUserInfo(user) == null) {
2424                        onUserRemoved(user);
2425                    }
2426                }
2427            }
2428
2429            // find the next operation to dispatch, if one is ready
2430            // iterate from the top, keep issuing (while potentially canceling existing syncs)
2431            // until the quotas are filled.
2432            // once the quotas are filled iterate once more to find when the next one would be
2433            // (also considering pre-emption reasons).
2434            if (isLoggable) Log.v(TAG, "sort the candidate operations, size " + operations.size());
2435            Collections.sort(operations);
2436            if (isLoggable) Log.v(TAG, "dispatch all ready sync operations");
2437            for (int i = 0, N = operations.size(); i < N; i++) {
2438                final SyncOperation candidate = operations.get(i);
2439                final boolean candidateIsInitialization = candidate.isInitialization();
2440
2441                int numInit = 0;
2442                int numRegular = 0;
2443                ActiveSyncContext conflict = null;
2444                ActiveSyncContext longRunning = null;
2445                ActiveSyncContext toReschedule = null;
2446                ActiveSyncContext oldestNonExpeditedRegular = null;
2447
2448                for (ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
2449                    final SyncOperation activeOp = activeSyncContext.mSyncOperation;
2450                    if (activeOp.isInitialization()) {
2451                        numInit++;
2452                    } else {
2453                        numRegular++;
2454                        if (!activeOp.isExpedited()) {
2455                            if (oldestNonExpeditedRegular == null
2456                                || (oldestNonExpeditedRegular.mStartTime
2457                                    > activeSyncContext.mStartTime)) {
2458                                oldestNonExpeditedRegular = activeSyncContext;
2459                            }
2460                        }
2461                    }
2462                    if (activeOp.isConflict(candidate)) {
2463                        conflict = activeSyncContext;
2464                        // don't break out since we want to do a full count of the varieties.
2465                    } else {
2466                        if (candidateIsInitialization == activeOp.isInitialization()
2467                                && activeSyncContext.mStartTime + MAX_TIME_PER_SYNC < now) {
2468                            longRunning = activeSyncContext;
2469                            // don't break out since we want to do a full count of the varieties
2470                        }
2471                    }
2472                }
2473
2474                if (isLoggable) {
2475                    Log.v(TAG, "candidate " + (i + 1) + " of " + N + ": " + candidate);
2476                    Log.v(TAG, "  numActiveInit=" + numInit + ", numActiveRegular=" + numRegular);
2477                    Log.v(TAG, "  longRunning: " + longRunning);
2478                    Log.v(TAG, "  conflict: " + conflict);
2479                    Log.v(TAG, "  oldestNonExpeditedRegular: " + oldestNonExpeditedRegular);
2480                }
2481
2482                final boolean roomAvailable = candidateIsInitialization
2483                        ? numInit < MAX_SIMULTANEOUS_INITIALIZATION_SYNCS
2484                        : numRegular < MAX_SIMULTANEOUS_REGULAR_SYNCS;
2485
2486                if (conflict != null) {
2487                    if (candidateIsInitialization && !conflict.mSyncOperation.isInitialization()
2488                            && numInit < MAX_SIMULTANEOUS_INITIALIZATION_SYNCS) {
2489                        toReschedule = conflict;
2490                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2491                            Log.v(TAG, "canceling and rescheduling sync since an initialization "
2492                                    + "takes higher priority, " + conflict);
2493                        }
2494                    } else if (candidate.isExpedited() && !conflict.mSyncOperation.isExpedited()
2495                            && (candidateIsInitialization
2496                                == conflict.mSyncOperation.isInitialization())) {
2497                        toReschedule = conflict;
2498                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2499                            Log.v(TAG, "canceling and rescheduling sync since an expedited "
2500                                    + "takes higher priority, " + conflict);
2501                        }
2502                    } else {
2503                        continue;
2504                    }
2505                } else if (roomAvailable) {
2506                    // dispatch candidate
2507                } else if (candidate.isExpedited() && oldestNonExpeditedRegular != null
2508                           && !candidateIsInitialization) {
2509                    // We found an active, non-expedited regular sync. We also know that the
2510                    // candidate doesn't conflict with this active sync since conflict
2511                    // is null. Reschedule the active sync and start the candidate.
2512                    toReschedule = oldestNonExpeditedRegular;
2513                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2514                        Log.v(TAG, "canceling and rescheduling sync since an expedited is ready to"
2515                                + " run, " + oldestNonExpeditedRegular);
2516                    }
2517                } else if (longRunning != null
2518                        && (candidateIsInitialization
2519                            == longRunning.mSyncOperation.isInitialization())) {
2520                    // We found an active, long-running sync. Reschedule the active
2521                    // sync and start the candidate.
2522                    toReschedule = longRunning;
2523                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2524                        Log.v(TAG, "canceling and rescheduling sync since it ran roo long, "
2525                              + longRunning);
2526                    }
2527                } else {
2528                    // we were unable to find or make space to run this candidate, go on to
2529                    // the next one
2530                    continue;
2531                }
2532
2533                if (toReschedule != null) {
2534                    runSyncFinishedOrCanceledLocked(null, toReschedule);
2535                    scheduleSyncOperation(toReschedule.mSyncOperation);
2536                }
2537                synchronized (mSyncQueue) {
2538                    mSyncQueue.remove(candidate);
2539                }
2540                dispatchSyncOperation(candidate);
2541            }
2542
2543            return nextReadyToRunTime;
2544        }
2545
2546        /**
2547         * Determine if a sync is no longer valid and should be dropped from the sync queue and its
2548         * pending op deleted.
2549         * @param op operation for which the sync is to be scheduled.
2550         */
2551        private boolean isOperationValidLocked(SyncOperation op) {
2552            final boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2553            int targetUid;
2554            int state;
2555            final SyncStorageEngine.EndPoint target = op.target;
2556            boolean syncEnabled = mSyncStorageEngine.getMasterSyncAutomatically(target.userId);
2557            if (target.target_provider) {
2558                // Drop the sync if the account of this operation no longer exists.
2559                AccountAndUser[] accounts = mRunningAccounts;
2560                if (!containsAccountAndUser(accounts, target.account, target.userId)) {
2561                    if (isLoggable) {
2562                        Log.v(TAG, "    Dropping sync operation: account doesn't exist.");
2563                    }
2564                    return false;
2565                }
2566                // Drop this sync request if it isn't syncable.
2567                state = getIsSyncable(target.account, target.userId, target.provider);
2568                if (state == 0) {
2569                    if (isLoggable) {
2570                        Log.v(TAG, "    Dropping sync operation: isSyncable == 0.");
2571                    }
2572                    return false;
2573                }
2574                syncEnabled = syncEnabled && mSyncStorageEngine.getSyncAutomatically(
2575                        target.account, target.userId, target.provider);
2576
2577                final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
2578                syncAdapterInfo = mSyncAdapters.getServiceInfo(
2579                        SyncAdapterType.newKey(
2580                                target.provider, target.account.type), target.userId);
2581                if (syncAdapterInfo != null) {
2582                    targetUid = syncAdapterInfo.uid;
2583                } else {
2584                    if (isLoggable) {
2585                        Log.v(TAG, "    Dropping sync operation: No sync adapter registered"
2586                                + "for: " + target);
2587                    }
2588                    return false;
2589                }
2590            } else if (target.target_service) {
2591                state = mSyncStorageEngine.getIsTargetServiceActive(target.service, target.userId)
2592                            ? 1 : 0;
2593                if (state == 0) {
2594                    // TODO: Change this to not drop disabled syncs - keep them in the pending queue.
2595                    if (isLoggable) {
2596                        Log.v(TAG, "    Dropping sync operation: isActive == 0.");
2597                    }
2598                    return false;
2599                }
2600                try {
2601                    targetUid = mContext.getPackageManager()
2602                            .getServiceInfo(target.service, 0)
2603                            .applicationInfo
2604                            .uid;
2605                } catch (PackageManager.NameNotFoundException e) {
2606                    if (isLoggable) {
2607                        Log.v(TAG, "    Dropping sync operation: No service registered for: "
2608                                + target.service);
2609                    }
2610                    return false;
2611                }
2612            } else {
2613                Log.e(TAG, "Unknown target for Sync Op: " + target);
2614                return false;
2615            }
2616
2617            // We ignore system settings that specify the sync is invalid if:
2618            // 1) It's manual - we try it anyway. When/if it fails it will be rescheduled.
2619            //      or
2620            // 2) it's an initialisation sync - we just need to connect to it.
2621            final boolean ignoreSystemConfiguration =
2622                    op.extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false)
2623                    || (state < 0);
2624
2625            // Sync not enabled.
2626            if (!syncEnabled && !ignoreSystemConfiguration) {
2627                if (isLoggable) {
2628                    Log.v(TAG, "    Dropping sync operation: disallowed by settings/network.");
2629                }
2630                return false;
2631            }
2632            // Network down.
2633            final NetworkInfo networkInfo = getConnectivityManager()
2634                    .getActiveNetworkInfoForUid(targetUid);
2635            final boolean uidNetworkConnected = networkInfo != null && networkInfo.isConnected();
2636            if (!uidNetworkConnected && !ignoreSystemConfiguration) {
2637                if (isLoggable) {
2638                    Log.v(TAG, "    Dropping sync operation: disallowed by settings/network.");
2639                }
2640                return false;
2641            }
2642            // Metered network.
2643            if (op.isNotAllowedOnMetered() && getConnectivityManager().isActiveNetworkMetered()
2644                    && !ignoreSystemConfiguration) {
2645                if (isLoggable) {
2646                    Log.v(TAG, "    Dropping sync operation: not allowed on metered network.");
2647                }
2648                return false;
2649            }
2650            return true;
2651        }
2652
2653        private boolean dispatchSyncOperation(SyncOperation op) {
2654            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2655                Log.v(TAG, "dispatchSyncOperation: we are going to sync " + op);
2656                Log.v(TAG, "num active syncs: " + mActiveSyncContexts.size());
2657                for (ActiveSyncContext syncContext : mActiveSyncContexts) {
2658                    Log.v(TAG, syncContext.toString());
2659                }
2660            }
2661            // Connect to the sync adapter.
2662            int targetUid;
2663            ComponentName targetComponent;
2664            final SyncStorageEngine.EndPoint info = op.target;
2665            if (info.target_provider) {
2666                SyncAdapterType syncAdapterType =
2667                        SyncAdapterType.newKey(info.provider, info.account.type);
2668                final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
2669                syncAdapterInfo = mSyncAdapters.getServiceInfo(syncAdapterType, info.userId);
2670                if (syncAdapterInfo == null) {
2671                    Log.d(TAG, "can't find a sync adapter for " + syncAdapterType
2672                            + ", removing settings for it");
2673                    mSyncStorageEngine.removeAuthority(info);
2674                    return false;
2675                }
2676                targetUid = syncAdapterInfo.uid;
2677                targetComponent = syncAdapterInfo.componentName;
2678            } else {
2679                // TODO: Store the uid of the service as part of the authority info in order to
2680                // avoid this call?
2681                try {
2682                    targetUid = mContext.getPackageManager()
2683                            .getServiceInfo(info.service, 0)
2684                            .applicationInfo
2685                            .uid;
2686                    targetComponent = info.service;
2687                } catch(PackageManager.NameNotFoundException e) {
2688                    Log.d(TAG, "Can't find a service for " + info.service
2689                            + ", removing settings for it");
2690                    mSyncStorageEngine.removeAuthority(info);
2691                    return false;
2692                }
2693            }
2694            ActiveSyncContext activeSyncContext =
2695                    new ActiveSyncContext(op, insertStartSyncEvent(op), targetUid);
2696            activeSyncContext.mSyncInfo = mSyncStorageEngine.addActiveSync(activeSyncContext);
2697            mActiveSyncContexts.add(activeSyncContext);
2698            if (!activeSyncContext.mSyncOperation.isInitialization() &&
2699                    !activeSyncContext.mSyncOperation.isExpedited() &&
2700                    !activeSyncContext.mSyncOperation.isManual() &&
2701                    !activeSyncContext.mSyncOperation.isIgnoreSettings()) {
2702                // Post message to expire this sync if it runs for too long.
2703                postSyncExpiryMessage(activeSyncContext);
2704            }
2705            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2706                Log.v(TAG, "dispatchSyncOperation: starting " + activeSyncContext);
2707            }
2708            if (!activeSyncContext.bindToSyncAdapter(targetComponent, info.userId)) {
2709                Log.e(TAG, "Bind attempt failed - target: " + targetComponent);
2710                closeActiveSyncContext(activeSyncContext);
2711                return false;
2712            }
2713
2714            return true;
2715        }
2716
2717        private void runBoundToAdapter(final ActiveSyncContext activeSyncContext,
2718                IBinder syncAdapter) {
2719            final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
2720            try {
2721                activeSyncContext.mIsLinkedToDeath = true;
2722                syncAdapter.linkToDeath(activeSyncContext, 0);
2723
2724                if (syncOperation.target.target_provider) {
2725                    activeSyncContext.mSyncAdapter = ISyncAdapter.Stub.asInterface(syncAdapter);
2726                    activeSyncContext.mSyncAdapter
2727                        .startSync(activeSyncContext, syncOperation.target.provider,
2728                                syncOperation.target.account, syncOperation.extras);
2729                } else if (syncOperation.target.target_service) {
2730                    activeSyncContext.mSyncServiceAdapter =
2731                            ISyncServiceAdapter.Stub.asInterface(syncAdapter);
2732                    activeSyncContext.mSyncServiceAdapter
2733                        .startSync(activeSyncContext, syncOperation.extras);
2734                }
2735            } catch (RemoteException remoteExc) {
2736                Log.d(TAG, "maybeStartNextSync: caught a RemoteException, rescheduling", remoteExc);
2737                closeActiveSyncContext(activeSyncContext);
2738                increaseBackoffSetting(syncOperation);
2739                scheduleSyncOperation(
2740                        new SyncOperation(syncOperation, 0L /* newRunTimeFromNow */));
2741            } catch (RuntimeException exc) {
2742                closeActiveSyncContext(activeSyncContext);
2743                Log.e(TAG, "Caught RuntimeException while starting the sync " + syncOperation, exc);
2744            }
2745        }
2746
2747        /**
2748         * Cancel the sync for the provided target that matches the given bundle.
2749         * @param info can have null fields to indicate all the active syncs for that field.
2750         */
2751        private void cancelActiveSyncLocked(SyncStorageEngine.EndPoint info, Bundle extras) {
2752            ArrayList<ActiveSyncContext> activeSyncs =
2753                    new ArrayList<ActiveSyncContext>(mActiveSyncContexts);
2754            for (ActiveSyncContext activeSyncContext : activeSyncs) {
2755                if (activeSyncContext != null) {
2756                    final SyncStorageEngine.EndPoint opInfo =
2757                            activeSyncContext.mSyncOperation.target;
2758                    if (!opInfo.matchesSpec(info)) {
2759                        continue;
2760                    }
2761                    if (extras != null &&
2762                            !syncExtrasEquals(activeSyncContext.mSyncOperation.extras,
2763                                    extras,
2764                                    false /* no config settings */)) {
2765                        continue;
2766                    }
2767                    runSyncFinishedOrCanceledLocked(null /* no result since this is a cancel */,
2768                            activeSyncContext);
2769                }
2770            }
2771        }
2772
2773        private void runSyncFinishedOrCanceledLocked(SyncResult syncResult,
2774                ActiveSyncContext activeSyncContext) {
2775            boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
2776
2777            final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
2778            final SyncStorageEngine.EndPoint info = syncOperation.target;
2779
2780            if (activeSyncContext.mIsLinkedToDeath) {
2781                if (info.target_provider) {
2782                    activeSyncContext.mSyncAdapter.asBinder().unlinkToDeath(activeSyncContext, 0);
2783                } else {
2784                    activeSyncContext.mSyncServiceAdapter.asBinder()
2785                        .unlinkToDeath(activeSyncContext, 0);
2786                }
2787                activeSyncContext.mIsLinkedToDeath = false;
2788            }
2789            closeActiveSyncContext(activeSyncContext);
2790            final long elapsedTime = SystemClock.elapsedRealtime() - activeSyncContext.mStartTime;
2791            String historyMessage;
2792            int downstreamActivity;
2793            int upstreamActivity;
2794            if (syncResult != null) {
2795                if (isLoggable) {
2796                    Log.v(TAG, "runSyncFinishedOrCanceled [finished]: "
2797                            + syncOperation + ", result " + syncResult);
2798                }
2799
2800                if (!syncResult.hasError()) {
2801                    historyMessage = SyncStorageEngine.MESG_SUCCESS;
2802                    // TODO: set these correctly when the SyncResult is extended to include it
2803                    downstreamActivity = 0;
2804                    upstreamActivity = 0;
2805                    clearBackoffSetting(syncOperation);
2806                } else {
2807                    Log.d(TAG, "failed sync operation " + syncOperation + ", " + syncResult);
2808                    // the operation failed so increase the backoff time
2809                    increaseBackoffSetting(syncOperation);
2810                    // reschedule the sync if so indicated by the syncResult
2811                    maybeRescheduleSync(syncResult, syncOperation);
2812                    historyMessage = ContentResolver.syncErrorToString(
2813                            syncResultToErrorNumber(syncResult));
2814                    // TODO: set these correctly when the SyncResult is extended to include it
2815                    downstreamActivity = 0;
2816                    upstreamActivity = 0;
2817                }
2818                setDelayUntilTime(syncOperation, syncResult.delayUntil);
2819            } else {
2820                if (isLoggable) {
2821                    Log.v(TAG, "runSyncFinishedOrCanceled [canceled]: " + syncOperation);
2822                }
2823                if (activeSyncContext.mSyncAdapter != null) {
2824                    try {
2825                        activeSyncContext.mSyncAdapter.cancelSync(activeSyncContext);
2826                    } catch (RemoteException e) {
2827                        // we don't need to retry this in this case
2828                    }
2829                } else if (activeSyncContext.mSyncServiceAdapter != null) {
2830                    try {
2831                        activeSyncContext.mSyncServiceAdapter.cancelSync(activeSyncContext);
2832                    } catch (RemoteException e) {
2833                        // we don't need to retry this in this case
2834                    }
2835                }
2836                historyMessage = SyncStorageEngine.MESG_CANCELED;
2837                downstreamActivity = 0;
2838                upstreamActivity = 0;
2839            }
2840
2841            stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
2842                    upstreamActivity, downstreamActivity, elapsedTime);
2843            // Check for full-resync and schedule it after closing off the last sync.
2844            if (info.target_provider) {
2845                if (syncResult != null && syncResult.tooManyDeletions) {
2846                    installHandleTooManyDeletesNotification(info.account,
2847                            info.provider, syncResult.stats.numDeletes,
2848                            info.userId);
2849                } else {
2850                    mNotificationMgr.cancelAsUser(null,
2851                            info.account.hashCode() ^ info.provider.hashCode(),
2852                            new UserHandle(info.userId));
2853                }
2854                if (syncResult != null && syncResult.fullSyncRequested) {
2855                    scheduleSyncOperation(
2856                            new SyncOperation(info.account, info.userId,
2857                                syncOperation.reason,
2858                                syncOperation.syncSource, info.provider, new Bundle(),
2859                                0 /* delay */, 0 /* flex */,
2860                                syncOperation.backoff, syncOperation.delayUntil,
2861                                syncOperation.allowParallelSyncs));
2862                }
2863            } else {
2864                if (syncResult != null && syncResult.fullSyncRequested) {
2865                    scheduleSyncOperation(
2866                            new SyncOperation(info.service, info.userId,
2867                                syncOperation.reason,
2868                                syncOperation.syncSource, new Bundle(),
2869                                0 /* delay */, 0 /* flex */,
2870                                syncOperation.backoff, syncOperation.delayUntil));
2871                }
2872            }
2873            // no need to schedule an alarm, as that will be done by our caller.
2874        }
2875
2876        private void closeActiveSyncContext(ActiveSyncContext activeSyncContext) {
2877            activeSyncContext.close();
2878            mActiveSyncContexts.remove(activeSyncContext);
2879            mSyncStorageEngine.removeActiveSync(activeSyncContext.mSyncInfo,
2880                    activeSyncContext.mSyncOperation.target.userId);
2881            removeSyncExpiryMessage(activeSyncContext);
2882        }
2883
2884        /**
2885         * Convert the error-containing SyncResult into the Sync.History error number. Since
2886         * the SyncResult may indicate multiple errors at once, this method just returns the
2887         * most "serious" error.
2888         * @param syncResult the SyncResult from which to read
2889         * @return the most "serious" error set in the SyncResult
2890         * @throws IllegalStateException if the SyncResult does not indicate any errors.
2891         *   If SyncResult.error() is true then it is safe to call this.
2892         */
2893        private int syncResultToErrorNumber(SyncResult syncResult) {
2894            if (syncResult.syncAlreadyInProgress)
2895                return ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
2896            if (syncResult.stats.numAuthExceptions > 0)
2897                return ContentResolver.SYNC_ERROR_AUTHENTICATION;
2898            if (syncResult.stats.numIoExceptions > 0)
2899                return ContentResolver.SYNC_ERROR_IO;
2900            if (syncResult.stats.numParseExceptions > 0)
2901                return ContentResolver.SYNC_ERROR_PARSE;
2902            if (syncResult.stats.numConflictDetectedExceptions > 0)
2903                return ContentResolver.SYNC_ERROR_CONFLICT;
2904            if (syncResult.tooManyDeletions)
2905                return ContentResolver.SYNC_ERROR_TOO_MANY_DELETIONS;
2906            if (syncResult.tooManyRetries)
2907                return ContentResolver.SYNC_ERROR_TOO_MANY_RETRIES;
2908            if (syncResult.databaseError)
2909                return ContentResolver.SYNC_ERROR_INTERNAL;
2910            throw new IllegalStateException("we are not in an error state, " + syncResult);
2911        }
2912
2913        private void manageSyncNotificationLocked() {
2914            boolean shouldCancel;
2915            boolean shouldInstall;
2916
2917            if (mActiveSyncContexts.isEmpty()) {
2918                mSyncNotificationInfo.startTime = null;
2919
2920                // we aren't syncing. if the notification is active then remember that we need
2921                // to cancel it and then clear out the info
2922                shouldCancel = mSyncNotificationInfo.isActive;
2923                shouldInstall = false;
2924            } else {
2925                // we are syncing
2926                final long now = SystemClock.elapsedRealtime();
2927                if (mSyncNotificationInfo.startTime == null) {
2928                    mSyncNotificationInfo.startTime = now;
2929                }
2930
2931                // there are three cases:
2932                // - the notification is up: do nothing
2933                // - the notification is not up but it isn't time yet: don't install
2934                // - the notification is not up and it is time: need to install
2935
2936                if (mSyncNotificationInfo.isActive) {
2937                    shouldInstall = shouldCancel = false;
2938                } else {
2939                    // it isn't currently up, so there is nothing to cancel
2940                    shouldCancel = false;
2941
2942                    final boolean timeToShowNotification =
2943                            now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY;
2944                    if (timeToShowNotification) {
2945                        shouldInstall = true;
2946                    } else {
2947                        // show the notification immediately if this is a manual sync
2948                        shouldInstall = false;
2949                        for (ActiveSyncContext activeSyncContext : mActiveSyncContexts) {
2950                            final boolean manualSync = activeSyncContext.mSyncOperation.extras
2951                                    .getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
2952                            if (manualSync) {
2953                                shouldInstall = true;
2954                                break;
2955                            }
2956                        }
2957                    }
2958                }
2959            }
2960
2961            if (shouldCancel && !shouldInstall) {
2962                mNeedSyncActiveNotification = false;
2963                sendSyncStateIntent();
2964                mSyncNotificationInfo.isActive = false;
2965            }
2966
2967            if (shouldInstall) {
2968                mNeedSyncActiveNotification = true;
2969                sendSyncStateIntent();
2970                mSyncNotificationInfo.isActive = true;
2971            }
2972        }
2973
2974        private void manageSyncAlarmLocked(long nextPeriodicEventElapsedTime,
2975                long nextPendingEventElapsedTime) {
2976            // in each of these cases the sync loop will be kicked, which will cause this
2977            // method to be called again
2978            if (!mDataConnectionIsConnected) return;
2979            if (mStorageIsLow) return;
2980
2981            // When the status bar notification should be raised
2982            final long notificationTime =
2983                    (!mSyncHandler.mSyncNotificationInfo.isActive
2984                            && mSyncHandler.mSyncNotificationInfo.startTime != null)
2985                            ? mSyncHandler.mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY
2986                            : Long.MAX_VALUE;
2987
2988            // When we should consider canceling an active sync
2989            long earliestTimeoutTime = Long.MAX_VALUE;
2990            for (ActiveSyncContext currentSyncContext : mActiveSyncContexts) {
2991                final long currentSyncTimeoutTime =
2992                        currentSyncContext.mTimeoutStartTime + MAX_TIME_PER_SYNC;
2993                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2994                    Log.v(TAG, "manageSyncAlarm: active sync, mTimeoutStartTime + MAX is "
2995                            + currentSyncTimeoutTime);
2996                }
2997                if (earliestTimeoutTime > currentSyncTimeoutTime) {
2998                    earliestTimeoutTime = currentSyncTimeoutTime;
2999                }
3000            }
3001
3002            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3003                Log.v(TAG, "manageSyncAlarm: notificationTime is " + notificationTime);
3004            }
3005
3006            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3007                Log.v(TAG, "manageSyncAlarm: earliestTimeoutTime is " + earliestTimeoutTime);
3008            }
3009
3010            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3011                Log.v(TAG, "manageSyncAlarm: nextPeriodicEventElapsedTime is "
3012                        + nextPeriodicEventElapsedTime);
3013            }
3014            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3015                Log.v(TAG, "manageSyncAlarm: nextPendingEventElapsedTime is "
3016                        + nextPendingEventElapsedTime);
3017            }
3018
3019            long alarmTime = Math.min(notificationTime, earliestTimeoutTime);
3020            alarmTime = Math.min(alarmTime, nextPeriodicEventElapsedTime);
3021            alarmTime = Math.min(alarmTime, nextPendingEventElapsedTime);
3022
3023            // Bound the alarm time.
3024            final long now = SystemClock.elapsedRealtime();
3025            if (alarmTime < now + SYNC_ALARM_TIMEOUT_MIN) {
3026                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3027                    Log.v(TAG, "manageSyncAlarm: the alarmTime is too small, "
3028                            + alarmTime + ", setting to " + (now + SYNC_ALARM_TIMEOUT_MIN));
3029                }
3030                alarmTime = now + SYNC_ALARM_TIMEOUT_MIN;
3031            } else if (alarmTime > now + SYNC_ALARM_TIMEOUT_MAX) {
3032                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3033                    Log.v(TAG, "manageSyncAlarm: the alarmTime is too large, "
3034                            + alarmTime + ", setting to " + (now + SYNC_ALARM_TIMEOUT_MIN));
3035                }
3036                alarmTime = now + SYNC_ALARM_TIMEOUT_MAX;
3037            }
3038
3039            // determine if we need to set or cancel the alarm
3040            boolean shouldSet = false;
3041            boolean shouldCancel = false;
3042            final boolean alarmIsActive = (mAlarmScheduleTime != null) && (now < mAlarmScheduleTime);
3043            final boolean needAlarm = alarmTime != Long.MAX_VALUE;
3044            if (needAlarm) {
3045                // Need the alarm if
3046                //  - it's currently not set
3047                //  - if the alarm is set in the past.
3048                if (!alarmIsActive || alarmTime < mAlarmScheduleTime) {
3049                    shouldSet = true;
3050                }
3051            } else {
3052                shouldCancel = alarmIsActive;
3053            }
3054
3055            // Set or cancel the alarm as directed.
3056            ensureAlarmService();
3057            if (shouldSet) {
3058                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3059                    Log.v(TAG, "requesting that the alarm manager wake us up at elapsed time "
3060                            + alarmTime + ", now is " + now + ", " + ((alarmTime - now) / 1000)
3061                            + " secs from now");
3062                }
3063                mAlarmScheduleTime = alarmTime;
3064                mAlarmService.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime,
3065                        mSyncAlarmIntent);
3066            } else if (shouldCancel) {
3067                mAlarmScheduleTime = null;
3068                mAlarmService.cancel(mSyncAlarmIntent);
3069            }
3070        }
3071
3072        private void sendSyncStateIntent() {
3073            Intent syncStateIntent = new Intent(Intent.ACTION_SYNC_STATE_CHANGED);
3074            syncStateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3075            syncStateIntent.putExtra("active", mNeedSyncActiveNotification);
3076            syncStateIntent.putExtra("failing", false);
3077            mContext.sendBroadcastAsUser(syncStateIntent, UserHandle.OWNER);
3078        }
3079
3080        private void installHandleTooManyDeletesNotification(Account account, String authority,
3081                long numDeletes, int userId) {
3082            if (mNotificationMgr == null) return;
3083
3084            final ProviderInfo providerInfo = mContext.getPackageManager().resolveContentProvider(
3085                    authority, 0 /* flags */);
3086            if (providerInfo == null) {
3087                return;
3088            }
3089            CharSequence authorityName = providerInfo.loadLabel(mContext.getPackageManager());
3090
3091            Intent clickIntent = new Intent(mContext, SyncActivityTooManyDeletes.class);
3092            clickIntent.putExtra("account", account);
3093            clickIntent.putExtra("authority", authority);
3094            clickIntent.putExtra("provider", authorityName.toString());
3095            clickIntent.putExtra("numDeletes", numDeletes);
3096
3097            if (!isActivityAvailable(clickIntent)) {
3098                Log.w(TAG, "No activity found to handle too many deletes.");
3099                return;
3100            }
3101
3102            UserHandle user = new UserHandle(userId);
3103            final PendingIntent pendingIntent = PendingIntent
3104                    .getActivityAsUser(mContext, 0, clickIntent,
3105                            PendingIntent.FLAG_CANCEL_CURRENT, null, user);
3106
3107            CharSequence tooManyDeletesDescFormat = mContext.getResources().getText(
3108                    R.string.contentServiceTooManyDeletesNotificationDesc);
3109
3110            Context contextForUser = getContextForUser(user);
3111            Notification notification =
3112                new Notification(R.drawable.stat_notify_sync_error,
3113                        mContext.getString(R.string.contentServiceSync),
3114                        System.currentTimeMillis());
3115            notification.color = contextForUser.getResources().getColor(
3116                    com.android.internal.R.color.system_notification_accent_color);
3117            notification.setLatestEventInfo(contextForUser,
3118                    contextForUser.getString(R.string.contentServiceSyncNotificationTitle),
3119                    String.format(tooManyDeletesDescFormat.toString(), authorityName),
3120                    pendingIntent);
3121            notification.flags |= Notification.FLAG_ONGOING_EVENT;
3122            mNotificationMgr.notifyAsUser(null, account.hashCode() ^ authority.hashCode(),
3123                    notification, user);
3124        }
3125
3126        /**
3127         * Checks whether an activity exists on the system image for the given intent.
3128         *
3129         * @param intent The intent for an activity.
3130         * @return Whether or not an activity exists.
3131         */
3132        private boolean isActivityAvailable(Intent intent) {
3133            PackageManager pm = mContext.getPackageManager();
3134            List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
3135            int listSize = list.size();
3136            for (int i = 0; i < listSize; i++) {
3137                ResolveInfo resolveInfo = list.get(i);
3138                if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3139                        != 0) {
3140                    return true;
3141                }
3142            }
3143
3144            return false;
3145        }
3146
3147        public long insertStartSyncEvent(SyncOperation syncOperation) {
3148            final long now = System.currentTimeMillis();
3149            EventLog.writeEvent(2720,
3150                    syncOperation.toEventLog(SyncStorageEngine.EVENT_START));
3151            return mSyncStorageEngine.insertStartSyncEvent(syncOperation, now);
3152        }
3153
3154        public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage,
3155                int upstreamActivity, int downstreamActivity, long elapsedTime) {
3156            EventLog.writeEvent(2720,
3157                    syncOperation.toEventLog(SyncStorageEngine.EVENT_STOP));
3158            mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime,
3159                    resultMessage, downstreamActivity, upstreamActivity);
3160        }
3161    }
3162
3163    private boolean isSyncStillActive(ActiveSyncContext activeSyncContext) {
3164        for (ActiveSyncContext sync : mActiveSyncContexts) {
3165            if (sync == activeSyncContext) {
3166                return true;
3167            }
3168        }
3169        return false;
3170    }
3171
3172    /**
3173     * Sync extra comparison function.
3174     * @param b1 bundle to compare
3175     * @param b2 other bundle to compare
3176     * @param includeSyncSettings if false, ignore system settings in bundle.
3177     */
3178    public static boolean syncExtrasEquals(Bundle b1, Bundle b2, boolean includeSyncSettings) {
3179        if (b1 == b2) {
3180            return true;
3181        }
3182        // Exit early if we can.
3183        if (includeSyncSettings && b1.size() != b2.size()) {
3184            return false;
3185        }
3186        Bundle bigger = b1.size() > b2.size() ? b1 : b2;
3187        Bundle smaller = b1.size() > b2.size() ? b2 : b1;
3188        for (String key : bigger.keySet()) {
3189            if (!includeSyncSettings && isSyncSetting(key)) {
3190                continue;
3191            }
3192            if (!smaller.containsKey(key)) {
3193                return false;
3194            }
3195            if (!bigger.get(key).equals(smaller.get(key))) {
3196                return false;
3197            }
3198        }
3199        return true;
3200    }
3201
3202    /**
3203     * TODO: Get rid of this when we separate sync settings extras from dev specified extras.
3204     * @return true if the provided key is used by the SyncManager in scheduling the sync.
3205     */
3206    private static boolean isSyncSetting(String key) {
3207        if (key.equals(ContentResolver.SYNC_EXTRAS_EXPEDITED)) {
3208            return true;
3209        }
3210        if (key.equals(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS)) {
3211            return true;
3212        }
3213        if (key.equals(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF)) {
3214            return true;
3215        }
3216        if (key.equals(ContentResolver.SYNC_EXTRAS_DO_NOT_RETRY)) {
3217            return true;
3218        }
3219        if (key.equals(ContentResolver.SYNC_EXTRAS_MANUAL)) {
3220            return true;
3221        }
3222        if (key.equals(ContentResolver.SYNC_EXTRAS_UPLOAD)) {
3223            return true;
3224        }
3225        if (key.equals(ContentResolver.SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS)) {
3226            return true;
3227        }
3228        if (key.equals(ContentResolver.SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS)) {
3229            return true;
3230        }
3231        if (key.equals(ContentResolver.SYNC_EXTRAS_EXPECTED_UPLOAD)) {
3232            return true;
3233        }
3234        if (key.equals(ContentResolver.SYNC_EXTRAS_EXPECTED_DOWNLOAD)) {
3235            return true;
3236        }
3237        if (key.equals(ContentResolver.SYNC_EXTRAS_PRIORITY)) {
3238            return true;
3239        }
3240        if (key.equals(ContentResolver.SYNC_EXTRAS_DISALLOW_METERED)) {
3241            return true;
3242        }
3243        if (key.equals(ContentResolver.SYNC_EXTRAS_INITIALIZE)) {
3244            return true;
3245        }
3246        return false;
3247    }
3248
3249    static class PrintTable {
3250        private ArrayList<Object[]> mTable = Lists.newArrayList();
3251        private final int mCols;
3252
3253        PrintTable(int cols) {
3254            mCols = cols;
3255        }
3256
3257        void set(int row, int col, Object... values) {
3258            if (col + values.length > mCols) {
3259                throw new IndexOutOfBoundsException("Table only has " + mCols +
3260                        " columns. can't set " + values.length + " at column " + col);
3261            }
3262            for (int i = mTable.size(); i <= row; i++) {
3263                final Object[] list = new Object[mCols];
3264                mTable.add(list);
3265                for (int j = 0; j < mCols; j++) {
3266                    list[j] = "";
3267                }
3268            }
3269            System.arraycopy(values, 0, mTable.get(row), col, values.length);
3270        }
3271
3272        void writeTo(PrintWriter out) {
3273            final String[] formats = new String[mCols];
3274            int totalLength = 0;
3275            for (int col = 0; col < mCols; ++col) {
3276                int maxLength = 0;
3277                for (Object[] row : mTable) {
3278                    final int length = row[col].toString().length();
3279                    if (length > maxLength) {
3280                        maxLength = length;
3281                    }
3282                }
3283                totalLength += maxLength;
3284                formats[col] = String.format("%%-%ds", maxLength);
3285            }
3286            formats[mCols - 1] = "%s";
3287            printRow(out, formats, mTable.get(0));
3288            totalLength += (mCols - 1) * 2;
3289            for (int i = 0; i < totalLength; ++i) {
3290                out.print("-");
3291            }
3292            out.println();
3293            for (int i = 1, mTableSize = mTable.size(); i < mTableSize; i++) {
3294                Object[] row = mTable.get(i);
3295                printRow(out, formats, row);
3296            }
3297        }
3298
3299        private void printRow(PrintWriter out, String[] formats, Object[] row) {
3300            for (int j = 0, rowLength = row.length; j < rowLength; j++) {
3301                out.printf(String.format(formats[j], row[j].toString()));
3302                out.print("  ");
3303            }
3304            out.println();
3305        }
3306
3307        public int getNumRows() {
3308            return mTable.size();
3309        }
3310    }
3311
3312    private Context getContextForUser(UserHandle user) {
3313        try {
3314            return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
3315        } catch (NameNotFoundException e) {
3316            // Default to mContext, not finding the package system is running as is unlikely.
3317            return mContext;
3318        }
3319    }
3320}
3321