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