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