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