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