blob: f154c73535afb5fbda46bf3a7bea2a69b2bcd0a8 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070042import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080044import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070045import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070046import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070047import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080048
49import com.android.internal.annotations.VisibleForTesting;
50import com.android.internal.util.ArrayUtils;
51import com.android.internal.util.FastXmlSerializer;
52
53import org.xmlpull.v1.XmlPullParser;
54import org.xmlpull.v1.XmlPullParserException;
55import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.io.File;
58import java.io.FileInputStream;
59import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070060import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070062import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070064import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080065import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070066import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060067import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
69/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070070 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070072 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 * @hide
74 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070075public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070078 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070079
Amith Yamasani04e0d262012-02-14 11:50:53 -080080 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
81 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070082 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080083 private static final String XML_ATTR_ENABLED = "enabled";
84 private static final String XML_ATTR_USER = "user";
85 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
86
Matthew Williamsfa774182013-06-18 15:44:11 -070087 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080088 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
89
Matthew Williamsfa774182013-06-18 15:44:11 -070090 /** Percentage of period that is flex by default, if no flex is set. */
91 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
92
93 /** Lower bound on sync time from which we assign a default flex time. */
94 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
95
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080096 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098
Dianne Hackborn231cc602009-04-27 17:10:36 -070099 /** Enum value for a sync start event. */
100 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 /** Enum value for a sync stop event. */
103 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Dianne Hackborn231cc602009-04-27 17:10:36 -0700105 // TODO: i18n -- grab these out of resources.
106 /** String names for the sync event types. */
107 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 /** Enum value for a server-initiated sync. */
110 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Dianne Hackborn231cc602009-04-27 17:10:36 -0700112 /** Enum value for a local-initiated sync. */
113 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700114 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700115 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Dianne Hackborn231cc602009-04-27 17:10:36 -0700117 /** Enum value for a user-initiated sync. */
118 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800120 /** Enum value for a periodic sync. */
121 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700122
123 /** Enum value for a sync started for a service. */
124 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800125
Fred Quintana307da1a2010-01-21 14:24:20 -0800126 public static final long NOT_IN_BACKOFF_MODE = -1;
127
Dianne Hackborn231cc602009-04-27 17:10:36 -0700128 // TODO: i18n -- grab these out of resources.
129 /** String names for the sync source types. */
130 public static final String[] SOURCES = { "SERVER",
131 "LOCAL",
132 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800133 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700134 "PERIODIC",
135 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Dianne Hackborn231cc602009-04-27 17:10:36 -0700137 // The MESG column will contain one of these or one of the Error types.
138 public static final String MESG_SUCCESS = "success";
139 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700141 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700142
Dianne Hackborn231cc602009-04-27 17:10:36 -0700143 private static final int MSG_WRITE_STATUS = 1;
144 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700145
Dianne Hackborn231cc602009-04-27 17:10:36 -0700146 private static final int MSG_WRITE_STATISTICS = 2;
147 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700148
149 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700150
Fred Quintanac2e46912010-03-15 16:10:44 -0700151 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700152 private static final int ACCOUNTS_VERSION = 2;
153
154 private static HashMap<String, String> sAuthorityRenames;
155
156 static {
157 sAuthorityRenames = new HashMap<String, String>();
158 sAuthorityRenames.put("contacts", "com.android.contacts");
159 sAuthorityRenames.put("calendar", "com.android.calendar");
160 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700161
Dianne Hackborn231cc602009-04-27 17:10:36 -0700162 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700163 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700164 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700166 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800167 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700168
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700169 final int authorityId;
170 // No longer used.
171 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700172 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700173
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700174 PendingOperation(AuthorityInfo authority, int reason, int source,
175 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700176 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700177 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700178 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800180 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700181 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700182 }
183
184 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700185 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700186 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700187 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700188 this.extras = other.extras;
189 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800190 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700191 }
192
193 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700194 * Considered equal if they target the same sync adapter (A
195 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700196 * is considered an adapter), for the same userId.
197 * @param other PendingOperation to compare.
198 * @return true if the two pending ops are the same.
199 */
200 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700201 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700202 }
203
204 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700205 return "service=" + target.service
206 + " user=" + target.userId
207 + " auth=" + target
208 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700209 + " src=" + syncSource
210 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 }
Costin Manolache360e4542009-09-04 13:36:04 -0700213
Dianne Hackborn231cc602009-04-27 17:10:36 -0700214 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800215 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700216 final HashMap<String, AuthorityInfo> authorities =
217 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700218
Amith Yamasani04e0d262012-02-14 11:50:53 -0800219 AccountInfo(AccountAndUser accountAndUser) {
220 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700221 }
222 }
Costin Manolache360e4542009-09-04 13:36:04 -0700223
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700224 /** Bare bones representation of a sync target. */
225 public static class EndPoint {
226 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
227 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700228 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700229 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800230 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700231 final String provider;
232 final boolean target_service;
233 final boolean target_provider;
234
235 public EndPoint(ComponentName service, int userId) {
236 this.service = service;
237 this.userId = userId;
238 this.account = null;
239 this.provider = null;
240 this.target_service = true;
241 this.target_provider = false;
242 }
243
244 public EndPoint(Account account, String provider, int userId) {
245 this.account = account;
246 this.provider = provider;
247 this.userId = userId;
248 this.service = null;
249 this.target_service = false;
250 this.target_provider = true;
251 }
252
253 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700254 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
255 *
256 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
257 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700258 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700259 public boolean matchesSpec(EndPoint spec) {
260 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700261 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700262 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700263 return false;
264 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700265 if (target_service && spec.target_service) {
266 return service.equals(spec.service);
267 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700268 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700269 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700270 accountsMatch = true;
271 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700272 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700273 }
274 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700275 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700276 providersMatch = true;
277 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700278 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700279 }
280 return accountsMatch && providersMatch;
281 }
282 return false;
283 }
284
285 public String toString() {
286 StringBuilder sb = new StringBuilder();
287 if (target_provider) {
288 sb.append(account == null ? "ALL ACCS" : account.name)
289 .append("/")
290 .append(provider == null ? "ALL PDRS" : provider);
291 } else if (target_service) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700292 sb.append(service.getPackageName() + "/")
293 .append(service.getClassName());
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700294 } else {
295 sb.append("invalid target");
296 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700297 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700298 return sb.toString();
299 }
300 }
301
302 public static class AuthorityInfo {
Matthew Williams8ef22042013-07-26 12:56:39 -0700303 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 final int ident;
305 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700306 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700307 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800308 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700309 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800310 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700311 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800312 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700313
Matthew Williamsfa774182013-06-18 15:44:11 -0700314 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700315
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700316 /**
317 * Copy constructor for making deep-ish copies. Only the bundles stored
318 * in periodic syncs can make unexpected changes.
319 *
320 * @param toCopy AuthorityInfo to be copied.
321 */
322 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700323 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700324 ident = toCopy.ident;
325 enabled = toCopy.enabled;
326 syncable = toCopy.syncable;
327 backoffTime = toCopy.backoffTime;
328 backoffDelay = toCopy.backoffDelay;
329 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700330 periodicSyncs = new ArrayList<PeriodicSync>();
331 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700332 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700333 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700334 }
335 }
336
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700337 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700338 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700339 ident = id;
340 enabled = info.target_provider ?
341 SYNC_ENABLED_DEFAULT : true;
342 // Service is active by default,
343 if (info.target_service) {
344 this.syncable = 1;
345 }
346 periodicSyncs = new ArrayList<PeriodicSync>();
347 defaultInitialisation();
348 }
349
350 private void defaultInitialisation() {
Fred Quintana4a6679b2009-08-17 13:05:39 -0700351 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800352 backoffTime = -1; // if < 0 then we aren't in backoff mode
353 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700354 PeriodicSync defaultSync;
355 // Old version is one sync a day. Empty bundle gets replaced by any addPeriodicSync()
356 // call.
Matthew Williams8ef22042013-07-26 12:56:39 -0700357 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700358 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700359 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700360 new Bundle(),
361 DEFAULT_POLL_FREQUENCY_SECONDS,
362 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
363 periodicSyncs.add(defaultSync);
364 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700365 }
Matthew Williams06485a72013-07-26 12:56:39 -0700366
367 @Override
368 public String toString() {
369 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
370 + backoffTime + ", delay=" + delayUntil;
371 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 }
Costin Manolache360e4542009-09-04 13:36:04 -0700373
Dianne Hackborn231cc602009-04-27 17:10:36 -0700374 public static class SyncHistoryItem {
375 int authorityId;
376 int historyId;
377 long eventTime;
378 long elapsedTime;
379 int source;
380 int event;
381 long upstreamActivity;
382 long downstreamActivity;
383 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700384 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700385 Bundle extras;
386 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700387 }
Costin Manolache360e4542009-09-04 13:36:04 -0700388
Dianne Hackborn231cc602009-04-27 17:10:36 -0700389 public static class DayStats {
390 public final int day;
391 public int successCount;
392 public long successTime;
393 public int failureCount;
394 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700395
Dianne Hackborn231cc602009-04-27 17:10:36 -0700396 public DayStats(int day) {
397 this.day = day;
398 }
399 }
Costin Manolache360e4542009-09-04 13:36:04 -0700400
Amith Yamasani04e0d262012-02-14 11:50:53 -0800401 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700402
403 /** Called when a sync is needed on an account(s) due to some change in state. */
404 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 }
406
Dianne Hackborn231cc602009-04-27 17:10:36 -0700407 // Primary list of all syncable authorities. Also our global lock.
408 private final SparseArray<AuthorityInfo> mAuthorities =
409 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Amith Yamasani04e0d262012-02-14 11:50:53 -0800411 private final HashMap<AccountAndUser, AccountInfo> mAccounts
412 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 private final ArrayList<PendingOperation> mPendingOperations =
415 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Amith Yamasani04e0d262012-02-14 11:50:53 -0800417 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
418 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 private final SparseArray<SyncStatusInfo> mSyncStatus =
421 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700422
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 private final ArrayList<SyncHistoryItem> mSyncHistory =
424 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700425
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
427 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700428
Matthew Williams8ef22042013-07-26 12:56:39 -0700429 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700430 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
431 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700432
Fred Quintana77c560f2010-03-29 22:20:26 -0700433 private int mNextAuthorityId = 0;
434
Dianne Hackborn231cc602009-04-27 17:10:36 -0700435 // We keep 4 weeks of stats.
436 private final DayStats[] mDayStats = new DayStats[7*4];
437 private final Calendar mCal;
438 private int mYear;
439 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700440
Dianne Hackborn231cc602009-04-27 17:10:36 -0700441 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800442
Dianne Hackborn231cc602009-04-27 17:10:36 -0700443 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700444
Ashish Sharma69d95de2012-04-11 17:27:24 -0700445 private int mSyncRandomOffset;
446
Dianne Hackborn231cc602009-04-27 17:10:36 -0700447 /**
448 * This file contains the core engine state: all accounts and the
449 * settings for them. It must never be lost, and should be changed
450 * infrequently, so it is stored as an XML file.
451 */
452 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700453
Dianne Hackborn231cc602009-04-27 17:10:36 -0700454 /**
455 * This file contains the current sync status. We would like to retain
456 * it across boots, but its loss is not the end of the world, so we store
457 * this information as binary data.
458 */
459 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 /**
462 * This file contains sync statistics. This is purely debugging information
463 * so is written infrequently and can be thrown away at any time.
464 */
465 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700466
Dianne Hackborn231cc602009-04-27 17:10:36 -0700467 /**
468 * This file contains the pending sync operations. It is a binary file,
469 * which must be updated every time an operation is added or removed,
470 * so we have special handling of it.
471 */
472 private final AtomicFile mPendingFile;
473 private static final int PENDING_FINISH_TO_WRITE = 4;
474 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700475
Dianne Hackborn231cc602009-04-27 17:10:36 -0700476 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800477 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800478 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800479
480 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700481
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800482 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700485
Dianne Hackborn231cc602009-04-27 17:10:36 -0700486 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700487
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800488 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
489 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
490
Dianne Hackborn231cc602009-04-27 17:10:36 -0700491 File systemDir = new File(dataDir, "system");
492 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800493 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700494
495 maybeDeleteLegacyPendingInfoLocked(syncDir);
496
Dianne Hackborn231cc602009-04-27 17:10:36 -0700497 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
498 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700499 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700500 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700501
Dianne Hackborn231cc602009-04-27 17:10:36 -0700502 readAccountInfoLocked();
503 readStatusLocked();
504 readPendingOperationsLocked();
505 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700506 readAndDeleteLegacyAccountInfoLocked();
507 writeAccountInfoLocked();
508 writeStatusLocked();
509 writePendingOperationsLocked();
510 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 }
512
513 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800514 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 }
516
517 public static void init(Context context) {
518 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800519 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800521 // This call will return the correct directory whether Encrypted File Systems is
522 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600523 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800524 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526
527 public static SyncStorageEngine getSingleton() {
528 if (sSyncStorageEngine == null) {
529 throw new IllegalStateException("not initialized");
530 }
531 return sSyncStorageEngine;
532 }
533
Amith Yamasani04e0d262012-02-14 11:50:53 -0800534 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
535 if (mSyncRequestListener == null) {
536 mSyncRequestListener = listener;
537 }
538 }
539
Dianne Hackborn231cc602009-04-27 17:10:36 -0700540 @Override public void handleMessage(Message msg) {
541 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700542 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700543 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700544 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700545 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700546 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700547 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 }
549 }
550 }
Costin Manolache360e4542009-09-04 13:36:04 -0700551
Ashish Sharma69d95de2012-04-11 17:27:24 -0700552 public int getSyncRandomOffset() {
553 return mSyncRandomOffset;
554 }
555
Dianne Hackborn231cc602009-04-27 17:10:36 -0700556 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
557 synchronized (mAuthorities) {
558 mChangeListeners.register(callback, mask);
559 }
560 }
Costin Manolache360e4542009-09-04 13:36:04 -0700561
Dianne Hackborn231cc602009-04-27 17:10:36 -0700562 public void removeStatusChangeListener(ISyncStatusObserver callback) {
563 synchronized (mAuthorities) {
564 mChangeListeners.unregister(callback);
565 }
566 }
Costin Manolache360e4542009-09-04 13:36:04 -0700567
Matthew Williamsfa774182013-06-18 15:44:11 -0700568 /**
569 * Figure out a reasonable flex time for cases where none is provided (old api calls).
570 * @param syncTimeSeconds requested sync time from now.
571 * @return amount of seconds before syncTimeSeconds that the sync can occur.
572 * I.e.
573 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700574 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700575 */
576 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
577 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
578 // Small enough sync request time that we don't add flex time - developer probably
579 // wants to wait for an operation to occur before syncing so we honour the
580 // request time.
581 return 0L;
582 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
583 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
584 } else {
585 // Large enough sync request time that we cap the flex time.
586 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
587 }
588 }
589
Dianne Hackborn231cc602009-04-27 17:10:36 -0700590 private void reportChange(int which) {
591 ArrayList<ISyncStatusObserver> reports = null;
592 synchronized (mAuthorities) {
593 int i = mChangeListeners.beginBroadcast();
594 while (i > 0) {
595 i--;
596 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
597 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 continue;
599 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700600 if (reports == null) {
601 reports = new ArrayList<ISyncStatusObserver>(i);
602 }
603 reports.add(mChangeListeners.getBroadcastItem(i));
604 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700605 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700606 }
Costin Manolache360e4542009-09-04 13:36:04 -0700607
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700609 Log.v(TAG, "reportChange " + which + " to: " + reports);
610 }
Costin Manolache360e4542009-09-04 13:36:04 -0700611
Dianne Hackborn231cc602009-04-27 17:10:36 -0700612 if (reports != null) {
613 int i = reports.size();
614 while (i > 0) {
615 i--;
616 try {
617 reports.get(i).onStatusChanged(which);
618 } catch (RemoteException e) {
619 // The remote callback list will take care of this for us.
620 }
621 }
622 }
623 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700624
Amith Yamasani04e0d262012-02-14 11:50:53 -0800625 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700626 synchronized (mAuthorities) {
627 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700628 AuthorityInfo authority = getAuthorityLocked(
629 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700630 "getSyncAutomatically");
631 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700632 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700633
Dianne Hackborn231cc602009-04-27 17:10:36 -0700634 int i = mAuthorities.size();
635 while (i > 0) {
636 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700637 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700638 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700639 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700640 return true;
641 }
642 }
643 return false;
644 }
645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646
Amith Yamasani04e0d262012-02-14 11:50:53 -0800647 public void setSyncAutomatically(Account account, int userId, String providerName,
648 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700649 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800650 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
651 + ", user " + userId + " -> " + sync);
652 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700653 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700654 AuthorityInfo authority =
655 getOrCreateAuthorityLocked(
656 new EndPoint(account, providerName, userId),
657 -1 /* ident */,
658 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700659 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700660 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800661 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
662 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700663 return;
664 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700665 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700666 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700668
Fred Quintana77c560f2010-03-29 22:20:26 -0700669 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700670 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
671 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700672 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700673 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800674 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676
Amith Yamasani04e0d262012-02-14 11:50:53 -0800677 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700678 synchronized (mAuthorities) {
679 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700680 AuthorityInfo authority = getAuthorityLocked(
681 new EndPoint(account, providerName, userId),
682 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700683 if (authority == null) {
684 return -1;
685 }
686 return authority.syncable;
687 }
688
689 int i = mAuthorities.size();
690 while (i > 0) {
691 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700692 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700693 if (authorityInfo.target != null
694 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700695 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700696 }
697 }
698 return -1;
699 }
700 }
701
Amith Yamasani04e0d262012-02-14 11:50:53 -0800702 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700703 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700704 }
705
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700706 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700707 synchronized (mAuthorities) {
708 if (cname != null) {
709 AuthorityInfo authority = getAuthorityLocked(
710 new EndPoint(cname, userId),
Matthew Williams8ef22042013-07-26 12:56:39 -0700711 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700712 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700713 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700714 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700715 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700716 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700717 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700718 }
719 }
720
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700721 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700722 setSyncableStateForEndPoint(new EndPoint(cname, userId), active ? 1 : 0);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700723 }
724
725 /**
726 * An enabled sync service and a syncable provider's adapter both get resolved to the same
727 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700728 * @param target target to set value for.
729 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700730 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700731 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700732 AuthorityInfo aInfo;
733 synchronized (mAuthorities) {
734 aInfo = getOrCreateAuthorityLocked(target, -1, false);
735 if (syncable > 1) {
736 syncable = 1;
737 } else if (syncable < -1) {
738 syncable = -1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700739 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
741 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
742 }
743 if (aInfo.syncable == syncable) {
744 if (Log.isLoggable(TAG, Log.VERBOSE)) {
745 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
746 }
747 return;
748 }
749 aInfo.syncable = syncable;
750 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700751 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700752 if (syncable > 0) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700753 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700754 }
755 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
756 }
757
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700758 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800759 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700760 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
761 if (authority != null) {
762 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800763 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700764 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800765 }
766 }
767
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700768 /**
769 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
770 * the account or provider info be null, which signifies all accounts or providers.
771 */
772 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
773 if (Log.isLoggable(TAG, Log.VERBOSE)) {
774 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800775 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
776 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700777 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800778 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700779 if (info.target_provider
780 && (info.account == null || info.provider == null)) {
781 // Do more work for a provider sync if the provided info has specified all
782 // accounts/providers.
783 changed = setBackoffLocked(
784 info.account /* may be null */,
785 info.userId,
786 info.provider /* may be null */,
787 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800788 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700789 AuthorityInfo authorityInfo =
790 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
791 if (authorityInfo.backoffTime == nextSyncTime
792 && authorityInfo.backoffDelay == nextDelay) {
793 changed = false;
794 } else {
795 authorityInfo.backoffTime = nextSyncTime;
796 authorityInfo.backoffDelay = nextDelay;
797 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800798 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800800 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800801 if (changed) {
802 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
803 }
804 }
805
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 /**
807 * Either set backoff for a specific authority, or set backoff for all the
808 * accounts on a specific adapter/all adapters.
809 *
810 * @param account account for which to set backoff. Null to specify all accounts.
811 * @param userId id of the user making this request.
812 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700813 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700814 */
815 private boolean setBackoffLocked(Account account, int userId, String providerName,
816 long nextSyncTime, long nextDelay) {
817 boolean changed = false;
818 for (AccountInfo accountInfo : mAccounts.values()) {
819 if (account != null && !account.equals(accountInfo.accountAndUser.account)
820 && userId != accountInfo.accountAndUser.userId) {
821 continue;
822 }
823 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
824 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700825 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700826 continue;
827 }
828 if (authorityInfo.backoffTime != nextSyncTime
829 || authorityInfo.backoffDelay != nextDelay) {
830 authorityInfo.backoffTime = nextSyncTime;
831 authorityInfo.backoffDelay = nextDelay;
832 changed = true;
833 }
834 }
835 }
836 return changed;
837 }
838
Matthew Williams119aac92014-09-28 20:42:23 -0700839 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800840 boolean changed = false;
841 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700842 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700843 for (AccountInfo accountInfo : mAccounts.values()) {
844 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
845 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
846 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams119aac92014-09-28 20:42:23 -0700848 Log.v(TAG, "clearAllBackoffsLocked:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700849 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700850 + " account:" + accountInfo.accountAndUser.account.name
851 + " user:" + accountInfo.accountAndUser.userId
852 + " backoffTime was: " + authorityInfo.backoffTime
853 + " backoffDelay was: " + authorityInfo.backoffDelay);
854 }
855 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
856 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700857 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800858 }
Alon Albert744e310f2010-12-14 11:37:20 -0800859 }
860 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700861 // Clear backoff for all sync services.
862 for (ComponentName service : mServices.keySet()) {
863 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
864 for (int i = 0; i < aInfos.size(); i++) {
865 AuthorityInfo authorityInfo = aInfos.valueAt(i);
866 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
867 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
868 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
869 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
870 }
871 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700872 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800873 }
874 }
875
876 if (changed) {
877 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
878 }
879 }
880
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700881 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800882 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700883 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800884 if (authority == null) {
885 return 0;
886 }
887 return authority.delayUntil;
888 }
889 }
890
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700891 public void setDelayUntilTime(EndPoint info, long delayUntil) {
892 if (Log.isLoggable(TAG, Log.VERBOSE)) {
893 Log.v(TAG, "setDelayUntil: " + info
894 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800895 }
896 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700897 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
898 if (authority.delayUntil == delayUntil) {
899 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700900 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700901 authority.delayUntil = delayUntil;
902 }
903 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
904 }
905
906 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
908 Log.v(TAG, "addPeriodicSync: " + info
909 + " -> period " + period + ", flex " + flextime + ", extras "
910 + extras.toString());
911 }
912 synchronized (mAuthorities) {
913 if (period <= 0) {
914 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
915 }
916 if (extras == null) {
917 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700918 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700919 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700920 PeriodicSync toUpdate;
921 if (info.target_provider) {
922 toUpdate = new PeriodicSync(info.account,
923 info.provider,
924 extras,
925 period,
926 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700927 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -0700928 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700929 }
930 AuthorityInfo authority =
931 getOrCreateAuthorityLocked(info, -1, false);
932 // add this periodic sync if an equivalent periodic doesn't already exist.
933 boolean alreadyPresent = false;
934 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
935 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
936 if (SyncManager.syncExtrasEquals(syncInfo.extras,
937 extras,
938 true /* includeSyncSettings*/)) {
939 if (period == syncInfo.period &&
940 flextime == syncInfo.flexTime) {
941 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700942 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700943 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700944 authority.periodicSyncs.set(i, toUpdate);
945 alreadyPresent = true;
946 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700947 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700948 }
949 // If we added an entry to the periodicSyncs array also add an entry to
950 // the periodic syncs status to correspond to it.
951 if (!alreadyPresent) {
952 authority.periodicSyncs.add(toUpdate);
953 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
954 // A new periodic sync is initialised as already having been run.
955 status.setPeriodicSyncTime(
956 authority.periodicSyncs.size() - 1,
957 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800958 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700959 } finally {
960 writeAccountInfoLocked();
961 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800962 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800963 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800964 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
965 }
966
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700967 public void removePeriodicSync(EndPoint info, Bundle extras) {
968 synchronized(mAuthorities) {
969 try {
970 AuthorityInfo authority =
971 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -0700972 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700973 SyncStatusInfo status = mSyncStatus.get(authority.ident);
974 boolean changed = false;
975 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
976 int i = 0;
977 while (iterator.hasNext()) {
978 PeriodicSync syncInfo = iterator.next();
979 if (SyncManager.syncExtrasEquals(syncInfo.extras,
980 extras,
981 true /* includeSyncSettings */)) {
982 iterator.remove();
983 changed = true;
984 // If we removed an entry from the periodicSyncs array also
985 // remove the corresponding entry from the status
986 if (status != null) {
987 status.removePeriodicSyncTime(i);
988 } else {
989 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
990 + " did not find it.");
991 }
992 } else {
993 i++;
994 }
995 }
996 if (!changed) {
997 return;
998 }
999 } finally {
1000 writeAccountInfoLocked();
1001 writeStatusLocked();
1002 }
1003 }
1004 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001005 }
1006
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001007 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001008 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1009 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001010 */
1011 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001012 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001013 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1014 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1015 if (authorityInfo != null) {
1016 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001017 // Copy and send out. Necessary for thread-safety although it's parceled.
1018 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001019 }
1020 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001021 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001022 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001023 }
1024
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001027 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001028 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001029 return;
1030 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001031 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 writeAccountInfoLocked();
1033 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001034 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001035 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1036 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001037 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001038 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001039 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -08001040 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001046 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 }
1048 }
Costin Manolache360e4542009-09-04 13:36:04 -07001049
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 public AuthorityInfo getAuthority(int authorityId) {
1051 synchronized (mAuthorities) {
1052 return mAuthorities.get(authorityId);
1053 }
1054 }
Costin Manolache360e4542009-09-04 13:36:04 -07001055
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001057 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001058 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001059 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001060 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001062 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001063 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001064 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 return true;
1066 }
1067 }
1068 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001069 return false;
1070 }
Costin Manolache360e4542009-09-04 13:36:04 -07001071
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001072 public PendingOperation insertIntoPending(SyncOperation op) {
1073 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001075 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1076 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001077 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001078 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001079 final EndPoint info = op.target;
1080 AuthorityInfo authority =
1081 getOrCreateAuthorityLocked(info,
1082 -1 /* desired identifier */,
1083 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 if (authority == null) {
1085 return null;
1086 }
Costin Manolache360e4542009-09-04 13:36:04 -07001087
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001088 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
Matthew Williams64280462014-01-09 10:49:23 -08001089 op.isExpedited());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001090 mPendingOperations.add(pop);
Matthew Williams06485a72013-07-26 12:56:39 -07001091 appendPendingOperationLocked(pop);
Costin Manolache360e4542009-09-04 13:36:04 -07001092
Dianne Hackborn231cc602009-04-27 17:10:36 -07001093 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1094 status.pending = true;
1095 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001096 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001097 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 }
1099
Matthew Williamsfa774182013-06-18 15:44:11 -07001100 /**
1101 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001102 * authorities. If there are no more pending syncs for the same target,
1103 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001104 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001105 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001106 public boolean deleteFromPending(PendingOperation op) {
1107 boolean res = false;
1108 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1110 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001111 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 if (mPendingOperations.remove(op)) {
1113 if (mPendingOperations.size() == 0
1114 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1115 writePendingOperationsLocked();
1116 mNumPendingFinished = 0;
1117 } else {
1118 mNumPendingFinished++;
1119 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001120 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001122 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1123 Log.v(TAG, "removing - " + authority.toString());
1124 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001125 final int N = mPendingOperations.size();
1126 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001127 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001128 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001129 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001130 morePending = true;
1131 break;
1132 }
1133 }
Costin Manolache360e4542009-09-04 13:36:04 -07001134
Dianne Hackborn231cc602009-04-27 17:10:36 -07001135 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001136 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001137 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1138 status.pending = false;
1139 }
1140 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 res = true;
1142 }
1143 }
Costin Manolache360e4542009-09-04 13:36:04 -07001144
Fred Quintanaac9385e2009-06-22 18:00:59 -07001145 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 return res;
1147 }
1148
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 /**
1150 * Return a copy of the current array of pending operations. The
1151 * PendingOperation objects are the real objects stored inside, so that
1152 * they can be used with deleteFromPending().
1153 */
1154 public ArrayList<PendingOperation> getPendingOperations() {
1155 synchronized (mAuthorities) {
1156 return new ArrayList<PendingOperation>(mPendingOperations);
1157 }
1158 }
Costin Manolache360e4542009-09-04 13:36:04 -07001159
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 /**
1161 * Return the number of currently pending operations.
1162 */
1163 public int getPendingOperationCount() {
1164 synchronized (mAuthorities) {
1165 return mPendingOperations.size();
1166 }
1167 }
Costin Manolache360e4542009-09-04 13:36:04 -07001168
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 /**
1170 * Called when the set of account has changed, given the new array of
1171 * active accounts.
1172 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001173 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001174 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001175 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1176 Log.v(TAG, "Updating for new accounts...");
1177 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001178 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1179 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1180 while (accIt.hasNext()) {
1181 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001182 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1183 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001184 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001185 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001186 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001187 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001188 for (AuthorityInfo auth : acc.authorities.values()) {
1189 removing.put(auth.ident, auth);
1190 }
1191 accIt.remove();
1192 }
1193 }
Costin Manolache360e4542009-09-04 13:36:04 -07001194
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 // Clean out all data structures.
1196 int i = removing.size();
1197 if (i > 0) {
1198 while (i > 0) {
1199 i--;
1200 int ident = removing.keyAt(i);
1201 mAuthorities.remove(ident);
1202 int j = mSyncStatus.size();
1203 while (j > 0) {
1204 j--;
1205 if (mSyncStatus.keyAt(j) == ident) {
1206 mSyncStatus.remove(mSyncStatus.keyAt(j));
1207 }
1208 }
1209 j = mSyncHistory.size();
1210 while (j > 0) {
1211 j--;
1212 if (mSyncHistory.get(j).authorityId == ident) {
1213 mSyncHistory.remove(j);
1214 }
1215 }
1216 }
1217 writeAccountInfoLocked();
1218 writeStatusLocked();
1219 writePendingOperationsLocked();
1220 writeStatisticsLocked();
1221 }
1222 }
1223 }
1224
1225 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001226 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1227 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 */
Fred Quintana918339a2010-10-05 14:00:39 -07001229 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1230 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001231 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001232 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001233 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001234 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001235 + " src=" + activeSyncContext.mSyncOperation.syncSource
1236 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001238 final EndPoint info = activeSyncContext.mSyncOperation.target;
1239 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1240 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001241 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001242 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001243 syncInfo = new SyncInfo(
1244 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001245 authorityInfo.target.account,
1246 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001247 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001248 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 }
Fred Quintana918339a2010-10-05 14:00:39 -07001250 reportActiveChange();
1251 return syncInfo;
1252 }
1253
1254 /**
1255 * Called to indicate that a previously active sync is no longer active.
1256 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001258 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001259 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001260 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1261 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001262 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001263 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001264 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001265 }
1266
1267 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 }
1269
1270 /**
1271 * To allow others to send active change reports, to poke clients.
1272 */
1273 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001274 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001275 }
Costin Manolache360e4542009-09-04 13:36:04 -07001276
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001278 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001279 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001280 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001281 long id;
1282 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001283 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1284 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001285 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001286 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001287 if (authority == null) {
1288 return -1;
1289 }
1290 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001291 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 item.authorityId = authority.ident;
1293 item.historyId = mNextHistoryId++;
1294 if (mNextHistoryId < 0) mNextHistoryId = 0;
1295 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001296 item.source = op.syncSource;
1297 item.reason = op.reason;
1298 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001299 item.event = EVENT_START;
1300 mSyncHistory.add(0, item);
1301 while (mSyncHistory.size() > MAX_HISTORY) {
1302 mSyncHistory.remove(mSyncHistory.size()-1);
1303 }
1304 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001305 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 }
Costin Manolache360e4542009-09-04 13:36:04 -07001307
Fred Quintanaac9385e2009-06-22 18:00:59 -07001308 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001309 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 }
1311
Fred Quintana77c560f2010-03-29 22:20:26 -07001312 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001314 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001316 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1317 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001318 SyncHistoryItem item = null;
1319 int i = mSyncHistory.size();
1320 while (i > 0) {
1321 i--;
1322 item = mSyncHistory.get(i);
1323 if (item.historyId == historyId) {
1324 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001326 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
Costin Manolache360e4542009-09-04 13:36:04 -07001328
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 if (item == null) {
1330 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1331 return;
1332 }
Costin Manolache360e4542009-09-04 13:36:04 -07001333
Dianne Hackborn231cc602009-04-27 17:10:36 -07001334 item.elapsedTime = elapsedTime;
1335 item.event = EVENT_STOP;
1336 item.mesg = resultMessage;
1337 item.downstreamActivity = downstreamActivity;
1338 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001339
Dianne Hackborn231cc602009-04-27 17:10:36 -07001340 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001341
Dianne Hackborn231cc602009-04-27 17:10:36 -07001342 status.numSyncs++;
1343 status.totalElapsedTime += elapsedTime;
1344 switch (item.source) {
1345 case SOURCE_LOCAL:
1346 status.numSourceLocal++;
1347 break;
1348 case SOURCE_POLL:
1349 status.numSourcePoll++;
1350 break;
1351 case SOURCE_USER:
1352 status.numSourceUser++;
1353 break;
1354 case SOURCE_SERVER:
1355 status.numSourceServer++;
1356 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001357 case SOURCE_PERIODIC:
1358 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001359 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 }
Costin Manolache360e4542009-09-04 13:36:04 -07001361
Dianne Hackborn231cc602009-04-27 17:10:36 -07001362 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001363 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 if (mDayStats[0] == null) {
1365 mDayStats[0] = new DayStats(day);
1366 } else if (day != mDayStats[0].day) {
1367 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1368 mDayStats[0] = new DayStats(day);
1369 writeStatisticsNow = true;
1370 } else if (mDayStats[0] == null) {
1371 }
1372 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001373
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 final long lastSyncTime = (item.eventTime + elapsedTime);
1375 boolean writeStatusNow = false;
1376 if (MESG_SUCCESS.equals(resultMessage)) {
1377 // - if successful, update the successful columns
1378 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1379 writeStatusNow = true;
1380 }
1381 status.lastSuccessTime = lastSyncTime;
1382 status.lastSuccessSource = item.source;
1383 status.lastFailureTime = 0;
1384 status.lastFailureSource = -1;
1385 status.lastFailureMesg = null;
1386 status.initialFailureTime = 0;
1387 ds.successCount++;
1388 ds.successTime += elapsedTime;
1389 } else if (!MESG_CANCELED.equals(resultMessage)) {
1390 if (status.lastFailureTime == 0) {
1391 writeStatusNow = true;
1392 }
1393 status.lastFailureTime = lastSyncTime;
1394 status.lastFailureSource = item.source;
1395 status.lastFailureMesg = resultMessage;
1396 if (status.initialFailureTime == 0) {
1397 status.initialFailureTime = lastSyncTime;
1398 }
1399 ds.failureCount++;
1400 ds.failureTime += elapsedTime;
1401 }
Costin Manolache360e4542009-09-04 13:36:04 -07001402
Dianne Hackborn231cc602009-04-27 17:10:36 -07001403 if (writeStatusNow) {
1404 writeStatusLocked();
1405 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1406 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1407 WRITE_STATUS_DELAY);
1408 }
1409 if (writeStatisticsNow) {
1410 writeStatisticsLocked();
1411 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1412 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1413 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001414 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001415 }
Costin Manolache360e4542009-09-04 13:36:04 -07001416
Fred Quintanaac9385e2009-06-22 18:00:59 -07001417 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001418 }
1419
1420 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001421 * Return a list of the currently active syncs. Note that the returned
1422 * items are the real, live active sync objects, so be careful what you do
1423 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001424 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001425 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001426 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001427 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001428 }
1429 }
Costin Manolache360e4542009-09-04 13:36:04 -07001430
Dianne Hackborn231cc602009-04-27 17:10:36 -07001431 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001432 * @return a copy of the current syncs data structure. Will not return
1433 * null.
1434 */
1435 public List<SyncInfo> getCurrentSyncsCopy(int userId) {
1436 synchronized (mAuthorities) {
1437 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1438 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1439 for (SyncInfo sync : syncs) {
1440 syncsCopy.add(new SyncInfo(sync));
1441 }
1442 return syncsCopy;
1443 }
1444 }
1445
1446 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1447 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1448 if (syncs == null) {
1449 syncs = new ArrayList<SyncInfo>();
1450 mCurrentSyncs.put(userId, syncs);
1451 }
1452 return syncs;
1453 }
1454
1455 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001456 * Return an array of the current sync status for all authorities. Note
1457 * that the objects inside the array are the real, live status objects,
1458 * so be careful what you do with them.
1459 */
1460 public ArrayList<SyncStatusInfo> getSyncStatus() {
1461 synchronized (mAuthorities) {
1462 final int N = mSyncStatus.size();
1463 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1464 for (int i=0; i<N; i++) {
1465 ops.add(mSyncStatus.valueAt(i));
1466 }
1467 return ops;
1468 }
1469 }
Costin Manolache360e4542009-09-04 13:36:04 -07001470
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001472 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001473 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001474 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001475 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001476 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001477 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001478 true /* write to storage if this results in a change */);
1479 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1480 }
1481 }
1482
1483 /**
1484 * Return a copy of all authorities with their corresponding sync status
1485 */
1486 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1487 synchronized (mAuthorities) {
1488 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1489 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1490 for (int i = 0; i < mAuthorities.size(); i++) {
1491 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001492 }
1493 return infos;
1494 }
1495 }
1496
1497 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001498 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001499 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001500 * @param info the endpoint target we are querying status info for.
1501 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001502 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001503 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1504 if (info.target_provider && (info.account == null || info.provider == null)) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001505 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001506 } else if (info.target_service && info.service == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001507 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001508 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001509 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001510 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001511 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001512 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001513 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001514 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001515 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001516 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001517 }
1518 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001519 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 }
1521 }
Costin Manolache360e4542009-09-04 13:36:04 -07001522
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001523 /** Return true if the pending status is true of any matching authorities. */
1524 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001525 synchronized (mAuthorities) {
1526 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001527 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001528 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001529 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1530 if (ainfo == null) {
1531 continue;
1532 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001533 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001534 continue;
1535 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001536 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001537 return true;
1538 }
1539 }
1540 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543
1544 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001545 * Return an array of the current sync status for all authorities. Note
1546 * that the objects inside the array are the real, live status objects,
1547 * so be careful what you do with them.
1548 */
1549 public ArrayList<SyncHistoryItem> getSyncHistory() {
1550 synchronized (mAuthorities) {
1551 final int N = mSyncHistory.size();
1552 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1553 for (int i=0; i<N; i++) {
1554 items.add(mSyncHistory.get(i));
1555 }
1556 return items;
1557 }
1558 }
Costin Manolache360e4542009-09-04 13:36:04 -07001559
Dianne Hackborn231cc602009-04-27 17:10:36 -07001560 /**
1561 * Return an array of the current per-day statistics. Note
1562 * that the objects inside the array are the real, live status objects,
1563 * so be careful what you do with them.
1564 */
1565 public DayStats[] getDayStatistics() {
1566 synchronized (mAuthorities) {
1567 DayStats[] ds = new DayStats[mDayStats.length];
1568 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1569 return ds;
1570 }
1571 }
Costin Manolache360e4542009-09-04 13:36:04 -07001572
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001573 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1574 AuthorityInfo authorityInfo) {
1575 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1576 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1577 }
1578
Dianne Hackborn55280a92009-05-07 15:53:46 -07001579 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001580 mCal.setTimeInMillis(System.currentTimeMillis());
1581 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1582 if (mYear != mCal.get(Calendar.YEAR)) {
1583 mYear = mCal.get(Calendar.YEAR);
1584 mCal.clear();
1585 mCal.set(Calendar.YEAR, mYear);
1586 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1587 }
1588 return dayOfYear + mYearInDays;
1589 }
Costin Manolache360e4542009-09-04 13:36:04 -07001590
Dianne Hackborn231cc602009-04-27 17:10:36 -07001591 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001592 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001593 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001594 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001595 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001596 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001597 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001598 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1599 if (info.target_service) {
1600 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1601 AuthorityInfo authority = null;
1602 if (aInfo != null) {
1603 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001604 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001605 if (authority == null) {
1606 if (tag != null) {
1607 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001608 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1609 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001610 }
1611 }
1612 return null;
1613 }
1614 return authority;
1615 } else if (info.target_provider){
1616 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1617 AccountInfo accountInfo = mAccounts.get(au);
1618 if (accountInfo == null) {
1619 if (tag != null) {
1620 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1621 Log.v(TAG, tag + ": unknown account " + au);
1622 }
1623 }
1624 return null;
1625 }
1626 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1627 if (authority == null) {
1628 if (tag != null) {
1629 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1630 Log.v(TAG, tag + ": unknown provider " + info.provider);
1631 }
1632 }
1633 return null;
1634 }
1635 return authority;
1636 } else {
1637 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001638 return null;
1639 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001640 }
Costin Manolache360e4542009-09-04 13:36:04 -07001641
Matthew Williamsfa774182013-06-18 15:44:11 -07001642 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001643 * @param info info identifying target.
1644 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001645 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001646 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001647 * exists.
1648 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001649 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1650 AuthorityInfo authority = null;
1651 if (info.target_service) {
1652 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1653 if (aInfo == null) {
1654 aInfo = new SparseArray<AuthorityInfo>();
1655 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001656 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001657 authority = aInfo.get(info.userId);
1658 if (authority == null) {
1659 authority = createAuthorityLocked(info, ident, doWrite);
1660 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001661 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001662 } else if (info.target_provider) {
1663 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1664 AccountInfo account = mAccounts.get(au);
1665 if (account == null) {
1666 account = new AccountInfo(au);
1667 mAccounts.put(au, account);
1668 }
1669 authority = account.authorities.get(info.provider);
1670 if (authority == null) {
1671 authority = createAuthorityLocked(info, ident, doWrite);
1672 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001673 }
1674 }
1675 return authority;
1676 }
1677
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001678 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1679 AuthorityInfo authority;
1680 if (ident < 0) {
1681 ident = mNextAuthorityId;
1682 mNextAuthorityId++;
1683 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001684 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1686 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001687 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001688 authority = new AuthorityInfo(info, ident);
1689 mAuthorities.put(ident, authority);
1690 if (doWrite) {
1691 writeAccountInfoLocked();
1692 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001693 return authority;
1694 }
Costin Manolache360e4542009-09-04 13:36:04 -07001695
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001696 public void removeAuthority(EndPoint info) {
1697 synchronized (mAuthorities) {
1698 if (info.target_provider) {
1699 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1700 } else {
1701 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1702 if (aInfos != null) {
1703 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1704 if (authorityInfo != null) {
1705 mAuthorities.remove(authorityInfo.ident);
1706 aInfos.delete(info.userId);
1707 writeAccountInfoLocked();
1708 }
1709 }
1710
1711 }
1712 }
1713 }
1714
1715 /**
1716 * Remove an authority associated with a provider. Needs to be a standalone function for
1717 * backward compatibility.
1718 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001719 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1720 boolean doWrite) {
1721 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001722 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001723 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1724 if (authorityInfo != null) {
1725 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001726 if (doWrite) {
1727 writeAccountInfoLocked();
1728 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001729 }
1730 }
1731 }
1732
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001733 /**
1734 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001735 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001736 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001737 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001738 boolean found = false;
1739 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001740 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001741 authorityInfo = mAuthorities.get(authorityId);
1742 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001743 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1744 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001745 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001746 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001747 break;
1748 }
1749 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001750 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001751 if (!found) {
1752 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001753 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001754 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001755 }
1756
Dianne Hackborn231cc602009-04-27 17:10:36 -07001757 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1758 SyncStatusInfo status = mSyncStatus.get(authorityId);
1759 if (status == null) {
1760 status = new SyncStatusInfo(authorityId);
1761 mSyncStatus.put(authorityId, status);
1762 }
1763 return status;
1764 }
Costin Manolache360e4542009-09-04 13:36:04 -07001765
Dianne Hackborn55280a92009-05-07 15:53:46 -07001766 public void writeAllState() {
1767 synchronized (mAuthorities) {
1768 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001769
Dianne Hackborn55280a92009-05-07 15:53:46 -07001770 if (mNumPendingFinished > 0) {
1771 // Only write these if they are out of date.
1772 writePendingOperationsLocked();
1773 }
Costin Manolache360e4542009-09-04 13:36:04 -07001774
Dianne Hackborn55280a92009-05-07 15:53:46 -07001775 // Just always write these... they are likely out of date.
1776 writeStatusLocked();
1777 writeStatisticsLocked();
1778 }
1779 }
Costin Manolache360e4542009-09-04 13:36:04 -07001780
Dianne Hackborn231cc602009-04-27 17:10:36 -07001781 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001782 * public for testing
1783 */
1784 public void clearAndReadState() {
1785 synchronized (mAuthorities) {
1786 mAuthorities.clear();
1787 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001788 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001789 mPendingOperations.clear();
1790 mSyncStatus.clear();
1791 mSyncHistory.clear();
1792
1793 readAccountInfoLocked();
1794 readStatusLocked();
1795 readPendingOperationsLocked();
1796 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001797 readAndDeleteLegacyAccountInfoLocked();
1798 writeAccountInfoLocked();
1799 writeStatusLocked();
1800 writePendingOperationsLocked();
1801 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001802 }
1803 }
1804
1805 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001806 * Read all account information back in to the initial engine state.
1807 */
1808 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001809 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001810 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001812 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001813 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001814 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001815 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 XmlPullParser parser = Xml.newPullParser();
1817 parser.setInput(fis, null);
1818 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001819 while (eventType != XmlPullParser.START_TAG &&
1820 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 eventType = parser.next();
1822 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001823 if (eventType == XmlPullParser.END_DOCUMENT) {
1824 Log.i(TAG, "No initial accounts");
1825 return;
1826 }
1827
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 String tagName = parser.getName();
1829 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001830 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001831 String versionString = parser.getAttributeValue(null, "version");
1832 int version;
1833 try {
1834 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1835 } catch (NumberFormatException e) {
1836 version = 0;
1837 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001838 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001839 try {
1840 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1841 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1842 } catch (NumberFormatException e) {
1843 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001844 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001845 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1846 try {
1847 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1848 } catch (NumberFormatException e) {
1849 mSyncRandomOffset = 0;
1850 }
1851 if (mSyncRandomOffset == 0) {
1852 Random random = new Random(System.currentTimeMillis());
1853 mSyncRandomOffset = random.nextInt(86400);
1854 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001855 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001856 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001857 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001858 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001859 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001860 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001861 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001862 if (parser.getDepth() == 2) {
1863 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001864 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001865 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001866 if (authority.ident > highestAuthorityId) {
1867 highestAuthorityId = authority.ident;
1868 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001869 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1870 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001871 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001872 } else if (parser.getDepth() == 3) {
1873 if ("periodicSync".equals(tagName) && authority != null) {
1874 periodicSync = parsePeriodicSync(parser, authority);
1875 }
1876 } else if (parser.getDepth() == 4 && periodicSync != null) {
1877 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001878 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001879 }
1880 }
1881 }
1882 eventType = parser.next();
1883 } while (eventType != XmlPullParser.END_DOCUMENT);
1884 }
1885 } catch (XmlPullParserException e) {
1886 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001887 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 } catch (java.io.IOException e) {
1889 if (fis == null) Log.i(TAG, "No initial accounts");
1890 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001891 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001892 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001893 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001894 if (fis != null) {
1895 try {
1896 fis.close();
1897 } catch (java.io.IOException e1) {
1898 }
1899 }
1900 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001901
Fred Quintana77c560f2010-03-29 22:20:26 -07001902 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001903 }
Costin Manolache360e4542009-09-04 13:36:04 -07001904
Fred Quintanafb084402010-03-23 17:57:03 -07001905 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001906 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1907 * pending.xml was used starting in KLP.
1908 * @param syncDir directory where the sync files are located.
1909 */
1910 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1911 File file = new File(syncDir, "pending.bin");
1912 if (!file.exists()) {
1913 return;
1914 } else {
1915 file.delete();
1916 }
1917 }
1918
1919 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001920 * some authority names have changed. copy over their settings and delete the old ones
1921 * @return true if a change was made
1922 */
1923 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1924 boolean writeNeeded = false;
1925
1926 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1927 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001928 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001929 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001930 // skip this authority if it doesn't target a provider
1931 if (authority.target.target_service) {
1932 continue;
1933 }
Fred Quintanafb084402010-03-23 17:57:03 -07001934 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001935 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001936 if (newAuthorityName == null) {
1937 continue;
1938 }
1939
1940 // remember this authority so we can remove it later. we can't remove it
1941 // now without messing up this loop iteration
1942 authoritiesToRemove.add(authority);
1943
1944 // this authority isn't enabled, no need to copy it to the new authority name since
1945 // the default is "disabled"
1946 if (!authority.enabled) {
1947 continue;
1948 }
1949
1950 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001951 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001952 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001953 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001954 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001955 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001956 continue;
1957 }
1958
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001959 AuthorityInfo newAuthority =
1960 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001961 newAuthority.enabled = true;
1962 writeNeeded = true;
1963 }
1964
1965 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001966 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001967 authorityInfo.target.account,
1968 authorityInfo.target.userId,
1969 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001970 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001971 writeNeeded = true;
1972 }
1973
1974 return writeNeeded;
1975 }
1976
Amith Yamasani04e0d262012-02-14 11:50:53 -08001977 private void parseListenForTickles(XmlPullParser parser) {
1978 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1979 int userId = 0;
1980 try {
1981 userId = Integer.parseInt(user);
1982 } catch (NumberFormatException e) {
1983 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1984 } catch (NullPointerException e) {
1985 Log.e(TAG, "the user in listen-for-tickles is null", e);
1986 }
1987 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1988 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1989 mMasterSyncAutomatically.put(userId, listen);
1990 }
1991
Fred Quintanac2e46912010-03-15 16:10:44 -07001992 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001993 AuthorityInfo authority = null;
1994 int id = -1;
1995 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001996 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001997 } catch (NumberFormatException e) {
1998 Log.e(TAG, "error parsing the id of the authority", e);
1999 } catch (NullPointerException e) {
2000 Log.e(TAG, "the id of the authority is null", e);
2001 }
2002 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07002003 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002004 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07002005 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002006 String accountName = parser.getAttributeValue(null, "account");
2007 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002008 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07002009 String packageName = parser.getAttributeValue(null, "package");
2010 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002011 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07002012 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002013 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07002014 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002015 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002016 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002017 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002018 Log.v(TAG_FILE, "Adding authority:"
2019 + " account=" + accountName
2020 + " accountType=" + accountType
2021 + " auth=" + authorityName
2022 + " package=" + packageName
2023 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07002024 + " user=" + userId
2025 + " enabled=" + enabled
2026 + " syncable=" + syncable);
2027 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002028 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002029 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002030 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002031 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002032 EndPoint info;
2033 if (accountName != null && authorityName != null) {
2034 info = new EndPoint(
2035 new Account(accountName, accountType),
2036 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002037 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002038 info = new EndPoint(
2039 new ComponentName(packageName, className),
2040 userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002041 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002042 authority = getOrCreateAuthorityLocked(info, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07002043 // If the version is 0 then we are upgrading from a file format that did not
2044 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002045 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002046 // Otherwise clear out this default list since we will populate it later with
2047 // the periodic sync descriptions that are read from the configuration file.
2048 if (version > 0) {
2049 authority.periodicSyncs.clear();
2050 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002051 }
2052 if (authority != null) {
2053 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
2054 if ("unknown".equals(syncable)) {
2055 authority.syncable = -1;
2056 } else {
2057 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07002058 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002059 }
2060 } else {
2061 Log.w(TAG, "Failure adding authority: account="
2062 + accountName + " auth=" + authorityName
2063 + " enabled=" + enabled
2064 + " syncable=" + syncable);
2065 }
2066 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002067 return authority;
2068 }
2069
Matthew Williamsfa774182013-06-18 15:44:11 -07002070 /**
2071 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2072 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002073 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002074 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002075 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002076 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002077 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002078 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002079 try {
2080 period = Long.parseLong(periodValue);
2081 } catch (NumberFormatException e) {
2082 Log.e(TAG, "error parsing the period of a periodic sync", e);
2083 return null;
2084 } catch (NullPointerException e) {
2085 Log.e(TAG, "the period of a periodic sync is null", e);
2086 return null;
2087 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002088 try {
2089 flextime = Long.parseLong(flexValue);
2090 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002091 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002092 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2093 + ", using default: "
2094 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002095 } catch (NullPointerException expected) {
2096 flextime = calculateDefaultFlexTime(period);
2097 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2098 + period + " flex: " + flextime);
2099 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002100 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002101 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002102 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002103 new PeriodicSync(authorityInfo.target.account,
2104 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002105 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002106 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002107 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002108 Log.e(TAG, "Unknown target.");
2109 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002110 }
2111 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002112 return periodicSync;
2113 }
2114
Matthew Williamsfa774182013-06-18 15:44:11 -07002115 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002116 String name = parser.getAttributeValue(null, "name");
2117 String type = parser.getAttributeValue(null, "type");
2118 String value1 = parser.getAttributeValue(null, "value1");
2119 String value2 = parser.getAttributeValue(null, "value2");
2120
2121 try {
2122 if ("long".equals(type)) {
2123 extras.putLong(name, Long.parseLong(value1));
2124 } else if ("integer".equals(type)) {
2125 extras.putInt(name, Integer.parseInt(value1));
2126 } else if ("double".equals(type)) {
2127 extras.putDouble(name, Double.parseDouble(value1));
2128 } else if ("float".equals(type)) {
2129 extras.putFloat(name, Float.parseFloat(value1));
2130 } else if ("boolean".equals(type)) {
2131 extras.putBoolean(name, Boolean.parseBoolean(value1));
2132 } else if ("string".equals(type)) {
2133 extras.putString(name, value1);
2134 } else if ("account".equals(type)) {
2135 extras.putParcelable(name, new Account(value1, value2));
2136 }
2137 } catch (NumberFormatException e) {
2138 Log.e(TAG, "error parsing bundle value", e);
2139 } catch (NullPointerException e) {
2140 Log.e(TAG, "error parsing bundle value", e);
2141 }
2142 }
2143
Dianne Hackborn231cc602009-04-27 17:10:36 -07002144 /**
2145 * Write all account information to the account file.
2146 */
2147 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002148 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002149 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002150 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002151 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002152
Dianne Hackborn231cc602009-04-27 17:10:36 -07002153 try {
2154 fos = mAccountInfoFile.startWrite();
2155 XmlSerializer out = new FastXmlSerializer();
2156 out.setOutput(fos, "utf-8");
2157 out.startDocument(null, true);
2158 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002159
Dianne Hackborn231cc602009-04-27 17:10:36 -07002160 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002161 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002162 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002163 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002164
2165 // Write the Sync Automatically flags for each user
2166 final int M = mMasterSyncAutomatically.size();
2167 for (int m = 0; m < M; m++) {
2168 int userId = mMasterSyncAutomatically.keyAt(m);
2169 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2170 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2171 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2172 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2173 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002174 }
Costin Manolache360e4542009-09-04 13:36:04 -07002175
Dianne Hackborn231cc602009-04-27 17:10:36 -07002176 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002177 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002178 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002179 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002180 out.startTag(null, "authority");
2181 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002182 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002183 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002184 if (info.service == null) {
2185 out.attribute(null, "account", info.account.name);
2186 out.attribute(null, "type", info.account.type);
2187 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002188 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002189 out.attribute(null, "package", info.service.getPackageName());
2190 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002191 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002192 if (authority.syncable < 0) {
2193 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002194 } else {
2195 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002196 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002197 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002198 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002199 out.attribute(null, "period", Long.toString(periodicSync.period));
2200 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2201 final Bundle extras = periodicSync.extras;
2202 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002203 out.endTag(null, "periodicSync");
2204 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002205 out.endTag(null, "authority");
2206 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002207 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002208 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002209 mAccountInfoFile.finishWrite(fos);
2210 } catch (java.io.IOException e1) {
2211 Log.w(TAG, "Error writing accounts", e1);
2212 if (fos != null) {
2213 mAccountInfoFile.failWrite(fos);
2214 }
2215 }
2216 }
Costin Manolache360e4542009-09-04 13:36:04 -07002217
Dianne Hackborn231cc602009-04-27 17:10:36 -07002218 static int getIntColumn(Cursor c, String name) {
2219 return c.getInt(c.getColumnIndex(name));
2220 }
Costin Manolache360e4542009-09-04 13:36:04 -07002221
Dianne Hackborn231cc602009-04-27 17:10:36 -07002222 static long getLongColumn(Cursor c, String name) {
2223 return c.getLong(c.getColumnIndex(name));
2224 }
Costin Manolache360e4542009-09-04 13:36:04 -07002225
Dianne Hackborn231cc602009-04-27 17:10:36 -07002226 /**
2227 * Load sync engine state from the old syncmanager database, and then
2228 * erase it. Note that we don't deal with pending operations, active
2229 * sync, or history.
2230 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002231 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002232 // Look for old database to initialize from.
2233 File file = mContext.getDatabasePath("syncmanager.db");
2234 if (!file.exists()) {
2235 return;
2236 }
2237 String path = file.getPath();
2238 SQLiteDatabase db = null;
2239 try {
2240 db = SQLiteDatabase.openDatabase(path, null,
2241 SQLiteDatabase.OPEN_READONLY);
2242 } catch (SQLiteException e) {
2243 }
Costin Manolache360e4542009-09-04 13:36:04 -07002244
Dianne Hackborn231cc602009-04-27 17:10:36 -07002245 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002246 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002247
Dianne Hackborn231cc602009-04-27 17:10:36 -07002248 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002249 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002250 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002251 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002252 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2253 qb.setTables("stats, status");
2254 HashMap<String,String> map = new HashMap<String,String>();
2255 map.put("_id", "status._id as _id");
2256 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002257 if (hasType) {
2258 map.put("account_type", "stats.account_type as account_type");
2259 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002260 map.put("authority", "stats.authority as authority");
2261 map.put("totalElapsedTime", "totalElapsedTime");
2262 map.put("numSyncs", "numSyncs");
2263 map.put("numSourceLocal", "numSourceLocal");
2264 map.put("numSourcePoll", "numSourcePoll");
2265 map.put("numSourceServer", "numSourceServer");
2266 map.put("numSourceUser", "numSourceUser");
2267 map.put("lastSuccessSource", "lastSuccessSource");
2268 map.put("lastSuccessTime", "lastSuccessTime");
2269 map.put("lastFailureSource", "lastFailureSource");
2270 map.put("lastFailureTime", "lastFailureTime");
2271 map.put("lastFailureMesg", "lastFailureMesg");
2272 map.put("pending", "pending");
2273 qb.setProjectionMap(map);
2274 qb.appendWhere("stats._id = status.stats_id");
2275 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002277 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002278 String accountType = hasType
2279 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002280 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002281 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002283 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002284 AuthorityInfo authority =
2285 this.getOrCreateAuthorityLocked(
2286 new EndPoint(new Account(accountName, accountType),
2287 authorityName,
2288 0 /* legacy is single-user */)
2289 , -1,
2290 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002291 if (authority != null) {
2292 int i = mSyncStatus.size();
2293 boolean found = false;
2294 SyncStatusInfo st = null;
2295 while (i > 0) {
2296 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002297 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002298 if (st.authorityId == authority.ident) {
2299 found = true;
2300 break;
2301 }
2302 }
2303 if (!found) {
2304 st = new SyncStatusInfo(authority.ident);
2305 mSyncStatus.put(authority.ident, st);
2306 }
2307 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2308 st.numSyncs = getIntColumn(c, "numSyncs");
2309 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2310 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2311 st.numSourceServer = getIntColumn(c, "numSourceServer");
2312 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002313 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002314 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2315 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2316 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2317 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2318 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2319 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
Costin Manolache360e4542009-09-04 13:36:04 -07002322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002324
Dianne Hackborn231cc602009-04-27 17:10:36 -07002325 // Retrieve the settings.
2326 qb = new SQLiteQueryBuilder();
2327 qb.setTables("settings");
2328 c = qb.query(db, null, null, null, null, null, null);
2329 while (c.moveToNext()) {
2330 String name = c.getString(c.getColumnIndex("name"));
2331 String value = c.getString(c.getColumnIndex("value"));
2332 if (name == null) continue;
2333 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002334 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002335 } else if (name.startsWith("sync_provider_")) {
2336 String provider = name.substring("sync_provider_".length(),
2337 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002338 int i = mAuthorities.size();
2339 while (i > 0) {
2340 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002341 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002342 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002343 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002344 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002345 }
2346 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
Costin Manolache360e4542009-09-04 13:36:04 -07002349
Dianne Hackborn231cc602009-04-27 17:10:36 -07002350 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002351
Dianne Hackborn231cc602009-04-27 17:10:36 -07002352 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002353
Dianne Hackborn231cc602009-04-27 17:10:36 -07002354 (new File(path)).delete();
2355 }
2356 }
Costin Manolache360e4542009-09-04 13:36:04 -07002357
Dianne Hackborn231cc602009-04-27 17:10:36 -07002358 public static final int STATUS_FILE_END = 0;
2359 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002360
Dianne Hackborn231cc602009-04-27 17:10:36 -07002361 /**
2362 * Read all sync status back in to the initial engine state.
2363 */
2364 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002365 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002366 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002367 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002368 try {
2369 byte[] data = mStatusFile.readFully();
2370 Parcel in = Parcel.obtain();
2371 in.unmarshall(data, 0, data.length);
2372 in.setDataPosition(0);
2373 int token;
2374 while ((token=in.readInt()) != STATUS_FILE_END) {
2375 if (token == STATUS_FILE_ITEM) {
2376 SyncStatusInfo status = new SyncStatusInfo(in);
2377 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2378 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002379 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002380 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002381 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002382 mSyncStatus.put(status.authorityId, status);
2383 }
2384 } else {
2385 // Ooops.
2386 Log.w(TAG, "Unknown status token: " + token);
2387 break;
2388 }
2389 }
2390 } catch (java.io.IOException e) {
2391 Log.i(TAG, "No initial status");
2392 }
2393 }
Costin Manolache360e4542009-09-04 13:36:04 -07002394
Dianne Hackborn231cc602009-04-27 17:10:36 -07002395 /**
2396 * Write all sync status to the sync status file.
2397 */
2398 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002399 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002400 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002401 }
Costin Manolache360e4542009-09-04 13:36:04 -07002402
Dianne Hackborn231cc602009-04-27 17:10:36 -07002403 // The file is being written, so we don't need to have a scheduled
2404 // write until the next change.
2405 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002406
Dianne Hackborn231cc602009-04-27 17:10:36 -07002407 FileOutputStream fos = null;
2408 try {
2409 fos = mStatusFile.startWrite();
2410 Parcel out = Parcel.obtain();
2411 final int N = mSyncStatus.size();
2412 for (int i=0; i<N; i++) {
2413 SyncStatusInfo status = mSyncStatus.valueAt(i);
2414 out.writeInt(STATUS_FILE_ITEM);
2415 status.writeToParcel(out, 0);
2416 }
2417 out.writeInt(STATUS_FILE_END);
2418 fos.write(out.marshall());
2419 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002420
Dianne Hackborn231cc602009-04-27 17:10:36 -07002421 mStatusFile.finishWrite(fos);
2422 } catch (java.io.IOException e1) {
2423 Log.w(TAG, "Error writing status", e1);
2424 if (fos != null) {
2425 mStatusFile.failWrite(fos);
2426 }
2427 }
2428 }
Costin Manolache360e4542009-09-04 13:36:04 -07002429
Matthew Williamsba352712013-08-13 15:53:31 -07002430 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002431
Matthew Williamsba352712013-08-13 15:53:31 -07002432 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002433 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002434 FileInputStream fis = null;
2435 if (!mPendingFile.getBaseFile().exists()) {
2436 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2437 Log.v(TAG_FILE, "No pending operation file.");
Matthew Williamsfa774182013-06-18 15:44:11 -07002438 }
Ji-Hwan Lee886113d2014-04-17 14:16:38 +09002439 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002440 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002441 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002442 fis = mPendingFile.openRead();
Matthew Williams06485a72013-07-26 12:56:39 -07002443 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2444 Log.v(TAG_FILE, "Reading " + mPendingFile.getBaseFile());
2445 }
Matthew Williamsba352712013-08-13 15:53:31 -07002446 XmlPullParser parser;
2447 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002448 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002449
Matthew Williamsfa774182013-06-18 15:44:11 -07002450 int eventType = parser.getEventType();
2451 while (eventType != XmlPullParser.START_TAG &&
2452 eventType != XmlPullParser.END_DOCUMENT) {
2453 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002454 }
Matthew Williamsba352712013-08-13 15:53:31 -07002455 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002456
Matthew Williamsba352712013-08-13 15:53:31 -07002457 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002458 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002459 if (eventType == XmlPullParser.START_TAG) {
2460 try {
Matthew Williams06485a72013-07-26 12:56:39 -07002461 String tagName = parser.getName();
Matthew Williams8ef22042013-07-26 12:56:39 -07002462 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2463 // Verify version.
2464 String versionString =
2465 parser.getAttributeValue(null, XML_ATTR_VERSION);
2466 if (versionString == null ||
2467 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2468 Log.w(TAG, "Unknown pending operation version " + versionString);
2469 throw new java.io.IOException("Unknown version.");
2470 }
2471 int authorityId = Integer.valueOf(parser.getAttributeValue(
2472 null, XML_ATTR_AUTHORITYID));
2473 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2474 null, XML_ATTR_EXPEDITED));
2475 int syncSource = Integer.valueOf(parser.getAttributeValue(
2476 null, XML_ATTR_SOURCE));
2477 int reason = Integer.valueOf(parser.getAttributeValue(
2478 null, XML_ATTR_REASON));
2479 AuthorityInfo authority = mAuthorities.get(authorityId);
2480 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2481 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2482 + reason);
2483 }
2484 if (authority != null) {
2485 pop = new PendingOperation(
2486 authority, reason, syncSource, new Bundle(), expedited);
2487 pop.flatExtras = null; // No longer used.
2488 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002489 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002490 Log.v(TAG_FILE, "Adding pending op: "
2491 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002492 + " src=" + pop.syncSource
2493 + " reason=" + pop.reason
2494 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002495 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002496 } else {
2497 // Skip non-existent authority.
2498 pop = null;
2499 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2500 Log.v(TAG_FILE, "No authority found for " + authorityId
2501 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002502 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002503 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002504 } else if (parser.getDepth() == 2 &&
2505 pop != null &&
2506 "extra".equals(tagName)) {
2507 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002508 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002509 } catch (NumberFormatException e) {
2510 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002511 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002512 }
Matthew Williamsba352712013-08-13 15:53:31 -07002513 eventType = parser.next();
2514 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002515 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002516 Log.w(TAG_FILE, "Error reading pending data.", e);
2517 } catch (XmlPullParserException e) {
2518 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2519 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2520 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002521 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002522 if (fis != null) {
2523 try {
2524 fis.close();
2525 } catch (java.io.IOException e1) {}
2526 }
2527 }
2528 }
Matthew Williamsba352712013-08-13 15:53:31 -07002529
Dianne Hackborn231cc602009-04-27 17:10:36 -07002530 static private byte[] flattenBundle(Bundle bundle) {
2531 byte[] flatData = null;
2532 Parcel parcel = Parcel.obtain();
2533 try {
2534 bundle.writeToParcel(parcel, 0);
2535 flatData = parcel.marshall();
2536 } finally {
2537 parcel.recycle();
2538 }
2539 return flatData;
2540 }
Costin Manolache360e4542009-09-04 13:36:04 -07002541
Dianne Hackborn231cc602009-04-27 17:10:36 -07002542 static private Bundle unflattenBundle(byte[] flatData) {
2543 Bundle bundle;
2544 Parcel parcel = Parcel.obtain();
2545 try {
2546 parcel.unmarshall(flatData, 0, flatData.length);
2547 parcel.setDataPosition(0);
2548 bundle = parcel.readBundle();
2549 } catch (RuntimeException e) {
2550 // A RuntimeException is thrown if we were unable to parse the parcel.
2551 // Create an empty parcel in this case.
2552 bundle = new Bundle();
2553 } finally {
2554 parcel.recycle();
2555 }
2556 return bundle;
2557 }
Costin Manolache360e4542009-09-04 13:36:04 -07002558
Matthew Williams8ef22042013-07-26 12:56:39 -07002559 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002560 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2561 private static final String XML_ATTR_SOURCE = "source";
2562 private static final String XML_ATTR_EXPEDITED = "expedited";
2563 private static final String XML_ATTR_REASON = "reason";
2564
2565 /**
2566 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002567 */
2568 private void writePendingOperationsLocked() {
2569 final int N = mPendingOperations.size();
2570 FileOutputStream fos = null;
2571 try {
2572 if (N == 0) {
2573 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2574 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2575 }
2576 mPendingFile.truncate();
2577 return;
2578 }
2579 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2580 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2581 }
2582 fos = mPendingFile.startWrite();
2583 XmlSerializer out = new FastXmlSerializer();
2584 out.setOutput(fos, "utf-8");
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002585
2586 for (int i = 0; i < N; i++) {
2587 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002588 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002589 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002590 out.endDocument();
2591 mPendingFile.finishWrite(fos);
2592 } catch (java.io.IOException e1) {
2593 Log.w(TAG, "Error writing pending operations", e1);
2594 if (fos != null) {
2595 mPendingFile.failWrite(fos);
2596 }
2597 }
2598 }
2599
Matthew Williams8ef22042013-07-26 12:56:39 -07002600 /** Write all currently pending ops to the pending ops file. */
2601 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2602 throws IOException {
2603 // Pending operation.
2604 out.startTag(null, "op");
2605
2606 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2607 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2608 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2609 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2610 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2611 extrasToXml(out, pop.extras);
2612
2613 out.endTag(null, "op");
2614 }
2615
2616 /**
2617 * Append the given operation to the pending ops file; if unable to,
2618 * write all pending ops.
2619 */
2620 private void appendPendingOperationLocked(PendingOperation op) {
2621 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2622 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2623 }
2624 FileOutputStream fos = null;
2625 try {
2626 fos = mPendingFile.openAppend();
2627 } catch (java.io.IOException e) {
2628 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2629 Log.v(TAG, "Failed append; writing full file");
2630 }
2631 writePendingOperationsLocked();
2632 return;
2633 }
2634
2635 try {
2636 XmlSerializer out = new FastXmlSerializer();
2637 out.setOutput(fos, "utf-8");
2638 writePendingOperationLocked(op, out);
2639 out.endDocument();
2640 mPendingFile.finishWrite(fos);
2641 } catch (java.io.IOException e1) {
2642 Log.w(TAG, "Error writing appending operation", e1);
2643 mPendingFile.failWrite(fos);
2644 } finally {
2645 try {
2646 fos.close();
2647 } catch (IOException e) {}
2648 }
2649 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002650
Matthew Williamsfa774182013-06-18 15:44:11 -07002651 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2652 for (String key : extras.keySet()) {
2653 out.startTag(null, "extra");
2654 out.attribute(null, "name", key);
2655 final Object value = extras.get(key);
2656 if (value instanceof Long) {
2657 out.attribute(null, "type", "long");
2658 out.attribute(null, "value1", value.toString());
2659 } else if (value instanceof Integer) {
2660 out.attribute(null, "type", "integer");
2661 out.attribute(null, "value1", value.toString());
2662 } else if (value instanceof Boolean) {
2663 out.attribute(null, "type", "boolean");
2664 out.attribute(null, "value1", value.toString());
2665 } else if (value instanceof Float) {
2666 out.attribute(null, "type", "float");
2667 out.attribute(null, "value1", value.toString());
2668 } else if (value instanceof Double) {
2669 out.attribute(null, "type", "double");
2670 out.attribute(null, "value1", value.toString());
2671 } else if (value instanceof String) {
2672 out.attribute(null, "type", "string");
2673 out.attribute(null, "value1", value.toString());
2674 } else if (value instanceof Account) {
2675 out.attribute(null, "type", "account");
2676 out.attribute(null, "value1", ((Account)value).name);
2677 out.attribute(null, "value2", ((Account)value).type);
2678 }
2679 out.endTag(null, "extra");
2680 }
2681 }
2682
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002683 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2684 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2685 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002686 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002687 } else {
2688 SyncRequest.Builder req =
2689 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002690 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002691 .setExtras(extras);
2692 if (authorityInfo.target.target_provider) {
2693 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002694 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002695 if (Log.isLoggable(TAG, Log.DEBUG)) {
2696 Log.d(TAG, "Unknown target, skipping sync request.");
2697 }
2698 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002699 }
2700 ContentResolver.requestSync(req.build());
2701 }
2702 }
2703
Alon Albert57286f92012-10-09 14:21:38 -07002704 private void requestSync(Account account, int userId, int reason, String authority,
2705 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002706 // If this is happening in the system process, then call the syncrequest listener
2707 // to make a request back to the SyncManager directly.
2708 // If this is probably a test instance, then call back through the ContentResolver
2709 // which will know which userId to apply based on the Binder id.
2710 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2711 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002712 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002713 new EndPoint(account, authority, userId),
2714 reason,
2715 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002716 } else {
2717 ContentResolver.requestSync(account, authority, extras);
2718 }
2719 }
2720
Dianne Hackborn231cc602009-04-27 17:10:36 -07002721 public static final int STATISTICS_FILE_END = 0;
2722 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2723 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002724
Dianne Hackborn231cc602009-04-27 17:10:36 -07002725 /**
2726 * Read all sync statistics back in to the initial engine state.
2727 */
2728 private void readStatisticsLocked() {
2729 try {
2730 byte[] data = mStatisticsFile.readFully();
2731 Parcel in = Parcel.obtain();
2732 in.unmarshall(data, 0, data.length);
2733 in.setDataPosition(0);
2734 int token;
2735 int index = 0;
2736 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2737 if (token == STATISTICS_FILE_ITEM
2738 || token == STATISTICS_FILE_ITEM_OLD) {
2739 int day = in.readInt();
2740 if (token == STATISTICS_FILE_ITEM_OLD) {
2741 day = day - 2009 + 14245; // Magic!
2742 }
2743 DayStats ds = new DayStats(day);
2744 ds.successCount = in.readInt();
2745 ds.successTime = in.readLong();
2746 ds.failureCount = in.readInt();
2747 ds.failureTime = in.readLong();
2748 if (index < mDayStats.length) {
2749 mDayStats[index] = ds;
2750 index++;
2751 }
2752 } else {
2753 // Ooops.
2754 Log.w(TAG, "Unknown stats token: " + token);
2755 break;
2756 }
2757 }
2758 } catch (java.io.IOException e) {
2759 Log.i(TAG, "No initial statistics");
2760 }
2761 }
Costin Manolache360e4542009-09-04 13:36:04 -07002762
Dianne Hackborn231cc602009-04-27 17:10:36 -07002763 /**
2764 * Write all sync statistics to the sync status file.
2765 */
2766 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002767 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2768 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2769 }
Costin Manolache360e4542009-09-04 13:36:04 -07002770
Dianne Hackborn231cc602009-04-27 17:10:36 -07002771 // The file is being written, so we don't need to have a scheduled
2772 // write until the next change.
2773 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002774
Dianne Hackborn231cc602009-04-27 17:10:36 -07002775 FileOutputStream fos = null;
2776 try {
2777 fos = mStatisticsFile.startWrite();
2778 Parcel out = Parcel.obtain();
2779 final int N = mDayStats.length;
2780 for (int i=0; i<N; i++) {
2781 DayStats ds = mDayStats[i];
2782 if (ds == null) {
2783 break;
2784 }
2785 out.writeInt(STATISTICS_FILE_ITEM);
2786 out.writeInt(ds.day);
2787 out.writeInt(ds.successCount);
2788 out.writeLong(ds.successTime);
2789 out.writeInt(ds.failureCount);
2790 out.writeLong(ds.failureTime);
2791 }
2792 out.writeInt(STATISTICS_FILE_END);
2793 fos.write(out.marshall());
2794 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002795
Dianne Hackborn231cc602009-04-27 17:10:36 -07002796 mStatisticsFile.finishWrite(fos);
2797 } catch (java.io.IOException e1) {
2798 Log.w(TAG, "Error writing stats", e1);
2799 if (fos != null) {
2800 mStatisticsFile.failWrite(fos);
2801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 }
2803 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002804
2805 /**
2806 * Dump state of PendingOperations.
2807 */
2808 public void dumpPendingOperations(StringBuilder sb) {
2809 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2810 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002811 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002812 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002813 .append(")\n");
2814 }
2815 }
Marvin Paula6533252014-11-24 12:57:48 -08002816
2817 /**
2818 * Let the BackupManager know that account sync settings have changed. This will trigger
2819 * {@link com.android.server.backup.SystemBackupAgent} to run.
2820 */
2821 public void queueBackup() {
2822 BackupManager.dataChanged("android");
2823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824}