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