blob: cca0c16f805fd72e22dd7c058a450517248cf0bd [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070042import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080044import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070045import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070046import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070047import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080048
49import com.android.internal.annotations.VisibleForTesting;
50import com.android.internal.util.ArrayUtils;
51import com.android.internal.util.FastXmlSerializer;
52
53import org.xmlpull.v1.XmlPullParser;
54import org.xmlpull.v1.XmlPullParserException;
55import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.io.File;
58import java.io.FileInputStream;
59import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070060import java.io.IOException;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010061import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070065import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080066import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070067import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060068import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070071 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070073 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * @hide
75 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070076public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070079 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070080
Amith Yamasani04e0d262012-02-14 11:50:53 -080081 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
82 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070083 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080084 private static final String XML_ATTR_ENABLED = "enabled";
85 private static final String XML_ATTR_USER = "user";
86 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
87
Matthew Williamsfa774182013-06-18 15:44:11 -070088 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080089 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
90
Matthew Williamsfa774182013-06-18 15:44:11 -070091 /** Percentage of period that is flex by default, if no flex is set. */
92 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
93
94 /** Lower bound on sync time from which we assign a default flex time. */
95 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
96
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080097 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a sync start event. */
101 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a sync stop event. */
104 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 // TODO: i18n -- grab these out of resources.
107 /** String names for the sync event types. */
108 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Dianne Hackborn231cc602009-04-27 17:10:36 -0700110 /** Enum value for a server-initiated sync. */
111 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Dianne Hackborn231cc602009-04-27 17:10:36 -0700113 /** Enum value for a local-initiated sync. */
114 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700115 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Dianne Hackborn231cc602009-04-27 17:10:36 -0700118 /** Enum value for a user-initiated sync. */
119 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800121 /** Enum value for a periodic sync. */
122 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700123
124 /** Enum value for a sync started for a service. */
125 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800126
Fred Quintana307da1a2010-01-21 14:24:20 -0800127 public static final long NOT_IN_BACKOFF_MODE = -1;
128
Dianne Hackborn231cc602009-04-27 17:10:36 -0700129 // TODO: i18n -- grab these out of resources.
130 /** String names for the sync source types. */
131 public static final String[] SOURCES = { "SERVER",
132 "LOCAL",
133 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800134 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700135 "PERIODIC",
136 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Dianne Hackborn231cc602009-04-27 17:10:36 -0700138 // The MESG column will contain one of these or one of the Error types.
139 public static final String MESG_SUCCESS = "success";
140 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700142 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700143
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 private static final int MSG_WRITE_STATUS = 1;
145 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700146
Dianne Hackborn231cc602009-04-27 17:10:36 -0700147 private static final int MSG_WRITE_STATISTICS = 2;
148 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700149
150 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700151
Fred Quintanac2e46912010-03-15 16:10:44 -0700152 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700153 private static final int ACCOUNTS_VERSION = 2;
154
155 private static HashMap<String, String> sAuthorityRenames;
156
157 static {
158 sAuthorityRenames = new HashMap<String, String>();
159 sAuthorityRenames.put("contacts", "com.android.contacts");
160 sAuthorityRenames.put("calendar", "com.android.calendar");
161 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700162
Dianne Hackborn231cc602009-04-27 17:10:36 -0700163 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700164 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700165 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700166 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800168 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700169
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700170 final int authorityId;
171 // No longer used.
172 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700173 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700174
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700175 PendingOperation(AuthorityInfo authority, int reason, int source,
176 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700177 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700179 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800181 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700182 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700183 }
184
185 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700186 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700188 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700189 this.extras = other.extras;
190 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800191 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
193
194 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700195 * Considered equal if they target the same sync adapter (A
196 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700197 * is considered an adapter), for the same userId.
198 * @param other PendingOperation to compare.
199 * @return true if the two pending ops are the same.
200 */
201 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700202 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700203 }
204
205 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700206 return "service=" + target.service
207 + " user=" + target.userId
208 + " auth=" + target
209 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700210 + " src=" + syncSource
211 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
Costin Manolache360e4542009-09-04 13:36:04 -0700214
Dianne Hackborn231cc602009-04-27 17:10:36 -0700215 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700217 final HashMap<String, AuthorityInfo> authorities =
218 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700219
Amith Yamasani04e0d262012-02-14 11:50:53 -0800220 AccountInfo(AccountAndUser accountAndUser) {
221 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700222 }
223 }
Costin Manolache360e4542009-09-04 13:36:04 -0700224
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700225 /** Bare bones representation of a sync target. */
226 public static class EndPoint {
227 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
228 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700229 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700230 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800231 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700232 final String provider;
233 final boolean target_service;
234 final boolean target_provider;
235
236 public EndPoint(ComponentName service, int userId) {
237 this.service = service;
238 this.userId = userId;
239 this.account = null;
240 this.provider = null;
241 this.target_service = true;
242 this.target_provider = false;
243 }
244
245 public EndPoint(Account account, String provider, int userId) {
246 this.account = account;
247 this.provider = provider;
248 this.userId = userId;
249 this.service = null;
250 this.target_service = false;
251 this.target_provider = true;
252 }
253
254 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700255 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
256 *
257 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
258 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700259 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700260 public boolean matchesSpec(EndPoint spec) {
261 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700262 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700263 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700264 return false;
265 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700266 if (target_service && spec.target_service) {
267 return service.equals(spec.service);
268 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700270 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 accountsMatch = true;
272 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700273 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700274 }
275 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700276 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700277 providersMatch = true;
278 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700279 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700280 }
281 return accountsMatch && providersMatch;
282 }
283 return false;
284 }
285
286 public String toString() {
287 StringBuilder sb = new StringBuilder();
288 if (target_provider) {
289 sb.append(account == null ? "ALL ACCS" : account.name)
290 .append("/")
291 .append(provider == null ? "ALL PDRS" : provider);
292 } else if (target_service) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700293 sb.append(service.getPackageName() + "/")
294 .append(service.getClassName());
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700295 } else {
296 sb.append("invalid target");
297 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700298 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700299 return sb.toString();
300 }
301 }
302
303 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700304 // Legal values of getIsSyncable
305 /**
306 * Default state for a newly installed adapter. An uninitialized adapter will receive an
307 * initialization sync which are governed by a different set of rules to that of regular
308 * syncs.
309 */
310 public static final int NOT_INITIALIZED = -1;
311 /**
312 * The adapter will not receive any syncs. This is behaviourally equivalent to
313 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
314 * while this is generally meant to be controlled by the developer.
315 */
316 public static final int NOT_SYNCABLE = 0;
317 /**
318 * The adapter is initialized and functioning. This is the normal state for an adapter.
319 */
320 public static final int SYNCABLE = 1;
321 /**
322 * The adapter is syncable but still requires an initialization sync. For example an adapter
323 * than has been restored from a previous device will be in this state. Not meant for
324 * external use.
325 */
326 public static final int SYNCABLE_NOT_INITIALIZED = 2;
327
Matthew Williams8ef22042013-07-26 12:56:39 -0700328 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700329 final int ident;
330 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700331 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700332 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800333 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700334 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800335 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700336 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800337 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700338
Matthew Williamsfa774182013-06-18 15:44:11 -0700339 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700340
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700341 /**
342 * Copy constructor for making deep-ish copies. Only the bundles stored
343 * in periodic syncs can make unexpected changes.
344 *
345 * @param toCopy AuthorityInfo to be copied.
346 */
347 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700348 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700349 ident = toCopy.ident;
350 enabled = toCopy.enabled;
351 syncable = toCopy.syncable;
352 backoffTime = toCopy.backoffTime;
353 backoffDelay = toCopy.backoffDelay;
354 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700355 periodicSyncs = new ArrayList<PeriodicSync>();
356 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700357 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700358 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700359 }
360 }
361
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700362 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700363 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700364 ident = id;
365 enabled = info.target_provider ?
366 SYNC_ENABLED_DEFAULT : true;
367 // Service is active by default,
368 if (info.target_service) {
369 this.syncable = 1;
370 }
371 periodicSyncs = new ArrayList<PeriodicSync>();
372 defaultInitialisation();
373 }
374
375 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700376 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800377 backoffTime = -1; // if < 0 then we aren't in backoff mode
378 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700379 PeriodicSync defaultSync;
Matthew Williams53abfdb2015-06-10 20:06:37 -0700380 // Old version is one sync a day.
Matthew Williams8ef22042013-07-26 12:56:39 -0700381 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700382 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700383 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700384 new Bundle(),
385 DEFAULT_POLL_FREQUENCY_SECONDS,
386 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
387 periodicSyncs.add(defaultSync);
388 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700389 }
Matthew Williams06485a72013-07-26 12:56:39 -0700390
391 @Override
392 public String toString() {
393 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
394 + backoffTime + ", delay=" + delayUntil;
395 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700396 }
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 public static class SyncHistoryItem {
399 int authorityId;
400 int historyId;
401 long eventTime;
402 long elapsedTime;
403 int source;
404 int event;
405 long upstreamActivity;
406 long downstreamActivity;
407 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700408 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700409 Bundle extras;
410 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700411 }
Costin Manolache360e4542009-09-04 13:36:04 -0700412
Dianne Hackborn231cc602009-04-27 17:10:36 -0700413 public static class DayStats {
414 public final int day;
415 public int successCount;
416 public long successTime;
417 public int failureCount;
418 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 public DayStats(int day) {
421 this.day = day;
422 }
423 }
Costin Manolache360e4542009-09-04 13:36:04 -0700424
Amith Yamasani04e0d262012-02-14 11:50:53 -0800425 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700426
427 /** Called when a sync is needed on an account(s) due to some change in state. */
428 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800429 }
430
Dianne Hackborn231cc602009-04-27 17:10:36 -0700431 // Primary list of all syncable authorities. Also our global lock.
432 private final SparseArray<AuthorityInfo> mAuthorities =
433 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700434
Amith Yamasani04e0d262012-02-14 11:50:53 -0800435 private final HashMap<AccountAndUser, AccountInfo> mAccounts
436 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 private final ArrayList<PendingOperation> mPendingOperations =
439 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700440
Amith Yamasani04e0d262012-02-14 11:50:53 -0800441 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
442 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 private final SparseArray<SyncStatusInfo> mSyncStatus =
445 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700446
Dianne Hackborn231cc602009-04-27 17:10:36 -0700447 private final ArrayList<SyncHistoryItem> mSyncHistory =
448 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700449
Dianne Hackborn231cc602009-04-27 17:10:36 -0700450 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
451 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700452
Matthew Williams8ef22042013-07-26 12:56:39 -0700453 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700454 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
455 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700456
Fred Quintana77c560f2010-03-29 22:20:26 -0700457 private int mNextAuthorityId = 0;
458
Dianne Hackborn231cc602009-04-27 17:10:36 -0700459 // We keep 4 weeks of stats.
460 private final DayStats[] mDayStats = new DayStats[7*4];
461 private final Calendar mCal;
462 private int mYear;
463 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700464
Dianne Hackborn231cc602009-04-27 17:10:36 -0700465 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800466
Dianne Hackborn231cc602009-04-27 17:10:36 -0700467 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700468
Ashish Sharma69d95de2012-04-11 17:27:24 -0700469 private int mSyncRandomOffset;
470
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 /**
472 * This file contains the core engine state: all accounts and the
473 * settings for them. It must never be lost, and should be changed
474 * infrequently, so it is stored as an XML file.
475 */
476 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700477
Dianne Hackborn231cc602009-04-27 17:10:36 -0700478 /**
479 * This file contains the current sync status. We would like to retain
480 * it across boots, but its loss is not the end of the world, so we store
481 * this information as binary data.
482 */
483 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700484
Dianne Hackborn231cc602009-04-27 17:10:36 -0700485 /**
486 * This file contains sync statistics. This is purely debugging information
487 * so is written infrequently and can be thrown away at any time.
488 */
489 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700490
Dianne Hackborn231cc602009-04-27 17:10:36 -0700491 /**
492 * This file contains the pending sync operations. It is a binary file,
493 * which must be updated every time an operation is added or removed,
494 * so we have special handling of it.
495 */
496 private final AtomicFile mPendingFile;
497 private static final int PENDING_FINISH_TO_WRITE = 4;
498 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700499
Dianne Hackborn231cc602009-04-27 17:10:36 -0700500 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800501 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800502 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800503
504 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700505
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800506 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700509
Dianne Hackborn231cc602009-04-27 17:10:36 -0700510 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700511
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800512 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
513 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
514
Dianne Hackborn231cc602009-04-27 17:10:36 -0700515 File systemDir = new File(dataDir, "system");
516 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800517 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700518
519 maybeDeleteLegacyPendingInfoLocked(syncDir);
520
Dianne Hackborn231cc602009-04-27 17:10:36 -0700521 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
522 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700523 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700524 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700525
Dianne Hackborn231cc602009-04-27 17:10:36 -0700526 readAccountInfoLocked();
527 readStatusLocked();
528 readPendingOperationsLocked();
529 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700530 readAndDeleteLegacyAccountInfoLocked();
531 writeAccountInfoLocked();
532 writeStatusLocked();
533 writePendingOperationsLocked();
534 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 }
536
537 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800538 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 }
540
541 public static void init(Context context) {
542 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800543 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800545 // This call will return the correct directory whether Encrypted File Systems is
546 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600547 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800548 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
550
551 public static SyncStorageEngine getSingleton() {
552 if (sSyncStorageEngine == null) {
553 throw new IllegalStateException("not initialized");
554 }
555 return sSyncStorageEngine;
556 }
557
Amith Yamasani04e0d262012-02-14 11:50:53 -0800558 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
559 if (mSyncRequestListener == null) {
560 mSyncRequestListener = listener;
561 }
562 }
563
Dianne Hackborn231cc602009-04-27 17:10:36 -0700564 @Override public void handleMessage(Message msg) {
565 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700566 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700567 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700568 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700569 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700570 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700571 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
574 }
Costin Manolache360e4542009-09-04 13:36:04 -0700575
Ashish Sharma69d95de2012-04-11 17:27:24 -0700576 public int getSyncRandomOffset() {
577 return mSyncRandomOffset;
578 }
579
Dianne Hackborn231cc602009-04-27 17:10:36 -0700580 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
581 synchronized (mAuthorities) {
582 mChangeListeners.register(callback, mask);
583 }
584 }
Costin Manolache360e4542009-09-04 13:36:04 -0700585
Dianne Hackborn231cc602009-04-27 17:10:36 -0700586 public void removeStatusChangeListener(ISyncStatusObserver callback) {
587 synchronized (mAuthorities) {
588 mChangeListeners.unregister(callback);
589 }
590 }
Costin Manolache360e4542009-09-04 13:36:04 -0700591
Matthew Williamsfa774182013-06-18 15:44:11 -0700592 /**
593 * Figure out a reasonable flex time for cases where none is provided (old api calls).
594 * @param syncTimeSeconds requested sync time from now.
595 * @return amount of seconds before syncTimeSeconds that the sync can occur.
596 * I.e.
597 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700598 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700599 */
600 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
601 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
602 // Small enough sync request time that we don't add flex time - developer probably
603 // wants to wait for an operation to occur before syncing so we honour the
604 // request time.
605 return 0L;
606 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
607 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
608 } else {
609 // Large enough sync request time that we cap the flex time.
610 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
611 }
612 }
613
Dianne Hackborn231cc602009-04-27 17:10:36 -0700614 private void reportChange(int which) {
615 ArrayList<ISyncStatusObserver> reports = null;
616 synchronized (mAuthorities) {
617 int i = mChangeListeners.beginBroadcast();
618 while (i > 0) {
619 i--;
620 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
621 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 continue;
623 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700624 if (reports == null) {
625 reports = new ArrayList<ISyncStatusObserver>(i);
626 }
627 reports.add(mChangeListeners.getBroadcastItem(i));
628 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700629 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700630 }
Costin Manolache360e4542009-09-04 13:36:04 -0700631
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700632 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700633 Log.v(TAG, "reportChange " + which + " to: " + reports);
634 }
Costin Manolache360e4542009-09-04 13:36:04 -0700635
Dianne Hackborn231cc602009-04-27 17:10:36 -0700636 if (reports != null) {
637 int i = reports.size();
638 while (i > 0) {
639 i--;
640 try {
641 reports.get(i).onStatusChanged(which);
642 } catch (RemoteException e) {
643 // The remote callback list will take care of this for us.
644 }
645 }
646 }
647 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700648
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700650 synchronized (mAuthorities) {
651 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700652 AuthorityInfo authority = getAuthorityLocked(
653 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700654 "getSyncAutomatically");
655 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700656 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700657
Dianne Hackborn231cc602009-04-27 17:10:36 -0700658 int i = mAuthorities.size();
659 while (i > 0) {
660 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700661 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700662 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700663 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700664 return true;
665 }
666 }
667 return false;
668 }
669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 public void setSyncAutomatically(Account account, int userId, String providerName,
672 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800674 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
675 + ", user " + userId + " -> " + sync);
676 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700677 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700678 AuthorityInfo authority =
679 getOrCreateAuthorityLocked(
680 new EndPoint(account, providerName, userId),
681 -1 /* ident */,
682 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700683 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700684 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800685 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
686 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700687 return;
688 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700689 // If the adapter was syncable but missing its initialization sync, set it to
690 // uninitialized now. This is to give it a chance to run any one-time initialization
691 // logic.
692 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
693 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
694 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700695 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700696 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700698
Fred Quintana77c560f2010-03-29 22:20:26 -0700699 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700700 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
701 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700702 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700703 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800704 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706
Amith Yamasani04e0d262012-02-14 11:50:53 -0800707 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700708 synchronized (mAuthorities) {
709 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700710 AuthorityInfo authority = getAuthorityLocked(
711 new EndPoint(account, providerName, userId),
712 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700713 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700714 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700715 }
716 return authority.syncable;
717 }
718
719 int i = mAuthorities.size();
720 while (i > 0) {
721 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700722 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700723 if (authorityInfo.target != null
724 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700725 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700726 }
727 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700728 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700729 }
730 }
731
Amith Yamasani04e0d262012-02-14 11:50:53 -0800732 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700733 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700734 }
735
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700736 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700737 synchronized (mAuthorities) {
738 if (cname != null) {
739 AuthorityInfo authority = getAuthorityLocked(
740 new EndPoint(cname, userId),
Matthew Williams8ef22042013-07-26 12:56:39 -0700741 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700742 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700743 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700744 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700745 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700746 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700747 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700748 }
749 }
750
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700751 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700752 setSyncableStateForEndPoint(new EndPoint(cname, userId), active ?
753 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700754 }
755
756 /**
757 * An enabled sync service and a syncable provider's adapter both get resolved to the same
758 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700759 * @param target target to set value for.
760 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700761 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700762 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700763 AuthorityInfo aInfo;
764 synchronized (mAuthorities) {
765 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700766 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
767 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700768 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
770 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
771 }
772 if (aInfo.syncable == syncable) {
773 if (Log.isLoggable(TAG, Log.VERBOSE)) {
774 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
775 }
776 return;
777 }
778 aInfo.syncable = syncable;
779 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700780 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700781 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700782 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700783 }
784 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
785 }
786
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700787 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800788 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700789 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
790 if (authority != null) {
791 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800792 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700793 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800794 }
795 }
796
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700797 /**
798 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
799 * the account or provider info be null, which signifies all accounts or providers.
800 */
801 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
802 if (Log.isLoggable(TAG, Log.VERBOSE)) {
803 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800804 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
805 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800807 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700808 if (info.target_provider
809 && (info.account == null || info.provider == null)) {
810 // Do more work for a provider sync if the provided info has specified all
811 // accounts/providers.
812 changed = setBackoffLocked(
813 info.account /* may be null */,
814 info.userId,
815 info.provider /* may be null */,
816 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800817 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700818 AuthorityInfo authorityInfo =
819 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
820 if (authorityInfo.backoffTime == nextSyncTime
821 && authorityInfo.backoffDelay == nextDelay) {
822 changed = false;
823 } else {
824 authorityInfo.backoffTime = nextSyncTime;
825 authorityInfo.backoffDelay = nextDelay;
826 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800827 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800828 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800829 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800830 if (changed) {
831 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
832 }
833 }
834
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700835 /**
836 * Either set backoff for a specific authority, or set backoff for all the
837 * accounts on a specific adapter/all adapters.
838 *
839 * @param account account for which to set backoff. Null to specify all accounts.
840 * @param userId id of the user making this request.
841 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700842 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700843 */
844 private boolean setBackoffLocked(Account account, int userId, String providerName,
845 long nextSyncTime, long nextDelay) {
846 boolean changed = false;
847 for (AccountInfo accountInfo : mAccounts.values()) {
848 if (account != null && !account.equals(accountInfo.accountAndUser.account)
849 && userId != accountInfo.accountAndUser.userId) {
850 continue;
851 }
852 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
853 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700854 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700855 continue;
856 }
857 if (authorityInfo.backoffTime != nextSyncTime
858 || authorityInfo.backoffDelay != nextDelay) {
859 authorityInfo.backoffTime = nextSyncTime;
860 authorityInfo.backoffDelay = nextDelay;
861 changed = true;
862 }
863 }
864 }
865 return changed;
866 }
867
Matthew Williams119aac92014-09-28 20:42:23 -0700868 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800869 boolean changed = false;
870 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700871 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700872 for (AccountInfo accountInfo : mAccounts.values()) {
873 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
874 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
875 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700876 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams119aac92014-09-28 20:42:23 -0700877 Log.v(TAG, "clearAllBackoffsLocked:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700878 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700879 + " account:" + accountInfo.accountAndUser.account.name
880 + " user:" + accountInfo.accountAndUser.userId
881 + " backoffTime was: " + authorityInfo.backoffTime
882 + " backoffDelay was: " + authorityInfo.backoffDelay);
883 }
884 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
885 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700886 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800887 }
Alon Albert744e310f2010-12-14 11:37:20 -0800888 }
889 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700890 // Clear backoff for all sync services.
891 for (ComponentName service : mServices.keySet()) {
892 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
893 for (int i = 0; i < aInfos.size(); i++) {
894 AuthorityInfo authorityInfo = aInfos.valueAt(i);
895 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
896 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
897 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
898 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
899 }
900 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700901 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800902 }
903 }
904
905 if (changed) {
906 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
907 }
908 }
909
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700910 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800911 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700912 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800913 if (authority == null) {
914 return 0;
915 }
916 return authority.delayUntil;
917 }
918 }
919
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700920 public void setDelayUntilTime(EndPoint info, long delayUntil) {
921 if (Log.isLoggable(TAG, Log.VERBOSE)) {
922 Log.v(TAG, "setDelayUntil: " + info
923 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800924 }
925 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700926 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
927 if (authority.delayUntil == delayUntil) {
928 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700929 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700930 authority.delayUntil = delayUntil;
931 }
932 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
933 }
934
935 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
936 if (Log.isLoggable(TAG, Log.VERBOSE)) {
937 Log.v(TAG, "addPeriodicSync: " + info
938 + " -> period " + period + ", flex " + flextime + ", extras "
939 + extras.toString());
940 }
941 synchronized (mAuthorities) {
942 if (period <= 0) {
943 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
944 }
945 if (extras == null) {
946 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700947 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700948 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700949 PeriodicSync toUpdate;
950 if (info.target_provider) {
951 toUpdate = new PeriodicSync(info.account,
952 info.provider,
953 extras,
954 period,
955 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700956 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -0700957 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700958 }
959 AuthorityInfo authority =
960 getOrCreateAuthorityLocked(info, -1, false);
961 // add this periodic sync if an equivalent periodic doesn't already exist.
962 boolean alreadyPresent = false;
963 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
964 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
965 if (SyncManager.syncExtrasEquals(syncInfo.extras,
966 extras,
967 true /* includeSyncSettings*/)) {
968 if (period == syncInfo.period &&
969 flextime == syncInfo.flexTime) {
970 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700971 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700972 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700973 authority.periodicSyncs.set(i, toUpdate);
974 alreadyPresent = true;
975 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700976 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700977 }
978 // If we added an entry to the periodicSyncs array also add an entry to
979 // the periodic syncs status to correspond to it.
980 if (!alreadyPresent) {
981 authority.periodicSyncs.add(toUpdate);
982 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
983 // A new periodic sync is initialised as already having been run.
984 status.setPeriodicSyncTime(
985 authority.periodicSyncs.size() - 1,
986 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800987 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700988 } finally {
989 writeAccountInfoLocked();
990 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800991 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800992 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800993 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
994 }
995
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700996 public void removePeriodicSync(EndPoint info, Bundle extras) {
997 synchronized(mAuthorities) {
998 try {
999 AuthorityInfo authority =
1000 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -07001001 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001002 SyncStatusInfo status = mSyncStatus.get(authority.ident);
1003 boolean changed = false;
1004 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
1005 int i = 0;
1006 while (iterator.hasNext()) {
1007 PeriodicSync syncInfo = iterator.next();
1008 if (SyncManager.syncExtrasEquals(syncInfo.extras,
1009 extras,
1010 true /* includeSyncSettings */)) {
1011 iterator.remove();
1012 changed = true;
1013 // If we removed an entry from the periodicSyncs array also
1014 // remove the corresponding entry from the status
1015 if (status != null) {
1016 status.removePeriodicSyncTime(i);
1017 } else {
1018 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
1019 + " did not find it.");
1020 }
1021 } else {
1022 i++;
1023 }
1024 }
1025 if (!changed) {
1026 return;
1027 }
1028 } finally {
1029 writeAccountInfoLocked();
1030 writeStatusLocked();
1031 }
1032 }
1033 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001034 }
1035
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001036 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001037 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1038 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001039 */
1040 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001041 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001042 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1043 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1044 if (authorityInfo != null) {
1045 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001046 // Copy and send out. Necessary for thread-safety although it's parceled.
1047 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001048 }
1049 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001050 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001051 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001052 }
1053
Amith Yamasani04e0d262012-02-14 11:50:53 -08001054 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001056 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001057 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001058 return;
1059 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001060 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 writeAccountInfoLocked();
1062 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001063 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001064 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1065 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001066 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001067 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001068 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -08001069 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071
Amith Yamasani04e0d262012-02-14 11:50:53 -08001072 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001073 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001074 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001075 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 }
1077 }
Costin Manolache360e4542009-09-04 13:36:04 -07001078
Dianne Hackborn231cc602009-04-27 17:10:36 -07001079 public AuthorityInfo getAuthority(int authorityId) {
1080 synchronized (mAuthorities) {
1081 return mAuthorities.get(authorityId);
1082 }
1083 }
Costin Manolache360e4542009-09-04 13:36:04 -07001084
Dianne Hackborn231cc602009-04-27 17:10:36 -07001085 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001086 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001087 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001089 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001091 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001092 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001093 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 return true;
1095 }
1096 }
1097 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 return false;
1099 }
Costin Manolache360e4542009-09-04 13:36:04 -07001100
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001101 public PendingOperation insertIntoPending(SyncOperation op) {
1102 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001104 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1105 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001106 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001107 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001108 final EndPoint info = op.target;
1109 AuthorityInfo authority =
1110 getOrCreateAuthorityLocked(info,
1111 -1 /* desired identifier */,
1112 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001113 if (authority == null) {
1114 return null;
1115 }
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001117 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
Matthew Williams64280462014-01-09 10:49:23 -08001118 op.isExpedited());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001119 mPendingOperations.add(pop);
Matthew Williams06485a72013-07-26 12:56:39 -07001120 appendPendingOperationLocked(pop);
Costin Manolache360e4542009-09-04 13:36:04 -07001121
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1123 status.pending = true;
1124 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001125 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001126 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 }
1128
Matthew Williamsfa774182013-06-18 15:44:11 -07001129 /**
1130 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001131 * authorities. If there are no more pending syncs for the same target,
1132 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001133 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001134 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001135 public boolean deleteFromPending(PendingOperation op) {
1136 boolean res = false;
1137 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001138 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1139 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001140 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 if (mPendingOperations.remove(op)) {
1142 if (mPendingOperations.size() == 0
1143 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1144 writePendingOperationsLocked();
1145 mNumPendingFinished = 0;
1146 } else {
1147 mNumPendingFinished++;
1148 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001149 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001151 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1152 Log.v(TAG, "removing - " + authority.toString());
1153 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001154 final int N = mPendingOperations.size();
1155 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001156 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001158 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001159 morePending = true;
1160 break;
1161 }
1162 }
Costin Manolache360e4542009-09-04 13:36:04 -07001163
Dianne Hackborn231cc602009-04-27 17:10:36 -07001164 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001165 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1167 status.pending = false;
1168 }
1169 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 res = true;
1171 }
1172 }
Costin Manolache360e4542009-09-04 13:36:04 -07001173
Fred Quintanaac9385e2009-06-22 18:00:59 -07001174 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 return res;
1176 }
1177
Dianne Hackborn231cc602009-04-27 17:10:36 -07001178 /**
1179 * Return a copy of the current array of pending operations. The
1180 * PendingOperation objects are the real objects stored inside, so that
1181 * they can be used with deleteFromPending().
1182 */
1183 public ArrayList<PendingOperation> getPendingOperations() {
1184 synchronized (mAuthorities) {
1185 return new ArrayList<PendingOperation>(mPendingOperations);
1186 }
1187 }
Costin Manolache360e4542009-09-04 13:36:04 -07001188
Dianne Hackborn231cc602009-04-27 17:10:36 -07001189 /**
1190 * Return the number of currently pending operations.
1191 */
1192 public int getPendingOperationCount() {
1193 synchronized (mAuthorities) {
1194 return mPendingOperations.size();
1195 }
1196 }
Costin Manolache360e4542009-09-04 13:36:04 -07001197
Dianne Hackborn231cc602009-04-27 17:10:36 -07001198 /**
1199 * Called when the set of account has changed, given the new array of
1200 * active accounts.
1201 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001202 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001203 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001204 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1205 Log.v(TAG, "Updating for new accounts...");
1206 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001207 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1208 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1209 while (accIt.hasNext()) {
1210 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001211 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1212 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001213 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001215 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001216 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 for (AuthorityInfo auth : acc.authorities.values()) {
1218 removing.put(auth.ident, auth);
1219 }
1220 accIt.remove();
1221 }
1222 }
Costin Manolache360e4542009-09-04 13:36:04 -07001223
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 // Clean out all data structures.
1225 int i = removing.size();
1226 if (i > 0) {
1227 while (i > 0) {
1228 i--;
1229 int ident = removing.keyAt(i);
1230 mAuthorities.remove(ident);
1231 int j = mSyncStatus.size();
1232 while (j > 0) {
1233 j--;
1234 if (mSyncStatus.keyAt(j) == ident) {
1235 mSyncStatus.remove(mSyncStatus.keyAt(j));
1236 }
1237 }
1238 j = mSyncHistory.size();
1239 while (j > 0) {
1240 j--;
1241 if (mSyncHistory.get(j).authorityId == ident) {
1242 mSyncHistory.remove(j);
1243 }
1244 }
1245 }
1246 writeAccountInfoLocked();
1247 writeStatusLocked();
1248 writePendingOperationsLocked();
1249 writeStatisticsLocked();
1250 }
1251 }
1252 }
1253
1254 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001255 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1256 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001257 */
Fred Quintana918339a2010-10-05 14:00:39 -07001258 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1259 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001260 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001262 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001263 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001264 + " src=" + activeSyncContext.mSyncOperation.syncSource
1265 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001267 final EndPoint info = activeSyncContext.mSyncOperation.target;
1268 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1269 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001270 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001271 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001272 syncInfo = new SyncInfo(
1273 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001274 authorityInfo.target.account,
1275 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001276 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001277 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 }
Fred Quintana918339a2010-10-05 14:00:39 -07001279 reportActiveChange();
1280 return syncInfo;
1281 }
1282
1283 /**
1284 * Called to indicate that a previously active sync is no longer active.
1285 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001286 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001287 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001288 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001289 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1290 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001291 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001292 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001293 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001294 }
1295
1296 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 }
1298
1299 /**
1300 * To allow others to send active change reports, to poke clients.
1301 */
1302 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001303 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001304 }
Costin Manolache360e4542009-09-04 13:36:04 -07001305
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001307 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001309 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001310 long id;
1311 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001312 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1313 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001314 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001315 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001316 if (authority == null) {
1317 return -1;
1318 }
1319 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001320 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 item.authorityId = authority.ident;
1322 item.historyId = mNextHistoryId++;
1323 if (mNextHistoryId < 0) mNextHistoryId = 0;
1324 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001325 item.source = op.syncSource;
1326 item.reason = op.reason;
1327 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001328 item.event = EVENT_START;
1329 mSyncHistory.add(0, item);
1330 while (mSyncHistory.size() > MAX_HISTORY) {
1331 mSyncHistory.remove(mSyncHistory.size()-1);
1332 }
1333 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001334 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001335 }
Costin Manolache360e4542009-09-04 13:36:04 -07001336
Fred Quintanaac9385e2009-06-22 18:00:59 -07001337 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001338 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
Fred Quintana77c560f2010-03-29 22:20:26 -07001341 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001343 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001344 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001345 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1346 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001347 SyncHistoryItem item = null;
1348 int i = mSyncHistory.size();
1349 while (i > 0) {
1350 i--;
1351 item = mSyncHistory.get(i);
1352 if (item.historyId == historyId) {
1353 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001355 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
Costin Manolache360e4542009-09-04 13:36:04 -07001357
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 if (item == null) {
1359 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1360 return;
1361 }
Costin Manolache360e4542009-09-04 13:36:04 -07001362
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 item.elapsedTime = elapsedTime;
1364 item.event = EVENT_STOP;
1365 item.mesg = resultMessage;
1366 item.downstreamActivity = downstreamActivity;
1367 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001368
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001370
Dianne Hackborn231cc602009-04-27 17:10:36 -07001371 status.numSyncs++;
1372 status.totalElapsedTime += elapsedTime;
1373 switch (item.source) {
1374 case SOURCE_LOCAL:
1375 status.numSourceLocal++;
1376 break;
1377 case SOURCE_POLL:
1378 status.numSourcePoll++;
1379 break;
1380 case SOURCE_USER:
1381 status.numSourceUser++;
1382 break;
1383 case SOURCE_SERVER:
1384 status.numSourceServer++;
1385 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001386 case SOURCE_PERIODIC:
1387 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001388 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001389 }
Costin Manolache360e4542009-09-04 13:36:04 -07001390
Dianne Hackborn231cc602009-04-27 17:10:36 -07001391 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001392 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001393 if (mDayStats[0] == null) {
1394 mDayStats[0] = new DayStats(day);
1395 } else if (day != mDayStats[0].day) {
1396 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1397 mDayStats[0] = new DayStats(day);
1398 writeStatisticsNow = true;
1399 } else if (mDayStats[0] == null) {
1400 }
1401 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001402
Dianne Hackborn231cc602009-04-27 17:10:36 -07001403 final long lastSyncTime = (item.eventTime + elapsedTime);
1404 boolean writeStatusNow = false;
1405 if (MESG_SUCCESS.equals(resultMessage)) {
1406 // - if successful, update the successful columns
1407 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1408 writeStatusNow = true;
1409 }
1410 status.lastSuccessTime = lastSyncTime;
1411 status.lastSuccessSource = item.source;
1412 status.lastFailureTime = 0;
1413 status.lastFailureSource = -1;
1414 status.lastFailureMesg = null;
1415 status.initialFailureTime = 0;
1416 ds.successCount++;
1417 ds.successTime += elapsedTime;
1418 } else if (!MESG_CANCELED.equals(resultMessage)) {
1419 if (status.lastFailureTime == 0) {
1420 writeStatusNow = true;
1421 }
1422 status.lastFailureTime = lastSyncTime;
1423 status.lastFailureSource = item.source;
1424 status.lastFailureMesg = resultMessage;
1425 if (status.initialFailureTime == 0) {
1426 status.initialFailureTime = lastSyncTime;
1427 }
1428 ds.failureCount++;
1429 ds.failureTime += elapsedTime;
1430 }
Costin Manolache360e4542009-09-04 13:36:04 -07001431
Dianne Hackborn231cc602009-04-27 17:10:36 -07001432 if (writeStatusNow) {
1433 writeStatusLocked();
1434 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1435 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1436 WRITE_STATUS_DELAY);
1437 }
1438 if (writeStatisticsNow) {
1439 writeStatisticsLocked();
1440 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1441 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1442 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001443 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001444 }
Costin Manolache360e4542009-09-04 13:36:04 -07001445
Fred Quintanaac9385e2009-06-22 18:00:59 -07001446 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 }
1448
1449 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001450 * Return a list of the currently active syncs. Note that the returned
1451 * items are the real, live active sync objects, so be careful what you do
1452 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001453 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001454 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001455 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001456 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001457 }
1458 }
Costin Manolache360e4542009-09-04 13:36:04 -07001459
Dianne Hackborn231cc602009-04-27 17:10:36 -07001460 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001461 * @return a copy of the current syncs data structure. Will not return
1462 * null.
1463 */
1464 public List<SyncInfo> getCurrentSyncsCopy(int userId) {
1465 synchronized (mAuthorities) {
1466 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1467 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1468 for (SyncInfo sync : syncs) {
1469 syncsCopy.add(new SyncInfo(sync));
1470 }
1471 return syncsCopy;
1472 }
1473 }
1474
1475 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1476 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1477 if (syncs == null) {
1478 syncs = new ArrayList<SyncInfo>();
1479 mCurrentSyncs.put(userId, syncs);
1480 }
1481 return syncs;
1482 }
1483
1484 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001485 * Return an array of the current sync status for all authorities. Note
1486 * that the objects inside the array are the real, live status objects,
1487 * so be careful what you do with them.
1488 */
1489 public ArrayList<SyncStatusInfo> getSyncStatus() {
1490 synchronized (mAuthorities) {
1491 final int N = mSyncStatus.size();
1492 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1493 for (int i=0; i<N; i++) {
1494 ops.add(mSyncStatus.valueAt(i));
1495 }
1496 return ops;
1497 }
1498 }
Costin Manolache360e4542009-09-04 13:36:04 -07001499
Dianne Hackborn231cc602009-04-27 17:10:36 -07001500 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001501 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001502 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001503 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001504 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001505 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001506 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001507 true /* write to storage if this results in a change */);
1508 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1509 }
1510 }
1511
1512 /**
1513 * Return a copy of all authorities with their corresponding sync status
1514 */
1515 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1516 synchronized (mAuthorities) {
1517 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1518 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1519 for (int i = 0; i < mAuthorities.size(); i++) {
1520 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001521 }
1522 return infos;
1523 }
1524 }
1525
1526 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001527 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001528 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001529 * @param info the endpoint target we are querying status info for.
1530 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001531 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001532 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1533 if (info.target_provider && (info.account == null || info.provider == null)) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001534 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001535 } else if (info.target_service && info.service == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001536 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001537 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001539 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001540 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001541 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001542 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001543 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001544 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001545 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 }
1547 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001548 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 }
1550 }
Costin Manolache360e4542009-09-04 13:36:04 -07001551
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001552 /** Return true if the pending status is true of any matching authorities. */
1553 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001554 synchronized (mAuthorities) {
1555 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001556 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001557 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1559 if (ainfo == null) {
1560 continue;
1561 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001562 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001563 continue;
1564 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001565 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001566 return true;
1567 }
1568 }
1569 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571 }
1572
1573 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001574 * Return an array of the current sync status for all authorities. Note
1575 * that the objects inside the array are the real, live status objects,
1576 * so be careful what you do with them.
1577 */
1578 public ArrayList<SyncHistoryItem> getSyncHistory() {
1579 synchronized (mAuthorities) {
1580 final int N = mSyncHistory.size();
1581 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1582 for (int i=0; i<N; i++) {
1583 items.add(mSyncHistory.get(i));
1584 }
1585 return items;
1586 }
1587 }
Costin Manolache360e4542009-09-04 13:36:04 -07001588
Dianne Hackborn231cc602009-04-27 17:10:36 -07001589 /**
1590 * Return an array of the current per-day statistics. Note
1591 * that the objects inside the array are the real, live status objects,
1592 * so be careful what you do with them.
1593 */
1594 public DayStats[] getDayStatistics() {
1595 synchronized (mAuthorities) {
1596 DayStats[] ds = new DayStats[mDayStats.length];
1597 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1598 return ds;
1599 }
1600 }
Costin Manolache360e4542009-09-04 13:36:04 -07001601
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001602 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1603 AuthorityInfo authorityInfo) {
1604 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1605 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1606 }
1607
Dianne Hackborn55280a92009-05-07 15:53:46 -07001608 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001609 mCal.setTimeInMillis(System.currentTimeMillis());
1610 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1611 if (mYear != mCal.get(Calendar.YEAR)) {
1612 mYear = mCal.get(Calendar.YEAR);
1613 mCal.clear();
1614 mCal.set(Calendar.YEAR, mYear);
1615 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1616 }
1617 return dayOfYear + mYearInDays;
1618 }
Costin Manolache360e4542009-09-04 13:36:04 -07001619
Dianne Hackborn231cc602009-04-27 17:10:36 -07001620 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001621 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001622 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001623 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001624 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001625 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001626 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001627 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1628 if (info.target_service) {
1629 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1630 AuthorityInfo authority = null;
1631 if (aInfo != null) {
1632 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001633 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001634 if (authority == null) {
1635 if (tag != null) {
1636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001637 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1638 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001639 }
1640 }
1641 return null;
1642 }
1643 return authority;
1644 } else if (info.target_provider){
1645 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1646 AccountInfo accountInfo = mAccounts.get(au);
1647 if (accountInfo == null) {
1648 if (tag != null) {
1649 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1650 Log.v(TAG, tag + ": unknown account " + au);
1651 }
1652 }
1653 return null;
1654 }
1655 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1656 if (authority == null) {
1657 if (tag != null) {
1658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1659 Log.v(TAG, tag + ": unknown provider " + info.provider);
1660 }
1661 }
1662 return null;
1663 }
1664 return authority;
1665 } else {
1666 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001667 return null;
1668 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001669 }
Costin Manolache360e4542009-09-04 13:36:04 -07001670
Matthew Williamsfa774182013-06-18 15:44:11 -07001671 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001672 * @param info info identifying target.
1673 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001674 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001675 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001676 * exists.
1677 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001678 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1679 AuthorityInfo authority = null;
1680 if (info.target_service) {
1681 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1682 if (aInfo == null) {
1683 aInfo = new SparseArray<AuthorityInfo>();
1684 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001685 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001686 authority = aInfo.get(info.userId);
1687 if (authority == null) {
1688 authority = createAuthorityLocked(info, ident, doWrite);
1689 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001690 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001691 } else if (info.target_provider) {
1692 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1693 AccountInfo account = mAccounts.get(au);
1694 if (account == null) {
1695 account = new AccountInfo(au);
1696 mAccounts.put(au, account);
1697 }
1698 authority = account.authorities.get(info.provider);
1699 if (authority == null) {
1700 authority = createAuthorityLocked(info, ident, doWrite);
1701 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001702 }
1703 }
1704 return authority;
1705 }
1706
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001707 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1708 AuthorityInfo authority;
1709 if (ident < 0) {
1710 ident = mNextAuthorityId;
1711 mNextAuthorityId++;
1712 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001713 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001714 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1715 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001716 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001717 authority = new AuthorityInfo(info, ident);
1718 mAuthorities.put(ident, authority);
1719 if (doWrite) {
1720 writeAccountInfoLocked();
1721 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001722 return authority;
1723 }
Costin Manolache360e4542009-09-04 13:36:04 -07001724
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001725 public void removeAuthority(EndPoint info) {
1726 synchronized (mAuthorities) {
1727 if (info.target_provider) {
1728 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1729 } else {
1730 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1731 if (aInfos != null) {
1732 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1733 if (authorityInfo != null) {
1734 mAuthorities.remove(authorityInfo.ident);
1735 aInfos.delete(info.userId);
1736 writeAccountInfoLocked();
1737 }
1738 }
1739
1740 }
1741 }
1742 }
1743
1744 /**
1745 * Remove an authority associated with a provider. Needs to be a standalone function for
1746 * backward compatibility.
1747 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001748 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1749 boolean doWrite) {
1750 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001751 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001752 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1753 if (authorityInfo != null) {
1754 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001755 if (doWrite) {
1756 writeAccountInfoLocked();
1757 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001758 }
1759 }
1760 }
1761
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001762 /**
1763 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001764 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001765 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001766 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001767 boolean found = false;
1768 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001769 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001770 authorityInfo = mAuthorities.get(authorityId);
1771 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001772 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1773 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001774 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001775 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001776 break;
1777 }
1778 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001779 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001780 if (!found) {
1781 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001782 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001783 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001784 }
1785
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1787 SyncStatusInfo status = mSyncStatus.get(authorityId);
1788 if (status == null) {
1789 status = new SyncStatusInfo(authorityId);
1790 mSyncStatus.put(authorityId, status);
1791 }
1792 return status;
1793 }
Costin Manolache360e4542009-09-04 13:36:04 -07001794
Dianne Hackborn55280a92009-05-07 15:53:46 -07001795 public void writeAllState() {
1796 synchronized (mAuthorities) {
1797 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001798
Dianne Hackborn55280a92009-05-07 15:53:46 -07001799 if (mNumPendingFinished > 0) {
1800 // Only write these if they are out of date.
1801 writePendingOperationsLocked();
1802 }
Costin Manolache360e4542009-09-04 13:36:04 -07001803
Dianne Hackborn55280a92009-05-07 15:53:46 -07001804 // Just always write these... they are likely out of date.
1805 writeStatusLocked();
1806 writeStatisticsLocked();
1807 }
1808 }
Costin Manolache360e4542009-09-04 13:36:04 -07001809
Dianne Hackborn231cc602009-04-27 17:10:36 -07001810 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001811 * public for testing
1812 */
1813 public void clearAndReadState() {
1814 synchronized (mAuthorities) {
1815 mAuthorities.clear();
1816 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001817 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001818 mPendingOperations.clear();
1819 mSyncStatus.clear();
1820 mSyncHistory.clear();
1821
1822 readAccountInfoLocked();
1823 readStatusLocked();
1824 readPendingOperationsLocked();
1825 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001826 readAndDeleteLegacyAccountInfoLocked();
1827 writeAccountInfoLocked();
1828 writeStatusLocked();
1829 writePendingOperationsLocked();
1830 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001831 }
1832 }
1833
1834 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001835 * Read all account information back in to the initial engine state.
1836 */
1837 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001838 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001839 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001841 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001842 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001843 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001844 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001845 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001846 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001847 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001848 while (eventType != XmlPullParser.START_TAG &&
1849 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001850 eventType = parser.next();
1851 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001852 if (eventType == XmlPullParser.END_DOCUMENT) {
1853 Log.i(TAG, "No initial accounts");
1854 return;
1855 }
1856
Dianne Hackborn231cc602009-04-27 17:10:36 -07001857 String tagName = parser.getName();
1858 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001859 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001860 String versionString = parser.getAttributeValue(null, "version");
1861 int version;
1862 try {
1863 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1864 } catch (NumberFormatException e) {
1865 version = 0;
1866 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001867 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001868 try {
1869 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1870 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1871 } catch (NumberFormatException e) {
1872 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001873 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001874 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1875 try {
1876 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1877 } catch (NumberFormatException e) {
1878 mSyncRandomOffset = 0;
1879 }
1880 if (mSyncRandomOffset == 0) {
1881 Random random = new Random(System.currentTimeMillis());
1882 mSyncRandomOffset = random.nextInt(86400);
1883 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001884 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001886 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001887 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001889 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001890 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001891 if (parser.getDepth() == 2) {
1892 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001893 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001894 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001895 if (authority.ident > highestAuthorityId) {
1896 highestAuthorityId = authority.ident;
1897 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001898 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1899 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001900 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001901 } else if (parser.getDepth() == 3) {
1902 if ("periodicSync".equals(tagName) && authority != null) {
1903 periodicSync = parsePeriodicSync(parser, authority);
1904 }
1905 } else if (parser.getDepth() == 4 && periodicSync != null) {
1906 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001907 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 }
1909 }
1910 }
1911 eventType = parser.next();
1912 } while (eventType != XmlPullParser.END_DOCUMENT);
1913 }
1914 } catch (XmlPullParserException e) {
1915 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001916 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001917 } catch (java.io.IOException e) {
1918 if (fis == null) Log.i(TAG, "No initial accounts");
1919 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001920 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001921 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001922 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 if (fis != null) {
1924 try {
1925 fis.close();
1926 } catch (java.io.IOException e1) {
1927 }
1928 }
1929 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001930
Fred Quintana77c560f2010-03-29 22:20:26 -07001931 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 }
Costin Manolache360e4542009-09-04 13:36:04 -07001933
Fred Quintanafb084402010-03-23 17:57:03 -07001934 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001935 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1936 * pending.xml was used starting in KLP.
1937 * @param syncDir directory where the sync files are located.
1938 */
1939 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1940 File file = new File(syncDir, "pending.bin");
1941 if (!file.exists()) {
1942 return;
1943 } else {
1944 file.delete();
1945 }
1946 }
1947
1948 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001949 * some authority names have changed. copy over their settings and delete the old ones
1950 * @return true if a change was made
1951 */
1952 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1953 boolean writeNeeded = false;
1954
1955 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1956 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001957 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001958 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001959 // skip this authority if it doesn't target a provider
1960 if (authority.target.target_service) {
1961 continue;
1962 }
Fred Quintanafb084402010-03-23 17:57:03 -07001963 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001964 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001965 if (newAuthorityName == null) {
1966 continue;
1967 }
1968
1969 // remember this authority so we can remove it later. we can't remove it
1970 // now without messing up this loop iteration
1971 authoritiesToRemove.add(authority);
1972
1973 // this authority isn't enabled, no need to copy it to the new authority name since
1974 // the default is "disabled"
1975 if (!authority.enabled) {
1976 continue;
1977 }
1978
1979 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001980 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001981 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001982 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001983 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001984 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001985 continue;
1986 }
1987
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001988 AuthorityInfo newAuthority =
1989 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001990 newAuthority.enabled = true;
1991 writeNeeded = true;
1992 }
1993
1994 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001995 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001996 authorityInfo.target.account,
1997 authorityInfo.target.userId,
1998 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001999 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07002000 writeNeeded = true;
2001 }
2002
2003 return writeNeeded;
2004 }
2005
Amith Yamasani04e0d262012-02-14 11:50:53 -08002006 private void parseListenForTickles(XmlPullParser parser) {
2007 String user = parser.getAttributeValue(null, XML_ATTR_USER);
2008 int userId = 0;
2009 try {
2010 userId = Integer.parseInt(user);
2011 } catch (NumberFormatException e) {
2012 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
2013 } catch (NullPointerException e) {
2014 Log.e(TAG, "the user in listen-for-tickles is null", e);
2015 }
2016 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
2017 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
2018 mMasterSyncAutomatically.put(userId, listen);
2019 }
2020
Fred Quintanac2e46912010-03-15 16:10:44 -07002021 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002022 AuthorityInfo authority = null;
2023 int id = -1;
2024 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002025 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002026 } catch (NumberFormatException e) {
2027 Log.e(TAG, "error parsing the id of the authority", e);
2028 } catch (NullPointerException e) {
2029 Log.e(TAG, "the id of the authority is null", e);
2030 }
2031 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07002032 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002033 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07002034 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002035 String accountName = parser.getAttributeValue(null, "account");
2036 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002037 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07002038 String packageName = parser.getAttributeValue(null, "package");
2039 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002040 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07002041 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002042 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07002043 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002044 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002045 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002046 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002047 Log.v(TAG_FILE, "Adding authority:"
2048 + " account=" + accountName
2049 + " accountType=" + accountType
2050 + " auth=" + authorityName
2051 + " package=" + packageName
2052 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07002053 + " user=" + userId
2054 + " enabled=" + enabled
2055 + " syncable=" + syncable);
2056 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002057 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002058 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002059 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002060 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002061 EndPoint info;
2062 if (accountName != null && authorityName != null) {
2063 info = new EndPoint(
2064 new Account(accountName, accountType),
2065 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002066 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002067 info = new EndPoint(
2068 new ComponentName(packageName, className),
2069 userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002070 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002071 authority = getOrCreateAuthorityLocked(info, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07002072 // If the version is 0 then we are upgrading from a file format that did not
2073 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002074 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002075 // Otherwise clear out this default list since we will populate it later with
2076 // the periodic sync descriptions that are read from the configuration file.
2077 if (version > 0) {
2078 authority.periodicSyncs.clear();
2079 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002080 }
2081 if (authority != null) {
2082 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07002083 try {
2084 authority.syncable = (syncable == null) ?
2085 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
2086 } catch (NumberFormatException e) {
2087 // On L we stored this as {"unknown", "true", "false"} so fall back to this
2088 // format.
2089 if ("unknown".equals(syncable)) {
2090 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
2091 } else {
2092 authority.syncable = Boolean.parseBoolean(syncable) ?
2093 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
2094 }
2095
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002096 }
2097 } else {
2098 Log.w(TAG, "Failure adding authority: account="
2099 + accountName + " auth=" + authorityName
2100 + " enabled=" + enabled
2101 + " syncable=" + syncable);
2102 }
2103 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002104 return authority;
2105 }
2106
Matthew Williamsfa774182013-06-18 15:44:11 -07002107 /**
2108 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2109 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002110 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002111 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002112 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002113 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002114 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002115 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002116 try {
2117 period = Long.parseLong(periodValue);
2118 } catch (NumberFormatException e) {
2119 Log.e(TAG, "error parsing the period of a periodic sync", e);
2120 return null;
2121 } catch (NullPointerException e) {
2122 Log.e(TAG, "the period of a periodic sync is null", e);
2123 return null;
2124 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002125 try {
2126 flextime = Long.parseLong(flexValue);
2127 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002128 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002129 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2130 + ", using default: "
2131 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002132 } catch (NullPointerException expected) {
2133 flextime = calculateDefaultFlexTime(period);
2134 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2135 + period + " flex: " + flextime);
2136 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002137 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002138 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002139 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002140 new PeriodicSync(authorityInfo.target.account,
2141 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002142 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002143 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002144 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002145 Log.e(TAG, "Unknown target.");
2146 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002147 }
2148 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002149 return periodicSync;
2150 }
2151
Matthew Williamsfa774182013-06-18 15:44:11 -07002152 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002153 String name = parser.getAttributeValue(null, "name");
2154 String type = parser.getAttributeValue(null, "type");
2155 String value1 = parser.getAttributeValue(null, "value1");
2156 String value2 = parser.getAttributeValue(null, "value2");
2157
2158 try {
2159 if ("long".equals(type)) {
2160 extras.putLong(name, Long.parseLong(value1));
2161 } else if ("integer".equals(type)) {
2162 extras.putInt(name, Integer.parseInt(value1));
2163 } else if ("double".equals(type)) {
2164 extras.putDouble(name, Double.parseDouble(value1));
2165 } else if ("float".equals(type)) {
2166 extras.putFloat(name, Float.parseFloat(value1));
2167 } else if ("boolean".equals(type)) {
2168 extras.putBoolean(name, Boolean.parseBoolean(value1));
2169 } else if ("string".equals(type)) {
2170 extras.putString(name, value1);
2171 } else if ("account".equals(type)) {
2172 extras.putParcelable(name, new Account(value1, value2));
2173 }
2174 } catch (NumberFormatException e) {
2175 Log.e(TAG, "error parsing bundle value", e);
2176 } catch (NullPointerException e) {
2177 Log.e(TAG, "error parsing bundle value", e);
2178 }
2179 }
2180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 /**
2182 * Write all account information to the account file.
2183 */
2184 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002185 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002186 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002187 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002188 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002189
Dianne Hackborn231cc602009-04-27 17:10:36 -07002190 try {
2191 fos = mAccountInfoFile.startWrite();
2192 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002193 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07002194 out.startDocument(null, true);
2195 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002196
Dianne Hackborn231cc602009-04-27 17:10:36 -07002197 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002198 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002200 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002201
2202 // Write the Sync Automatically flags for each user
2203 final int M = mMasterSyncAutomatically.size();
2204 for (int m = 0; m < M; m++) {
2205 int userId = mMasterSyncAutomatically.keyAt(m);
2206 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2207 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2208 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2209 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2210 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002211 }
Costin Manolache360e4542009-09-04 13:36:04 -07002212
Dianne Hackborn231cc602009-04-27 17:10:36 -07002213 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002214 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002215 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002216 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002217 out.startTag(null, "authority");
2218 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002219 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002220 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002221 if (info.service == null) {
2222 out.attribute(null, "account", info.account.name);
2223 out.attribute(null, "type", info.account.type);
2224 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002225 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002226 out.attribute(null, "package", info.service.getPackageName());
2227 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002228 }
Matthew Williams53abfdb2015-06-10 20:06:37 -07002229 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Matthew Williamsfa774182013-06-18 15:44:11 -07002230 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002231 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002232 out.attribute(null, "period", Long.toString(periodicSync.period));
2233 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2234 final Bundle extras = periodicSync.extras;
2235 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002236 out.endTag(null, "periodicSync");
2237 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002238 out.endTag(null, "authority");
2239 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002240 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002241 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002242 mAccountInfoFile.finishWrite(fos);
2243 } catch (java.io.IOException e1) {
2244 Log.w(TAG, "Error writing accounts", e1);
2245 if (fos != null) {
2246 mAccountInfoFile.failWrite(fos);
2247 }
2248 }
2249 }
Costin Manolache360e4542009-09-04 13:36:04 -07002250
Dianne Hackborn231cc602009-04-27 17:10:36 -07002251 static int getIntColumn(Cursor c, String name) {
2252 return c.getInt(c.getColumnIndex(name));
2253 }
Costin Manolache360e4542009-09-04 13:36:04 -07002254
Dianne Hackborn231cc602009-04-27 17:10:36 -07002255 static long getLongColumn(Cursor c, String name) {
2256 return c.getLong(c.getColumnIndex(name));
2257 }
Costin Manolache360e4542009-09-04 13:36:04 -07002258
Dianne Hackborn231cc602009-04-27 17:10:36 -07002259 /**
2260 * Load sync engine state from the old syncmanager database, and then
2261 * erase it. Note that we don't deal with pending operations, active
2262 * sync, or history.
2263 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002264 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002265 // Look for old database to initialize from.
2266 File file = mContext.getDatabasePath("syncmanager.db");
2267 if (!file.exists()) {
2268 return;
2269 }
2270 String path = file.getPath();
2271 SQLiteDatabase db = null;
2272 try {
2273 db = SQLiteDatabase.openDatabase(path, null,
2274 SQLiteDatabase.OPEN_READONLY);
2275 } catch (SQLiteException e) {
2276 }
Costin Manolache360e4542009-09-04 13:36:04 -07002277
Dianne Hackborn231cc602009-04-27 17:10:36 -07002278 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002279 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002280
Dianne Hackborn231cc602009-04-27 17:10:36 -07002281 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002282 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002283 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002284 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002285 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2286 qb.setTables("stats, status");
2287 HashMap<String,String> map = new HashMap<String,String>();
2288 map.put("_id", "status._id as _id");
2289 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002290 if (hasType) {
2291 map.put("account_type", "stats.account_type as account_type");
2292 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002293 map.put("authority", "stats.authority as authority");
2294 map.put("totalElapsedTime", "totalElapsedTime");
2295 map.put("numSyncs", "numSyncs");
2296 map.put("numSourceLocal", "numSourceLocal");
2297 map.put("numSourcePoll", "numSourcePoll");
2298 map.put("numSourceServer", "numSourceServer");
2299 map.put("numSourceUser", "numSourceUser");
2300 map.put("lastSuccessSource", "lastSuccessSource");
2301 map.put("lastSuccessTime", "lastSuccessTime");
2302 map.put("lastFailureSource", "lastFailureSource");
2303 map.put("lastFailureTime", "lastFailureTime");
2304 map.put("lastFailureMesg", "lastFailureMesg");
2305 map.put("pending", "pending");
2306 qb.setProjectionMap(map);
2307 qb.appendWhere("stats._id = status.stats_id");
2308 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002310 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002311 String accountType = hasType
2312 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002313 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002314 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002316 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002317 AuthorityInfo authority =
2318 this.getOrCreateAuthorityLocked(
2319 new EndPoint(new Account(accountName, accountType),
2320 authorityName,
2321 0 /* legacy is single-user */)
2322 , -1,
2323 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002324 if (authority != null) {
2325 int i = mSyncStatus.size();
2326 boolean found = false;
2327 SyncStatusInfo st = null;
2328 while (i > 0) {
2329 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002330 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002331 if (st.authorityId == authority.ident) {
2332 found = true;
2333 break;
2334 }
2335 }
2336 if (!found) {
2337 st = new SyncStatusInfo(authority.ident);
2338 mSyncStatus.put(authority.ident, st);
2339 }
2340 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2341 st.numSyncs = getIntColumn(c, "numSyncs");
2342 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2343 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2344 st.numSourceServer = getIntColumn(c, "numSourceServer");
2345 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002346 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002347 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2348 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2349 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2350 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2351 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2352 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 }
Costin Manolache360e4542009-09-04 13:36:04 -07002355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002357
Dianne Hackborn231cc602009-04-27 17:10:36 -07002358 // Retrieve the settings.
2359 qb = new SQLiteQueryBuilder();
2360 qb.setTables("settings");
2361 c = qb.query(db, null, null, null, null, null, null);
2362 while (c.moveToNext()) {
2363 String name = c.getString(c.getColumnIndex("name"));
2364 String value = c.getString(c.getColumnIndex("value"));
2365 if (name == null) continue;
2366 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002367 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002368 } else if (name.startsWith("sync_provider_")) {
2369 String provider = name.substring("sync_provider_".length(),
2370 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002371 int i = mAuthorities.size();
2372 while (i > 0) {
2373 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002374 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002375 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002376 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002377 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002378 }
2379 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 }
Costin Manolache360e4542009-09-04 13:36:04 -07002382
Dianne Hackborn231cc602009-04-27 17:10:36 -07002383 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002384
Dianne Hackborn231cc602009-04-27 17:10:36 -07002385 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002386
Dianne Hackborn231cc602009-04-27 17:10:36 -07002387 (new File(path)).delete();
2388 }
2389 }
Costin Manolache360e4542009-09-04 13:36:04 -07002390
Dianne Hackborn231cc602009-04-27 17:10:36 -07002391 public static final int STATUS_FILE_END = 0;
2392 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002393
Dianne Hackborn231cc602009-04-27 17:10:36 -07002394 /**
2395 * Read all sync status back in to the initial engine state.
2396 */
2397 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002398 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002399 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002400 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002401 try {
2402 byte[] data = mStatusFile.readFully();
2403 Parcel in = Parcel.obtain();
2404 in.unmarshall(data, 0, data.length);
2405 in.setDataPosition(0);
2406 int token;
2407 while ((token=in.readInt()) != STATUS_FILE_END) {
2408 if (token == STATUS_FILE_ITEM) {
2409 SyncStatusInfo status = new SyncStatusInfo(in);
2410 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2411 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002412 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002413 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002414 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002415 mSyncStatus.put(status.authorityId, status);
2416 }
2417 } else {
2418 // Ooops.
2419 Log.w(TAG, "Unknown status token: " + token);
2420 break;
2421 }
2422 }
2423 } catch (java.io.IOException e) {
2424 Log.i(TAG, "No initial status");
2425 }
2426 }
Costin Manolache360e4542009-09-04 13:36:04 -07002427
Dianne Hackborn231cc602009-04-27 17:10:36 -07002428 /**
2429 * Write all sync status to the sync status file.
2430 */
2431 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002432 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002433 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002434 }
Costin Manolache360e4542009-09-04 13:36:04 -07002435
Dianne Hackborn231cc602009-04-27 17:10:36 -07002436 // The file is being written, so we don't need to have a scheduled
2437 // write until the next change.
2438 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002439
Dianne Hackborn231cc602009-04-27 17:10:36 -07002440 FileOutputStream fos = null;
2441 try {
2442 fos = mStatusFile.startWrite();
2443 Parcel out = Parcel.obtain();
2444 final int N = mSyncStatus.size();
2445 for (int i=0; i<N; i++) {
2446 SyncStatusInfo status = mSyncStatus.valueAt(i);
2447 out.writeInt(STATUS_FILE_ITEM);
2448 status.writeToParcel(out, 0);
2449 }
2450 out.writeInt(STATUS_FILE_END);
2451 fos.write(out.marshall());
2452 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002453
Dianne Hackborn231cc602009-04-27 17:10:36 -07002454 mStatusFile.finishWrite(fos);
2455 } catch (java.io.IOException e1) {
2456 Log.w(TAG, "Error writing status", e1);
2457 if (fos != null) {
2458 mStatusFile.failWrite(fos);
2459 }
2460 }
2461 }
Costin Manolache360e4542009-09-04 13:36:04 -07002462
Matthew Williamsba352712013-08-13 15:53:31 -07002463 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002464
Matthew Williamsba352712013-08-13 15:53:31 -07002465 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002466 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002467 FileInputStream fis = null;
2468 if (!mPendingFile.getBaseFile().exists()) {
2469 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2470 Log.v(TAG_FILE, "No pending operation file.");
Matthew Williamsfa774182013-06-18 15:44:11 -07002471 }
Ji-Hwan Lee886113d2014-04-17 14:16:38 +09002472 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002473 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002474 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002475 fis = mPendingFile.openRead();
Matthew Williams06485a72013-07-26 12:56:39 -07002476 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2477 Log.v(TAG_FILE, "Reading " + mPendingFile.getBaseFile());
2478 }
Matthew Williamsba352712013-08-13 15:53:31 -07002479 XmlPullParser parser;
2480 parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002481 parser.setInput(fis, StandardCharsets.UTF_8.name());
Matthew Williamsba352712013-08-13 15:53:31 -07002482
Matthew Williamsfa774182013-06-18 15:44:11 -07002483 int eventType = parser.getEventType();
2484 while (eventType != XmlPullParser.START_TAG &&
2485 eventType != XmlPullParser.END_DOCUMENT) {
2486 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002487 }
Matthew Williamsba352712013-08-13 15:53:31 -07002488 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002489
Matthew Williamsba352712013-08-13 15:53:31 -07002490 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002491 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002492 if (eventType == XmlPullParser.START_TAG) {
2493 try {
Matthew Williams06485a72013-07-26 12:56:39 -07002494 String tagName = parser.getName();
Matthew Williams8ef22042013-07-26 12:56:39 -07002495 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2496 // Verify version.
2497 String versionString =
2498 parser.getAttributeValue(null, XML_ATTR_VERSION);
2499 if (versionString == null ||
2500 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2501 Log.w(TAG, "Unknown pending operation version " + versionString);
2502 throw new java.io.IOException("Unknown version.");
2503 }
2504 int authorityId = Integer.valueOf(parser.getAttributeValue(
2505 null, XML_ATTR_AUTHORITYID));
2506 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2507 null, XML_ATTR_EXPEDITED));
2508 int syncSource = Integer.valueOf(parser.getAttributeValue(
2509 null, XML_ATTR_SOURCE));
2510 int reason = Integer.valueOf(parser.getAttributeValue(
2511 null, XML_ATTR_REASON));
2512 AuthorityInfo authority = mAuthorities.get(authorityId);
2513 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2514 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2515 + reason);
2516 }
2517 if (authority != null) {
2518 pop = new PendingOperation(
2519 authority, reason, syncSource, new Bundle(), expedited);
2520 pop.flatExtras = null; // No longer used.
2521 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002522 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002523 Log.v(TAG_FILE, "Adding pending op: "
2524 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002525 + " src=" + pop.syncSource
2526 + " reason=" + pop.reason
2527 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002528 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002529 } else {
2530 // Skip non-existent authority.
2531 pop = null;
2532 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2533 Log.v(TAG_FILE, "No authority found for " + authorityId
2534 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002535 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002536 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002537 } else if (parser.getDepth() == 2 &&
2538 pop != null &&
2539 "extra".equals(tagName)) {
2540 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002541 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002542 } catch (NumberFormatException e) {
2543 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002544 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002545 }
Matthew Williamsba352712013-08-13 15:53:31 -07002546 eventType = parser.next();
2547 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002548 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002549 Log.w(TAG_FILE, "Error reading pending data.", e);
2550 } catch (XmlPullParserException e) {
2551 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2552 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2553 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002554 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002555 if (fis != null) {
2556 try {
2557 fis.close();
2558 } catch (java.io.IOException e1) {}
2559 }
2560 }
2561 }
Matthew Williamsba352712013-08-13 15:53:31 -07002562
Dianne Hackborn231cc602009-04-27 17:10:36 -07002563 static private byte[] flattenBundle(Bundle bundle) {
2564 byte[] flatData = null;
2565 Parcel parcel = Parcel.obtain();
2566 try {
2567 bundle.writeToParcel(parcel, 0);
2568 flatData = parcel.marshall();
2569 } finally {
2570 parcel.recycle();
2571 }
2572 return flatData;
2573 }
Costin Manolache360e4542009-09-04 13:36:04 -07002574
Dianne Hackborn231cc602009-04-27 17:10:36 -07002575 static private Bundle unflattenBundle(byte[] flatData) {
2576 Bundle bundle;
2577 Parcel parcel = Parcel.obtain();
2578 try {
2579 parcel.unmarshall(flatData, 0, flatData.length);
2580 parcel.setDataPosition(0);
2581 bundle = parcel.readBundle();
2582 } catch (RuntimeException e) {
2583 // A RuntimeException is thrown if we were unable to parse the parcel.
2584 // Create an empty parcel in this case.
2585 bundle = new Bundle();
2586 } finally {
2587 parcel.recycle();
2588 }
2589 return bundle;
2590 }
Costin Manolache360e4542009-09-04 13:36:04 -07002591
Matthew Williams8ef22042013-07-26 12:56:39 -07002592 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002593 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2594 private static final String XML_ATTR_SOURCE = "source";
2595 private static final String XML_ATTR_EXPEDITED = "expedited";
2596 private static final String XML_ATTR_REASON = "reason";
2597
2598 /**
2599 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002600 */
2601 private void writePendingOperationsLocked() {
2602 final int N = mPendingOperations.size();
2603 FileOutputStream fos = null;
2604 try {
2605 if (N == 0) {
2606 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2607 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2608 }
2609 mPendingFile.truncate();
2610 return;
2611 }
2612 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2613 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2614 }
2615 fos = mPendingFile.startWrite();
2616 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002617 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002618
2619 for (int i = 0; i < N; i++) {
2620 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002621 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002622 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002623 out.endDocument();
2624 mPendingFile.finishWrite(fos);
2625 } catch (java.io.IOException e1) {
2626 Log.w(TAG, "Error writing pending operations", e1);
2627 if (fos != null) {
2628 mPendingFile.failWrite(fos);
2629 }
2630 }
2631 }
2632
Matthew Williams8ef22042013-07-26 12:56:39 -07002633 /** Write all currently pending ops to the pending ops file. */
2634 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2635 throws IOException {
2636 // Pending operation.
2637 out.startTag(null, "op");
2638
2639 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2640 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2641 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2642 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2643 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2644 extrasToXml(out, pop.extras);
2645
2646 out.endTag(null, "op");
2647 }
2648
2649 /**
2650 * Append the given operation to the pending ops file; if unable to,
2651 * write all pending ops.
2652 */
2653 private void appendPendingOperationLocked(PendingOperation op) {
2654 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2655 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2656 }
2657 FileOutputStream fos = null;
2658 try {
2659 fos = mPendingFile.openAppend();
2660 } catch (java.io.IOException e) {
2661 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2662 Log.v(TAG, "Failed append; writing full file");
2663 }
2664 writePendingOperationsLocked();
2665 return;
2666 }
2667
2668 try {
2669 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002670 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams8ef22042013-07-26 12:56:39 -07002671 writePendingOperationLocked(op, out);
2672 out.endDocument();
2673 mPendingFile.finishWrite(fos);
2674 } catch (java.io.IOException e1) {
2675 Log.w(TAG, "Error writing appending operation", e1);
2676 mPendingFile.failWrite(fos);
2677 } finally {
2678 try {
2679 fos.close();
2680 } catch (IOException e) {}
2681 }
2682 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002683
Matthew Williamsfa774182013-06-18 15:44:11 -07002684 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2685 for (String key : extras.keySet()) {
2686 out.startTag(null, "extra");
2687 out.attribute(null, "name", key);
2688 final Object value = extras.get(key);
2689 if (value instanceof Long) {
2690 out.attribute(null, "type", "long");
2691 out.attribute(null, "value1", value.toString());
2692 } else if (value instanceof Integer) {
2693 out.attribute(null, "type", "integer");
2694 out.attribute(null, "value1", value.toString());
2695 } else if (value instanceof Boolean) {
2696 out.attribute(null, "type", "boolean");
2697 out.attribute(null, "value1", value.toString());
2698 } else if (value instanceof Float) {
2699 out.attribute(null, "type", "float");
2700 out.attribute(null, "value1", value.toString());
2701 } else if (value instanceof Double) {
2702 out.attribute(null, "type", "double");
2703 out.attribute(null, "value1", value.toString());
2704 } else if (value instanceof String) {
2705 out.attribute(null, "type", "string");
2706 out.attribute(null, "value1", value.toString());
2707 } else if (value instanceof Account) {
2708 out.attribute(null, "type", "account");
2709 out.attribute(null, "value1", ((Account)value).name);
2710 out.attribute(null, "value2", ((Account)value).type);
2711 }
2712 out.endTag(null, "extra");
2713 }
2714 }
2715
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002716 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2717 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2718 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002719 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002720 } else {
2721 SyncRequest.Builder req =
2722 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002723 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002724 .setExtras(extras);
2725 if (authorityInfo.target.target_provider) {
2726 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002727 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002728 if (Log.isLoggable(TAG, Log.DEBUG)) {
2729 Log.d(TAG, "Unknown target, skipping sync request.");
2730 }
2731 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002732 }
2733 ContentResolver.requestSync(req.build());
2734 }
2735 }
2736
Alon Albert57286f92012-10-09 14:21:38 -07002737 private void requestSync(Account account, int userId, int reason, String authority,
2738 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002739 // If this is happening in the system process, then call the syncrequest listener
2740 // to make a request back to the SyncManager directly.
2741 // If this is probably a test instance, then call back through the ContentResolver
2742 // which will know which userId to apply based on the Binder id.
2743 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2744 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002745 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002746 new EndPoint(account, authority, userId),
2747 reason,
2748 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002749 } else {
2750 ContentResolver.requestSync(account, authority, extras);
2751 }
2752 }
2753
Dianne Hackborn231cc602009-04-27 17:10:36 -07002754 public static final int STATISTICS_FILE_END = 0;
2755 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2756 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002757
Dianne Hackborn231cc602009-04-27 17:10:36 -07002758 /**
2759 * Read all sync statistics back in to the initial engine state.
2760 */
2761 private void readStatisticsLocked() {
2762 try {
2763 byte[] data = mStatisticsFile.readFully();
2764 Parcel in = Parcel.obtain();
2765 in.unmarshall(data, 0, data.length);
2766 in.setDataPosition(0);
2767 int token;
2768 int index = 0;
2769 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2770 if (token == STATISTICS_FILE_ITEM
2771 || token == STATISTICS_FILE_ITEM_OLD) {
2772 int day = in.readInt();
2773 if (token == STATISTICS_FILE_ITEM_OLD) {
2774 day = day - 2009 + 14245; // Magic!
2775 }
2776 DayStats ds = new DayStats(day);
2777 ds.successCount = in.readInt();
2778 ds.successTime = in.readLong();
2779 ds.failureCount = in.readInt();
2780 ds.failureTime = in.readLong();
2781 if (index < mDayStats.length) {
2782 mDayStats[index] = ds;
2783 index++;
2784 }
2785 } else {
2786 // Ooops.
2787 Log.w(TAG, "Unknown stats token: " + token);
2788 break;
2789 }
2790 }
2791 } catch (java.io.IOException e) {
2792 Log.i(TAG, "No initial statistics");
2793 }
2794 }
Costin Manolache360e4542009-09-04 13:36:04 -07002795
Dianne Hackborn231cc602009-04-27 17:10:36 -07002796 /**
2797 * Write all sync statistics to the sync status file.
2798 */
2799 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002800 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2801 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2802 }
Costin Manolache360e4542009-09-04 13:36:04 -07002803
Dianne Hackborn231cc602009-04-27 17:10:36 -07002804 // The file is being written, so we don't need to have a scheduled
2805 // write until the next change.
2806 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002807
Dianne Hackborn231cc602009-04-27 17:10:36 -07002808 FileOutputStream fos = null;
2809 try {
2810 fos = mStatisticsFile.startWrite();
2811 Parcel out = Parcel.obtain();
2812 final int N = mDayStats.length;
2813 for (int i=0; i<N; i++) {
2814 DayStats ds = mDayStats[i];
2815 if (ds == null) {
2816 break;
2817 }
2818 out.writeInt(STATISTICS_FILE_ITEM);
2819 out.writeInt(ds.day);
2820 out.writeInt(ds.successCount);
2821 out.writeLong(ds.successTime);
2822 out.writeInt(ds.failureCount);
2823 out.writeLong(ds.failureTime);
2824 }
2825 out.writeInt(STATISTICS_FILE_END);
2826 fos.write(out.marshall());
2827 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002828
Dianne Hackborn231cc602009-04-27 17:10:36 -07002829 mStatisticsFile.finishWrite(fos);
2830 } catch (java.io.IOException e1) {
2831 Log.w(TAG, "Error writing stats", e1);
2832 if (fos != null) {
2833 mStatisticsFile.failWrite(fos);
2834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002837
2838 /**
2839 * Dump state of PendingOperations.
2840 */
2841 public void dumpPendingOperations(StringBuilder sb) {
2842 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2843 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002844 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002845 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002846 .append(")\n");
2847 }
2848 }
Marvin Paula6533252014-11-24 12:57:48 -08002849
2850 /**
2851 * Let the BackupManager know that account sync settings have changed. This will trigger
2852 * {@link com.android.server.backup.SystemBackupAgent} to run.
2853 */
2854 public void queueBackup() {
2855 BackupManager.dataChanged("android");
2856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857}