This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
SyncManager.java
3507 lines (3189 loc) · 157 KB
/
SyncManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.content;
import android.accounts.Account;
import android.accounts.AccountAndUser;
import android.accounts.AccountManager;
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AppGlobals;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ISyncAdapter;
import android.content.ISyncContext;
import android.content.ISyncServiceAdapter;
import android.content.ISyncStatusObserver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.PeriodicSync;
import android.content.ServiceConnection;
import android.content.SyncActivityTooManyDeletes;
import android.content.SyncAdapterType;
import android.content.SyncAdaptersCache;
import android.content.SyncInfo;
import android.content.SyncResult;
import android.content.SyncStatusInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ProviderInfo;
import android.content.pm.RegisteredServicesCache;
import android.content.pm.RegisteredServicesCacheListener;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.os.BatteryStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.WorkSource;
import android.provider.Settings;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.util.Pair;
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.app.IBatteryStats;
import com.android.internal.os.BackgroundThread;
import com.android.internal.util.IndentingPrintWriter;
import com.android.server.accounts.AccountManagerService;
import com.android.server.content.SyncStorageEngine.AuthorityInfo;
import com.android.server.content.SyncStorageEngine.EndPoint;
import com.android.server.content.SyncStorageEngine.OnSyncRequestListener;
import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import com.google.android.collect.Sets;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
/**
* @hide
*/
public class SyncManager {
static final String TAG = "SyncManager";
/** Delay a sync due to local changes this long. In milliseconds */
private static final long LOCAL_SYNC_DELAY;
/**
* If a sync takes longer than this and the sync queue is not empty then we will
* cancel it and add it back to the end of the sync queue. In milliseconds.
*/
private static final long MAX_TIME_PER_SYNC;
static {
final boolean isLargeRAM = !ActivityManager.isLowRamDeviceStatic();
int defaultMaxInitSyncs = isLargeRAM ? 5 : 2;
int defaultMaxRegularSyncs = isLargeRAM ? 2 : 1;
MAX_SIMULTANEOUS_INITIALIZATION_SYNCS =
SystemProperties.getInt("sync.max_init_syncs", defaultMaxInitSyncs);
MAX_SIMULTANEOUS_REGULAR_SYNCS =
SystemProperties.getInt("sync.max_regular_syncs", defaultMaxRegularSyncs);
LOCAL_SYNC_DELAY =
SystemProperties.getLong("sync.local_sync_delay", 30 * 1000 /* 30 seconds */);
MAX_TIME_PER_SYNC =
SystemProperties.getLong("sync.max_time_per_sync", 5 * 60 * 1000 /* 5 minutes */);
SYNC_NOTIFICATION_DELAY =
SystemProperties.getLong("sync.notification_delay", 30 * 1000 /* 30 seconds */);
}
private static final long SYNC_NOTIFICATION_DELAY;
/**
* When retrying a sync for the first time use this delay. After that
* the retry time will double until it reached MAX_SYNC_RETRY_TIME.
* In milliseconds.
*/
private static final long INITIAL_SYNC_RETRY_TIME_IN_MS = 30 * 1000; // 30 seconds
/**
* Default the max sync retry time to this value.
*/
private static final long DEFAULT_MAX_SYNC_RETRY_TIME_IN_SECONDS = 60 * 60; // one hour
/**
* How long to wait before retrying a sync that failed due to one already being in progress.
*/
private static final int DELAY_RETRY_SYNC_IN_PROGRESS_IN_SECONDS = 10;
/**
* How long to wait before considering an active sync to have timed-out, and cancelling it.
*/
private static final long ACTIVE_SYNC_TIMEOUT_MILLIS = 30L * 60 * 1000; // 30 mins
/**
* How often to periodically poll network traffic for an adapter performing a sync to determine
* whether progress is being made.
*/
private static final long SYNC_MONITOR_WINDOW_LENGTH_MILLIS = 60 * 1000; // 60 seconds
/**
* How many bytes must be transferred (Tx + Rx) over the period of time defined by
* {@link #SYNC_MONITOR_WINDOW_LENGTH_MILLIS} for the sync to be considered to be making
* progress.
*/
private static final int SYNC_MONITOR_PROGRESS_THRESHOLD_BYTES = 10; // 10 bytes
/**
* How long to delay each queued {@link SyncHandler} message that may have occurred before boot
* or befor the device became provisioned.
*/
private static final long PER_SYNC_BOOT_DELAY_MILLIS = 3000L; // 3 seconds
/**
* The maximum amount of time we're willing to delay syncs out of boot, after device has been
* provisioned, etc.
*/
private static final long MAX_SYNC_BOOT_DELAY_MILLIS = 120000L; // 2 minutes
private static final String SYNC_WAKE_LOCK_PREFIX = "*sync*/";
private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarm";
private static final String SYNC_LOOP_WAKE_LOCK = "SyncLoopWakeLock";
private static final int MAX_SIMULTANEOUS_REGULAR_SYNCS;
private static final int MAX_SIMULTANEOUS_INITIALIZATION_SYNCS;
private Context mContext;
private static final AccountAndUser[] INITIAL_ACCOUNTS_ARRAY = new AccountAndUser[0];
// TODO: add better locking around mRunningAccounts
private volatile AccountAndUser[] mRunningAccounts = INITIAL_ACCOUNTS_ARRAY;
volatile private PowerManager.WakeLock mHandleAlarmWakeLock;
volatile private PowerManager.WakeLock mSyncManagerWakeLock;
volatile private boolean mDataConnectionIsConnected = false;
volatile private boolean mStorageIsLow = false;
volatile private boolean mDeviceIsIdle = false;
private final NotificationManager mNotificationMgr;
private AlarmManager mAlarmService = null;
private final IBatteryStats mBatteryStats;
private SyncStorageEngine mSyncStorageEngine;
@GuardedBy("mSyncQueue")
private final SyncQueue mSyncQueue;
protected final ArrayList<ActiveSyncContext> mActiveSyncContexts = Lists.newArrayList();
// set if the sync active indicator should be reported
private boolean mNeedSyncActiveNotification = false;
private final PendingIntent mSyncAlarmIntent;
// Synchronized on "this". Instead of using this directly one should instead call
// its accessor, getConnManager().
private ConnectivityManager mConnManagerDoNotUseDirectly;
/** Track whether the device has already been provisioned. */
private boolean mProvisioned;
protected SyncAdaptersCache mSyncAdapters;
private final AppIdleMonitor mAppIdleMonitor;
private BroadcastReceiver mStorageIntentReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Internal storage is low.");
}
mStorageIsLow = true;
cancelActiveSync(
SyncStorageEngine.EndPoint.USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL,
null /* any sync */);
} else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action)) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Internal storage is ok.");
}
mStorageIsLow = false;
sendCheckAlarmsMessage();
}
}
};
private BroadcastReceiver mDeviceIdleReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
boolean idle = mPowerManager.isDeviceIdleMode();
mDeviceIsIdle = idle;
if (idle) {
cancelActiveSync(
SyncStorageEngine.EndPoint.USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL,
null /* any sync */);
} else {
sendCheckAlarmsMessage();
}
}
};
private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mBootCompleted = true;
mSyncHandler.onBootCompleted();
}
};
private BroadcastReceiver mAccountsUpdatedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRunningAccounts();
// Kick off sync for everyone, since this was a radical account change
scheduleSync(null, UserHandle.USER_ALL, SyncOperation.REASON_ACCOUNTS_UPDATED, null,
null, 0 /* no delay */, 0/* no delay */, false);
}
};
private final PowerManager mPowerManager;
// Use this as a random offset to seed all periodic syncs.
private int mSyncRandomOffsetMillis;
private final UserManager mUserManager;
private static final long SYNC_ALARM_TIMEOUT_MIN = 30 * 1000; // 30 seconds
private List<UserInfo> getAllUsers() {
return mUserManager.getUsers();
}
private boolean containsAccountAndUser(AccountAndUser[] accounts, Account account, int userId) {
boolean found = false;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].userId == userId
&& accounts[i].account.equals(account)) {
found = true;
break;
}
}
return found;
}
public void updateRunningAccounts() {
mRunningAccounts = AccountManagerService.getSingleton().getRunningAccounts();
if (mBootCompleted) {
doDatabaseCleanup();
}
AccountAndUser[] accounts = mRunningAccounts;
for (ActiveSyncContext currentSyncContext : mActiveSyncContexts) {
if (!containsAccountAndUser(accounts,
currentSyncContext.mSyncOperation.target.account,
currentSyncContext.mSyncOperation.target.userId)) {
Log.d(TAG, "canceling sync since the account is no longer running");
sendSyncFinishedOrCanceledMessage(currentSyncContext,
null /* no result since this is a cancel */);
}
}
// we must do this since we don't bother scheduling alarms when
// the accounts are not set yet
sendCheckAlarmsMessage();
}
private void doDatabaseCleanup() {
for (UserInfo user : mUserManager.getUsers(true)) {
// Skip any partially created/removed users
if (user.partial) continue;
Account[] accountsForUser = AccountManagerService.getSingleton().getAccounts(
user.id, mContext.getOpPackageName());
mSyncStorageEngine.doDatabaseCleanup(accountsForUser, user.id);
}
}
private BroadcastReceiver mConnectivityIntentReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final boolean wasConnected = mDataConnectionIsConnected;
// don't use the intent to figure out if network is connected, just check
// ConnectivityManager directly.
mDataConnectionIsConnected = readDataConnectionState();
if (mDataConnectionIsConnected) {
if (!wasConnected) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Reconnection detected: clearing all backoffs");
}
synchronized (mSyncQueue) {
mSyncStorageEngine.clearAllBackoffsLocked(mSyncQueue);
}
}
sendCheckAlarmsMessage();
}
}
};
private boolean readDataConnectionState() {
NetworkInfo networkInfo = getConnectivityManager().getActiveNetworkInfo();
return (networkInfo != null) && networkInfo.isConnected();
}
private BroadcastReceiver mShutdownIntentReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "Writing sync state before shutdown...");
getSyncStorageEngine().writeAllState();
}
};
private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
if (userId == UserHandle.USER_NULL) return;
if (Intent.ACTION_USER_REMOVED.equals(action)) {
onUserRemoved(userId);
} else if (Intent.ACTION_USER_STARTING.equals(action)) {
onUserStarting(userId);
} else if (Intent.ACTION_USER_STOPPING.equals(action)) {
onUserStopping(userId);
}
}
};
private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM";
private final SyncHandler mSyncHandler;
private volatile boolean mBootCompleted = false;
private ConnectivityManager getConnectivityManager() {
synchronized (this) {
if (mConnManagerDoNotUseDirectly == null) {
mConnManagerDoNotUseDirectly = (ConnectivityManager)mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
}
return mConnManagerDoNotUseDirectly;
}
}
/**
* Should only be created after {@link ContentService#systemReady()} so that
* {@link PackageManager} is ready to query.
*/
public SyncManager(Context context, boolean factoryTest) {
// Initialize the SyncStorageEngine first, before registering observers
// and creating threads and so on; it may fail if the disk is full.
mContext = context;
SyncStorageEngine.init(context);
mSyncStorageEngine = SyncStorageEngine.getSingleton();
mSyncStorageEngine.setOnSyncRequestListener(new OnSyncRequestListener() {
@Override
public void onSyncRequest(SyncStorageEngine.EndPoint info, int reason, Bundle extras) {
if (info.target_provider) {
scheduleSync(info.account, info.userId, reason, info.provider, extras,
0 /* no flex */,
0 /* run immediately */,
false);
} else if (info.target_service) {
scheduleSync(info.service, info.userId, reason, extras,
0 /* no flex */,
0 /* run immediately */);
}
}
});
mSyncAdapters = new SyncAdaptersCache(mContext);
mSyncQueue = new SyncQueue(mContext.getPackageManager(), mSyncStorageEngine, mSyncAdapters);
mSyncHandler = new SyncHandler(BackgroundThread.get().getLooper());
mSyncAdapters.setListener(new RegisteredServicesCacheListener<SyncAdapterType>() {
@Override
public void onServiceChanged(SyncAdapterType type, int userId, boolean removed) {
if (!removed) {
scheduleSync(null, UserHandle.USER_ALL,
SyncOperation.REASON_SERVICE_CHANGED,
type.authority, null, 0 /* no delay */, 0 /* no delay */,
false /* onlyThoseWithUnkownSyncableState */);
}
}
}, mSyncHandler);
mSyncAlarmIntent = PendingIntent.getBroadcast(
mContext, 0 /* ignored */, new Intent(ACTION_SYNC_ALARM), 0);
mAppIdleMonitor = new AppIdleMonitor(this);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(mConnectivityIntentReceiver, intentFilter);
if (!factoryTest) {
intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
context.registerReceiver(mBootCompletedReceiver, intentFilter);
}
intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
context.registerReceiver(mStorageIntentReceiver, intentFilter);
intentFilter = new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
context.registerReceiver(mDeviceIdleReceiver, intentFilter);
intentFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
intentFilter.setPriority(100);
context.registerReceiver(mShutdownIntentReceiver, intentFilter);
intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_USER_REMOVED);
intentFilter.addAction(Intent.ACTION_USER_STARTING);
intentFilter.addAction(Intent.ACTION_USER_STOPPING);
mContext.registerReceiverAsUser(
mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
if (!factoryTest) {
mNotificationMgr = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
context.registerReceiver(new SyncAlarmIntentReceiver(),
new IntentFilter(ACTION_SYNC_ALARM));
} else {
mNotificationMgr = null;
}
mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
BatteryStats.SERVICE_NAME));
// This WakeLock is used to ensure that we stay awake between the time that we receive
// a sync alarm notification and when we finish processing it. We need to do this
// because we don't do the work in the alarm handler, rather we do it in a message
// handler.
mHandleAlarmWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
HANDLE_SYNC_ALARM_WAKE_LOCK);
mHandleAlarmWakeLock.setReferenceCounted(false);
// This WakeLock is used to ensure that we stay awake while running the sync loop
// message handler. Normally we will hold a sync adapter wake lock while it is being
// synced but during the execution of the sync loop it might finish a sync for
// one sync adapter before starting the sync for the other sync adapter and we
// don't want the device to go to sleep during that window.
mSyncManagerWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
SYNC_LOOP_WAKE_LOCK);
mSyncManagerWakeLock.setReferenceCounted(false);
mSyncStorageEngine.addStatusChangeListener(
ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, new ISyncStatusObserver.Stub() {
@Override
public void onStatusChanged(int which) {
// force the sync loop to run if the settings change
sendCheckAlarmsMessage();
}
});
mProvisioned = isDeviceProvisioned();
if (!mProvisioned) {
final ContentResolver resolver = context.getContentResolver();
ContentObserver provisionedObserver =
new ContentObserver(null /* current thread */) {
public void onChange(boolean selfChange) {
mProvisioned |= isDeviceProvisioned();
if (mProvisioned) {
mSyncHandler.onDeviceProvisioned();
resolver.unregisterContentObserver(this);
}
}
};
synchronized (mSyncHandler) {
resolver.registerContentObserver(
Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED),
false /* notifyForDescendents */,
provisionedObserver);
// The device *may* have been provisioned while we were registering above observer.
// Check again to make sure.
mProvisioned |= isDeviceProvisioned();
if (mProvisioned) {
resolver.unregisterContentObserver(provisionedObserver);
}
}
}
if (!factoryTest) {
// Register for account list updates for all users
mContext.registerReceiverAsUser(mAccountsUpdatedReceiver,
UserHandle.ALL,
new IntentFilter(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION),
null, null);
}
// Pick a random second in a day to seed all periodic syncs
mSyncRandomOffsetMillis = mSyncStorageEngine.getSyncRandomOffset() * 1000;
}
private boolean isDeviceProvisioned() {
final ContentResolver resolver = mContext.getContentResolver();
return (Settings.Global.getInt(resolver, Settings.Global.DEVICE_PROVISIONED, 0) != 0);
}
/**
* Return a random value v that satisfies minValue <= v < maxValue. The difference between
* maxValue and minValue must be less than Integer.MAX_VALUE.
*/
private long jitterize(long minValue, long maxValue) {
Random random = new Random(SystemClock.elapsedRealtime());
long spread = maxValue - minValue;
if (spread > Integer.MAX_VALUE) {
throw new IllegalArgumentException("the difference between the maxValue and the "
+ "minValue must be less than " + Integer.MAX_VALUE);
}
return minValue + random.nextInt((int)spread);
}
public SyncStorageEngine getSyncStorageEngine() {
return mSyncStorageEngine;
}
public int getIsSyncable(Account account, int userId, String providerName) {
int isSyncable = mSyncStorageEngine.getIsSyncable(account, userId, providerName);
UserInfo userInfo = UserManager.get(mContext).getUserInfo(userId);
// If it's not a restricted user, return isSyncable
if (userInfo == null || !userInfo.isRestricted()) return isSyncable;
// Else check if the sync adapter has opted-in or not
RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
mSyncAdapters.getServiceInfo(
SyncAdapterType.newKey(providerName, account.type), userId);
if (syncAdapterInfo == null) return isSyncable;
PackageInfo pInfo = null;
try {
pInfo = AppGlobals.getPackageManager().getPackageInfo(
syncAdapterInfo.componentName.getPackageName(), 0, userId);
if (pInfo == null) return isSyncable;
} catch (RemoteException re) {
// Shouldn't happen
return isSyncable;
}
if (pInfo.restrictedAccountType != null
&& pInfo.restrictedAccountType.equals(account.type)) {
return isSyncable;
} else {
return 0;
}
}
private void ensureAlarmService() {
if (mAlarmService == null) {
mAlarmService = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
}
}
/**
* Initiate a sync using the new anonymous service API.
* @param cname SyncService component bound to in order to perform the sync.
* @param userId the id of the user whose accounts are to be synced. If userId is USER_ALL,
* then all users' accounts are considered.
* @param uid Linux uid of the application that is performing the sync.
* @param extras a Map of SyncAdapter-specific information to control
* syncs of a specific provider. Cannot be null.
* @param beforeRunTimeMillis milliseconds before <code>runtimeMillis</code> that this sync may
* be run.
* @param runtimeMillis milliseconds from now by which this sync must be run.
*/
public void scheduleSync(ComponentName cname, int userId, int uid, Bundle extras,
long beforeRunTimeMillis, long runtimeMillis) {
boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
if (isLoggable) {
Log.d(TAG, "one off sync for: " + cname + " " + extras.toString());
}
Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
if (expedited) {
runtimeMillis = -1; // this means schedule at the front of the queue
}
final boolean ignoreSettings =
extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false);
int source = SyncStorageEngine.SOURCE_SERVICE;
boolean isEnabled = mSyncStorageEngine.getIsTargetServiceActive(cname, userId);
// Only schedule this sync if
// - we've explicitly been told to ignore settings.
// - global sync is enabled for this user.
boolean syncAllowed =
ignoreSettings
|| mSyncStorageEngine.getMasterSyncAutomatically(userId);
if (!syncAllowed) {
if (isLoggable) {
Log.d(TAG, "scheduleSync: sync of " + cname + " not allowed, dropping request.");
}
return;
}
if (!isEnabled) {
if (isLoggable) {
Log.d(TAG, "scheduleSync: " + cname + " is not enabled, dropping request");
}
return;
}
SyncStorageEngine.EndPoint info = new SyncStorageEngine.EndPoint(cname, userId);
Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(info);
long delayUntil = mSyncStorageEngine.getDelayUntilTime(info);
final long backoffTime = backoff != null ? backoff.first : 0;
if (isLoggable) {
Log.v(TAG, "schedule Sync:"
+ ", delay until " + delayUntil
+ ", run by " + runtimeMillis
+ ", flex " + beforeRunTimeMillis
+ ", source " + source
+ ", sync service " + cname
+ ", extras " + extras);
}
scheduleSyncOperation(
new SyncOperation(cname, userId, uid, source, extras,
runtimeMillis /* runtime */,
beforeRunTimeMillis /* flextime */,
backoffTime,
delayUntil));
}
/**
* Initiate a sync. This can start a sync for all providers
* (pass null to url, set onlyTicklable to false), only those
* providers that are marked as ticklable (pass null to url,
* set onlyTicklable to true), or a specific provider (set url
* to the content url of the provider).
*
* <p>If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is
* true then initiate a sync that just checks for local changes to send
* to the server, otherwise initiate a sync that first gets any
* changes from the server before sending local changes back to
* the server.
*
* <p>If a specific provider is being synced (the url is non-null)
* then the extras can contain SyncAdapter-specific information
* to control what gets synced (e.g. which specific feed to sync).
*
* <p>You'll start getting callbacks after this.
*
* @param requestedAccount the account to sync, may be null to signify all accounts
* @param userId the id of the user whose accounts are to be synced. If userId is USER_ALL,
* then all users' accounts are considered.
* @param reason for sync request. If this is a positive integer, it is the Linux uid
* assigned to the process that requested the sync. If it's negative, the sync was requested by
* the SyncManager itself and could be one of the following:
* {@link SyncOperation#REASON_BACKGROUND_DATA_SETTINGS_CHANGED}
* {@link SyncOperation#REASON_ACCOUNTS_UPDATED}
* {@link SyncOperation#REASON_SERVICE_CHANGED}
* {@link SyncOperation#REASON_PERIODIC}
* {@link SyncOperation#REASON_IS_SYNCABLE}
* {@link SyncOperation#REASON_SYNC_AUTO}
* {@link SyncOperation#REASON_MASTER_SYNC_AUTO}
* {@link SyncOperation#REASON_USER_START}
* @param requestedAuthority the authority to sync, may be null to indicate all authorities
* @param extras a Map of SyncAdapter-specific information to control
* syncs of a specific provider. Can be null. Is ignored
* if the url is null.
* @param beforeRuntimeMillis milliseconds before runtimeMillis that this sync can run.
* @param runtimeMillis maximum milliseconds in the future to wait before performing sync.
* @param onlyThoseWithUnkownSyncableState Only sync authorities that have unknown state.
*/
public void scheduleSync(Account requestedAccount, int userId, int reason,
String requestedAuthority, Bundle extras, long beforeRuntimeMillis,
long runtimeMillis, boolean onlyThoseWithUnkownSyncableState) {
boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE);
if (extras == null) {
extras = new Bundle();
}
if (isLoggable) {
Log.d(TAG, "one-time sync for: " + requestedAccount + " " + extras.toString() + " "
+ requestedAuthority);
}
Boolean expedited = extras.getBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
if (expedited) {
runtimeMillis = -1; // this means schedule at the front of the queue
}
AccountAndUser[] accounts;
if (requestedAccount != null && userId != UserHandle.USER_ALL) {
accounts = new AccountAndUser[] { new AccountAndUser(requestedAccount, userId) };
} else {
accounts = mRunningAccounts;
if (accounts.length == 0) {
if (isLoggable) {
Log.v(TAG, "scheduleSync: no accounts configured, dropping");
}
return;
}
}
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
if (manualSync) {
extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, true);
}
final boolean ignoreSettings =
extras.getBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, false);
int source;
if (uploadOnly) {
source = SyncStorageEngine.SOURCE_LOCAL;
} else if (manualSync) {
source = SyncStorageEngine.SOURCE_USER;
} else if (requestedAuthority == null) {
source = SyncStorageEngine.SOURCE_POLL;
} else {
// this isn't strictly server, since arbitrary callers can (and do) request
// a non-forced two-way sync on a specific url
source = SyncStorageEngine.SOURCE_SERVER;
}
for (AccountAndUser account : accounts) {
// If userId is specified, do not sync accounts of other users
if (userId >= UserHandle.USER_OWNER && account.userId >= UserHandle.USER_OWNER
&& userId != account.userId) {
continue;
}
// Compile a list of authorities that have sync adapters.
// For each authority sync each account that matches a sync adapter.
final HashSet<String> syncableAuthorities = new HashSet<String>();
for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
mSyncAdapters.getAllServices(account.userId)) {
syncableAuthorities.add(syncAdapter.type.authority);
}
// if the url was specified then replace the list of authorities
// with just this authority or clear it if this authority isn't
// syncable
if (requestedAuthority != null) {
final boolean hasSyncAdapter = syncableAuthorities.contains(requestedAuthority);
syncableAuthorities.clear();
if (hasSyncAdapter) syncableAuthorities.add(requestedAuthority);
}
for (String authority : syncableAuthorities) {
int isSyncable = getIsSyncable(account.account, account.userId,
authority);
if (isSyncable == AuthorityInfo.NOT_SYNCABLE) {
continue;
}
final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
syncAdapterInfo = mSyncAdapters.getServiceInfo(
SyncAdapterType.newKey(authority, account.account.type), account.userId);
if (syncAdapterInfo == null) {
continue;
}
final boolean allowParallelSyncs = syncAdapterInfo.type.allowParallelSyncs();
final boolean isAlwaysSyncable = syncAdapterInfo.type.isAlwaysSyncable();
if (isSyncable < 0 && isAlwaysSyncable) {
mSyncStorageEngine.setIsSyncable(
account.account, account.userId, authority, AuthorityInfo.SYNCABLE);
isSyncable = AuthorityInfo.SYNCABLE;
}
if (onlyThoseWithUnkownSyncableState && isSyncable >= 0) {
continue;
}
if (!syncAdapterInfo.type.supportsUploading() && uploadOnly) {
continue;
}
boolean syncAllowed =
(isSyncable < 0) // always allow if the isSyncable state is unknown
|| ignoreSettings
|| (mSyncStorageEngine.getMasterSyncAutomatically(account.userId)
&& mSyncStorageEngine.getSyncAutomatically(account.account,
account.userId, authority));
if (!syncAllowed) {
if (isLoggable) {
Log.d(TAG, "scheduleSync: sync of " + account + ", " + authority
+ " is not allowed, dropping request");
}
continue;
}
SyncStorageEngine.EndPoint info =
new SyncStorageEngine.EndPoint(
account.account, authority, account.userId);
Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(info);
long delayUntil =
mSyncStorageEngine.getDelayUntilTime(info);
final long backoffTime = backoff != null ? backoff.first : 0;
if (isSyncable < 0) {
// Initialisation sync.
Bundle newExtras = new Bundle();
newExtras.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
if (isLoggable) {
Log.v(TAG, "schedule initialisation Sync:"
+ ", delay until " + delayUntil
+ ", run by " + 0
+ ", flex " + 0
+ ", source " + source
+ ", account " + account
+ ", authority " + authority
+ ", extras " + newExtras);
}
scheduleSyncOperation(
new SyncOperation(account.account, account.userId, reason, source,
authority, newExtras, 0 /* immediate */, 0 /* No flex time*/,
backoffTime, delayUntil, allowParallelSyncs));
}
if (!onlyThoseWithUnkownSyncableState) {
if (isLoggable) {
Log.v(TAG, "scheduleSync:"
+ " delay until " + delayUntil
+ " run by " + runtimeMillis
+ " flex " + beforeRuntimeMillis
+ ", source " + source
+ ", account " + account
+ ", authority " + authority
+ ", extras " + extras);
}
scheduleSyncOperation(
new SyncOperation(account.account, account.userId, reason, source,
authority, extras, runtimeMillis, beforeRuntimeMillis,
backoffTime, delayUntil, allowParallelSyncs));
}
}
}
}
/**
* Schedule sync based on local changes to a provider. Occurs within interval
* [LOCAL_SYNC_DELAY, 2*LOCAL_SYNC_DELAY].
*/
public void scheduleLocalSync(Account account, int userId, int reason, String authority) {
final Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
scheduleSync(account, userId, reason, authority, extras,
LOCAL_SYNC_DELAY /* earliest run time */,
2 * LOCAL_SYNC_DELAY /* latest sync time. */,
false /* onlyThoseWithUnkownSyncableState */);
}
public SyncAdapterType[] getSyncAdapterTypes(int userId) {
final Collection<RegisteredServicesCache.ServiceInfo<SyncAdapterType>> serviceInfos;
serviceInfos = mSyncAdapters.getAllServices(userId);
SyncAdapterType[] types = new SyncAdapterType[serviceInfos.size()];
int i = 0;
for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> serviceInfo : serviceInfos) {
types[i] = serviceInfo.type;
++i;
}
return types;
}
public String[] getSyncAdapterPackagesForAuthorityAsUser(String authority, int userId) {
return mSyncAdapters.getSyncAdapterPackagesForAuthority(authority, userId);
}
private void sendSyncAlarmMessage() {
if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_ALARM");
mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_SYNC_ALARM);
}
private void sendCheckAlarmsMessage() {
if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CHECK_ALARMS");
mSyncHandler.removeMessages(SyncHandler.MESSAGE_CHECK_ALARMS);
mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS);
}
private void sendSyncFinishedOrCanceledMessage(ActiveSyncContext syncContext,
SyncResult syncResult) {
if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_SYNC_FINISHED");
Message msg = mSyncHandler.obtainMessage();
msg.what = SyncHandler.MESSAGE_SYNC_FINISHED;
msg.obj = new SyncHandlerMessagePayload(syncContext, syncResult);
mSyncHandler.sendMessage(msg);
}
private void sendCancelSyncsMessage(final SyncStorageEngine.EndPoint info, Bundle extras) {
if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "sending MESSAGE_CANCEL");
Message msg = mSyncHandler.obtainMessage();
msg.what = SyncHandler.MESSAGE_CANCEL;
msg.setData(extras);
msg.obj = info;
mSyncHandler.sendMessage(msg);
}
/**
* Post a delayed message to the handler that will result in the cancellation of the provided
* running sync's context.
*/
private void postSyncExpiryMessage(ActiveSyncContext activeSyncContext) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "posting MESSAGE_SYNC_EXPIRED in " +
(ACTIVE_SYNC_TIMEOUT_MILLIS/1000) + "s");
}
Message msg = mSyncHandler.obtainMessage();
msg.what = SyncHandler.MESSAGE_SYNC_EXPIRED;
msg.obj = activeSyncContext;
mSyncHandler.sendMessageDelayed(msg, ACTIVE_SYNC_TIMEOUT_MILLIS);
}
/**
* Post a delayed message that will monitor the given sync context by periodically checking how
* much network has been used by the uid.
*/
private void postMonitorSyncProgressMessage(ActiveSyncContext activeSyncContext) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "posting MESSAGE_SYNC_MONITOR in " +
(SYNC_MONITOR_WINDOW_LENGTH_MILLIS/1000) + "s");
}
activeSyncContext.mBytesTransferredAtLastPoll =
getTotalBytesTransferredByUid(activeSyncContext.mSyncAdapterUid);
activeSyncContext.mLastPolledTimeElapsed = SystemClock.elapsedRealtime();
Message monitorMessage =
mSyncHandler.obtainMessage(
SyncHandler.MESSAGE_MONITOR_SYNC,
activeSyncContext);
mSyncHandler.sendMessageDelayed(monitorMessage, SYNC_MONITOR_WINDOW_LENGTH_MILLIS);
}
/**
* Monitor sync progress by calculating how many bytes it is managing to send to and fro.
*/
private long getTotalBytesTransferredByUid(int uid) {
return (TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid));
}