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