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