blob: 8266c08f310f383ac48494c3d073bb5b9a56ded6 [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;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070030import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070033import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070035import android.os.Bundle;
36import android.os.Environment;
37import android.os.Handler;
38import android.os.Message;
39import android.os.Parcel;
40import android.os.RemoteCallbackList;
41import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070042import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070043import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080045import android.util.Pair;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070046import android.util.Slog;
Dianne Hackborn231cc602009-04-27 17:10:36 -070047import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070048import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070049import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080050
51import com.android.internal.annotations.VisibleForTesting;
52import com.android.internal.util.ArrayUtils;
53import com.android.internal.util.FastXmlSerializer;
54
55import org.xmlpull.v1.XmlPullParser;
56import org.xmlpull.v1.XmlPullParserException;
57import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.io.File;
60import java.io.FileInputStream;
61import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070062import java.io.IOException;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010063import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070065import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070067import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080068import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070069import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060070import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070073 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070075 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * @hide
77 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070078public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070081 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070082
Amith Yamasani04e0d262012-02-14 11:50:53 -080083 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
84 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070085 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080086 private static final String XML_ATTR_ENABLED = "enabled";
87 private static final String XML_ATTR_USER = "user";
88 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
89
Matthew Williamsfa774182013-06-18 15:44:11 -070090 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080091 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
92
Matthew Williamsfa774182013-06-18 15:44:11 -070093 /** Percentage of period that is flex by default, if no flex is set. */
94 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
95
96 /** Lower bound on sync time from which we assign a default flex time. */
97 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
98
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080099 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 /** Enum value for a sync start event. */
103 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Dianne Hackborn231cc602009-04-27 17:10:36 -0700105 /** Enum value for a sync stop event. */
106 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 // TODO: i18n -- grab these out of resources.
109 /** String names for the sync event types. */
110 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Dianne Hackborn231cc602009-04-27 17:10:36 -0700112 /** Enum value for a server-initiated sync. */
113 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Dianne Hackborn231cc602009-04-27 17:10:36 -0700115 /** Enum value for a local-initiated sync. */
116 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700117 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700118 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Dianne Hackborn231cc602009-04-27 17:10:36 -0700120 /** Enum value for a user-initiated sync. */
121 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800123 /** Enum value for a periodic sync. */
124 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700125
126 /** Enum value for a sync started for a service. */
127 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800128
Fred Quintana307da1a2010-01-21 14:24:20 -0800129 public static final long NOT_IN_BACKOFF_MODE = -1;
130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 // TODO: i18n -- grab these out of resources.
132 /** String names for the sync source types. */
133 public static final String[] SOURCES = { "SERVER",
134 "LOCAL",
135 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800136 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700137 "PERIODIC",
138 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Dianne Hackborn231cc602009-04-27 17:10:36 -0700140 // The MESG column will contain one of these or one of the Error types.
141 public static final String MESG_SUCCESS = "success";
142 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700144 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700145
Dianne Hackborn231cc602009-04-27 17:10:36 -0700146 private static final int MSG_WRITE_STATUS = 1;
147 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700148
Dianne Hackborn231cc602009-04-27 17:10:36 -0700149 private static final int MSG_WRITE_STATISTICS = 2;
150 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700151
152 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700153
Fred Quintanac2e46912010-03-15 16:10:44 -0700154 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700155 private static final int ACCOUNTS_VERSION = 2;
156
157 private static HashMap<String, String> sAuthorityRenames;
158
159 static {
160 sAuthorityRenames = new HashMap<String, String>();
161 sAuthorityRenames.put("contacts", "com.android.contacts");
162 sAuthorityRenames.put("calendar", "com.android.calendar");
163 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700164
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700166 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700167 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700168 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700169 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800170 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700171
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700172 final int authorityId;
173 // No longer used.
174 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700175 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700176
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700177 PendingOperation(AuthorityInfo authority, int reason, int source,
178 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700179 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700181 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700182 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800183 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700184 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 }
186
187 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700188 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700189 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700190 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700191 this.extras = other.extras;
192 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800193 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700194 }
195
196 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700197 * Considered equal if they target the same sync adapter (A
198 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700199 * is considered an adapter), for the same userId.
200 * @param other PendingOperation to compare.
201 * @return true if the two pending ops are the same.
202 */
203 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700204 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 }
206
207 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700208 return "service=" + target.service
209 + " user=" + target.userId
210 + " auth=" + target
211 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700212 + " src=" + syncSource
213 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
Costin Manolache360e4542009-09-04 13:36:04 -0700216
Dianne Hackborn231cc602009-04-27 17:10:36 -0700217 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800218 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700219 final HashMap<String, AuthorityInfo> authorities =
220 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700221
Amith Yamasani04e0d262012-02-14 11:50:53 -0800222 AccountInfo(AccountAndUser accountAndUser) {
223 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700224 }
225 }
Costin Manolache360e4542009-09-04 13:36:04 -0700226
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700227 /** Bare bones representation of a sync target. */
228 public static class EndPoint {
229 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
230 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700231 final ComponentName service;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700232 final int serviceUid; // -1 for "any"
Dianne Hackborn7a135592009-05-06 00:28:37 -0700233 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800234 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700235 final String provider;
236 final boolean target_service;
237 final boolean target_provider;
238
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700239 public EndPoint(ComponentName service, int userId, int uid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700240 this.service = service;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700241 this.serviceUid = uid;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700242 this.userId = userId;
243 this.account = null;
244 this.provider = null;
245 this.target_service = true;
246 this.target_provider = false;
247 }
248
249 public EndPoint(Account account, String provider, int userId) {
250 this.account = account;
251 this.provider = provider;
252 this.userId = userId;
253 this.service = null;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700254 this.serviceUid = -1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700255 this.target_service = false;
256 this.target_provider = true;
257 }
258
259 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700260 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
261 *
262 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
263 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700264 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700265 public boolean matchesSpec(EndPoint spec) {
266 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700267 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700268 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 return false;
270 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700271 if (target_service && spec.target_service) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700272 if (serviceUid != spec.serviceUid
273 && serviceUid >= 0
274 && spec.serviceUid >= 0) {
275 return false;
276 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700277 return service.equals(spec.service);
278 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700279 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700280 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700281 accountsMatch = true;
282 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700283 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700284 }
285 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700286 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700287 providersMatch = true;
288 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700289 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700290 }
291 return accountsMatch && providersMatch;
292 }
293 return false;
294 }
295
296 public String toString() {
297 StringBuilder sb = new StringBuilder();
298 if (target_provider) {
299 sb.append(account == null ? "ALL ACCS" : account.name)
300 .append("/")
301 .append(provider == null ? "ALL PDRS" : provider);
302 } else if (target_service) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700303 service.appendShortString(sb);
304 sb.append(":");
305 UserHandle.formatUid(sb,serviceUid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700306 } else {
307 sb.append("invalid target");
308 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700309 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700310 return sb.toString();
311 }
312 }
313
314 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700315 // Legal values of getIsSyncable
316 /**
317 * Default state for a newly installed adapter. An uninitialized adapter will receive an
318 * initialization sync which are governed by a different set of rules to that of regular
319 * syncs.
320 */
321 public static final int NOT_INITIALIZED = -1;
322 /**
323 * The adapter will not receive any syncs. This is behaviourally equivalent to
324 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
325 * while this is generally meant to be controlled by the developer.
326 */
327 public static final int NOT_SYNCABLE = 0;
328 /**
329 * The adapter is initialized and functioning. This is the normal state for an adapter.
330 */
331 public static final int SYNCABLE = 1;
332 /**
333 * The adapter is syncable but still requires an initialization sync. For example an adapter
334 * than has been restored from a previous device will be in this state. Not meant for
335 * external use.
336 */
337 public static final int SYNCABLE_NOT_INITIALIZED = 2;
338
Matthew Williams8ef22042013-07-26 12:56:39 -0700339 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700340 final int ident;
341 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700342 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700343 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800344 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700345 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800346 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700347 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800348 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700349
Matthew Williamsfa774182013-06-18 15:44:11 -0700350 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700351
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700352 /**
353 * Copy constructor for making deep-ish copies. Only the bundles stored
354 * in periodic syncs can make unexpected changes.
355 *
356 * @param toCopy AuthorityInfo to be copied.
357 */
358 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700359 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700360 ident = toCopy.ident;
361 enabled = toCopy.enabled;
362 syncable = toCopy.syncable;
363 backoffTime = toCopy.backoffTime;
364 backoffDelay = toCopy.backoffDelay;
365 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700366 periodicSyncs = new ArrayList<PeriodicSync>();
367 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700368 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700369 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700370 }
371 }
372
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700373 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700374 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700375 ident = id;
376 enabled = info.target_provider ?
377 SYNC_ENABLED_DEFAULT : true;
378 // Service is active by default,
379 if (info.target_service) {
380 this.syncable = 1;
381 }
382 periodicSyncs = new ArrayList<PeriodicSync>();
383 defaultInitialisation();
384 }
385
386 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700387 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800388 backoffTime = -1; // if < 0 then we aren't in backoff mode
389 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700390 PeriodicSync defaultSync;
Matthew Williams53abfdb2015-06-10 20:06:37 -0700391 // Old version is one sync a day.
Matthew Williams8ef22042013-07-26 12:56:39 -0700392 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700393 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700394 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700395 new Bundle(),
396 DEFAULT_POLL_FREQUENCY_SECONDS,
397 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
398 periodicSyncs.add(defaultSync);
399 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 }
Matthew Williams06485a72013-07-26 12:56:39 -0700401
402 @Override
403 public String toString() {
404 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
405 + backoffTime + ", delay=" + delayUntil;
406 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700407 }
Costin Manolache360e4542009-09-04 13:36:04 -0700408
Dianne Hackborn231cc602009-04-27 17:10:36 -0700409 public static class SyncHistoryItem {
410 int authorityId;
411 int historyId;
412 long eventTime;
413 long elapsedTime;
414 int source;
415 int event;
416 long upstreamActivity;
417 long downstreamActivity;
418 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700419 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700420 Bundle extras;
421 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 }
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 public static class DayStats {
425 public final int day;
426 public int successCount;
427 public long successTime;
428 public int failureCount;
429 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700430
Dianne Hackborn231cc602009-04-27 17:10:36 -0700431 public DayStats(int day) {
432 this.day = day;
433 }
434 }
Costin Manolache360e4542009-09-04 13:36:04 -0700435
Amith Yamasani04e0d262012-02-14 11:50:53 -0800436 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700437
438 /** Called when a sync is needed on an account(s) due to some change in state. */
439 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800440 }
441
Dianne Hackborn231cc602009-04-27 17:10:36 -0700442 // Primary list of all syncable authorities. Also our global lock.
443 private final SparseArray<AuthorityInfo> mAuthorities =
444 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Amith Yamasani04e0d262012-02-14 11:50:53 -0800446 private final HashMap<AccountAndUser, AccountInfo> mAccounts
447 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448
Dianne Hackborn231cc602009-04-27 17:10:36 -0700449 private final ArrayList<PendingOperation> mPendingOperations =
450 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700451
Amith Yamasani04e0d262012-02-14 11:50:53 -0800452 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
453 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700454
Dianne Hackborn231cc602009-04-27 17:10:36 -0700455 private final SparseArray<SyncStatusInfo> mSyncStatus =
456 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700457
Dianne Hackborn231cc602009-04-27 17:10:36 -0700458 private final ArrayList<SyncHistoryItem> mSyncHistory =
459 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
462 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700463
Matthew Williams8ef22042013-07-26 12:56:39 -0700464 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700465 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
466 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700467
Fred Quintana77c560f2010-03-29 22:20:26 -0700468 private int mNextAuthorityId = 0;
469
Dianne Hackborn231cc602009-04-27 17:10:36 -0700470 // We keep 4 weeks of stats.
471 private final DayStats[] mDayStats = new DayStats[7*4];
472 private final Calendar mCal;
473 private int mYear;
474 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700475
Dianne Hackborn231cc602009-04-27 17:10:36 -0700476 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800477
Dianne Hackborn231cc602009-04-27 17:10:36 -0700478 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700479
Ashish Sharma69d95de2012-04-11 17:27:24 -0700480 private int mSyncRandomOffset;
481
Dianne Hackborn231cc602009-04-27 17:10:36 -0700482 /**
483 * This file contains the core engine state: all accounts and the
484 * settings for them. It must never be lost, and should be changed
485 * infrequently, so it is stored as an XML file.
486 */
487 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700488
Dianne Hackborn231cc602009-04-27 17:10:36 -0700489 /**
490 * This file contains the current sync status. We would like to retain
491 * it across boots, but its loss is not the end of the world, so we store
492 * this information as binary data.
493 */
494 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700495
Dianne Hackborn231cc602009-04-27 17:10:36 -0700496 /**
497 * This file contains sync statistics. This is purely debugging information
498 * so is written infrequently and can be thrown away at any time.
499 */
500 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700501
Dianne Hackborn231cc602009-04-27 17:10:36 -0700502 /**
503 * This file contains the pending sync operations. It is a binary file,
504 * which must be updated every time an operation is added or removed,
505 * so we have special handling of it.
506 */
507 private final AtomicFile mPendingFile;
508 private static final int PENDING_FINISH_TO_WRITE = 4;
509 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700510
Dianne Hackborn231cc602009-04-27 17:10:36 -0700511 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800512 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800513 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514
515 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700516
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800517 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700520
Dianne Hackborn231cc602009-04-27 17:10:36 -0700521 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700522
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800523 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
524 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
525
Dianne Hackborn231cc602009-04-27 17:10:36 -0700526 File systemDir = new File(dataDir, "system");
527 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800528 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700529
530 maybeDeleteLegacyPendingInfoLocked(syncDir);
531
Dianne Hackborn231cc602009-04-27 17:10:36 -0700532 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
533 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700534 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700535 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700536
Dianne Hackborn231cc602009-04-27 17:10:36 -0700537 readAccountInfoLocked();
538 readStatusLocked();
539 readPendingOperationsLocked();
540 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700541 readAndDeleteLegacyAccountInfoLocked();
542 writeAccountInfoLocked();
543 writeStatusLocked();
544 writePendingOperationsLocked();
545 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 }
547
548 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800549 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
551
552 public static void init(Context context) {
553 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800554 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800556 // This call will return the correct directory whether Encrypted File Systems is
557 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600558 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800559 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561
562 public static SyncStorageEngine getSingleton() {
563 if (sSyncStorageEngine == null) {
564 throw new IllegalStateException("not initialized");
565 }
566 return sSyncStorageEngine;
567 }
568
Amith Yamasani04e0d262012-02-14 11:50:53 -0800569 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
570 if (mSyncRequestListener == null) {
571 mSyncRequestListener = listener;
572 }
573 }
574
Dianne Hackborn231cc602009-04-27 17:10:36 -0700575 @Override public void handleMessage(Message msg) {
576 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700577 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700578 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700579 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700580 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700581 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700582 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584 }
585 }
Costin Manolache360e4542009-09-04 13:36:04 -0700586
Ashish Sharma69d95de2012-04-11 17:27:24 -0700587 public int getSyncRandomOffset() {
588 return mSyncRandomOffset;
589 }
590
Dianne Hackborn231cc602009-04-27 17:10:36 -0700591 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
592 synchronized (mAuthorities) {
593 mChangeListeners.register(callback, mask);
594 }
595 }
Costin Manolache360e4542009-09-04 13:36:04 -0700596
Dianne Hackborn231cc602009-04-27 17:10:36 -0700597 public void removeStatusChangeListener(ISyncStatusObserver callback) {
598 synchronized (mAuthorities) {
599 mChangeListeners.unregister(callback);
600 }
601 }
Costin Manolache360e4542009-09-04 13:36:04 -0700602
Matthew Williamsfa774182013-06-18 15:44:11 -0700603 /**
604 * Figure out a reasonable flex time for cases where none is provided (old api calls).
605 * @param syncTimeSeconds requested sync time from now.
606 * @return amount of seconds before syncTimeSeconds that the sync can occur.
607 * I.e.
608 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700609 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700610 */
611 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
612 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
613 // Small enough sync request time that we don't add flex time - developer probably
614 // wants to wait for an operation to occur before syncing so we honour the
615 // request time.
616 return 0L;
617 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
618 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
619 } else {
620 // Large enough sync request time that we cap the flex time.
621 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
622 }
623 }
624
Dianne Hackborn231cc602009-04-27 17:10:36 -0700625 private void reportChange(int which) {
626 ArrayList<ISyncStatusObserver> reports = null;
627 synchronized (mAuthorities) {
628 int i = mChangeListeners.beginBroadcast();
629 while (i > 0) {
630 i--;
631 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
632 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 continue;
634 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 if (reports == null) {
636 reports = new ArrayList<ISyncStatusObserver>(i);
637 }
638 reports.add(mChangeListeners.getBroadcastItem(i));
639 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700640 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700641 }
Costin Manolache360e4542009-09-04 13:36:04 -0700642
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700643 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700644 Log.v(TAG, "reportChange " + which + " to: " + reports);
645 }
Costin Manolache360e4542009-09-04 13:36:04 -0700646
Dianne Hackborn231cc602009-04-27 17:10:36 -0700647 if (reports != null) {
648 int i = reports.size();
649 while (i > 0) {
650 i--;
651 try {
652 reports.get(i).onStatusChanged(which);
653 } catch (RemoteException e) {
654 // The remote callback list will take care of this for us.
655 }
656 }
657 }
658 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700659
Amith Yamasani04e0d262012-02-14 11:50:53 -0800660 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700661 synchronized (mAuthorities) {
662 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700663 AuthorityInfo authority = getAuthorityLocked(
664 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700665 "getSyncAutomatically");
666 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700667 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700668
Dianne Hackborn231cc602009-04-27 17:10:36 -0700669 int i = mAuthorities.size();
670 while (i > 0) {
671 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700672 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700673 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700674 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700675 return true;
676 }
677 }
678 return false;
679 }
680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
Amith Yamasani04e0d262012-02-14 11:50:53 -0800682 public void setSyncAutomatically(Account account, int userId, String providerName,
683 boolean 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: " + /* account + */" provider " + providerName
686 + ", user " + userId + " -> " + sync);
687 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700688 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 AuthorityInfo authority =
690 getOrCreateAuthorityLocked(
691 new EndPoint(account, providerName, userId),
692 -1 /* ident */,
693 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700694 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800696 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
697 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700698 return;
699 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700700 // If the adapter was syncable but missing its initialization sync, set it to
701 // uninitialized now. This is to give it a chance to run any one-time initialization
702 // logic.
703 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
704 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
705 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700706 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700707 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700709
Fred Quintana77c560f2010-03-29 22:20:26 -0700710 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700711 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
712 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700713 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700714 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800715 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717
Amith Yamasani04e0d262012-02-14 11:50:53 -0800718 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700719 synchronized (mAuthorities) {
720 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700721 AuthorityInfo authority = getAuthorityLocked(
722 new EndPoint(account, providerName, userId),
723 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700724 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700725 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700726 }
727 return authority.syncable;
728 }
729
730 int i = mAuthorities.size();
731 while (i > 0) {
732 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700733 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700734 if (authorityInfo.target != null
735 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700736 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700737 }
738 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700739 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700740 }
741 }
742
Amith Yamasani04e0d262012-02-14 11:50:53 -0800743 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700744 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700745 }
746
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700747 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700748 synchronized (mAuthorities) {
749 if (cname != null) {
750 AuthorityInfo authority = getAuthorityLocked(
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700751 new EndPoint(cname, userId, -1),
Matthew Williams8ef22042013-07-26 12:56:39 -0700752 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700753 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700754 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700755 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700756 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700757 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700758 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700759 }
760 }
761
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700762 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700763 setSyncableStateForEndPoint(new EndPoint(cname, userId, -1), active ?
Matthew Williams53abfdb2015-06-10 20:06:37 -0700764 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700765 }
766
767 /**
768 * An enabled sync service and a syncable provider's adapter both get resolved to the same
769 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700770 * @param target target to set value for.
771 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700772 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700773 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700774 AuthorityInfo aInfo;
775 synchronized (mAuthorities) {
776 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700777 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
778 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700779 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700780 if (Log.isLoggable(TAG, Log.VERBOSE)) {
781 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
782 }
783 if (aInfo.syncable == syncable) {
784 if (Log.isLoggable(TAG, Log.VERBOSE)) {
785 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
786 }
787 return;
788 }
789 aInfo.syncable = syncable;
790 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700791 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700792 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700793 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700794 }
795 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
796 }
797
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700800 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
801 if (authority != null) {
802 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800803 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800805 }
806 }
807
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700808 /**
809 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
810 * the account or provider info be null, which signifies all accounts or providers.
811 */
812 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
813 if (Log.isLoggable(TAG, Log.VERBOSE)) {
814 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800815 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
816 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700817 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800818 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700819 if (info.target_provider
820 && (info.account == null || info.provider == null)) {
821 // Do more work for a provider sync if the provided info has specified all
822 // accounts/providers.
823 changed = setBackoffLocked(
824 info.account /* may be null */,
825 info.userId,
826 info.provider /* may be null */,
827 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800828 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700829 AuthorityInfo authorityInfo =
830 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
831 if (authorityInfo.backoffTime == nextSyncTime
832 && authorityInfo.backoffDelay == nextDelay) {
833 changed = false;
834 } else {
835 authorityInfo.backoffTime = nextSyncTime;
836 authorityInfo.backoffDelay = nextDelay;
837 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800838 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800839 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800840 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800841 if (changed) {
842 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
843 }
844 }
845
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700846 /**
847 * Either set backoff for a specific authority, or set backoff for all the
848 * accounts on a specific adapter/all adapters.
849 *
850 * @param account account for which to set backoff. Null to specify all accounts.
851 * @param userId id of the user making this request.
852 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700853 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700854 */
855 private boolean setBackoffLocked(Account account, int userId, String providerName,
856 long nextSyncTime, long nextDelay) {
857 boolean changed = false;
858 for (AccountInfo accountInfo : mAccounts.values()) {
859 if (account != null && !account.equals(accountInfo.accountAndUser.account)
860 && userId != accountInfo.accountAndUser.userId) {
861 continue;
862 }
863 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
864 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700865 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 continue;
867 }
868 if (authorityInfo.backoffTime != nextSyncTime
869 || authorityInfo.backoffDelay != nextDelay) {
870 authorityInfo.backoffTime = nextSyncTime;
871 authorityInfo.backoffDelay = nextDelay;
872 changed = true;
873 }
874 }
875 }
876 return changed;
877 }
878
Matthew Williams119aac92014-09-28 20:42:23 -0700879 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800880 boolean changed = false;
881 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700882 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700883 for (AccountInfo accountInfo : mAccounts.values()) {
884 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
885 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
886 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700887 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams119aac92014-09-28 20:42:23 -0700888 Log.v(TAG, "clearAllBackoffsLocked:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700889 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700890 + " account:" + accountInfo.accountAndUser.account.name
891 + " user:" + accountInfo.accountAndUser.userId
892 + " backoffTime was: " + authorityInfo.backoffTime
893 + " backoffDelay was: " + authorityInfo.backoffDelay);
894 }
895 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
896 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700897 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800898 }
Alon Albert744e310f2010-12-14 11:37:20 -0800899 }
900 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700901 // Clear backoff for all sync services.
902 for (ComponentName service : mServices.keySet()) {
903 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
904 for (int i = 0; i < aInfos.size(); i++) {
905 AuthorityInfo authorityInfo = aInfos.valueAt(i);
906 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
907 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
908 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
909 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
910 }
911 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700912 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800913 }
914 }
915
916 if (changed) {
917 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
918 }
919 }
920
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700921 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800922 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700923 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800924 if (authority == null) {
925 return 0;
926 }
927 return authority.delayUntil;
928 }
929 }
930
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700931 public void setDelayUntilTime(EndPoint info, long delayUntil) {
932 if (Log.isLoggable(TAG, Log.VERBOSE)) {
933 Log.v(TAG, "setDelayUntil: " + info
934 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800935 }
936 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700937 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
938 if (authority.delayUntil == delayUntil) {
939 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700940 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700941 authority.delayUntil = delayUntil;
942 }
943 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
944 }
945
946 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
948 Log.v(TAG, "addPeriodicSync: " + info
949 + " -> period " + period + ", flex " + flextime + ", extras "
950 + extras.toString());
951 }
952 synchronized (mAuthorities) {
953 if (period <= 0) {
954 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
955 }
956 if (extras == null) {
957 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700958 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700959 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700960 PeriodicSync toUpdate;
961 if (info.target_provider) {
962 toUpdate = new PeriodicSync(info.account,
963 info.provider,
964 extras,
965 period,
966 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700967 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -0700968 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700969 }
970 AuthorityInfo authority =
971 getOrCreateAuthorityLocked(info, -1, false);
972 // add this periodic sync if an equivalent periodic doesn't already exist.
973 boolean alreadyPresent = false;
974 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
975 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
976 if (SyncManager.syncExtrasEquals(syncInfo.extras,
977 extras,
978 true /* includeSyncSettings*/)) {
979 if (period == syncInfo.period &&
980 flextime == syncInfo.flexTime) {
981 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700982 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700983 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700984 authority.periodicSyncs.set(i, toUpdate);
985 alreadyPresent = true;
986 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700987 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700988 }
989 // If we added an entry to the periodicSyncs array also add an entry to
990 // the periodic syncs status to correspond to it.
991 if (!alreadyPresent) {
992 authority.periodicSyncs.add(toUpdate);
993 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
994 // A new periodic sync is initialised as already having been run.
995 status.setPeriodicSyncTime(
996 authority.periodicSyncs.size() - 1,
997 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800998 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700999 } finally {
1000 writeAccountInfoLocked();
1001 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001002 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001003 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001004 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
1005 }
1006
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001007 public void removePeriodicSync(EndPoint info, Bundle extras) {
1008 synchronized(mAuthorities) {
1009 try {
1010 AuthorityInfo authority =
1011 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -07001012 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001013 SyncStatusInfo status = mSyncStatus.get(authority.ident);
1014 boolean changed = false;
1015 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
1016 int i = 0;
1017 while (iterator.hasNext()) {
1018 PeriodicSync syncInfo = iterator.next();
1019 if (SyncManager.syncExtrasEquals(syncInfo.extras,
1020 extras,
1021 true /* includeSyncSettings */)) {
1022 iterator.remove();
1023 changed = true;
1024 // If we removed an entry from the periodicSyncs array also
1025 // remove the corresponding entry from the status
1026 if (status != null) {
1027 status.removePeriodicSyncTime(i);
1028 } else {
1029 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
1030 + " did not find it.");
1031 }
1032 } else {
1033 i++;
1034 }
1035 }
1036 if (!changed) {
1037 return;
1038 }
1039 } finally {
1040 writeAccountInfoLocked();
1041 writeStatusLocked();
1042 }
1043 }
1044 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001045 }
1046
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001047 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001048 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1049 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001050 */
1051 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001052 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001053 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1054 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1055 if (authorityInfo != null) {
1056 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001057 // Copy and send out. Necessary for thread-safety although it's parceled.
1058 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001059 }
1060 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001061 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001062 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001063 }
1064
Amith Yamasani04e0d262012-02-14 11:50:53 -08001065 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001067 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001068 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001069 return;
1070 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001071 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 writeAccountInfoLocked();
1073 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001074 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001075 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1076 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001077 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001078 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001079 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -08001080 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082
Amith Yamasani04e0d262012-02-14 11:50:53 -08001083 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001085 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001086 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001087 }
1088 }
Costin Manolache360e4542009-09-04 13:36:04 -07001089
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 public AuthorityInfo getAuthority(int authorityId) {
1091 synchronized (mAuthorities) {
1092 return mAuthorities.get(authorityId);
1093 }
1094 }
Costin Manolache360e4542009-09-04 13:36:04 -07001095
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001097 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001098 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001099 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001100 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001101 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001102 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001103 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001104 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001105 return true;
1106 }
1107 }
1108 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001109 return false;
1110 }
Costin Manolache360e4542009-09-04 13:36:04 -07001111
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001112 public PendingOperation insertIntoPending(SyncOperation op) {
1113 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001114 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001115 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1116 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001117 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001118 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001119 final EndPoint info = op.target;
1120 AuthorityInfo authority =
1121 getOrCreateAuthorityLocked(info,
1122 -1 /* desired identifier */,
1123 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 if (authority == null) {
1125 return null;
1126 }
Costin Manolache360e4542009-09-04 13:36:04 -07001127
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001128 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
Matthew Williams64280462014-01-09 10:49:23 -08001129 op.isExpedited());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001130 mPendingOperations.add(pop);
Matthew Williams06485a72013-07-26 12:56:39 -07001131 appendPendingOperationLocked(pop);
Costin Manolache360e4542009-09-04 13:36:04 -07001132
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1134 status.pending = true;
1135 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001136 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001137 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 }
1139
Matthew Williamsfa774182013-06-18 15:44:11 -07001140 /**
1141 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001142 * authorities. If there are no more pending syncs for the same target,
1143 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001144 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001145 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 public boolean deleteFromPending(PendingOperation op) {
1147 boolean res = false;
1148 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001149 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1150 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001151 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 if (mPendingOperations.remove(op)) {
1153 if (mPendingOperations.size() == 0
1154 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1155 writePendingOperationsLocked();
1156 mNumPendingFinished = 0;
1157 } else {
1158 mNumPendingFinished++;
1159 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001160 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001162 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1163 Log.v(TAG, "removing - " + authority.toString());
1164 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 final int N = mPendingOperations.size();
1166 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001167 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001168 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001169 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 morePending = true;
1171 break;
1172 }
1173 }
Costin Manolache360e4542009-09-04 13:36:04 -07001174
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001176 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001177 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1178 status.pending = false;
1179 }
1180 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 res = true;
1182 }
1183 }
Costin Manolache360e4542009-09-04 13:36:04 -07001184
Fred Quintanaac9385e2009-06-22 18:00:59 -07001185 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001186 return res;
1187 }
1188
Dianne Hackborn231cc602009-04-27 17:10:36 -07001189 /**
1190 * Return a copy of the current array of pending operations. The
1191 * PendingOperation objects are the real objects stored inside, so that
1192 * they can be used with deleteFromPending().
1193 */
1194 public ArrayList<PendingOperation> getPendingOperations() {
1195 synchronized (mAuthorities) {
1196 return new ArrayList<PendingOperation>(mPendingOperations);
1197 }
1198 }
Costin Manolache360e4542009-09-04 13:36:04 -07001199
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 /**
1201 * Return the number of currently pending operations.
1202 */
1203 public int getPendingOperationCount() {
1204 synchronized (mAuthorities) {
1205 return mPendingOperations.size();
1206 }
1207 }
Costin Manolache360e4542009-09-04 13:36:04 -07001208
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 /**
1210 * Called when the set of account has changed, given the new array of
1211 * active accounts.
1212 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001213 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001215 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1216 Log.v(TAG, "Updating for new accounts...");
1217 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1219 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1220 while (accIt.hasNext()) {
1221 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001222 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1223 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001225 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001226 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001227 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 for (AuthorityInfo auth : acc.authorities.values()) {
1229 removing.put(auth.ident, auth);
1230 }
1231 accIt.remove();
1232 }
1233 }
Costin Manolache360e4542009-09-04 13:36:04 -07001234
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 // Clean out all data structures.
1236 int i = removing.size();
1237 if (i > 0) {
1238 while (i > 0) {
1239 i--;
1240 int ident = removing.keyAt(i);
1241 mAuthorities.remove(ident);
1242 int j = mSyncStatus.size();
1243 while (j > 0) {
1244 j--;
1245 if (mSyncStatus.keyAt(j) == ident) {
1246 mSyncStatus.remove(mSyncStatus.keyAt(j));
1247 }
1248 }
1249 j = mSyncHistory.size();
1250 while (j > 0) {
1251 j--;
1252 if (mSyncHistory.get(j).authorityId == ident) {
1253 mSyncHistory.remove(j);
1254 }
1255 }
1256 }
1257 writeAccountInfoLocked();
1258 writeStatusLocked();
1259 writePendingOperationsLocked();
1260 writeStatisticsLocked();
1261 }
1262 }
1263 }
1264
1265 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001266 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1267 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 */
Fred Quintana918339a2010-10-05 14:00:39 -07001269 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1270 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001271 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001272 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001273 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001274 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001275 + " src=" + activeSyncContext.mSyncOperation.syncSource
1276 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001278 final EndPoint info = activeSyncContext.mSyncOperation.target;
1279 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1280 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001281 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001282 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001283 syncInfo = new SyncInfo(
1284 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001285 authorityInfo.target.account,
1286 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001287 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001288 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001289 }
Fred Quintana918339a2010-10-05 14:00:39 -07001290 reportActiveChange();
1291 return syncInfo;
1292 }
1293
1294 /**
1295 * Called to indicate that a previously active sync is no longer active.
1296 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001297 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001298 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001299 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1301 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001302 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001303 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001304 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001305 }
1306
1307 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 }
1309
1310 /**
1311 * To allow others to send active change reports, to poke clients.
1312 */
1313 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001314 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 }
Costin Manolache360e4542009-09-04 13:36:04 -07001316
Dianne Hackborn231cc602009-04-27 17:10:36 -07001317 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001318 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001319 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001320 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 long id;
1322 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001323 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1324 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001325 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001326 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 if (authority == null) {
1328 return -1;
1329 }
1330 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001331 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001332 item.authorityId = authority.ident;
1333 item.historyId = mNextHistoryId++;
1334 if (mNextHistoryId < 0) mNextHistoryId = 0;
1335 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001336 item.source = op.syncSource;
1337 item.reason = op.reason;
1338 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001339 item.event = EVENT_START;
1340 mSyncHistory.add(0, item);
1341 while (mSyncHistory.size() > MAX_HISTORY) {
1342 mSyncHistory.remove(mSyncHistory.size()-1);
1343 }
1344 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001345 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001346 }
Costin Manolache360e4542009-09-04 13:36:04 -07001347
Fred Quintanaac9385e2009-06-22 18:00:59 -07001348 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001349 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351
Fred Quintana77c560f2010-03-29 22:20:26 -07001352 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001354 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001355 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001356 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1357 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 SyncHistoryItem item = null;
1359 int i = mSyncHistory.size();
1360 while (i > 0) {
1361 i--;
1362 item = mSyncHistory.get(i);
1363 if (item.historyId == historyId) {
1364 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
Costin Manolache360e4542009-09-04 13:36:04 -07001368
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 if (item == null) {
1370 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1371 return;
1372 }
Costin Manolache360e4542009-09-04 13:36:04 -07001373
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 item.elapsedTime = elapsedTime;
1375 item.event = EVENT_STOP;
1376 item.mesg = resultMessage;
1377 item.downstreamActivity = downstreamActivity;
1378 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001379
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001381
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 status.numSyncs++;
1383 status.totalElapsedTime += elapsedTime;
1384 switch (item.source) {
1385 case SOURCE_LOCAL:
1386 status.numSourceLocal++;
1387 break;
1388 case SOURCE_POLL:
1389 status.numSourcePoll++;
1390 break;
1391 case SOURCE_USER:
1392 status.numSourceUser++;
1393 break;
1394 case SOURCE_SERVER:
1395 status.numSourceServer++;
1396 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001397 case SOURCE_PERIODIC:
1398 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001399 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 }
Costin Manolache360e4542009-09-04 13:36:04 -07001401
Dianne Hackborn231cc602009-04-27 17:10:36 -07001402 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001403 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001404 if (mDayStats[0] == null) {
1405 mDayStats[0] = new DayStats(day);
1406 } else if (day != mDayStats[0].day) {
1407 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1408 mDayStats[0] = new DayStats(day);
1409 writeStatisticsNow = true;
1410 } else if (mDayStats[0] == null) {
1411 }
1412 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001413
Dianne Hackborn231cc602009-04-27 17:10:36 -07001414 final long lastSyncTime = (item.eventTime + elapsedTime);
1415 boolean writeStatusNow = false;
1416 if (MESG_SUCCESS.equals(resultMessage)) {
1417 // - if successful, update the successful columns
1418 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1419 writeStatusNow = true;
1420 }
1421 status.lastSuccessTime = lastSyncTime;
1422 status.lastSuccessSource = item.source;
1423 status.lastFailureTime = 0;
1424 status.lastFailureSource = -1;
1425 status.lastFailureMesg = null;
1426 status.initialFailureTime = 0;
1427 ds.successCount++;
1428 ds.successTime += elapsedTime;
1429 } else if (!MESG_CANCELED.equals(resultMessage)) {
1430 if (status.lastFailureTime == 0) {
1431 writeStatusNow = true;
1432 }
1433 status.lastFailureTime = lastSyncTime;
1434 status.lastFailureSource = item.source;
1435 status.lastFailureMesg = resultMessage;
1436 if (status.initialFailureTime == 0) {
1437 status.initialFailureTime = lastSyncTime;
1438 }
1439 ds.failureCount++;
1440 ds.failureTime += elapsedTime;
1441 }
Costin Manolache360e4542009-09-04 13:36:04 -07001442
Dianne Hackborn231cc602009-04-27 17:10:36 -07001443 if (writeStatusNow) {
1444 writeStatusLocked();
1445 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1446 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1447 WRITE_STATUS_DELAY);
1448 }
1449 if (writeStatisticsNow) {
1450 writeStatisticsLocked();
1451 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1452 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1453 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001454 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001455 }
Costin Manolache360e4542009-09-04 13:36:04 -07001456
Fred Quintanaac9385e2009-06-22 18:00:59 -07001457 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001458 }
1459
1460 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001461 * Return a list of the currently active syncs. Note that the returned
1462 * items are the real, live active sync objects, so be careful what you do
1463 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001464 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001465 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001466 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001467 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001468 }
1469 }
Costin Manolache360e4542009-09-04 13:36:04 -07001470
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001472 * @return a copy of the current syncs data structure. Will not return
1473 * null.
1474 */
1475 public List<SyncInfo> getCurrentSyncsCopy(int userId) {
1476 synchronized (mAuthorities) {
1477 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1478 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1479 for (SyncInfo sync : syncs) {
1480 syncsCopy.add(new SyncInfo(sync));
1481 }
1482 return syncsCopy;
1483 }
1484 }
1485
1486 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1487 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1488 if (syncs == null) {
1489 syncs = new ArrayList<SyncInfo>();
1490 mCurrentSyncs.put(userId, syncs);
1491 }
1492 return syncs;
1493 }
1494
1495 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001496 * Return an array of the current sync status for all authorities. Note
1497 * that the objects inside the array are the real, live status objects,
1498 * so be careful what you do with them.
1499 */
1500 public ArrayList<SyncStatusInfo> getSyncStatus() {
1501 synchronized (mAuthorities) {
1502 final int N = mSyncStatus.size();
1503 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1504 for (int i=0; i<N; i++) {
1505 ops.add(mSyncStatus.valueAt(i));
1506 }
1507 return ops;
1508 }
1509 }
Costin Manolache360e4542009-09-04 13:36:04 -07001510
Dianne Hackborn231cc602009-04-27 17:10:36 -07001511 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001512 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001513 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001514 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001515 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001516 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001517 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001518 true /* write to storage if this results in a change */);
1519 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1520 }
1521 }
1522
1523 /**
1524 * Return a copy of all authorities with their corresponding sync status
1525 */
1526 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1527 synchronized (mAuthorities) {
1528 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1529 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1530 for (int i = 0; i < mAuthorities.size(); i++) {
1531 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001532 }
1533 return infos;
1534 }
1535 }
1536
1537 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001538 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001539 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001540 * @param info the endpoint target we are querying status info for.
1541 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001542 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001543 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1544 if (info.target_provider && (info.account == null || info.provider == null)) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001545 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001546 } else if (info.target_service && info.service == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001547 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001548 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001550 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001551 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001552 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001553 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001554 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001555 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001556 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001557 }
1558 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001559 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001560 }
1561 }
Costin Manolache360e4542009-09-04 13:36:04 -07001562
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001563 /** Return true if the pending status is true of any matching authorities. */
1564 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001565 synchronized (mAuthorities) {
1566 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001567 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001568 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001569 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1570 if (ainfo == null) {
1571 continue;
1572 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001573 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001574 continue;
1575 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001576 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001577 return true;
1578 }
1579 }
1580 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
1582 }
1583
1584 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 * Return an array of the current sync status for all authorities. Note
1586 * that the objects inside the array are the real, live status objects,
1587 * so be careful what you do with them.
1588 */
1589 public ArrayList<SyncHistoryItem> getSyncHistory() {
1590 synchronized (mAuthorities) {
1591 final int N = mSyncHistory.size();
1592 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1593 for (int i=0; i<N; i++) {
1594 items.add(mSyncHistory.get(i));
1595 }
1596 return items;
1597 }
1598 }
Costin Manolache360e4542009-09-04 13:36:04 -07001599
Dianne Hackborn231cc602009-04-27 17:10:36 -07001600 /**
1601 * Return an array of the current per-day statistics. Note
1602 * that the objects inside the array are the real, live status objects,
1603 * so be careful what you do with them.
1604 */
1605 public DayStats[] getDayStatistics() {
1606 synchronized (mAuthorities) {
1607 DayStats[] ds = new DayStats[mDayStats.length];
1608 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1609 return ds;
1610 }
1611 }
Costin Manolache360e4542009-09-04 13:36:04 -07001612
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001613 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1614 AuthorityInfo authorityInfo) {
1615 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1616 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1617 }
1618
Dianne Hackborn55280a92009-05-07 15:53:46 -07001619 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001620 mCal.setTimeInMillis(System.currentTimeMillis());
1621 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1622 if (mYear != mCal.get(Calendar.YEAR)) {
1623 mYear = mCal.get(Calendar.YEAR);
1624 mCal.clear();
1625 mCal.set(Calendar.YEAR, mYear);
1626 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1627 }
1628 return dayOfYear + mYearInDays;
1629 }
Costin Manolache360e4542009-09-04 13:36:04 -07001630
Dianne Hackborn231cc602009-04-27 17:10:36 -07001631 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001632 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001633 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001634 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001635 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001636 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001637 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001638 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1639 if (info.target_service) {
1640 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1641 AuthorityInfo authority = null;
1642 if (aInfo != null) {
1643 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001644 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001645 if (authority == null) {
1646 if (tag != null) {
1647 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001648 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1649 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001650 }
1651 }
1652 return null;
1653 }
1654 return authority;
1655 } else if (info.target_provider){
1656 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1657 AccountInfo accountInfo = mAccounts.get(au);
1658 if (accountInfo == null) {
1659 if (tag != null) {
1660 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1661 Log.v(TAG, tag + ": unknown account " + au);
1662 }
1663 }
1664 return null;
1665 }
1666 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1667 if (authority == null) {
1668 if (tag != null) {
1669 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1670 Log.v(TAG, tag + ": unknown provider " + info.provider);
1671 }
1672 }
1673 return null;
1674 }
1675 return authority;
1676 } else {
1677 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001678 return null;
1679 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001680 }
Costin Manolache360e4542009-09-04 13:36:04 -07001681
Matthew Williamsfa774182013-06-18 15:44:11 -07001682 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001683 * @param info info identifying target.
1684 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001685 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001686 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001687 * exists.
1688 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001689 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1690 AuthorityInfo authority = null;
1691 if (info.target_service) {
1692 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1693 if (aInfo == null) {
1694 aInfo = new SparseArray<AuthorityInfo>();
1695 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001696 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001697 authority = aInfo.get(info.userId);
1698 if (authority == null) {
1699 authority = createAuthorityLocked(info, ident, doWrite);
1700 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001701 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001702 } else if (info.target_provider) {
1703 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1704 AccountInfo account = mAccounts.get(au);
1705 if (account == null) {
1706 account = new AccountInfo(au);
1707 mAccounts.put(au, account);
1708 }
1709 authority = account.authorities.get(info.provider);
1710 if (authority == null) {
1711 authority = createAuthorityLocked(info, ident, doWrite);
1712 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001713 }
1714 }
1715 return authority;
1716 }
1717
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001718 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1719 AuthorityInfo authority;
1720 if (ident < 0) {
1721 ident = mNextAuthorityId;
1722 mNextAuthorityId++;
1723 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001724 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001725 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1726 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001727 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001728 authority = new AuthorityInfo(info, ident);
1729 mAuthorities.put(ident, authority);
1730 if (doWrite) {
1731 writeAccountInfoLocked();
1732 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001733 return authority;
1734 }
Costin Manolache360e4542009-09-04 13:36:04 -07001735
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001736 public void removeAuthority(EndPoint info) {
1737 synchronized (mAuthorities) {
1738 if (info.target_provider) {
1739 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1740 } else {
1741 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1742 if (aInfos != null) {
1743 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1744 if (authorityInfo != null) {
1745 mAuthorities.remove(authorityInfo.ident);
1746 aInfos.delete(info.userId);
1747 writeAccountInfoLocked();
1748 }
1749 }
1750
1751 }
1752 }
1753 }
1754
1755 /**
1756 * Remove an authority associated with a provider. Needs to be a standalone function for
1757 * backward compatibility.
1758 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1760 boolean doWrite) {
1761 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001762 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001763 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1764 if (authorityInfo != null) {
1765 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001766 if (doWrite) {
1767 writeAccountInfoLocked();
1768 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001769 }
1770 }
1771 }
1772
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001773 /**
1774 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001775 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001776 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001777 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001778 boolean found = false;
1779 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001780 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001781 authorityInfo = mAuthorities.get(authorityId);
1782 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001783 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1784 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001785 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001786 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001787 break;
1788 }
1789 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001790 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001791 if (!found) {
1792 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001793 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001794 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001795 }
1796
Dianne Hackborn231cc602009-04-27 17:10:36 -07001797 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1798 SyncStatusInfo status = mSyncStatus.get(authorityId);
1799 if (status == null) {
1800 status = new SyncStatusInfo(authorityId);
1801 mSyncStatus.put(authorityId, status);
1802 }
1803 return status;
1804 }
Costin Manolache360e4542009-09-04 13:36:04 -07001805
Dianne Hackborn55280a92009-05-07 15:53:46 -07001806 public void writeAllState() {
1807 synchronized (mAuthorities) {
1808 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001809
Dianne Hackborn55280a92009-05-07 15:53:46 -07001810 if (mNumPendingFinished > 0) {
1811 // Only write these if they are out of date.
1812 writePendingOperationsLocked();
1813 }
Costin Manolache360e4542009-09-04 13:36:04 -07001814
Dianne Hackborn55280a92009-05-07 15:53:46 -07001815 // Just always write these... they are likely out of date.
1816 writeStatusLocked();
1817 writeStatisticsLocked();
1818 }
1819 }
Costin Manolache360e4542009-09-04 13:36:04 -07001820
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001822 * public for testing
1823 */
1824 public void clearAndReadState() {
1825 synchronized (mAuthorities) {
1826 mAuthorities.clear();
1827 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001828 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001829 mPendingOperations.clear();
1830 mSyncStatus.clear();
1831 mSyncHistory.clear();
1832
1833 readAccountInfoLocked();
1834 readStatusLocked();
1835 readPendingOperationsLocked();
1836 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001837 readAndDeleteLegacyAccountInfoLocked();
1838 writeAccountInfoLocked();
1839 writeStatusLocked();
1840 writePendingOperationsLocked();
1841 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001842 }
1843 }
1844
1845 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001846 * Read all account information back in to the initial engine state.
1847 */
1848 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001849 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001850 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001852 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001853 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001854 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001855 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001856 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001857 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001858 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001859 while (eventType != XmlPullParser.START_TAG &&
1860 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001861 eventType = parser.next();
1862 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001863 if (eventType == XmlPullParser.END_DOCUMENT) {
1864 Log.i(TAG, "No initial accounts");
1865 return;
1866 }
1867
Dianne Hackborn231cc602009-04-27 17:10:36 -07001868 String tagName = parser.getName();
1869 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001870 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001871 String versionString = parser.getAttributeValue(null, "version");
1872 int version;
1873 try {
1874 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1875 } catch (NumberFormatException e) {
1876 version = 0;
1877 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001878 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001879 try {
1880 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1881 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1882 } catch (NumberFormatException e) {
1883 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001884 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001885 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1886 try {
1887 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1888 } catch (NumberFormatException e) {
1889 mSyncRandomOffset = 0;
1890 }
1891 if (mSyncRandomOffset == 0) {
1892 Random random = new Random(System.currentTimeMillis());
1893 mSyncRandomOffset = random.nextInt(86400);
1894 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001895 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001896 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001897 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001898 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001900 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001901 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001902 if (parser.getDepth() == 2) {
1903 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001904 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001905 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001906 if (authority.ident > highestAuthorityId) {
1907 highestAuthorityId = authority.ident;
1908 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001909 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1910 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001911 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001912 } else if (parser.getDepth() == 3) {
1913 if ("periodicSync".equals(tagName) && authority != null) {
1914 periodicSync = parsePeriodicSync(parser, authority);
1915 }
1916 } else if (parser.getDepth() == 4 && periodicSync != null) {
1917 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001918 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001919 }
1920 }
1921 }
1922 eventType = parser.next();
1923 } while (eventType != XmlPullParser.END_DOCUMENT);
1924 }
1925 } catch (XmlPullParserException e) {
1926 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001927 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001928 } catch (java.io.IOException e) {
1929 if (fis == null) Log.i(TAG, "No initial accounts");
1930 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001931 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001933 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001934 if (fis != null) {
1935 try {
1936 fis.close();
1937 } catch (java.io.IOException e1) {
1938 }
1939 }
1940 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001941
Fred Quintana77c560f2010-03-29 22:20:26 -07001942 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 }
Costin Manolache360e4542009-09-04 13:36:04 -07001944
Fred Quintanafb084402010-03-23 17:57:03 -07001945 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001946 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1947 * pending.xml was used starting in KLP.
1948 * @param syncDir directory where the sync files are located.
1949 */
1950 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1951 File file = new File(syncDir, "pending.bin");
1952 if (!file.exists()) {
1953 return;
1954 } else {
1955 file.delete();
1956 }
1957 }
1958
1959 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001960 * some authority names have changed. copy over their settings and delete the old ones
1961 * @return true if a change was made
1962 */
1963 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1964 boolean writeNeeded = false;
1965
1966 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1967 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001968 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001969 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001970 // skip this authority if it doesn't target a provider
1971 if (authority.target.target_service) {
1972 continue;
1973 }
Fred Quintanafb084402010-03-23 17:57:03 -07001974 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001975 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001976 if (newAuthorityName == null) {
1977 continue;
1978 }
1979
1980 // remember this authority so we can remove it later. we can't remove it
1981 // now without messing up this loop iteration
1982 authoritiesToRemove.add(authority);
1983
1984 // this authority isn't enabled, no need to copy it to the new authority name since
1985 // the default is "disabled"
1986 if (!authority.enabled) {
1987 continue;
1988 }
1989
1990 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001991 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001992 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001993 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001994 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001995 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001996 continue;
1997 }
1998
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001999 AuthorityInfo newAuthority =
2000 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07002001 newAuthority.enabled = true;
2002 writeNeeded = true;
2003 }
2004
2005 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002006 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07002007 authorityInfo.target.account,
2008 authorityInfo.target.userId,
2009 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002010 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07002011 writeNeeded = true;
2012 }
2013
2014 return writeNeeded;
2015 }
2016
Amith Yamasani04e0d262012-02-14 11:50:53 -08002017 private void parseListenForTickles(XmlPullParser parser) {
2018 String user = parser.getAttributeValue(null, XML_ATTR_USER);
2019 int userId = 0;
2020 try {
2021 userId = Integer.parseInt(user);
2022 } catch (NumberFormatException e) {
2023 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
2024 } catch (NullPointerException e) {
2025 Log.e(TAG, "the user in listen-for-tickles is null", e);
2026 }
2027 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
2028 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
2029 mMasterSyncAutomatically.put(userId, listen);
2030 }
2031
Fred Quintanac2e46912010-03-15 16:10:44 -07002032 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002033 AuthorityInfo authority = null;
2034 int id = -1;
2035 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002036 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002037 } catch (NumberFormatException e) {
2038 Log.e(TAG, "error parsing the id of the authority", e);
2039 } catch (NullPointerException e) {
2040 Log.e(TAG, "the id of the authority is null", e);
2041 }
2042 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07002043 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002044 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07002045 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002046 String accountName = parser.getAttributeValue(null, "account");
2047 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002048 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07002049 String packageName = parser.getAttributeValue(null, "package");
2050 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002051 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07002052 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002053 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07002054 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002055 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002056 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002057 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002058 Log.v(TAG_FILE, "Adding authority:"
2059 + " account=" + accountName
2060 + " accountType=" + accountType
2061 + " auth=" + authorityName
2062 + " package=" + packageName
2063 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07002064 + " user=" + userId
2065 + " enabled=" + enabled
2066 + " syncable=" + syncable);
2067 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002068 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002069 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002070 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002071 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002072 EndPoint info;
2073 if (accountName != null && authorityName != null) {
2074 info = new EndPoint(
2075 new Account(accountName, accountType),
2076 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002077 } else {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002078 final ComponentName cname = new ComponentName(packageName, className);
2079 android.content.pm.ServiceInfo sinfo = null;
2080 try {
2081 sinfo = mContext.getPackageManager().getServiceInfo(cname, userId);
2082 } catch (PackageManager.NameNotFoundException e) {
2083 Slog.w(TAG, "Not restoring sync " + cname
2084 + " -- can't find service for user " + userId);
2085 }
2086 if (sinfo != null) {
2087 info = new EndPoint(cname, userId, sinfo.applicationInfo.uid);
2088 } else {
2089 info = null;
2090 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002091 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002092 if (info != null) {
2093 authority = getOrCreateAuthorityLocked(info, id, false);
2094 // If the version is 0 then we are upgrading from a file format that did not
2095 // know about periodic syncs. In that case don't clear the list since we
2096 // want the default, which is a daily periodic sync.
2097 // Otherwise clear out this default list since we will populate it later with
2098 // the periodic sync descriptions that are read from the configuration file.
2099 if (version > 0) {
2100 authority.periodicSyncs.clear();
2101 }
Fred Quintanac2e46912010-03-15 16:10:44 -07002102 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002103 }
2104 if (authority != null) {
2105 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07002106 try {
2107 authority.syncable = (syncable == null) ?
2108 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
2109 } catch (NumberFormatException e) {
2110 // On L we stored this as {"unknown", "true", "false"} so fall back to this
2111 // format.
2112 if ("unknown".equals(syncable)) {
2113 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
2114 } else {
2115 authority.syncable = Boolean.parseBoolean(syncable) ?
2116 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
2117 }
2118
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002119 }
2120 } else {
2121 Log.w(TAG, "Failure adding authority: account="
2122 + accountName + " auth=" + authorityName
2123 + " enabled=" + enabled
2124 + " syncable=" + syncable);
2125 }
2126 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002127 return authority;
2128 }
2129
Matthew Williamsfa774182013-06-18 15:44:11 -07002130 /**
2131 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2132 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002133 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002134 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002135 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002136 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002137 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002138 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002139 try {
2140 period = Long.parseLong(periodValue);
2141 } catch (NumberFormatException e) {
2142 Log.e(TAG, "error parsing the period of a periodic sync", e);
2143 return null;
2144 } catch (NullPointerException e) {
2145 Log.e(TAG, "the period of a periodic sync is null", e);
2146 return null;
2147 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002148 try {
2149 flextime = Long.parseLong(flexValue);
2150 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002151 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002152 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2153 + ", using default: "
2154 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002155 } catch (NullPointerException expected) {
2156 flextime = calculateDefaultFlexTime(period);
2157 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2158 + period + " flex: " + flextime);
2159 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002160 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002161 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002162 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002163 new PeriodicSync(authorityInfo.target.account,
2164 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002165 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002166 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002167 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002168 Log.e(TAG, "Unknown target.");
2169 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002170 }
2171 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002172 return periodicSync;
2173 }
2174
Matthew Williamsfa774182013-06-18 15:44:11 -07002175 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002176 String name = parser.getAttributeValue(null, "name");
2177 String type = parser.getAttributeValue(null, "type");
2178 String value1 = parser.getAttributeValue(null, "value1");
2179 String value2 = parser.getAttributeValue(null, "value2");
2180
2181 try {
2182 if ("long".equals(type)) {
2183 extras.putLong(name, Long.parseLong(value1));
2184 } else if ("integer".equals(type)) {
2185 extras.putInt(name, Integer.parseInt(value1));
2186 } else if ("double".equals(type)) {
2187 extras.putDouble(name, Double.parseDouble(value1));
2188 } else if ("float".equals(type)) {
2189 extras.putFloat(name, Float.parseFloat(value1));
2190 } else if ("boolean".equals(type)) {
2191 extras.putBoolean(name, Boolean.parseBoolean(value1));
2192 } else if ("string".equals(type)) {
2193 extras.putString(name, value1);
2194 } else if ("account".equals(type)) {
2195 extras.putParcelable(name, new Account(value1, value2));
2196 }
2197 } catch (NumberFormatException e) {
2198 Log.e(TAG, "error parsing bundle value", e);
2199 } catch (NullPointerException e) {
2200 Log.e(TAG, "error parsing bundle value", e);
2201 }
2202 }
2203
Dianne Hackborn231cc602009-04-27 17:10:36 -07002204 /**
2205 * Write all account information to the account file.
2206 */
2207 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002208 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002209 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002210 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002211 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002212
Dianne Hackborn231cc602009-04-27 17:10:36 -07002213 try {
2214 fos = mAccountInfoFile.startWrite();
2215 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002216 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07002217 out.startDocument(null, true);
2218 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002219
Dianne Hackborn231cc602009-04-27 17:10:36 -07002220 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002221 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002222 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002223 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002224
2225 // Write the Sync Automatically flags for each user
2226 final int M = mMasterSyncAutomatically.size();
2227 for (int m = 0; m < M; m++) {
2228 int userId = mMasterSyncAutomatically.keyAt(m);
2229 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2230 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2231 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2232 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2233 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002234 }
Costin Manolache360e4542009-09-04 13:36:04 -07002235
Dianne Hackborn231cc602009-04-27 17:10:36 -07002236 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002237 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002238 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002239 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002240 out.startTag(null, "authority");
2241 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002242 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002243 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002244 if (info.service == null) {
2245 out.attribute(null, "account", info.account.name);
2246 out.attribute(null, "type", info.account.type);
2247 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002248 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002249 out.attribute(null, "package", info.service.getPackageName());
2250 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002251 }
Matthew Williams53abfdb2015-06-10 20:06:37 -07002252 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Matthew Williamsfa774182013-06-18 15:44:11 -07002253 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002254 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002255 out.attribute(null, "period", Long.toString(periodicSync.period));
2256 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2257 final Bundle extras = periodicSync.extras;
2258 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002259 out.endTag(null, "periodicSync");
2260 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002261 out.endTag(null, "authority");
2262 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002263 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002264 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002265 mAccountInfoFile.finishWrite(fos);
2266 } catch (java.io.IOException e1) {
2267 Log.w(TAG, "Error writing accounts", e1);
2268 if (fos != null) {
2269 mAccountInfoFile.failWrite(fos);
2270 }
2271 }
2272 }
Costin Manolache360e4542009-09-04 13:36:04 -07002273
Dianne Hackborn231cc602009-04-27 17:10:36 -07002274 static int getIntColumn(Cursor c, String name) {
2275 return c.getInt(c.getColumnIndex(name));
2276 }
Costin Manolache360e4542009-09-04 13:36:04 -07002277
Dianne Hackborn231cc602009-04-27 17:10:36 -07002278 static long getLongColumn(Cursor c, String name) {
2279 return c.getLong(c.getColumnIndex(name));
2280 }
Costin Manolache360e4542009-09-04 13:36:04 -07002281
Dianne Hackborn231cc602009-04-27 17:10:36 -07002282 /**
2283 * Load sync engine state from the old syncmanager database, and then
2284 * erase it. Note that we don't deal with pending operations, active
2285 * sync, or history.
2286 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002287 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002288 // Look for old database to initialize from.
2289 File file = mContext.getDatabasePath("syncmanager.db");
2290 if (!file.exists()) {
2291 return;
2292 }
2293 String path = file.getPath();
2294 SQLiteDatabase db = null;
2295 try {
2296 db = SQLiteDatabase.openDatabase(path, null,
2297 SQLiteDatabase.OPEN_READONLY);
2298 } catch (SQLiteException e) {
2299 }
Costin Manolache360e4542009-09-04 13:36:04 -07002300
Dianne Hackborn231cc602009-04-27 17:10:36 -07002301 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002302 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002303
Dianne Hackborn231cc602009-04-27 17:10:36 -07002304 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002305 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002306 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002307 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002308 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2309 qb.setTables("stats, status");
2310 HashMap<String,String> map = new HashMap<String,String>();
2311 map.put("_id", "status._id as _id");
2312 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002313 if (hasType) {
2314 map.put("account_type", "stats.account_type as account_type");
2315 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002316 map.put("authority", "stats.authority as authority");
2317 map.put("totalElapsedTime", "totalElapsedTime");
2318 map.put("numSyncs", "numSyncs");
2319 map.put("numSourceLocal", "numSourceLocal");
2320 map.put("numSourcePoll", "numSourcePoll");
2321 map.put("numSourceServer", "numSourceServer");
2322 map.put("numSourceUser", "numSourceUser");
2323 map.put("lastSuccessSource", "lastSuccessSource");
2324 map.put("lastSuccessTime", "lastSuccessTime");
2325 map.put("lastFailureSource", "lastFailureSource");
2326 map.put("lastFailureTime", "lastFailureTime");
2327 map.put("lastFailureMesg", "lastFailureMesg");
2328 map.put("pending", "pending");
2329 qb.setProjectionMap(map);
2330 qb.appendWhere("stats._id = status.stats_id");
2331 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002333 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002334 String accountType = hasType
2335 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002336 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002337 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002339 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002340 AuthorityInfo authority =
2341 this.getOrCreateAuthorityLocked(
2342 new EndPoint(new Account(accountName, accountType),
2343 authorityName,
2344 0 /* legacy is single-user */)
2345 , -1,
2346 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002347 if (authority != null) {
2348 int i = mSyncStatus.size();
2349 boolean found = false;
2350 SyncStatusInfo st = null;
2351 while (i > 0) {
2352 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002353 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002354 if (st.authorityId == authority.ident) {
2355 found = true;
2356 break;
2357 }
2358 }
2359 if (!found) {
2360 st = new SyncStatusInfo(authority.ident);
2361 mSyncStatus.put(authority.ident, st);
2362 }
2363 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2364 st.numSyncs = getIntColumn(c, "numSyncs");
2365 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2366 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2367 st.numSourceServer = getIntColumn(c, "numSourceServer");
2368 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002369 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002370 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2371 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2372 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2373 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2374 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2375 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
Costin Manolache360e4542009-09-04 13:36:04 -07002378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002380
Dianne Hackborn231cc602009-04-27 17:10:36 -07002381 // Retrieve the settings.
2382 qb = new SQLiteQueryBuilder();
2383 qb.setTables("settings");
2384 c = qb.query(db, null, null, null, null, null, null);
2385 while (c.moveToNext()) {
2386 String name = c.getString(c.getColumnIndex("name"));
2387 String value = c.getString(c.getColumnIndex("value"));
2388 if (name == null) continue;
2389 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002390 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002391 } else if (name.startsWith("sync_provider_")) {
2392 String provider = name.substring("sync_provider_".length(),
2393 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002394 int i = mAuthorities.size();
2395 while (i > 0) {
2396 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002397 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002398 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002399 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002400 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002401 }
2402 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 }
Costin Manolache360e4542009-09-04 13:36:04 -07002405
Dianne Hackborn231cc602009-04-27 17:10:36 -07002406 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002407
Dianne Hackborn231cc602009-04-27 17:10:36 -07002408 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002409
Dianne Hackborn231cc602009-04-27 17:10:36 -07002410 (new File(path)).delete();
2411 }
2412 }
Costin Manolache360e4542009-09-04 13:36:04 -07002413
Dianne Hackborn231cc602009-04-27 17:10:36 -07002414 public static final int STATUS_FILE_END = 0;
2415 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002416
Dianne Hackborn231cc602009-04-27 17:10:36 -07002417 /**
2418 * Read all sync status back in to the initial engine state.
2419 */
2420 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002421 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002422 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002423 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002424 try {
2425 byte[] data = mStatusFile.readFully();
2426 Parcel in = Parcel.obtain();
2427 in.unmarshall(data, 0, data.length);
2428 in.setDataPosition(0);
2429 int token;
2430 while ((token=in.readInt()) != STATUS_FILE_END) {
2431 if (token == STATUS_FILE_ITEM) {
2432 SyncStatusInfo status = new SyncStatusInfo(in);
2433 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2434 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002435 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002436 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002437 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002438 mSyncStatus.put(status.authorityId, status);
2439 }
2440 } else {
2441 // Ooops.
2442 Log.w(TAG, "Unknown status token: " + token);
2443 break;
2444 }
2445 }
2446 } catch (java.io.IOException e) {
2447 Log.i(TAG, "No initial status");
2448 }
2449 }
Costin Manolache360e4542009-09-04 13:36:04 -07002450
Dianne Hackborn231cc602009-04-27 17:10:36 -07002451 /**
2452 * Write all sync status to the sync status file.
2453 */
2454 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002455 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002456 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002457 }
Costin Manolache360e4542009-09-04 13:36:04 -07002458
Dianne Hackborn231cc602009-04-27 17:10:36 -07002459 // The file is being written, so we don't need to have a scheduled
2460 // write until the next change.
2461 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002462
Dianne Hackborn231cc602009-04-27 17:10:36 -07002463 FileOutputStream fos = null;
2464 try {
2465 fos = mStatusFile.startWrite();
2466 Parcel out = Parcel.obtain();
2467 final int N = mSyncStatus.size();
2468 for (int i=0; i<N; i++) {
2469 SyncStatusInfo status = mSyncStatus.valueAt(i);
2470 out.writeInt(STATUS_FILE_ITEM);
2471 status.writeToParcel(out, 0);
2472 }
2473 out.writeInt(STATUS_FILE_END);
2474 fos.write(out.marshall());
2475 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002476
Dianne Hackborn231cc602009-04-27 17:10:36 -07002477 mStatusFile.finishWrite(fos);
2478 } catch (java.io.IOException e1) {
2479 Log.w(TAG, "Error writing status", e1);
2480 if (fos != null) {
2481 mStatusFile.failWrite(fos);
2482 }
2483 }
2484 }
Costin Manolache360e4542009-09-04 13:36:04 -07002485
Matthew Williamsba352712013-08-13 15:53:31 -07002486 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002487
Matthew Williamsba352712013-08-13 15:53:31 -07002488 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002489 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002490 FileInputStream fis = null;
2491 if (!mPendingFile.getBaseFile().exists()) {
2492 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2493 Log.v(TAG_FILE, "No pending operation file.");
Matthew Williamsfa774182013-06-18 15:44:11 -07002494 }
Ji-Hwan Lee886113d2014-04-17 14:16:38 +09002495 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002496 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002497 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002498 fis = mPendingFile.openRead();
Matthew Williams06485a72013-07-26 12:56:39 -07002499 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2500 Log.v(TAG_FILE, "Reading " + mPendingFile.getBaseFile());
2501 }
Matthew Williamsba352712013-08-13 15:53:31 -07002502 XmlPullParser parser;
2503 parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002504 parser.setInput(fis, StandardCharsets.UTF_8.name());
Matthew Williamsba352712013-08-13 15:53:31 -07002505
Matthew Williamsfa774182013-06-18 15:44:11 -07002506 int eventType = parser.getEventType();
2507 while (eventType != XmlPullParser.START_TAG &&
2508 eventType != XmlPullParser.END_DOCUMENT) {
2509 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002510 }
Matthew Williamsba352712013-08-13 15:53:31 -07002511 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002512
Matthew Williamsba352712013-08-13 15:53:31 -07002513 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002514 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002515 if (eventType == XmlPullParser.START_TAG) {
2516 try {
Matthew Williams06485a72013-07-26 12:56:39 -07002517 String tagName = parser.getName();
Matthew Williams8ef22042013-07-26 12:56:39 -07002518 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2519 // Verify version.
2520 String versionString =
2521 parser.getAttributeValue(null, XML_ATTR_VERSION);
2522 if (versionString == null ||
2523 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2524 Log.w(TAG, "Unknown pending operation version " + versionString);
2525 throw new java.io.IOException("Unknown version.");
2526 }
2527 int authorityId = Integer.valueOf(parser.getAttributeValue(
2528 null, XML_ATTR_AUTHORITYID));
2529 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2530 null, XML_ATTR_EXPEDITED));
2531 int syncSource = Integer.valueOf(parser.getAttributeValue(
2532 null, XML_ATTR_SOURCE));
2533 int reason = Integer.valueOf(parser.getAttributeValue(
2534 null, XML_ATTR_REASON));
2535 AuthorityInfo authority = mAuthorities.get(authorityId);
2536 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2537 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2538 + reason);
2539 }
2540 if (authority != null) {
2541 pop = new PendingOperation(
2542 authority, reason, syncSource, new Bundle(), expedited);
2543 pop.flatExtras = null; // No longer used.
2544 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002545 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002546 Log.v(TAG_FILE, "Adding pending op: "
2547 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002548 + " src=" + pop.syncSource
2549 + " reason=" + pop.reason
2550 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002551 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002552 } else {
2553 // Skip non-existent authority.
2554 pop = null;
2555 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2556 Log.v(TAG_FILE, "No authority found for " + authorityId
2557 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002558 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002559 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002560 } else if (parser.getDepth() == 2 &&
2561 pop != null &&
2562 "extra".equals(tagName)) {
2563 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002564 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002565 } catch (NumberFormatException e) {
2566 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002567 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002568 }
Matthew Williamsba352712013-08-13 15:53:31 -07002569 eventType = parser.next();
2570 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002571 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002572 Log.w(TAG_FILE, "Error reading pending data.", e);
2573 } catch (XmlPullParserException e) {
2574 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2575 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2576 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002577 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002578 if (fis != null) {
2579 try {
2580 fis.close();
2581 } catch (java.io.IOException e1) {}
2582 }
2583 }
2584 }
Matthew Williamsba352712013-08-13 15:53:31 -07002585
Dianne Hackborn231cc602009-04-27 17:10:36 -07002586 static private byte[] flattenBundle(Bundle bundle) {
2587 byte[] flatData = null;
2588 Parcel parcel = Parcel.obtain();
2589 try {
2590 bundle.writeToParcel(parcel, 0);
2591 flatData = parcel.marshall();
2592 } finally {
2593 parcel.recycle();
2594 }
2595 return flatData;
2596 }
Costin Manolache360e4542009-09-04 13:36:04 -07002597
Dianne Hackborn231cc602009-04-27 17:10:36 -07002598 static private Bundle unflattenBundle(byte[] flatData) {
2599 Bundle bundle;
2600 Parcel parcel = Parcel.obtain();
2601 try {
2602 parcel.unmarshall(flatData, 0, flatData.length);
2603 parcel.setDataPosition(0);
2604 bundle = parcel.readBundle();
2605 } catch (RuntimeException e) {
2606 // A RuntimeException is thrown if we were unable to parse the parcel.
2607 // Create an empty parcel in this case.
2608 bundle = new Bundle();
2609 } finally {
2610 parcel.recycle();
2611 }
2612 return bundle;
2613 }
Costin Manolache360e4542009-09-04 13:36:04 -07002614
Matthew Williams8ef22042013-07-26 12:56:39 -07002615 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002616 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2617 private static final String XML_ATTR_SOURCE = "source";
2618 private static final String XML_ATTR_EXPEDITED = "expedited";
2619 private static final String XML_ATTR_REASON = "reason";
2620
2621 /**
2622 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002623 */
2624 private void writePendingOperationsLocked() {
2625 final int N = mPendingOperations.size();
2626 FileOutputStream fos = null;
2627 try {
2628 if (N == 0) {
2629 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2630 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2631 }
2632 mPendingFile.truncate();
2633 return;
2634 }
2635 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2636 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2637 }
2638 fos = mPendingFile.startWrite();
2639 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002640 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002641
2642 for (int i = 0; i < N; i++) {
2643 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002644 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002645 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002646 out.endDocument();
2647 mPendingFile.finishWrite(fos);
2648 } catch (java.io.IOException e1) {
2649 Log.w(TAG, "Error writing pending operations", e1);
2650 if (fos != null) {
2651 mPendingFile.failWrite(fos);
2652 }
2653 }
2654 }
2655
Matthew Williams8ef22042013-07-26 12:56:39 -07002656 /** Write all currently pending ops to the pending ops file. */
2657 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2658 throws IOException {
2659 // Pending operation.
2660 out.startTag(null, "op");
2661
2662 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2663 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2664 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2665 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2666 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2667 extrasToXml(out, pop.extras);
2668
2669 out.endTag(null, "op");
2670 }
2671
2672 /**
2673 * Append the given operation to the pending ops file; if unable to,
2674 * write all pending ops.
2675 */
2676 private void appendPendingOperationLocked(PendingOperation op) {
2677 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2678 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2679 }
2680 FileOutputStream fos = null;
2681 try {
2682 fos = mPendingFile.openAppend();
2683 } catch (java.io.IOException e) {
2684 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2685 Log.v(TAG, "Failed append; writing full file");
2686 }
2687 writePendingOperationsLocked();
2688 return;
2689 }
2690
2691 try {
2692 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002693 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams8ef22042013-07-26 12:56:39 -07002694 writePendingOperationLocked(op, out);
2695 out.endDocument();
2696 mPendingFile.finishWrite(fos);
2697 } catch (java.io.IOException e1) {
2698 Log.w(TAG, "Error writing appending operation", e1);
2699 mPendingFile.failWrite(fos);
2700 } finally {
2701 try {
2702 fos.close();
2703 } catch (IOException e) {}
2704 }
2705 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002706
Matthew Williamsfa774182013-06-18 15:44:11 -07002707 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2708 for (String key : extras.keySet()) {
2709 out.startTag(null, "extra");
2710 out.attribute(null, "name", key);
2711 final Object value = extras.get(key);
2712 if (value instanceof Long) {
2713 out.attribute(null, "type", "long");
2714 out.attribute(null, "value1", value.toString());
2715 } else if (value instanceof Integer) {
2716 out.attribute(null, "type", "integer");
2717 out.attribute(null, "value1", value.toString());
2718 } else if (value instanceof Boolean) {
2719 out.attribute(null, "type", "boolean");
2720 out.attribute(null, "value1", value.toString());
2721 } else if (value instanceof Float) {
2722 out.attribute(null, "type", "float");
2723 out.attribute(null, "value1", value.toString());
2724 } else if (value instanceof Double) {
2725 out.attribute(null, "type", "double");
2726 out.attribute(null, "value1", value.toString());
2727 } else if (value instanceof String) {
2728 out.attribute(null, "type", "string");
2729 out.attribute(null, "value1", value.toString());
2730 } else if (value instanceof Account) {
2731 out.attribute(null, "type", "account");
2732 out.attribute(null, "value1", ((Account)value).name);
2733 out.attribute(null, "value2", ((Account)value).type);
2734 }
2735 out.endTag(null, "extra");
2736 }
2737 }
2738
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002739 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2740 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2741 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002742 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002743 } else {
2744 SyncRequest.Builder req =
2745 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002746 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002747 .setExtras(extras);
2748 if (authorityInfo.target.target_provider) {
2749 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002750 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002751 if (Log.isLoggable(TAG, Log.DEBUG)) {
2752 Log.d(TAG, "Unknown target, skipping sync request.");
2753 }
2754 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002755 }
2756 ContentResolver.requestSync(req.build());
2757 }
2758 }
2759
Alon Albert57286f92012-10-09 14:21:38 -07002760 private void requestSync(Account account, int userId, int reason, String authority,
2761 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002762 // If this is happening in the system process, then call the syncrequest listener
2763 // to make a request back to the SyncManager directly.
2764 // If this is probably a test instance, then call back through the ContentResolver
2765 // which will know which userId to apply based on the Binder id.
2766 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2767 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002768 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002769 new EndPoint(account, authority, userId),
2770 reason,
2771 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002772 } else {
2773 ContentResolver.requestSync(account, authority, extras);
2774 }
2775 }
2776
Dianne Hackborn231cc602009-04-27 17:10:36 -07002777 public static final int STATISTICS_FILE_END = 0;
2778 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2779 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002780
Dianne Hackborn231cc602009-04-27 17:10:36 -07002781 /**
2782 * Read all sync statistics back in to the initial engine state.
2783 */
2784 private void readStatisticsLocked() {
2785 try {
2786 byte[] data = mStatisticsFile.readFully();
2787 Parcel in = Parcel.obtain();
2788 in.unmarshall(data, 0, data.length);
2789 in.setDataPosition(0);
2790 int token;
2791 int index = 0;
2792 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2793 if (token == STATISTICS_FILE_ITEM
2794 || token == STATISTICS_FILE_ITEM_OLD) {
2795 int day = in.readInt();
2796 if (token == STATISTICS_FILE_ITEM_OLD) {
2797 day = day - 2009 + 14245; // Magic!
2798 }
2799 DayStats ds = new DayStats(day);
2800 ds.successCount = in.readInt();
2801 ds.successTime = in.readLong();
2802 ds.failureCount = in.readInt();
2803 ds.failureTime = in.readLong();
2804 if (index < mDayStats.length) {
2805 mDayStats[index] = ds;
2806 index++;
2807 }
2808 } else {
2809 // Ooops.
2810 Log.w(TAG, "Unknown stats token: " + token);
2811 break;
2812 }
2813 }
2814 } catch (java.io.IOException e) {
2815 Log.i(TAG, "No initial statistics");
2816 }
2817 }
Costin Manolache360e4542009-09-04 13:36:04 -07002818
Dianne Hackborn231cc602009-04-27 17:10:36 -07002819 /**
2820 * Write all sync statistics to the sync status file.
2821 */
2822 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002823 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2824 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2825 }
Costin Manolache360e4542009-09-04 13:36:04 -07002826
Dianne Hackborn231cc602009-04-27 17:10:36 -07002827 // The file is being written, so we don't need to have a scheduled
2828 // write until the next change.
2829 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002830
Dianne Hackborn231cc602009-04-27 17:10:36 -07002831 FileOutputStream fos = null;
2832 try {
2833 fos = mStatisticsFile.startWrite();
2834 Parcel out = Parcel.obtain();
2835 final int N = mDayStats.length;
2836 for (int i=0; i<N; i++) {
2837 DayStats ds = mDayStats[i];
2838 if (ds == null) {
2839 break;
2840 }
2841 out.writeInt(STATISTICS_FILE_ITEM);
2842 out.writeInt(ds.day);
2843 out.writeInt(ds.successCount);
2844 out.writeLong(ds.successTime);
2845 out.writeInt(ds.failureCount);
2846 out.writeLong(ds.failureTime);
2847 }
2848 out.writeInt(STATISTICS_FILE_END);
2849 fos.write(out.marshall());
2850 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002851
Dianne Hackborn231cc602009-04-27 17:10:36 -07002852 mStatisticsFile.finishWrite(fos);
2853 } catch (java.io.IOException e1) {
2854 Log.w(TAG, "Error writing stats", e1);
2855 if (fos != null) {
2856 mStatisticsFile.failWrite(fos);
2857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 }
2859 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002860
2861 /**
2862 * Dump state of PendingOperations.
2863 */
2864 public void dumpPendingOperations(StringBuilder sb) {
2865 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2866 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002867 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002868 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002869 .append(")\n");
2870 }
2871 }
Marvin Paula6533252014-11-24 12:57:48 -08002872
2873 /**
2874 * Let the BackupManager know that account sync settings have changed. This will trigger
2875 * {@link com.android.server.backup.SystemBackupAgent} to run.
2876 */
2877 public void queueBackup() {
2878 BackupManager.dataChanged("android");
2879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880}