blob: 1bd1709c74a7121fe4f5430947a5a66990577d7d [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;
Matthew Williamsfa774182013-06-18 15:44:11 -070021import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.ISyncStatusObserver;
25import android.content.PeriodicSync;
26import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070027import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070033import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Message;
37import android.os.Parcel;
38import android.os.RemoteCallbackList;
39import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070040import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070041import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070045import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070046import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080047
48import com.android.internal.annotations.VisibleForTesting;
49import com.android.internal.util.ArrayUtils;
50import com.android.internal.util.FastXmlSerializer;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Dianne Hackborn231cc602009-04-27 17:10:36 -070056import java.io.File;
57import java.io.FileInputStream;
58import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070059import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070061import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080064import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070065import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060066import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070069 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070071 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * @hide
73 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070074public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070077 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070078
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
80 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070081 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080082 private static final String XML_ATTR_ENABLED = "enabled";
83 private static final String XML_ATTR_USER = "user";
84 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
85
Matthew Williamsfa774182013-06-18 15:44:11 -070086 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080087 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
88
Matthew Williamsfa774182013-06-18 15:44:11 -070089 /** Percentage of period that is flex by default, if no flex is set. */
90 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
91
92 /** Lower bound on sync time from which we assign a default flex time. */
93 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
94
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080095 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070096 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a sync start event. */
99 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a sync stop event. */
102 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 // TODO: i18n -- grab these out of resources.
105 /** String names for the sync event types. */
106 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a server-initiated sync. */
109 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a local-initiated sync. */
112 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700113 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700114 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 /** Enum value for a user-initiated sync. */
117 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800119 /** Enum value for a periodic sync. */
120 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700121
122 /** Enum value for a sync started for a service. */
123 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800124
Fred Quintana307da1a2010-01-21 14:24:20 -0800125 public static final long NOT_IN_BACKOFF_MODE = -1;
126
Dianne Hackborn231cc602009-04-27 17:10:36 -0700127 // TODO: i18n -- grab these out of resources.
128 /** String names for the sync source types. */
129 public static final String[] SOURCES = { "SERVER",
130 "LOCAL",
131 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800132 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700133 "PERIODIC",
134 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborn231cc602009-04-27 17:10:36 -0700136 // The MESG column will contain one of these or one of the Error types.
137 public static final String MESG_SUCCESS = "success";
138 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700140 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700141
Dianne Hackborn231cc602009-04-27 17:10:36 -0700142 private static final int MSG_WRITE_STATUS = 1;
143 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 private static final int MSG_WRITE_STATISTICS = 2;
146 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700147
148 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700149
Fred Quintanac2e46912010-03-15 16:10:44 -0700150 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700151 private static final int ACCOUNTS_VERSION = 2;
152
153 private static HashMap<String, String> sAuthorityRenames;
154
155 static {
156 sAuthorityRenames = new HashMap<String, String>();
157 sAuthorityRenames.put("contacts", "com.android.contacts");
158 sAuthorityRenames.put("calendar", "com.android.calendar");
159 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700160
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700162 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700163 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800166 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700167
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168 final int authorityId;
169 // No longer used.
170 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700172
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 PendingOperation(AuthorityInfo authority, int reason, int source,
174 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700175 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700177 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800179 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700181 }
182
183 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700184 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700186 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 this.extras = other.extras;
188 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800189 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700190 }
191
192 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700193 * Considered equal if they target the same sync adapter (A
194 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700195 * is considered an adapter), for the same userId.
196 * @param other PendingOperation to compare.
197 * @return true if the two pending ops are the same.
198 */
199 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700200 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700201 }
202
203 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700204 return "service=" + target.service
205 + " user=" + target.userId
206 + " auth=" + target
207 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 + " src=" + syncSource
209 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 }
Costin Manolache360e4542009-09-04 13:36:04 -0700212
Dianne Hackborn231cc602009-04-27 17:10:36 -0700213 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700215 final HashMap<String, AuthorityInfo> authorities =
216 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700217
Amith Yamasani04e0d262012-02-14 11:50:53 -0800218 AccountInfo(AccountAndUser accountAndUser) {
219 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700220 }
221 }
Costin Manolache360e4542009-09-04 13:36:04 -0700222
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700223 /** Bare bones representation of a sync target. */
224 public static class EndPoint {
225 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
226 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700227 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700228 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800229 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700230 final String provider;
231 final boolean target_service;
232 final boolean target_provider;
233
234 public EndPoint(ComponentName service, int userId) {
235 this.service = service;
236 this.userId = userId;
237 this.account = null;
238 this.provider = null;
239 this.target_service = true;
240 this.target_provider = false;
241 }
242
243 public EndPoint(Account account, String provider, int userId) {
244 this.account = account;
245 this.provider = provider;
246 this.userId = userId;
247 this.service = null;
248 this.target_service = false;
249 this.target_provider = true;
250 }
251
252 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700253 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
254 *
255 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
256 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700257 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700258 public boolean matchesSpec(EndPoint spec) {
259 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700260 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700261 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700262 return false;
263 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700264 if (target_service && spec.target_service) {
265 return service.equals(spec.service);
266 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700267 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700268 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 accountsMatch = true;
270 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700271 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700272 }
273 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700274 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275 providersMatch = true;
276 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700277 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700278 }
279 return accountsMatch && providersMatch;
280 }
281 return false;
282 }
283
284 public String toString() {
285 StringBuilder sb = new StringBuilder();
286 if (target_provider) {
287 sb.append(account == null ? "ALL ACCS" : account.name)
288 .append("/")
289 .append(provider == null ? "ALL PDRS" : provider);
290 } else if (target_service) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700291 sb.append(service.getPackageName() + "/")
292 .append(service.getClassName());
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700293 } else {
294 sb.append("invalid target");
295 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700296 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700297 return sb.toString();
298 }
299 }
300
301 public static class AuthorityInfo {
Matthew Williams8ef22042013-07-26 12:56:39 -0700302 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700303 final int ident;
304 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700305 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700306 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800307 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700308 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800309 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700310 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800311 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700312
Matthew Williamsfa774182013-06-18 15:44:11 -0700313 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700314
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700315 /**
316 * Copy constructor for making deep-ish copies. Only the bundles stored
317 * in periodic syncs can make unexpected changes.
318 *
319 * @param toCopy AuthorityInfo to be copied.
320 */
321 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700322 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700323 ident = toCopy.ident;
324 enabled = toCopy.enabled;
325 syncable = toCopy.syncable;
326 backoffTime = toCopy.backoffTime;
327 backoffDelay = toCopy.backoffDelay;
328 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700329 periodicSyncs = new ArrayList<PeriodicSync>();
330 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700331 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700332 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700333 }
334 }
335
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700336 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700337 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700338 ident = id;
339 enabled = info.target_provider ?
340 SYNC_ENABLED_DEFAULT : true;
341 // Service is active by default,
342 if (info.target_service) {
343 this.syncable = 1;
344 }
345 periodicSyncs = new ArrayList<PeriodicSync>();
346 defaultInitialisation();
347 }
348
349 private void defaultInitialisation() {
Fred Quintana4a6679b2009-08-17 13:05:39 -0700350 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800351 backoffTime = -1; // if < 0 then we aren't in backoff mode
352 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700353 PeriodicSync defaultSync;
354 // Old version is one sync a day. Empty bundle gets replaced by any addPeriodicSync()
355 // call.
Matthew Williams8ef22042013-07-26 12:56:39 -0700356 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700357 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700358 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700359 new Bundle(),
360 DEFAULT_POLL_FREQUENCY_SECONDS,
361 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
362 periodicSyncs.add(defaultSync);
363 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 }
Matthew Williams06485a72013-07-26 12:56:39 -0700365
366 @Override
367 public String toString() {
368 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
369 + backoffTime + ", delay=" + delayUntil;
370 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700371 }
Costin Manolache360e4542009-09-04 13:36:04 -0700372
Dianne Hackborn231cc602009-04-27 17:10:36 -0700373 public static class SyncHistoryItem {
374 int authorityId;
375 int historyId;
376 long eventTime;
377 long elapsedTime;
378 int source;
379 int event;
380 long upstreamActivity;
381 long downstreamActivity;
382 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700383 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700384 Bundle extras;
385 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700386 }
Costin Manolache360e4542009-09-04 13:36:04 -0700387
Dianne Hackborn231cc602009-04-27 17:10:36 -0700388 public static class DayStats {
389 public final int day;
390 public int successCount;
391 public long successTime;
392 public int failureCount;
393 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700394
Dianne Hackborn231cc602009-04-27 17:10:36 -0700395 public DayStats(int day) {
396 this.day = day;
397 }
398 }
Costin Manolache360e4542009-09-04 13:36:04 -0700399
Amith Yamasani04e0d262012-02-14 11:50:53 -0800400 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700401
402 /** Called when a sync is needed on an account(s) due to some change in state. */
403 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800404 }
405
Dianne Hackborn231cc602009-04-27 17:10:36 -0700406 // Primary list of all syncable authorities. Also our global lock.
407 private final SparseArray<AuthorityInfo> mAuthorities =
408 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700409
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 private final HashMap<AccountAndUser, AccountInfo> mAccounts
411 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412
Dianne Hackborn231cc602009-04-27 17:10:36 -0700413 private final ArrayList<PendingOperation> mPendingOperations =
414 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700415
Amith Yamasani04e0d262012-02-14 11:50:53 -0800416 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
417 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700418
Dianne Hackborn231cc602009-04-27 17:10:36 -0700419 private final SparseArray<SyncStatusInfo> mSyncStatus =
420 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700421
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 private final ArrayList<SyncHistoryItem> mSyncHistory =
423 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700424
Dianne Hackborn231cc602009-04-27 17:10:36 -0700425 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
426 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700427
Matthew Williams8ef22042013-07-26 12:56:39 -0700428 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700429 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
430 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700431
Fred Quintana77c560f2010-03-29 22:20:26 -0700432 private int mNextAuthorityId = 0;
433
Dianne Hackborn231cc602009-04-27 17:10:36 -0700434 // We keep 4 weeks of stats.
435 private final DayStats[] mDayStats = new DayStats[7*4];
436 private final Calendar mCal;
437 private int mYear;
438 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700439
Dianne Hackborn231cc602009-04-27 17:10:36 -0700440 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800441
Dianne Hackborn231cc602009-04-27 17:10:36 -0700442 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700443
Ashish Sharma69d95de2012-04-11 17:27:24 -0700444 private int mSyncRandomOffset;
445
Dianne Hackborn231cc602009-04-27 17:10:36 -0700446 /**
447 * This file contains the core engine state: all accounts and the
448 * settings for them. It must never be lost, and should be changed
449 * infrequently, so it is stored as an XML file.
450 */
451 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700452
Dianne Hackborn231cc602009-04-27 17:10:36 -0700453 /**
454 * This file contains the current sync status. We would like to retain
455 * it across boots, but its loss is not the end of the world, so we store
456 * this information as binary data.
457 */
458 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700459
Dianne Hackborn231cc602009-04-27 17:10:36 -0700460 /**
461 * This file contains sync statistics. This is purely debugging information
462 * so is written infrequently and can be thrown away at any time.
463 */
464 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700465
Dianne Hackborn231cc602009-04-27 17:10:36 -0700466 /**
467 * This file contains the pending sync operations. It is a binary file,
468 * which must be updated every time an operation is added or removed,
469 * so we have special handling of it.
470 */
471 private final AtomicFile mPendingFile;
472 private static final int PENDING_FINISH_TO_WRITE = 4;
473 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700474
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800476 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800477 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800478
479 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700480
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800481 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700484
Dianne Hackborn231cc602009-04-27 17:10:36 -0700485 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700486
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800487 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
488 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
489
Dianne Hackborn231cc602009-04-27 17:10:36 -0700490 File systemDir = new File(dataDir, "system");
491 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800492 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700493
494 maybeDeleteLegacyPendingInfoLocked(syncDir);
495
Dianne Hackborn231cc602009-04-27 17:10:36 -0700496 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
497 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700498 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700499 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700500
Dianne Hackborn231cc602009-04-27 17:10:36 -0700501 readAccountInfoLocked();
502 readStatusLocked();
503 readPendingOperationsLocked();
504 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700505 readAndDeleteLegacyAccountInfoLocked();
506 writeAccountInfoLocked();
507 writeStatusLocked();
508 writePendingOperationsLocked();
509 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 }
511
512 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800513 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 }
515
516 public static void init(Context context) {
517 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800518 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800520 // This call will return the correct directory whether Encrypted File Systems is
521 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600522 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800523 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 }
525
526 public static SyncStorageEngine getSingleton() {
527 if (sSyncStorageEngine == null) {
528 throw new IllegalStateException("not initialized");
529 }
530 return sSyncStorageEngine;
531 }
532
Amith Yamasani04e0d262012-02-14 11:50:53 -0800533 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
534 if (mSyncRequestListener == null) {
535 mSyncRequestListener = listener;
536 }
537 }
538
Dianne Hackborn231cc602009-04-27 17:10:36 -0700539 @Override public void handleMessage(Message msg) {
540 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700541 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700542 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700543 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700545 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700546 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 }
548 }
549 }
Costin Manolache360e4542009-09-04 13:36:04 -0700550
Ashish Sharma69d95de2012-04-11 17:27:24 -0700551 public int getSyncRandomOffset() {
552 return mSyncRandomOffset;
553 }
554
Dianne Hackborn231cc602009-04-27 17:10:36 -0700555 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
556 synchronized (mAuthorities) {
557 mChangeListeners.register(callback, mask);
558 }
559 }
Costin Manolache360e4542009-09-04 13:36:04 -0700560
Dianne Hackborn231cc602009-04-27 17:10:36 -0700561 public void removeStatusChangeListener(ISyncStatusObserver callback) {
562 synchronized (mAuthorities) {
563 mChangeListeners.unregister(callback);
564 }
565 }
Costin Manolache360e4542009-09-04 13:36:04 -0700566
Matthew Williamsfa774182013-06-18 15:44:11 -0700567 /**
568 * Figure out a reasonable flex time for cases where none is provided (old api calls).
569 * @param syncTimeSeconds requested sync time from now.
570 * @return amount of seconds before syncTimeSeconds that the sync can occur.
571 * I.e.
572 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700573 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700574 */
575 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
576 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
577 // Small enough sync request time that we don't add flex time - developer probably
578 // wants to wait for an operation to occur before syncing so we honour the
579 // request time.
580 return 0L;
581 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
582 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
583 } else {
584 // Large enough sync request time that we cap the flex time.
585 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
586 }
587 }
588
Dianne Hackborn231cc602009-04-27 17:10:36 -0700589 private void reportChange(int which) {
590 ArrayList<ISyncStatusObserver> reports = null;
591 synchronized (mAuthorities) {
592 int i = mChangeListeners.beginBroadcast();
593 while (i > 0) {
594 i--;
595 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
596 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 continue;
598 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700599 if (reports == null) {
600 reports = new ArrayList<ISyncStatusObserver>(i);
601 }
602 reports.add(mChangeListeners.getBroadcastItem(i));
603 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700604 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700605 }
Costin Manolache360e4542009-09-04 13:36:04 -0700606
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700607 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700608 Log.v(TAG, "reportChange " + which + " to: " + reports);
609 }
Costin Manolache360e4542009-09-04 13:36:04 -0700610
Dianne Hackborn231cc602009-04-27 17:10:36 -0700611 if (reports != null) {
612 int i = reports.size();
613 while (i > 0) {
614 i--;
615 try {
616 reports.get(i).onStatusChanged(which);
617 } catch (RemoteException e) {
618 // The remote callback list will take care of this for us.
619 }
620 }
621 }
622 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700623
Amith Yamasani04e0d262012-02-14 11:50:53 -0800624 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700625 synchronized (mAuthorities) {
626 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700627 AuthorityInfo authority = getAuthorityLocked(
628 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700629 "getSyncAutomatically");
630 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700631 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700632
Dianne Hackborn231cc602009-04-27 17:10:36 -0700633 int i = mAuthorities.size();
634 while (i > 0) {
635 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700636 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700637 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700638 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700639 return true;
640 }
641 }
642 return false;
643 }
644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645
Amith Yamasani04e0d262012-02-14 11:50:53 -0800646 public void setSyncAutomatically(Account account, int userId, String providerName,
647 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700648 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800649 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
650 + ", user " + userId + " -> " + sync);
651 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700652 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700653 AuthorityInfo authority =
654 getOrCreateAuthorityLocked(
655 new EndPoint(account, providerName, userId),
656 -1 /* ident */,
657 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700658 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700659 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800660 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
661 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700662 return;
663 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700664 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700665 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700667
Fred Quintana77c560f2010-03-29 22:20:26 -0700668 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700669 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
670 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700671 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700672 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674
Amith Yamasani04e0d262012-02-14 11:50:53 -0800675 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700676 synchronized (mAuthorities) {
677 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700678 AuthorityInfo authority = getAuthorityLocked(
679 new EndPoint(account, providerName, userId),
680 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700681 if (authority == null) {
682 return -1;
683 }
684 return authority.syncable;
685 }
686
687 int i = mAuthorities.size();
688 while (i > 0) {
689 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700690 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700691 if (authorityInfo.target != null
692 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700693 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700694 }
695 }
696 return -1;
697 }
698 }
699
Amith Yamasani04e0d262012-02-14 11:50:53 -0800700 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700701 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700702 }
703
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700704 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700705 synchronized (mAuthorities) {
706 if (cname != null) {
707 AuthorityInfo authority = getAuthorityLocked(
708 new EndPoint(cname, userId),
Matthew Williams8ef22042013-07-26 12:56:39 -0700709 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700710 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700711 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700712 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700713 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700714 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700715 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700716 }
717 }
718
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700719 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700720 setSyncableStateForEndPoint(new EndPoint(cname, userId), active ? 1 : 0);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700721 }
722
723 /**
724 * An enabled sync service and a syncable provider's adapter both get resolved to the same
725 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700726 * @param target target to set value for.
727 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700729 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700730 AuthorityInfo aInfo;
731 synchronized (mAuthorities) {
732 aInfo = getOrCreateAuthorityLocked(target, -1, false);
733 if (syncable > 1) {
734 syncable = 1;
735 } else if (syncable < -1) {
736 syncable = -1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700737 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700738 if (Log.isLoggable(TAG, Log.VERBOSE)) {
739 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
740 }
741 if (aInfo.syncable == syncable) {
742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
743 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
744 }
745 return;
746 }
747 aInfo.syncable = syncable;
748 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700750 if (syncable > 0) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700751 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700752 }
753 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
754 }
755
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700756 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800757 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700758 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
759 if (authority != null) {
760 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800761 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700762 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800763 }
764 }
765
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700766 /**
767 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
768 * the account or provider info be null, which signifies all accounts or providers.
769 */
770 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
771 if (Log.isLoggable(TAG, Log.VERBOSE)) {
772 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800773 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
774 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700775 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800776 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700777 if (info.target_provider
778 && (info.account == null || info.provider == null)) {
779 // Do more work for a provider sync if the provided info has specified all
780 // accounts/providers.
781 changed = setBackoffLocked(
782 info.account /* may be null */,
783 info.userId,
784 info.provider /* may be null */,
785 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800786 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700787 AuthorityInfo authorityInfo =
788 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
789 if (authorityInfo.backoffTime == nextSyncTime
790 && authorityInfo.backoffDelay == nextDelay) {
791 changed = false;
792 } else {
793 authorityInfo.backoffTime = nextSyncTime;
794 authorityInfo.backoffDelay = nextDelay;
795 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800796 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800797 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800798 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 if (changed) {
800 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
801 }
802 }
803
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 /**
805 * Either set backoff for a specific authority, or set backoff for all the
806 * accounts on a specific adapter/all adapters.
807 *
808 * @param account account for which to set backoff. Null to specify all accounts.
809 * @param userId id of the user making this request.
810 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700811 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700812 */
813 private boolean setBackoffLocked(Account account, int userId, String providerName,
814 long nextSyncTime, long nextDelay) {
815 boolean changed = false;
816 for (AccountInfo accountInfo : mAccounts.values()) {
817 if (account != null && !account.equals(accountInfo.accountAndUser.account)
818 && userId != accountInfo.accountAndUser.userId) {
819 continue;
820 }
821 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
822 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700823 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700824 continue;
825 }
826 if (authorityInfo.backoffTime != nextSyncTime
827 || authorityInfo.backoffDelay != nextDelay) {
828 authorityInfo.backoffTime = nextSyncTime;
829 authorityInfo.backoffDelay = nextDelay;
830 changed = true;
831 }
832 }
833 }
834 return changed;
835 }
836
Matthew Williams119aac92014-09-28 20:42:23 -0700837 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800838 boolean changed = false;
839 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700840 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700841 for (AccountInfo accountInfo : mAccounts.values()) {
842 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
843 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
844 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700845 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams119aac92014-09-28 20:42:23 -0700846 Log.v(TAG, "clearAllBackoffsLocked:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700847 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700848 + " account:" + accountInfo.accountAndUser.account.name
849 + " user:" + accountInfo.accountAndUser.userId
850 + " backoffTime was: " + authorityInfo.backoffTime
851 + " backoffDelay was: " + authorityInfo.backoffDelay);
852 }
853 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
854 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700855 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800856 }
Alon Albert744e310f2010-12-14 11:37:20 -0800857 }
858 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700859 // Clear backoff for all sync services.
860 for (ComponentName service : mServices.keySet()) {
861 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
862 for (int i = 0; i < aInfos.size(); i++) {
863 AuthorityInfo authorityInfo = aInfos.valueAt(i);
864 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
865 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
866 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
867 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
868 }
869 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700870 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800871 }
872 }
873
874 if (changed) {
875 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
876 }
877 }
878
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700879 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800880 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700881 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800882 if (authority == null) {
883 return 0;
884 }
885 return authority.delayUntil;
886 }
887 }
888
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700889 public void setDelayUntilTime(EndPoint info, long delayUntil) {
890 if (Log.isLoggable(TAG, Log.VERBOSE)) {
891 Log.v(TAG, "setDelayUntil: " + info
892 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800893 }
894 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700895 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
896 if (authority.delayUntil == delayUntil) {
897 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700898 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700899 authority.delayUntil = delayUntil;
900 }
901 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
902 }
903
904 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
905 if (Log.isLoggable(TAG, Log.VERBOSE)) {
906 Log.v(TAG, "addPeriodicSync: " + info
907 + " -> period " + period + ", flex " + flextime + ", extras "
908 + extras.toString());
909 }
910 synchronized (mAuthorities) {
911 if (period <= 0) {
912 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
913 }
914 if (extras == null) {
915 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700916 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700917 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700918 PeriodicSync toUpdate;
919 if (info.target_provider) {
920 toUpdate = new PeriodicSync(info.account,
921 info.provider,
922 extras,
923 period,
924 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700925 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -0700926 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700927 }
928 AuthorityInfo authority =
929 getOrCreateAuthorityLocked(info, -1, false);
930 // add this periodic sync if an equivalent periodic doesn't already exist.
931 boolean alreadyPresent = false;
932 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
933 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
934 if (SyncManager.syncExtrasEquals(syncInfo.extras,
935 extras,
936 true /* includeSyncSettings*/)) {
937 if (period == syncInfo.period &&
938 flextime == syncInfo.flexTime) {
939 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700940 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700941 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700942 authority.periodicSyncs.set(i, toUpdate);
943 alreadyPresent = true;
944 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700945 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700946 }
947 // If we added an entry to the periodicSyncs array also add an entry to
948 // the periodic syncs status to correspond to it.
949 if (!alreadyPresent) {
950 authority.periodicSyncs.add(toUpdate);
951 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
952 // A new periodic sync is initialised as already having been run.
953 status.setPeriodicSyncTime(
954 authority.periodicSyncs.size() - 1,
955 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800956 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700957 } finally {
958 writeAccountInfoLocked();
959 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800960 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800961 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800962 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
963 }
964
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700965 public void removePeriodicSync(EndPoint info, Bundle extras) {
966 synchronized(mAuthorities) {
967 try {
968 AuthorityInfo authority =
969 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -0700970 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700971 SyncStatusInfo status = mSyncStatus.get(authority.ident);
972 boolean changed = false;
973 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
974 int i = 0;
975 while (iterator.hasNext()) {
976 PeriodicSync syncInfo = iterator.next();
977 if (SyncManager.syncExtrasEquals(syncInfo.extras,
978 extras,
979 true /* includeSyncSettings */)) {
980 iterator.remove();
981 changed = true;
982 // If we removed an entry from the periodicSyncs array also
983 // remove the corresponding entry from the status
984 if (status != null) {
985 status.removePeriodicSyncTime(i);
986 } else {
987 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
988 + " did not find it.");
989 }
990 } else {
991 i++;
992 }
993 }
994 if (!changed) {
995 return;
996 }
997 } finally {
998 writeAccountInfoLocked();
999 writeStatusLocked();
1000 }
1001 }
1002 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001003 }
1004
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001005 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001006 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1007 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001008 */
1009 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001010 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001011 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1012 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1013 if (authorityInfo != null) {
1014 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001015 // Copy and send out. Necessary for thread-safety although it's parceled.
1016 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001017 }
1018 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001019 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001020 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001021 }
1022
Amith Yamasani04e0d262012-02-14 11:50:53 -08001023 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001024 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001026 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001027 return;
1028 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001029 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 writeAccountInfoLocked();
1031 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001032 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001033 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1034 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001035 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001036 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001037 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
Amith Yamasani04e0d262012-02-14 11:50:53 -08001040 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001043 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 }
1045 }
Costin Manolache360e4542009-09-04 13:36:04 -07001046
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 public AuthorityInfo getAuthority(int authorityId) {
1048 synchronized (mAuthorities) {
1049 return mAuthorities.get(authorityId);
1050 }
1051 }
Costin Manolache360e4542009-09-04 13:36:04 -07001052
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001054 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001055 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001057 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001059 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001060 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001061 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001062 return true;
1063 }
1064 }
1065 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 return false;
1067 }
Costin Manolache360e4542009-09-04 13:36:04 -07001068
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001069 public PendingOperation insertIntoPending(SyncOperation op) {
1070 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1073 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001074 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001075 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001076 final EndPoint info = op.target;
1077 AuthorityInfo authority =
1078 getOrCreateAuthorityLocked(info,
1079 -1 /* desired identifier */,
1080 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001081 if (authority == null) {
1082 return null;
1083 }
Costin Manolache360e4542009-09-04 13:36:04 -07001084
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001085 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
Matthew Williams64280462014-01-09 10:49:23 -08001086 op.isExpedited());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001087 mPendingOperations.add(pop);
Matthew Williams06485a72013-07-26 12:56:39 -07001088 appendPendingOperationLocked(pop);
Costin Manolache360e4542009-09-04 13:36:04 -07001089
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1091 status.pending = true;
1092 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001093 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001094 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001095 }
1096
Matthew Williamsfa774182013-06-18 15:44:11 -07001097 /**
1098 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001099 * authorities. If there are no more pending syncs for the same target,
1100 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001101 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001102 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 public boolean deleteFromPending(PendingOperation op) {
1104 boolean res = false;
1105 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001106 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1107 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001108 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001109 if (mPendingOperations.remove(op)) {
1110 if (mPendingOperations.size() == 0
1111 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1112 writePendingOperationsLocked();
1113 mNumPendingFinished = 0;
1114 } else {
1115 mNumPendingFinished++;
1116 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001117 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001118 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001119 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1120 Log.v(TAG, "removing - " + authority.toString());
1121 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 final int N = mPendingOperations.size();
1123 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001124 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001125 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001126 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 morePending = true;
1128 break;
1129 }
1130 }
Costin Manolache360e4542009-09-04 13:36:04 -07001131
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001133 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001134 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1135 status.pending = false;
1136 }
1137 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 res = true;
1139 }
1140 }
Costin Manolache360e4542009-09-04 13:36:04 -07001141
Fred Quintanaac9385e2009-06-22 18:00:59 -07001142 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001143 return res;
1144 }
1145
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 /**
1147 * Return a copy of the current array of pending operations. The
1148 * PendingOperation objects are the real objects stored inside, so that
1149 * they can be used with deleteFromPending().
1150 */
1151 public ArrayList<PendingOperation> getPendingOperations() {
1152 synchronized (mAuthorities) {
1153 return new ArrayList<PendingOperation>(mPendingOperations);
1154 }
1155 }
Costin Manolache360e4542009-09-04 13:36:04 -07001156
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 /**
1158 * Return the number of currently pending operations.
1159 */
1160 public int getPendingOperationCount() {
1161 synchronized (mAuthorities) {
1162 return mPendingOperations.size();
1163 }
1164 }
Costin Manolache360e4542009-09-04 13:36:04 -07001165
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 /**
1167 * Called when the set of account has changed, given the new array of
1168 * active accounts.
1169 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001170 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001172 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1173 Log.v(TAG, "Updating for new accounts...");
1174 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1176 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1177 while (accIt.hasNext()) {
1178 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001179 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1180 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001182 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001183 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001184 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 for (AuthorityInfo auth : acc.authorities.values()) {
1186 removing.put(auth.ident, auth);
1187 }
1188 accIt.remove();
1189 }
1190 }
Costin Manolache360e4542009-09-04 13:36:04 -07001191
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 // Clean out all data structures.
1193 int i = removing.size();
1194 if (i > 0) {
1195 while (i > 0) {
1196 i--;
1197 int ident = removing.keyAt(i);
1198 mAuthorities.remove(ident);
1199 int j = mSyncStatus.size();
1200 while (j > 0) {
1201 j--;
1202 if (mSyncStatus.keyAt(j) == ident) {
1203 mSyncStatus.remove(mSyncStatus.keyAt(j));
1204 }
1205 }
1206 j = mSyncHistory.size();
1207 while (j > 0) {
1208 j--;
1209 if (mSyncHistory.get(j).authorityId == ident) {
1210 mSyncHistory.remove(j);
1211 }
1212 }
1213 }
1214 writeAccountInfoLocked();
1215 writeStatusLocked();
1216 writePendingOperationsLocked();
1217 writeStatisticsLocked();
1218 }
1219 }
1220 }
1221
1222 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001223 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1224 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001225 */
Fred Quintana918339a2010-10-05 14:00:39 -07001226 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1227 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001229 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001230 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001231 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001232 + " src=" + activeSyncContext.mSyncOperation.syncSource
1233 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001235 final EndPoint info = activeSyncContext.mSyncOperation.target;
1236 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1237 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001238 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001239 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001240 syncInfo = new SyncInfo(
1241 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001242 authorityInfo.target.account,
1243 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001244 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001245 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001246 }
Fred Quintana918339a2010-10-05 14:00:39 -07001247 reportActiveChange();
1248 return syncInfo;
1249 }
1250
1251 /**
1252 * Called to indicate that a previously active sync is no longer active.
1253 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001254 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001255 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001256 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1258 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001259 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001260 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001261 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001262 }
1263
1264 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001265 }
1266
1267 /**
1268 * To allow others to send active change reports, to poke clients.
1269 */
1270 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001271 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 }
Costin Manolache360e4542009-09-04 13:36:04 -07001273
Dianne Hackborn231cc602009-04-27 17:10:36 -07001274 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001275 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001277 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 long id;
1279 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001280 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1281 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001282 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001283 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 if (authority == null) {
1285 return -1;
1286 }
1287 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001288 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001289 item.authorityId = authority.ident;
1290 item.historyId = mNextHistoryId++;
1291 if (mNextHistoryId < 0) mNextHistoryId = 0;
1292 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001293 item.source = op.syncSource;
1294 item.reason = op.reason;
1295 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 item.event = EVENT_START;
1297 mSyncHistory.add(0, item);
1298 while (mSyncHistory.size() > MAX_HISTORY) {
1299 mSyncHistory.remove(mSyncHistory.size()-1);
1300 }
1301 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001302 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 }
Costin Manolache360e4542009-09-04 13:36:04 -07001304
Fred Quintanaac9385e2009-06-22 18:00:59 -07001305 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308
Fred Quintana77c560f2010-03-29 22:20:26 -07001309 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001312 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001313 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1314 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 SyncHistoryItem item = null;
1316 int i = mSyncHistory.size();
1317 while (i > 0) {
1318 i--;
1319 item = mSyncHistory.get(i);
1320 if (item.historyId == historyId) {
1321 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001323 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
Costin Manolache360e4542009-09-04 13:36:04 -07001325
Dianne Hackborn231cc602009-04-27 17:10:36 -07001326 if (item == null) {
1327 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1328 return;
1329 }
Costin Manolache360e4542009-09-04 13:36:04 -07001330
Dianne Hackborn231cc602009-04-27 17:10:36 -07001331 item.elapsedTime = elapsedTime;
1332 item.event = EVENT_STOP;
1333 item.mesg = resultMessage;
1334 item.downstreamActivity = downstreamActivity;
1335 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001336
Dianne Hackborn231cc602009-04-27 17:10:36 -07001337 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001338
Dianne Hackborn231cc602009-04-27 17:10:36 -07001339 status.numSyncs++;
1340 status.totalElapsedTime += elapsedTime;
1341 switch (item.source) {
1342 case SOURCE_LOCAL:
1343 status.numSourceLocal++;
1344 break;
1345 case SOURCE_POLL:
1346 status.numSourcePoll++;
1347 break;
1348 case SOURCE_USER:
1349 status.numSourceUser++;
1350 break;
1351 case SOURCE_SERVER:
1352 status.numSourceServer++;
1353 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001354 case SOURCE_PERIODIC:
1355 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001356 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 }
Costin Manolache360e4542009-09-04 13:36:04 -07001358
Dianne Hackborn231cc602009-04-27 17:10:36 -07001359 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001360 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 if (mDayStats[0] == null) {
1362 mDayStats[0] = new DayStats(day);
1363 } else if (day != mDayStats[0].day) {
1364 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1365 mDayStats[0] = new DayStats(day);
1366 writeStatisticsNow = true;
1367 } else if (mDayStats[0] == null) {
1368 }
1369 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001370
Dianne Hackborn231cc602009-04-27 17:10:36 -07001371 final long lastSyncTime = (item.eventTime + elapsedTime);
1372 boolean writeStatusNow = false;
1373 if (MESG_SUCCESS.equals(resultMessage)) {
1374 // - if successful, update the successful columns
1375 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1376 writeStatusNow = true;
1377 }
1378 status.lastSuccessTime = lastSyncTime;
1379 status.lastSuccessSource = item.source;
1380 status.lastFailureTime = 0;
1381 status.lastFailureSource = -1;
1382 status.lastFailureMesg = null;
1383 status.initialFailureTime = 0;
1384 ds.successCount++;
1385 ds.successTime += elapsedTime;
1386 } else if (!MESG_CANCELED.equals(resultMessage)) {
1387 if (status.lastFailureTime == 0) {
1388 writeStatusNow = true;
1389 }
1390 status.lastFailureTime = lastSyncTime;
1391 status.lastFailureSource = item.source;
1392 status.lastFailureMesg = resultMessage;
1393 if (status.initialFailureTime == 0) {
1394 status.initialFailureTime = lastSyncTime;
1395 }
1396 ds.failureCount++;
1397 ds.failureTime += elapsedTime;
1398 }
Costin Manolache360e4542009-09-04 13:36:04 -07001399
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 if (writeStatusNow) {
1401 writeStatusLocked();
1402 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1403 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1404 WRITE_STATUS_DELAY);
1405 }
1406 if (writeStatisticsNow) {
1407 writeStatisticsLocked();
1408 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1409 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1410 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001411 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001412 }
Costin Manolache360e4542009-09-04 13:36:04 -07001413
Fred Quintanaac9385e2009-06-22 18:00:59 -07001414 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001415 }
1416
1417 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001418 * Return a list of the currently active syncs. Note that the returned
1419 * items are the real, live active sync objects, so be careful what you do
1420 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001421 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001422 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001423 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001424 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001425 }
1426 }
Costin Manolache360e4542009-09-04 13:36:04 -07001427
Dianne Hackborn231cc602009-04-27 17:10:36 -07001428 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001429 * @param userId Id of user to return current sync info.
1430 * @param canAccessAccounts Determines whether to redact Account information from the result.
1431 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001432 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001433 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001434 synchronized (mAuthorities) {
1435 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1436 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1437 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001438 SyncInfo copy;
1439 if (!canAccessAccounts) {
1440 copy = SyncInfo.createAccountRedacted(
1441 sync.authorityId, sync.authority, sync.startTime);
1442 } else {
1443 copy = new SyncInfo(sync);
1444 }
1445 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001446 }
1447 return syncsCopy;
1448 }
1449 }
1450
1451 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1452 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1453 if (syncs == null) {
1454 syncs = new ArrayList<SyncInfo>();
1455 mCurrentSyncs.put(userId, syncs);
1456 }
1457 return syncs;
1458 }
1459
1460 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001461 * Return an array of the current sync status for all authorities. Note
1462 * that the objects inside the array are the real, live status objects,
1463 * so be careful what you do with them.
1464 */
1465 public ArrayList<SyncStatusInfo> getSyncStatus() {
1466 synchronized (mAuthorities) {
1467 final int N = mSyncStatus.size();
1468 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1469 for (int i=0; i<N; i++) {
1470 ops.add(mSyncStatus.valueAt(i));
1471 }
1472 return ops;
1473 }
1474 }
Costin Manolache360e4542009-09-04 13:36:04 -07001475
Dianne Hackborn231cc602009-04-27 17:10:36 -07001476 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001477 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001478 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001479 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001480 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001481 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001482 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001483 true /* write to storage if this results in a change */);
1484 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1485 }
1486 }
1487
1488 /**
1489 * Return a copy of all authorities with their corresponding sync status
1490 */
1491 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1492 synchronized (mAuthorities) {
1493 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1494 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1495 for (int i = 0; i < mAuthorities.size(); i++) {
1496 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001497 }
1498 return infos;
1499 }
1500 }
1501
1502 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001503 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001504 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001505 * @param info the endpoint target we are querying status info for.
1506 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001507 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001508 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1509 if (info.target_provider && (info.account == null || info.provider == null)) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001510 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001511 } else if (info.target_service && info.service == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001512 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001513 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001514 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001515 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001516 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001517 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001518 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001519 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001520 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001521 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 }
1523 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001524 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001525 }
1526 }
Costin Manolache360e4542009-09-04 13:36:04 -07001527
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001528 /** Return true if the pending status is true of any matching authorities. */
1529 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 synchronized (mAuthorities) {
1531 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001532 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001533 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001534 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1535 if (ainfo == null) {
1536 continue;
1537 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001538 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001539 continue;
1540 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001541 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001542 return true;
1543 }
1544 }
1545 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548
1549 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001550 * Return an array of the current sync status for all authorities. Note
1551 * that the objects inside the array are the real, live status objects,
1552 * so be careful what you do with them.
1553 */
1554 public ArrayList<SyncHistoryItem> getSyncHistory() {
1555 synchronized (mAuthorities) {
1556 final int N = mSyncHistory.size();
1557 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1558 for (int i=0; i<N; i++) {
1559 items.add(mSyncHistory.get(i));
1560 }
1561 return items;
1562 }
1563 }
Costin Manolache360e4542009-09-04 13:36:04 -07001564
Dianne Hackborn231cc602009-04-27 17:10:36 -07001565 /**
1566 * Return an array of the current per-day statistics. Note
1567 * that the objects inside the array are the real, live status objects,
1568 * so be careful what you do with them.
1569 */
1570 public DayStats[] getDayStatistics() {
1571 synchronized (mAuthorities) {
1572 DayStats[] ds = new DayStats[mDayStats.length];
1573 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1574 return ds;
1575 }
1576 }
Costin Manolache360e4542009-09-04 13:36:04 -07001577
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001578 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1579 AuthorityInfo authorityInfo) {
1580 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1581 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1582 }
1583
Dianne Hackborn55280a92009-05-07 15:53:46 -07001584 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 mCal.setTimeInMillis(System.currentTimeMillis());
1586 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1587 if (mYear != mCal.get(Calendar.YEAR)) {
1588 mYear = mCal.get(Calendar.YEAR);
1589 mCal.clear();
1590 mCal.set(Calendar.YEAR, mYear);
1591 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1592 }
1593 return dayOfYear + mYearInDays;
1594 }
Costin Manolache360e4542009-09-04 13:36:04 -07001595
Dianne Hackborn231cc602009-04-27 17:10:36 -07001596 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001597 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001598 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001599 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001600 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001601 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001602 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001603 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1604 if (info.target_service) {
1605 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1606 AuthorityInfo authority = null;
1607 if (aInfo != null) {
1608 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001609 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001610 if (authority == null) {
1611 if (tag != null) {
1612 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001613 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1614 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001615 }
1616 }
1617 return null;
1618 }
1619 return authority;
1620 } else if (info.target_provider){
1621 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1622 AccountInfo accountInfo = mAccounts.get(au);
1623 if (accountInfo == null) {
1624 if (tag != null) {
1625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1626 Log.v(TAG, tag + ": unknown account " + au);
1627 }
1628 }
1629 return null;
1630 }
1631 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1632 if (authority == null) {
1633 if (tag != null) {
1634 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1635 Log.v(TAG, tag + ": unknown provider " + info.provider);
1636 }
1637 }
1638 return null;
1639 }
1640 return authority;
1641 } else {
1642 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001643 return null;
1644 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001645 }
Costin Manolache360e4542009-09-04 13:36:04 -07001646
Matthew Williamsfa774182013-06-18 15:44:11 -07001647 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001648 * @param info info identifying target.
1649 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001650 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001651 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001652 * exists.
1653 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001654 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1655 AuthorityInfo authority = null;
1656 if (info.target_service) {
1657 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1658 if (aInfo == null) {
1659 aInfo = new SparseArray<AuthorityInfo>();
1660 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001661 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001662 authority = aInfo.get(info.userId);
1663 if (authority == null) {
1664 authority = createAuthorityLocked(info, ident, doWrite);
1665 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001666 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001667 } else if (info.target_provider) {
1668 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1669 AccountInfo account = mAccounts.get(au);
1670 if (account == null) {
1671 account = new AccountInfo(au);
1672 mAccounts.put(au, account);
1673 }
1674 authority = account.authorities.get(info.provider);
1675 if (authority == null) {
1676 authority = createAuthorityLocked(info, ident, doWrite);
1677 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001678 }
1679 }
1680 return authority;
1681 }
1682
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001683 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1684 AuthorityInfo authority;
1685 if (ident < 0) {
1686 ident = mNextAuthorityId;
1687 mNextAuthorityId++;
1688 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001689 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1691 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001692 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001693 authority = new AuthorityInfo(info, ident);
1694 mAuthorities.put(ident, authority);
1695 if (doWrite) {
1696 writeAccountInfoLocked();
1697 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001698 return authority;
1699 }
Costin Manolache360e4542009-09-04 13:36:04 -07001700
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001701 public void removeAuthority(EndPoint info) {
1702 synchronized (mAuthorities) {
1703 if (info.target_provider) {
1704 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1705 } else {
1706 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1707 if (aInfos != null) {
1708 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1709 if (authorityInfo != null) {
1710 mAuthorities.remove(authorityInfo.ident);
1711 aInfos.delete(info.userId);
1712 writeAccountInfoLocked();
1713 }
1714 }
1715
1716 }
1717 }
1718 }
1719
1720 /**
1721 * Remove an authority associated with a provider. Needs to be a standalone function for
1722 * backward compatibility.
1723 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001724 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1725 boolean doWrite) {
1726 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001727 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001728 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1729 if (authorityInfo != null) {
1730 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001731 if (doWrite) {
1732 writeAccountInfoLocked();
1733 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001734 }
1735 }
1736 }
1737
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001738 /**
1739 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001740 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001741 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001742 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001743 boolean found = false;
1744 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001745 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001746 authorityInfo = mAuthorities.get(authorityId);
1747 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001748 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1749 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001750 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001751 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001752 break;
1753 }
1754 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001755 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001756 if (!found) {
1757 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001758 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001759 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001760 }
1761
Dianne Hackborn231cc602009-04-27 17:10:36 -07001762 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1763 SyncStatusInfo status = mSyncStatus.get(authorityId);
1764 if (status == null) {
1765 status = new SyncStatusInfo(authorityId);
1766 mSyncStatus.put(authorityId, status);
1767 }
1768 return status;
1769 }
Costin Manolache360e4542009-09-04 13:36:04 -07001770
Dianne Hackborn55280a92009-05-07 15:53:46 -07001771 public void writeAllState() {
1772 synchronized (mAuthorities) {
1773 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001774
Dianne Hackborn55280a92009-05-07 15:53:46 -07001775 if (mNumPendingFinished > 0) {
1776 // Only write these if they are out of date.
1777 writePendingOperationsLocked();
1778 }
Costin Manolache360e4542009-09-04 13:36:04 -07001779
Dianne Hackborn55280a92009-05-07 15:53:46 -07001780 // Just always write these... they are likely out of date.
1781 writeStatusLocked();
1782 writeStatisticsLocked();
1783 }
1784 }
Costin Manolache360e4542009-09-04 13:36:04 -07001785
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001787 * public for testing
1788 */
1789 public void clearAndReadState() {
1790 synchronized (mAuthorities) {
1791 mAuthorities.clear();
1792 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001793 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001794 mPendingOperations.clear();
1795 mSyncStatus.clear();
1796 mSyncHistory.clear();
1797
1798 readAccountInfoLocked();
1799 readStatusLocked();
1800 readPendingOperationsLocked();
1801 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001802 readAndDeleteLegacyAccountInfoLocked();
1803 writeAccountInfoLocked();
1804 writeStatusLocked();
1805 writePendingOperationsLocked();
1806 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001807 }
1808 }
1809
1810 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 * Read all account information back in to the initial engine state.
1812 */
1813 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001814 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001817 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001818 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001819 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001820 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 XmlPullParser parser = Xml.newPullParser();
1822 parser.setInput(fis, null);
1823 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001824 while (eventType != XmlPullParser.START_TAG &&
1825 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 eventType = parser.next();
1827 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001828 if (eventType == XmlPullParser.END_DOCUMENT) {
1829 Log.i(TAG, "No initial accounts");
1830 return;
1831 }
1832
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 String tagName = parser.getName();
1834 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001835 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001836 String versionString = parser.getAttributeValue(null, "version");
1837 int version;
1838 try {
1839 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1840 } catch (NumberFormatException e) {
1841 version = 0;
1842 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001843 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001844 try {
1845 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1846 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1847 } catch (NumberFormatException e) {
1848 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001849 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001850 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1851 try {
1852 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1853 } catch (NumberFormatException e) {
1854 mSyncRandomOffset = 0;
1855 }
1856 if (mSyncRandomOffset == 0) {
1857 Random random = new Random(System.currentTimeMillis());
1858 mSyncRandomOffset = random.nextInt(86400);
1859 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001860 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001861 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001862 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001863 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001864 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001865 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001866 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001867 if (parser.getDepth() == 2) {
1868 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001869 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001870 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001871 if (authority.ident > highestAuthorityId) {
1872 highestAuthorityId = authority.ident;
1873 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001874 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1875 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001876 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001877 } else if (parser.getDepth() == 3) {
1878 if ("periodicSync".equals(tagName) && authority != null) {
1879 periodicSync = parsePeriodicSync(parser, authority);
1880 }
1881 } else if (parser.getDepth() == 4 && periodicSync != null) {
1882 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001883 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001884 }
1885 }
1886 }
1887 eventType = parser.next();
1888 } while (eventType != XmlPullParser.END_DOCUMENT);
1889 }
1890 } catch (XmlPullParserException e) {
1891 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001892 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001893 } catch (java.io.IOException e) {
1894 if (fis == null) Log.i(TAG, "No initial accounts");
1895 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001896 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001897 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001898 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 if (fis != null) {
1900 try {
1901 fis.close();
1902 } catch (java.io.IOException e1) {
1903 }
1904 }
1905 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001906
Fred Quintana77c560f2010-03-29 22:20:26 -07001907 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 }
Costin Manolache360e4542009-09-04 13:36:04 -07001909
Fred Quintanafb084402010-03-23 17:57:03 -07001910 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001911 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1912 * pending.xml was used starting in KLP.
1913 * @param syncDir directory where the sync files are located.
1914 */
1915 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1916 File file = new File(syncDir, "pending.bin");
1917 if (!file.exists()) {
1918 return;
1919 } else {
1920 file.delete();
1921 }
1922 }
1923
1924 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001925 * some authority names have changed. copy over their settings and delete the old ones
1926 * @return true if a change was made
1927 */
1928 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1929 boolean writeNeeded = false;
1930
1931 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1932 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001933 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001934 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001935 // skip this authority if it doesn't target a provider
1936 if (authority.target.target_service) {
1937 continue;
1938 }
Fred Quintanafb084402010-03-23 17:57:03 -07001939 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001940 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001941 if (newAuthorityName == null) {
1942 continue;
1943 }
1944
1945 // remember this authority so we can remove it later. we can't remove it
1946 // now without messing up this loop iteration
1947 authoritiesToRemove.add(authority);
1948
1949 // this authority isn't enabled, no need to copy it to the new authority name since
1950 // the default is "disabled"
1951 if (!authority.enabled) {
1952 continue;
1953 }
1954
1955 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001956 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001957 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001958 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001959 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001960 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001961 continue;
1962 }
1963
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001964 AuthorityInfo newAuthority =
1965 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001966 newAuthority.enabled = true;
1967 writeNeeded = true;
1968 }
1969
1970 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001971 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001972 authorityInfo.target.account,
1973 authorityInfo.target.userId,
1974 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001975 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001976 writeNeeded = true;
1977 }
1978
1979 return writeNeeded;
1980 }
1981
Amith Yamasani04e0d262012-02-14 11:50:53 -08001982 private void parseListenForTickles(XmlPullParser parser) {
1983 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1984 int userId = 0;
1985 try {
1986 userId = Integer.parseInt(user);
1987 } catch (NumberFormatException e) {
1988 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1989 } catch (NullPointerException e) {
1990 Log.e(TAG, "the user in listen-for-tickles is null", e);
1991 }
1992 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1993 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1994 mMasterSyncAutomatically.put(userId, listen);
1995 }
1996
Fred Quintanac2e46912010-03-15 16:10:44 -07001997 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001998 AuthorityInfo authority = null;
1999 int id = -1;
2000 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002001 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002002 } catch (NumberFormatException e) {
2003 Log.e(TAG, "error parsing the id of the authority", e);
2004 } catch (NullPointerException e) {
2005 Log.e(TAG, "the id of the authority is null", e);
2006 }
2007 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07002008 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002009 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07002010 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002011 String accountName = parser.getAttributeValue(null, "account");
2012 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002013 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07002014 String packageName = parser.getAttributeValue(null, "package");
2015 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002016 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07002017 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002018 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07002019 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002020 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002021 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002022 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002023 Log.v(TAG_FILE, "Adding authority:"
2024 + " account=" + accountName
2025 + " accountType=" + accountType
2026 + " auth=" + authorityName
2027 + " package=" + packageName
2028 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07002029 + " user=" + userId
2030 + " enabled=" + enabled
2031 + " syncable=" + syncable);
2032 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002033 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002034 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002035 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002036 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002037 EndPoint info;
2038 if (accountName != null && authorityName != null) {
2039 info = new EndPoint(
2040 new Account(accountName, accountType),
2041 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002042 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002043 info = new EndPoint(
2044 new ComponentName(packageName, className),
2045 userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002046 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002047 authority = getOrCreateAuthorityLocked(info, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07002048 // If the version is 0 then we are upgrading from a file format that did not
2049 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002050 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002051 // Otherwise clear out this default list since we will populate it later with
2052 // the periodic sync descriptions that are read from the configuration file.
2053 if (version > 0) {
2054 authority.periodicSyncs.clear();
2055 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002056 }
2057 if (authority != null) {
2058 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
2059 if ("unknown".equals(syncable)) {
2060 authority.syncable = -1;
2061 } else {
2062 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07002063 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002064 }
2065 } else {
2066 Log.w(TAG, "Failure adding authority: account="
2067 + accountName + " auth=" + authorityName
2068 + " enabled=" + enabled
2069 + " syncable=" + syncable);
2070 }
2071 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002072 return authority;
2073 }
2074
Matthew Williamsfa774182013-06-18 15:44:11 -07002075 /**
2076 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2077 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002078 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002079 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002080 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002081 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002082 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002083 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002084 try {
2085 period = Long.parseLong(periodValue);
2086 } catch (NumberFormatException e) {
2087 Log.e(TAG, "error parsing the period of a periodic sync", e);
2088 return null;
2089 } catch (NullPointerException e) {
2090 Log.e(TAG, "the period of a periodic sync is null", e);
2091 return null;
2092 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002093 try {
2094 flextime = Long.parseLong(flexValue);
2095 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002096 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002097 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2098 + ", using default: "
2099 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002100 } catch (NullPointerException expected) {
2101 flextime = calculateDefaultFlexTime(period);
2102 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2103 + period + " flex: " + flextime);
2104 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002105 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002106 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002107 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002108 new PeriodicSync(authorityInfo.target.account,
2109 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002110 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002111 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002112 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002113 Log.e(TAG, "Unknown target.");
2114 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002115 }
2116 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002117 return periodicSync;
2118 }
2119
Matthew Williamsfa774182013-06-18 15:44:11 -07002120 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002121 String name = parser.getAttributeValue(null, "name");
2122 String type = parser.getAttributeValue(null, "type");
2123 String value1 = parser.getAttributeValue(null, "value1");
2124 String value2 = parser.getAttributeValue(null, "value2");
2125
2126 try {
2127 if ("long".equals(type)) {
2128 extras.putLong(name, Long.parseLong(value1));
2129 } else if ("integer".equals(type)) {
2130 extras.putInt(name, Integer.parseInt(value1));
2131 } else if ("double".equals(type)) {
2132 extras.putDouble(name, Double.parseDouble(value1));
2133 } else if ("float".equals(type)) {
2134 extras.putFloat(name, Float.parseFloat(value1));
2135 } else if ("boolean".equals(type)) {
2136 extras.putBoolean(name, Boolean.parseBoolean(value1));
2137 } else if ("string".equals(type)) {
2138 extras.putString(name, value1);
2139 } else if ("account".equals(type)) {
2140 extras.putParcelable(name, new Account(value1, value2));
2141 }
2142 } catch (NumberFormatException e) {
2143 Log.e(TAG, "error parsing bundle value", e);
2144 } catch (NullPointerException e) {
2145 Log.e(TAG, "error parsing bundle value", e);
2146 }
2147 }
2148
Dianne Hackborn231cc602009-04-27 17:10:36 -07002149 /**
2150 * Write all account information to the account file.
2151 */
2152 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002153 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002154 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002155 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002156 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002157
Dianne Hackborn231cc602009-04-27 17:10:36 -07002158 try {
2159 fos = mAccountInfoFile.startWrite();
2160 XmlSerializer out = new FastXmlSerializer();
2161 out.setOutput(fos, "utf-8");
2162 out.startDocument(null, true);
2163 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002164
Dianne Hackborn231cc602009-04-27 17:10:36 -07002165 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002166 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002167 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002168 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002169
2170 // Write the Sync Automatically flags for each user
2171 final int M = mMasterSyncAutomatically.size();
2172 for (int m = 0; m < M; m++) {
2173 int userId = mMasterSyncAutomatically.keyAt(m);
2174 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2175 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2176 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2177 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2178 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002179 }
Costin Manolache360e4542009-09-04 13:36:04 -07002180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002182 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002183 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002184 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002185 out.startTag(null, "authority");
2186 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002187 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002188 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002189 if (info.service == null) {
2190 out.attribute(null, "account", info.account.name);
2191 out.attribute(null, "type", info.account.type);
2192 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002193 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002194 out.attribute(null, "package", info.service.getPackageName());
2195 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002196 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002197 if (authority.syncable < 0) {
2198 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002199 } else {
2200 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002201 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002202 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002203 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002204 out.attribute(null, "period", Long.toString(periodicSync.period));
2205 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2206 final Bundle extras = periodicSync.extras;
2207 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002208 out.endTag(null, "periodicSync");
2209 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002210 out.endTag(null, "authority");
2211 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002212 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002213 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002214 mAccountInfoFile.finishWrite(fos);
2215 } catch (java.io.IOException e1) {
2216 Log.w(TAG, "Error writing accounts", e1);
2217 if (fos != null) {
2218 mAccountInfoFile.failWrite(fos);
2219 }
2220 }
2221 }
Costin Manolache360e4542009-09-04 13:36:04 -07002222
Dianne Hackborn231cc602009-04-27 17:10:36 -07002223 static int getIntColumn(Cursor c, String name) {
2224 return c.getInt(c.getColumnIndex(name));
2225 }
Costin Manolache360e4542009-09-04 13:36:04 -07002226
Dianne Hackborn231cc602009-04-27 17:10:36 -07002227 static long getLongColumn(Cursor c, String name) {
2228 return c.getLong(c.getColumnIndex(name));
2229 }
Costin Manolache360e4542009-09-04 13:36:04 -07002230
Dianne Hackborn231cc602009-04-27 17:10:36 -07002231 /**
2232 * Load sync engine state from the old syncmanager database, and then
2233 * erase it. Note that we don't deal with pending operations, active
2234 * sync, or history.
2235 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002236 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002237 // Look for old database to initialize from.
2238 File file = mContext.getDatabasePath("syncmanager.db");
2239 if (!file.exists()) {
2240 return;
2241 }
2242 String path = file.getPath();
2243 SQLiteDatabase db = null;
2244 try {
2245 db = SQLiteDatabase.openDatabase(path, null,
2246 SQLiteDatabase.OPEN_READONLY);
2247 } catch (SQLiteException e) {
2248 }
Costin Manolache360e4542009-09-04 13:36:04 -07002249
Dianne Hackborn231cc602009-04-27 17:10:36 -07002250 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002251 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002252
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002254 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002255 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002256 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002257 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2258 qb.setTables("stats, status");
2259 HashMap<String,String> map = new HashMap<String,String>();
2260 map.put("_id", "status._id as _id");
2261 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002262 if (hasType) {
2263 map.put("account_type", "stats.account_type as account_type");
2264 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002265 map.put("authority", "stats.authority as authority");
2266 map.put("totalElapsedTime", "totalElapsedTime");
2267 map.put("numSyncs", "numSyncs");
2268 map.put("numSourceLocal", "numSourceLocal");
2269 map.put("numSourcePoll", "numSourcePoll");
2270 map.put("numSourceServer", "numSourceServer");
2271 map.put("numSourceUser", "numSourceUser");
2272 map.put("lastSuccessSource", "lastSuccessSource");
2273 map.put("lastSuccessTime", "lastSuccessTime");
2274 map.put("lastFailureSource", "lastFailureSource");
2275 map.put("lastFailureTime", "lastFailureTime");
2276 map.put("lastFailureMesg", "lastFailureMesg");
2277 map.put("pending", "pending");
2278 qb.setProjectionMap(map);
2279 qb.appendWhere("stats._id = status.stats_id");
2280 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002282 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002283 String accountType = hasType
2284 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002285 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002286 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002288 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002289 AuthorityInfo authority =
2290 this.getOrCreateAuthorityLocked(
2291 new EndPoint(new Account(accountName, accountType),
2292 authorityName,
2293 0 /* legacy is single-user */)
2294 , -1,
2295 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002296 if (authority != null) {
2297 int i = mSyncStatus.size();
2298 boolean found = false;
2299 SyncStatusInfo st = null;
2300 while (i > 0) {
2301 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002302 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002303 if (st.authorityId == authority.ident) {
2304 found = true;
2305 break;
2306 }
2307 }
2308 if (!found) {
2309 st = new SyncStatusInfo(authority.ident);
2310 mSyncStatus.put(authority.ident, st);
2311 }
2312 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2313 st.numSyncs = getIntColumn(c, "numSyncs");
2314 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2315 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2316 st.numSourceServer = getIntColumn(c, "numSourceServer");
2317 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002318 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002319 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2320 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2321 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2322 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2323 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2324 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
Costin Manolache360e4542009-09-04 13:36:04 -07002327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002329
Dianne Hackborn231cc602009-04-27 17:10:36 -07002330 // Retrieve the settings.
2331 qb = new SQLiteQueryBuilder();
2332 qb.setTables("settings");
2333 c = qb.query(db, null, null, null, null, null, null);
2334 while (c.moveToNext()) {
2335 String name = c.getString(c.getColumnIndex("name"));
2336 String value = c.getString(c.getColumnIndex("value"));
2337 if (name == null) continue;
2338 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002339 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002340 } else if (name.startsWith("sync_provider_")) {
2341 String provider = name.substring("sync_provider_".length(),
2342 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002343 int i = mAuthorities.size();
2344 while (i > 0) {
2345 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002346 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002347 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002348 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002349 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002350 }
2351 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 }
Costin Manolache360e4542009-09-04 13:36:04 -07002354
Dianne Hackborn231cc602009-04-27 17:10:36 -07002355 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002356
Dianne Hackborn231cc602009-04-27 17:10:36 -07002357 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002358
Dianne Hackborn231cc602009-04-27 17:10:36 -07002359 (new File(path)).delete();
2360 }
2361 }
Costin Manolache360e4542009-09-04 13:36:04 -07002362
Dianne Hackborn231cc602009-04-27 17:10:36 -07002363 public static final int STATUS_FILE_END = 0;
2364 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002365
Dianne Hackborn231cc602009-04-27 17:10:36 -07002366 /**
2367 * Read all sync status back in to the initial engine state.
2368 */
2369 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002370 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002371 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002372 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002373 try {
2374 byte[] data = mStatusFile.readFully();
2375 Parcel in = Parcel.obtain();
2376 in.unmarshall(data, 0, data.length);
2377 in.setDataPosition(0);
2378 int token;
2379 while ((token=in.readInt()) != STATUS_FILE_END) {
2380 if (token == STATUS_FILE_ITEM) {
2381 SyncStatusInfo status = new SyncStatusInfo(in);
2382 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2383 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002384 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002385 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002386 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002387 mSyncStatus.put(status.authorityId, status);
2388 }
2389 } else {
2390 // Ooops.
2391 Log.w(TAG, "Unknown status token: " + token);
2392 break;
2393 }
2394 }
2395 } catch (java.io.IOException e) {
2396 Log.i(TAG, "No initial status");
2397 }
2398 }
Costin Manolache360e4542009-09-04 13:36:04 -07002399
Dianne Hackborn231cc602009-04-27 17:10:36 -07002400 /**
2401 * Write all sync status to the sync status file.
2402 */
2403 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002404 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002405 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002406 }
Costin Manolache360e4542009-09-04 13:36:04 -07002407
Dianne Hackborn231cc602009-04-27 17:10:36 -07002408 // The file is being written, so we don't need to have a scheduled
2409 // write until the next change.
2410 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002411
Dianne Hackborn231cc602009-04-27 17:10:36 -07002412 FileOutputStream fos = null;
2413 try {
2414 fos = mStatusFile.startWrite();
2415 Parcel out = Parcel.obtain();
2416 final int N = mSyncStatus.size();
2417 for (int i=0; i<N; i++) {
2418 SyncStatusInfo status = mSyncStatus.valueAt(i);
2419 out.writeInt(STATUS_FILE_ITEM);
2420 status.writeToParcel(out, 0);
2421 }
2422 out.writeInt(STATUS_FILE_END);
2423 fos.write(out.marshall());
2424 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002425
Dianne Hackborn231cc602009-04-27 17:10:36 -07002426 mStatusFile.finishWrite(fos);
2427 } catch (java.io.IOException e1) {
2428 Log.w(TAG, "Error writing status", e1);
2429 if (fos != null) {
2430 mStatusFile.failWrite(fos);
2431 }
2432 }
2433 }
Costin Manolache360e4542009-09-04 13:36:04 -07002434
Matthew Williamsba352712013-08-13 15:53:31 -07002435 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002436
Matthew Williamsba352712013-08-13 15:53:31 -07002437 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002438 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002439 FileInputStream fis = null;
2440 if (!mPendingFile.getBaseFile().exists()) {
2441 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2442 Log.v(TAG_FILE, "No pending operation file.");
Matthew Williamsfa774182013-06-18 15:44:11 -07002443 }
Ji-Hwan Lee886113d2014-04-17 14:16:38 +09002444 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002445 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002446 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002447 fis = mPendingFile.openRead();
Matthew Williams06485a72013-07-26 12:56:39 -07002448 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2449 Log.v(TAG_FILE, "Reading " + mPendingFile.getBaseFile());
2450 }
Matthew Williamsba352712013-08-13 15:53:31 -07002451 XmlPullParser parser;
2452 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002453 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002454
Matthew Williamsfa774182013-06-18 15:44:11 -07002455 int eventType = parser.getEventType();
2456 while (eventType != XmlPullParser.START_TAG &&
2457 eventType != XmlPullParser.END_DOCUMENT) {
2458 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002459 }
Matthew Williamsba352712013-08-13 15:53:31 -07002460 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002461
Matthew Williamsba352712013-08-13 15:53:31 -07002462 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002463 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002464 if (eventType == XmlPullParser.START_TAG) {
2465 try {
Matthew Williams06485a72013-07-26 12:56:39 -07002466 String tagName = parser.getName();
Matthew Williams8ef22042013-07-26 12:56:39 -07002467 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2468 // Verify version.
2469 String versionString =
2470 parser.getAttributeValue(null, XML_ATTR_VERSION);
2471 if (versionString == null ||
2472 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2473 Log.w(TAG, "Unknown pending operation version " + versionString);
2474 throw new java.io.IOException("Unknown version.");
2475 }
2476 int authorityId = Integer.valueOf(parser.getAttributeValue(
2477 null, XML_ATTR_AUTHORITYID));
2478 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2479 null, XML_ATTR_EXPEDITED));
2480 int syncSource = Integer.valueOf(parser.getAttributeValue(
2481 null, XML_ATTR_SOURCE));
2482 int reason = Integer.valueOf(parser.getAttributeValue(
2483 null, XML_ATTR_REASON));
2484 AuthorityInfo authority = mAuthorities.get(authorityId);
2485 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2486 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2487 + reason);
2488 }
2489 if (authority != null) {
2490 pop = new PendingOperation(
2491 authority, reason, syncSource, new Bundle(), expedited);
2492 pop.flatExtras = null; // No longer used.
2493 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002494 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002495 Log.v(TAG_FILE, "Adding pending op: "
2496 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002497 + " src=" + pop.syncSource
2498 + " reason=" + pop.reason
2499 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002500 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002501 } else {
2502 // Skip non-existent authority.
2503 pop = null;
2504 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2505 Log.v(TAG_FILE, "No authority found for " + authorityId
2506 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002507 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002508 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002509 } else if (parser.getDepth() == 2 &&
2510 pop != null &&
2511 "extra".equals(tagName)) {
2512 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002513 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002514 } catch (NumberFormatException e) {
2515 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002516 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002517 }
Matthew Williamsba352712013-08-13 15:53:31 -07002518 eventType = parser.next();
2519 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002520 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002521 Log.w(TAG_FILE, "Error reading pending data.", e);
2522 } catch (XmlPullParserException e) {
2523 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2524 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2525 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002526 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002527 if (fis != null) {
2528 try {
2529 fis.close();
2530 } catch (java.io.IOException e1) {}
2531 }
2532 }
2533 }
Matthew Williamsba352712013-08-13 15:53:31 -07002534
Dianne Hackborn231cc602009-04-27 17:10:36 -07002535 static private byte[] flattenBundle(Bundle bundle) {
2536 byte[] flatData = null;
2537 Parcel parcel = Parcel.obtain();
2538 try {
2539 bundle.writeToParcel(parcel, 0);
2540 flatData = parcel.marshall();
2541 } finally {
2542 parcel.recycle();
2543 }
2544 return flatData;
2545 }
Costin Manolache360e4542009-09-04 13:36:04 -07002546
Dianne Hackborn231cc602009-04-27 17:10:36 -07002547 static private Bundle unflattenBundle(byte[] flatData) {
2548 Bundle bundle;
2549 Parcel parcel = Parcel.obtain();
2550 try {
2551 parcel.unmarshall(flatData, 0, flatData.length);
2552 parcel.setDataPosition(0);
2553 bundle = parcel.readBundle();
2554 } catch (RuntimeException e) {
2555 // A RuntimeException is thrown if we were unable to parse the parcel.
2556 // Create an empty parcel in this case.
2557 bundle = new Bundle();
2558 } finally {
2559 parcel.recycle();
2560 }
2561 return bundle;
2562 }
Costin Manolache360e4542009-09-04 13:36:04 -07002563
Matthew Williams8ef22042013-07-26 12:56:39 -07002564 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002565 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2566 private static final String XML_ATTR_SOURCE = "source";
2567 private static final String XML_ATTR_EXPEDITED = "expedited";
2568 private static final String XML_ATTR_REASON = "reason";
2569
2570 /**
2571 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002572 */
2573 private void writePendingOperationsLocked() {
2574 final int N = mPendingOperations.size();
2575 FileOutputStream fos = null;
2576 try {
2577 if (N == 0) {
2578 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2579 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2580 }
2581 mPendingFile.truncate();
2582 return;
2583 }
2584 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2585 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2586 }
2587 fos = mPendingFile.startWrite();
2588 XmlSerializer out = new FastXmlSerializer();
2589 out.setOutput(fos, "utf-8");
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002590
2591 for (int i = 0; i < N; i++) {
2592 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002593 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002594 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002595 out.endDocument();
2596 mPendingFile.finishWrite(fos);
2597 } catch (java.io.IOException e1) {
2598 Log.w(TAG, "Error writing pending operations", e1);
2599 if (fos != null) {
2600 mPendingFile.failWrite(fos);
2601 }
2602 }
2603 }
2604
Matthew Williams8ef22042013-07-26 12:56:39 -07002605 /** Write all currently pending ops to the pending ops file. */
2606 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2607 throws IOException {
2608 // Pending operation.
2609 out.startTag(null, "op");
2610
2611 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2612 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2613 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2614 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2615 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2616 extrasToXml(out, pop.extras);
2617
2618 out.endTag(null, "op");
2619 }
2620
2621 /**
2622 * Append the given operation to the pending ops file; if unable to,
2623 * write all pending ops.
2624 */
2625 private void appendPendingOperationLocked(PendingOperation op) {
2626 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2627 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2628 }
2629 FileOutputStream fos = null;
2630 try {
2631 fos = mPendingFile.openAppend();
2632 } catch (java.io.IOException e) {
2633 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2634 Log.v(TAG, "Failed append; writing full file");
2635 }
2636 writePendingOperationsLocked();
2637 return;
2638 }
2639
2640 try {
2641 XmlSerializer out = new FastXmlSerializer();
2642 out.setOutput(fos, "utf-8");
2643 writePendingOperationLocked(op, out);
2644 out.endDocument();
2645 mPendingFile.finishWrite(fos);
2646 } catch (java.io.IOException e1) {
2647 Log.w(TAG, "Error writing appending operation", e1);
2648 mPendingFile.failWrite(fos);
2649 } finally {
2650 try {
2651 fos.close();
2652 } catch (IOException e) {}
2653 }
2654 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002655
Matthew Williamsfa774182013-06-18 15:44:11 -07002656 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2657 for (String key : extras.keySet()) {
2658 out.startTag(null, "extra");
2659 out.attribute(null, "name", key);
2660 final Object value = extras.get(key);
2661 if (value instanceof Long) {
2662 out.attribute(null, "type", "long");
2663 out.attribute(null, "value1", value.toString());
2664 } else if (value instanceof Integer) {
2665 out.attribute(null, "type", "integer");
2666 out.attribute(null, "value1", value.toString());
2667 } else if (value instanceof Boolean) {
2668 out.attribute(null, "type", "boolean");
2669 out.attribute(null, "value1", value.toString());
2670 } else if (value instanceof Float) {
2671 out.attribute(null, "type", "float");
2672 out.attribute(null, "value1", value.toString());
2673 } else if (value instanceof Double) {
2674 out.attribute(null, "type", "double");
2675 out.attribute(null, "value1", value.toString());
2676 } else if (value instanceof String) {
2677 out.attribute(null, "type", "string");
2678 out.attribute(null, "value1", value.toString());
2679 } else if (value instanceof Account) {
2680 out.attribute(null, "type", "account");
2681 out.attribute(null, "value1", ((Account)value).name);
2682 out.attribute(null, "value2", ((Account)value).type);
2683 }
2684 out.endTag(null, "extra");
2685 }
2686 }
2687
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002688 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2689 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2690 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002691 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002692 } else {
2693 SyncRequest.Builder req =
2694 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002695 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002696 .setExtras(extras);
2697 if (authorityInfo.target.target_provider) {
2698 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002699 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002700 if (Log.isLoggable(TAG, Log.DEBUG)) {
2701 Log.d(TAG, "Unknown target, skipping sync request.");
2702 }
2703 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002704 }
2705 ContentResolver.requestSync(req.build());
2706 }
2707 }
2708
Alon Albert57286f92012-10-09 14:21:38 -07002709 private void requestSync(Account account, int userId, int reason, String authority,
2710 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002711 // If this is happening in the system process, then call the syncrequest listener
2712 // to make a request back to the SyncManager directly.
2713 // If this is probably a test instance, then call back through the ContentResolver
2714 // which will know which userId to apply based on the Binder id.
2715 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2716 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002717 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002718 new EndPoint(account, authority, userId),
2719 reason,
2720 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002721 } else {
2722 ContentResolver.requestSync(account, authority, extras);
2723 }
2724 }
2725
Dianne Hackborn231cc602009-04-27 17:10:36 -07002726 public static final int STATISTICS_FILE_END = 0;
2727 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2728 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002729
Dianne Hackborn231cc602009-04-27 17:10:36 -07002730 /**
2731 * Read all sync statistics back in to the initial engine state.
2732 */
2733 private void readStatisticsLocked() {
2734 try {
2735 byte[] data = mStatisticsFile.readFully();
2736 Parcel in = Parcel.obtain();
2737 in.unmarshall(data, 0, data.length);
2738 in.setDataPosition(0);
2739 int token;
2740 int index = 0;
2741 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2742 if (token == STATISTICS_FILE_ITEM
2743 || token == STATISTICS_FILE_ITEM_OLD) {
2744 int day = in.readInt();
2745 if (token == STATISTICS_FILE_ITEM_OLD) {
2746 day = day - 2009 + 14245; // Magic!
2747 }
2748 DayStats ds = new DayStats(day);
2749 ds.successCount = in.readInt();
2750 ds.successTime = in.readLong();
2751 ds.failureCount = in.readInt();
2752 ds.failureTime = in.readLong();
2753 if (index < mDayStats.length) {
2754 mDayStats[index] = ds;
2755 index++;
2756 }
2757 } else {
2758 // Ooops.
2759 Log.w(TAG, "Unknown stats token: " + token);
2760 break;
2761 }
2762 }
2763 } catch (java.io.IOException e) {
2764 Log.i(TAG, "No initial statistics");
2765 }
2766 }
Costin Manolache360e4542009-09-04 13:36:04 -07002767
Dianne Hackborn231cc602009-04-27 17:10:36 -07002768 /**
2769 * Write all sync statistics to the sync status file.
2770 */
2771 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002772 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2773 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2774 }
Costin Manolache360e4542009-09-04 13:36:04 -07002775
Dianne Hackborn231cc602009-04-27 17:10:36 -07002776 // The file is being written, so we don't need to have a scheduled
2777 // write until the next change.
2778 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002779
Dianne Hackborn231cc602009-04-27 17:10:36 -07002780 FileOutputStream fos = null;
2781 try {
2782 fos = mStatisticsFile.startWrite();
2783 Parcel out = Parcel.obtain();
2784 final int N = mDayStats.length;
2785 for (int i=0; i<N; i++) {
2786 DayStats ds = mDayStats[i];
2787 if (ds == null) {
2788 break;
2789 }
2790 out.writeInt(STATISTICS_FILE_ITEM);
2791 out.writeInt(ds.day);
2792 out.writeInt(ds.successCount);
2793 out.writeLong(ds.successTime);
2794 out.writeInt(ds.failureCount);
2795 out.writeLong(ds.failureTime);
2796 }
2797 out.writeInt(STATISTICS_FILE_END);
2798 fos.write(out.marshall());
2799 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002800
Dianne Hackborn231cc602009-04-27 17:10:36 -07002801 mStatisticsFile.finishWrite(fos);
2802 } catch (java.io.IOException e1) {
2803 Log.w(TAG, "Error writing stats", e1);
2804 if (fos != null) {
2805 mStatisticsFile.failWrite(fos);
2806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 }
2808 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002809
2810 /**
2811 * Dump state of PendingOperations.
2812 */
2813 public void dumpPendingOperations(StringBuilder sb) {
2814 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2815 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002816 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002817 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002818 .append(")\n");
2819 }
2820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821}