blob: d68b615899d679f87a8d16ab2343b1fe31fcea99 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070042import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080044import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070045import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070046import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070047import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080048
49import com.android.internal.annotations.VisibleForTesting;
50import com.android.internal.util.ArrayUtils;
51import com.android.internal.util.FastXmlSerializer;
52
53import org.xmlpull.v1.XmlPullParser;
54import org.xmlpull.v1.XmlPullParserException;
55import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.io.File;
58import java.io.FileInputStream;
59import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070060import java.io.IOException;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010061import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070065import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080066import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070067import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060068import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
70/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070071 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070073 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * @hide
75 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070076public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070079 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070080
Amith Yamasani04e0d262012-02-14 11:50:53 -080081 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
82 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070083 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080084 private static final String XML_ATTR_ENABLED = "enabled";
85 private static final String XML_ATTR_USER = "user";
86 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
87
Matthew Williamsfa774182013-06-18 15:44:11 -070088 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080089 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
90
Matthew Williamsfa774182013-06-18 15:44:11 -070091 /** Percentage of period that is flex by default, if no flex is set. */
92 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
93
94 /** Lower bound on sync time from which we assign a default flex time. */
95 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
96
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080097 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a sync start event. */
101 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a sync stop event. */
104 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 // TODO: i18n -- grab these out of resources.
107 /** String names for the sync event types. */
108 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Dianne Hackborn231cc602009-04-27 17:10:36 -0700110 /** Enum value for a server-initiated sync. */
111 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Dianne Hackborn231cc602009-04-27 17:10:36 -0700113 /** Enum value for a local-initiated sync. */
114 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700115 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Dianne Hackborn231cc602009-04-27 17:10:36 -0700118 /** Enum value for a user-initiated sync. */
119 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800121 /** Enum value for a periodic sync. */
122 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700123
124 /** Enum value for a sync started for a service. */
125 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800126
Fred Quintana307da1a2010-01-21 14:24:20 -0800127 public static final long NOT_IN_BACKOFF_MODE = -1;
128
Dianne Hackborn231cc602009-04-27 17:10:36 -0700129 // TODO: i18n -- grab these out of resources.
130 /** String names for the sync source types. */
131 public static final String[] SOURCES = { "SERVER",
132 "LOCAL",
133 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800134 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700135 "PERIODIC",
136 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Dianne Hackborn231cc602009-04-27 17:10:36 -0700138 // The MESG column will contain one of these or one of the Error types.
139 public static final String MESG_SUCCESS = "success";
140 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700142 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700143
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 private static final int MSG_WRITE_STATUS = 1;
145 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700146
Dianne Hackborn231cc602009-04-27 17:10:36 -0700147 private static final int MSG_WRITE_STATISTICS = 2;
148 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700149
150 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700151
Fred Quintanac2e46912010-03-15 16:10:44 -0700152 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700153 private static final int ACCOUNTS_VERSION = 2;
154
155 private static HashMap<String, String> sAuthorityRenames;
156
157 static {
158 sAuthorityRenames = new HashMap<String, String>();
159 sAuthorityRenames.put("contacts", "com.android.contacts");
160 sAuthorityRenames.put("calendar", "com.android.calendar");
161 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700162
Dianne Hackborn231cc602009-04-27 17:10:36 -0700163 public static class PendingOperation {
Matthew Williams8ef22042013-07-26 12:56:39 -0700164 final EndPoint target;
Alon Albert57286f92012-10-09 14:21:38 -0700165 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700166 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800168 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700169
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700170 final int authorityId;
171 // No longer used.
172 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700173 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700174
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700175 PendingOperation(AuthorityInfo authority, int reason, int source,
176 Bundle extras, boolean expedited) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700177 this.target = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700179 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800181 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700182 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700183 }
184
185 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700186 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 this.syncSource = other.syncSource;
Matthew Williams8ef22042013-07-26 12:56:39 -0700188 this.target = other.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700189 this.extras = other.extras;
190 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800191 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
193
194 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700195 * Considered equal if they target the same sync adapter (A
196 * {@link android.content.SyncService}
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700197 * is considered an adapter), for the same userId.
198 * @param other PendingOperation to compare.
199 * @return true if the two pending ops are the same.
200 */
201 public boolean equals(PendingOperation other) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700202 return target.matchesSpec(other.target);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700203 }
204
205 public String toString() {
Matthew Williams8ef22042013-07-26 12:56:39 -0700206 return "service=" + target.service
207 + " user=" + target.userId
208 + " auth=" + target
209 + " account=" + target.account
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700210 + " src=" + syncSource
211 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
Costin Manolache360e4542009-09-04 13:36:04 -0700214
Dianne Hackborn231cc602009-04-27 17:10:36 -0700215 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700217 final HashMap<String, AuthorityInfo> authorities =
218 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700219
Amith Yamasani04e0d262012-02-14 11:50:53 -0800220 AccountInfo(AccountAndUser accountAndUser) {
221 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700222 }
223 }
Costin Manolache360e4542009-09-04 13:36:04 -0700224
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700225 /** Bare bones representation of a sync target. */
226 public static class EndPoint {
227 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
228 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700229 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700230 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800231 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700232 final String provider;
233 final boolean target_service;
234 final boolean target_provider;
235
236 public EndPoint(ComponentName service, int userId) {
237 this.service = service;
238 this.userId = userId;
239 this.account = null;
240 this.provider = null;
241 this.target_service = true;
242 this.target_provider = false;
243 }
244
245 public EndPoint(Account account, String provider, int userId) {
246 this.account = account;
247 this.provider = provider;
248 this.userId = userId;
249 this.service = null;
250 this.target_service = false;
251 this.target_provider = true;
252 }
253
254 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700255 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
256 *
257 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
258 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700259 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700260 public boolean matchesSpec(EndPoint spec) {
261 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700262 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700263 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700264 return false;
265 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700266 if (target_service && spec.target_service) {
267 return service.equals(spec.service);
268 } else if (target_provider && spec.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 boolean accountsMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700270 if (spec.account == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 accountsMatch = true;
272 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700273 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700274 }
275 boolean providersMatch;
Matthew Williams8ef22042013-07-26 12:56:39 -0700276 if (spec.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700277 providersMatch = true;
278 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -0700279 providersMatch = provider.equals(spec.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700280 }
281 return accountsMatch && providersMatch;
282 }
283 return false;
284 }
285
286 public String toString() {
287 StringBuilder sb = new StringBuilder();
288 if (target_provider) {
289 sb.append(account == null ? "ALL ACCS" : account.name)
290 .append("/")
291 .append(provider == null ? "ALL PDRS" : provider);
292 } else if (target_service) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700293 sb.append(service.getPackageName() + "/")
294 .append(service.getClassName());
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700295 } else {
296 sb.append("invalid target");
297 }
Matthew Williams8ef22042013-07-26 12:56:39 -0700298 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700299 return sb.toString();
300 }
301 }
302
303 public static class AuthorityInfo {
Matthew Williams8ef22042013-07-26 12:56:39 -0700304 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700305 final int ident;
306 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700307 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700308 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800309 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700310 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800311 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700312 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800313 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700314
Matthew Williamsfa774182013-06-18 15:44:11 -0700315 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700316
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700317 /**
318 * Copy constructor for making deep-ish copies. Only the bundles stored
319 * in periodic syncs can make unexpected changes.
320 *
321 * @param toCopy AuthorityInfo to be copied.
322 */
323 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700324 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700325 ident = toCopy.ident;
326 enabled = toCopy.enabled;
327 syncable = toCopy.syncable;
328 backoffTime = toCopy.backoffTime;
329 backoffDelay = toCopy.backoffDelay;
330 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700331 periodicSyncs = new ArrayList<PeriodicSync>();
332 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700333 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700334 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700335 }
336 }
337
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700338 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700339 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700340 ident = id;
341 enabled = info.target_provider ?
342 SYNC_ENABLED_DEFAULT : true;
343 // Service is active by default,
344 if (info.target_service) {
345 this.syncable = 1;
346 }
347 periodicSyncs = new ArrayList<PeriodicSync>();
348 defaultInitialisation();
349 }
350
351 private void defaultInitialisation() {
Fred Quintana4a6679b2009-08-17 13:05:39 -0700352 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800353 backoffTime = -1; // if < 0 then we aren't in backoff mode
354 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700355 PeriodicSync defaultSync;
356 // Old version is one sync a day. Empty bundle gets replaced by any addPeriodicSync()
357 // call.
Matthew Williams8ef22042013-07-26 12:56:39 -0700358 if (target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700359 defaultSync =
Matthew Williams8ef22042013-07-26 12:56:39 -0700360 new PeriodicSync(target.account, target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700361 new Bundle(),
362 DEFAULT_POLL_FREQUENCY_SECONDS,
363 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
364 periodicSyncs.add(defaultSync);
365 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700366 }
Matthew Williams06485a72013-07-26 12:56:39 -0700367
368 @Override
369 public String toString() {
370 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
371 + backoffTime + ", delay=" + delayUntil;
372 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700373 }
Costin Manolache360e4542009-09-04 13:36:04 -0700374
Dianne Hackborn231cc602009-04-27 17:10:36 -0700375 public static class SyncHistoryItem {
376 int authorityId;
377 int historyId;
378 long eventTime;
379 long elapsedTime;
380 int source;
381 int event;
382 long upstreamActivity;
383 long downstreamActivity;
384 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700385 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700386 Bundle extras;
387 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700388 }
Costin Manolache360e4542009-09-04 13:36:04 -0700389
Dianne Hackborn231cc602009-04-27 17:10:36 -0700390 public static class DayStats {
391 public final int day;
392 public int successCount;
393 public long successTime;
394 public int failureCount;
395 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700396
Dianne Hackborn231cc602009-04-27 17:10:36 -0700397 public DayStats(int day) {
398 this.day = day;
399 }
400 }
Costin Manolache360e4542009-09-04 13:36:04 -0700401
Amith Yamasani04e0d262012-02-14 11:50:53 -0800402 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700403
404 /** Called when a sync is needed on an account(s) due to some change in state. */
405 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 }
407
Dianne Hackborn231cc602009-04-27 17:10:36 -0700408 // Primary list of all syncable authorities. Also our global lock.
409 private final SparseArray<AuthorityInfo> mAuthorities =
410 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700411
Amith Yamasani04e0d262012-02-14 11:50:53 -0800412 private final HashMap<AccountAndUser, AccountInfo> mAccounts
413 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 private final ArrayList<PendingOperation> mPendingOperations =
416 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700417
Amith Yamasani04e0d262012-02-14 11:50:53 -0800418 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
419 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700420
Dianne Hackborn231cc602009-04-27 17:10:36 -0700421 private final SparseArray<SyncStatusInfo> mSyncStatus =
422 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 private final ArrayList<SyncHistoryItem> mSyncHistory =
425 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
428 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700429
Matthew Williams8ef22042013-07-26 12:56:39 -0700430 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700431 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
432 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700433
Fred Quintana77c560f2010-03-29 22:20:26 -0700434 private int mNextAuthorityId = 0;
435
Dianne Hackborn231cc602009-04-27 17:10:36 -0700436 // We keep 4 weeks of stats.
437 private final DayStats[] mDayStats = new DayStats[7*4];
438 private final Calendar mCal;
439 private int mYear;
440 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700441
Dianne Hackborn231cc602009-04-27 17:10:36 -0700442 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Ashish Sharma69d95de2012-04-11 17:27:24 -0700446 private int mSyncRandomOffset;
447
Dianne Hackborn231cc602009-04-27 17:10:36 -0700448 /**
449 * This file contains the core engine state: all accounts and the
450 * settings for them. It must never be lost, and should be changed
451 * infrequently, so it is stored as an XML file.
452 */
453 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700454
Dianne Hackborn231cc602009-04-27 17:10:36 -0700455 /**
456 * This file contains the current sync status. We would like to retain
457 * it across boots, but its loss is not the end of the world, so we store
458 * this information as binary data.
459 */
460 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700461
Dianne Hackborn231cc602009-04-27 17:10:36 -0700462 /**
463 * This file contains sync statistics. This is purely debugging information
464 * so is written infrequently and can be thrown away at any time.
465 */
466 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700467
Dianne Hackborn231cc602009-04-27 17:10:36 -0700468 /**
469 * This file contains the pending sync operations. It is a binary file,
470 * which must be updated every time an operation is added or removed,
471 * so we have special handling of it.
472 */
473 private final AtomicFile mPendingFile;
474 private static final int PENDING_FINISH_TO_WRITE = 4;
475 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700476
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800478 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800479 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480
481 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700482
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800483 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700486
Dianne Hackborn231cc602009-04-27 17:10:36 -0700487 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700488
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800489 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
490 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
491
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 File systemDir = new File(dataDir, "system");
493 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800494 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700495
496 maybeDeleteLegacyPendingInfoLocked(syncDir);
497
Dianne Hackborn231cc602009-04-27 17:10:36 -0700498 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
499 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700500 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700501 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700502
Dianne Hackborn231cc602009-04-27 17:10:36 -0700503 readAccountInfoLocked();
504 readStatusLocked();
505 readPendingOperationsLocked();
506 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700507 readAndDeleteLegacyAccountInfoLocked();
508 writeAccountInfoLocked();
509 writeStatusLocked();
510 writePendingOperationsLocked();
511 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513
514 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800515 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 }
517
518 public static void init(Context context) {
519 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800520 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800522 // This call will return the correct directory whether Encrypted File Systems is
523 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600524 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800525 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 }
527
528 public static SyncStorageEngine getSingleton() {
529 if (sSyncStorageEngine == null) {
530 throw new IllegalStateException("not initialized");
531 }
532 return sSyncStorageEngine;
533 }
534
Amith Yamasani04e0d262012-02-14 11:50:53 -0800535 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
536 if (mSyncRequestListener == null) {
537 mSyncRequestListener = listener;
538 }
539 }
540
Dianne Hackborn231cc602009-04-27 17:10:36 -0700541 @Override public void handleMessage(Message msg) {
542 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700543 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700545 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700546 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700547 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700548 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
550 }
551 }
Costin Manolache360e4542009-09-04 13:36:04 -0700552
Ashish Sharma69d95de2012-04-11 17:27:24 -0700553 public int getSyncRandomOffset() {
554 return mSyncRandomOffset;
555 }
556
Dianne Hackborn231cc602009-04-27 17:10:36 -0700557 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
558 synchronized (mAuthorities) {
559 mChangeListeners.register(callback, mask);
560 }
561 }
Costin Manolache360e4542009-09-04 13:36:04 -0700562
Dianne Hackborn231cc602009-04-27 17:10:36 -0700563 public void removeStatusChangeListener(ISyncStatusObserver callback) {
564 synchronized (mAuthorities) {
565 mChangeListeners.unregister(callback);
566 }
567 }
Costin Manolache360e4542009-09-04 13:36:04 -0700568
Matthew Williamsfa774182013-06-18 15:44:11 -0700569 /**
570 * Figure out a reasonable flex time for cases where none is provided (old api calls).
571 * @param syncTimeSeconds requested sync time from now.
572 * @return amount of seconds before syncTimeSeconds that the sync can occur.
573 * I.e.
574 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700575 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700576 */
577 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
578 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
579 // Small enough sync request time that we don't add flex time - developer probably
580 // wants to wait for an operation to occur before syncing so we honour the
581 // request time.
582 return 0L;
583 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
584 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
585 } else {
586 // Large enough sync request time that we cap the flex time.
587 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
588 }
589 }
590
Dianne Hackborn231cc602009-04-27 17:10:36 -0700591 private void reportChange(int which) {
592 ArrayList<ISyncStatusObserver> reports = null;
593 synchronized (mAuthorities) {
594 int i = mChangeListeners.beginBroadcast();
595 while (i > 0) {
596 i--;
597 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
598 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 continue;
600 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700601 if (reports == null) {
602 reports = new ArrayList<ISyncStatusObserver>(i);
603 }
604 reports.add(mChangeListeners.getBroadcastItem(i));
605 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700606 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700607 }
Costin Manolache360e4542009-09-04 13:36:04 -0700608
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700610 Log.v(TAG, "reportChange " + which + " to: " + reports);
611 }
Costin Manolache360e4542009-09-04 13:36:04 -0700612
Dianne Hackborn231cc602009-04-27 17:10:36 -0700613 if (reports != null) {
614 int i = reports.size();
615 while (i > 0) {
616 i--;
617 try {
618 reports.get(i).onStatusChanged(which);
619 } catch (RemoteException e) {
620 // The remote callback list will take care of this for us.
621 }
622 }
623 }
624 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700625
Amith Yamasani04e0d262012-02-14 11:50:53 -0800626 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700627 synchronized (mAuthorities) {
628 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700629 AuthorityInfo authority = getAuthorityLocked(
630 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700631 "getSyncAutomatically");
632 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700633 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700634
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 int i = mAuthorities.size();
636 while (i > 0) {
637 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700638 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700639 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700640 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700641 return true;
642 }
643 }
644 return false;
645 }
646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647
Amith Yamasani04e0d262012-02-14 11:50:53 -0800648 public void setSyncAutomatically(Account account, int userId, String providerName,
649 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800651 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
652 + ", user " + userId + " -> " + sync);
653 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700654 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700655 AuthorityInfo authority =
656 getOrCreateAuthorityLocked(
657 new EndPoint(account, providerName, userId),
658 -1 /* ident */,
659 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700660 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800662 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
663 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700664 return;
665 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700666 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700667 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700669
Fred Quintana77c560f2010-03-29 22:20:26 -0700670 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700671 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
672 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700673 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700674 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800675 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700679 synchronized (mAuthorities) {
680 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700681 AuthorityInfo authority = getAuthorityLocked(
682 new EndPoint(account, providerName, userId),
683 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700684 if (authority == null) {
685 return -1;
686 }
687 return authority.syncable;
688 }
689
690 int i = mAuthorities.size();
691 while (i > 0) {
692 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700693 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700694 if (authorityInfo.target != null
695 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700696 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700697 }
698 }
699 return -1;
700 }
701 }
702
Amith Yamasani04e0d262012-02-14 11:50:53 -0800703 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700704 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700705 }
706
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700707 public boolean getIsTargetServiceActive(ComponentName cname, int userId) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700708 synchronized (mAuthorities) {
709 if (cname != null) {
710 AuthorityInfo authority = getAuthorityLocked(
711 new EndPoint(cname, userId),
Matthew Williams8ef22042013-07-26 12:56:39 -0700712 "get service active");
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700713 if (authority == null) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700714 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700715 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700716 return (authority.syncable == 1);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700717 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700718 return false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700719 }
720 }
721
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700722 public void setIsTargetServiceActive(ComponentName cname, int userId, boolean active) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700723 setSyncableStateForEndPoint(new EndPoint(cname, userId), active ? 1 : 0);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700724 }
725
726 /**
727 * An enabled sync service and a syncable provider's adapter both get resolved to the same
728 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700729 * @param target target to set value for.
730 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700731 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700732 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700733 AuthorityInfo aInfo;
734 synchronized (mAuthorities) {
735 aInfo = getOrCreateAuthorityLocked(target, -1, false);
736 if (syncable > 1) {
737 syncable = 1;
738 } else if (syncable < -1) {
739 syncable = -1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700740 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700741 if (Log.isLoggable(TAG, Log.VERBOSE)) {
742 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
743 }
744 if (aInfo.syncable == syncable) {
745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
746 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
747 }
748 return;
749 }
750 aInfo.syncable = syncable;
751 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700752 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700753 if (syncable > 0) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700754 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700755 }
756 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
757 }
758
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700759 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800760 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700761 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
762 if (authority != null) {
763 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800764 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700765 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800766 }
767 }
768
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700769 /**
770 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
771 * the account or provider info be null, which signifies all accounts or providers.
772 */
773 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
775 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800776 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
777 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700778 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800779 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700780 if (info.target_provider
781 && (info.account == null || info.provider == null)) {
782 // Do more work for a provider sync if the provided info has specified all
783 // accounts/providers.
784 changed = setBackoffLocked(
785 info.account /* may be null */,
786 info.userId,
787 info.provider /* may be null */,
788 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800789 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700790 AuthorityInfo authorityInfo =
791 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
792 if (authorityInfo.backoffTime == nextSyncTime
793 && authorityInfo.backoffDelay == nextDelay) {
794 changed = false;
795 } else {
796 authorityInfo.backoffTime = nextSyncTime;
797 authorityInfo.backoffDelay = nextDelay;
798 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800800 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800801 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800802 if (changed) {
803 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
804 }
805 }
806
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700807 /**
808 * Either set backoff for a specific authority, or set backoff for all the
809 * accounts on a specific adapter/all adapters.
810 *
811 * @param account account for which to set backoff. Null to specify all accounts.
812 * @param userId id of the user making this request.
813 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700814 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700815 */
816 private boolean setBackoffLocked(Account account, int userId, String providerName,
817 long nextSyncTime, long nextDelay) {
818 boolean changed = false;
819 for (AccountInfo accountInfo : mAccounts.values()) {
820 if (account != null && !account.equals(accountInfo.accountAndUser.account)
821 && userId != accountInfo.accountAndUser.userId) {
822 continue;
823 }
824 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
825 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700826 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700827 continue;
828 }
829 if (authorityInfo.backoffTime != nextSyncTime
830 || authorityInfo.backoffDelay != nextDelay) {
831 authorityInfo.backoffTime = nextSyncTime;
832 authorityInfo.backoffDelay = nextDelay;
833 changed = true;
834 }
835 }
836 }
837 return changed;
838 }
839
Matthew Williams119aac92014-09-28 20:42:23 -0700840 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800841 boolean changed = false;
842 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700843 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700844 for (AccountInfo accountInfo : mAccounts.values()) {
845 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
846 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
847 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700848 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams119aac92014-09-28 20:42:23 -0700849 Log.v(TAG, "clearAllBackoffsLocked:"
Matthew Williams8ef22042013-07-26 12:56:39 -0700850 + " authority:" + authorityInfo.target
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700851 + " account:" + accountInfo.accountAndUser.account.name
852 + " user:" + accountInfo.accountAndUser.userId
853 + " backoffTime was: " + authorityInfo.backoffTime
854 + " backoffDelay was: " + authorityInfo.backoffDelay);
855 }
856 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
857 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700858 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800859 }
Alon Albert744e310f2010-12-14 11:37:20 -0800860 }
861 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700862 // Clear backoff for all sync services.
863 for (ComponentName service : mServices.keySet()) {
864 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
865 for (int i = 0; i < aInfos.size(); i++) {
866 AuthorityInfo authorityInfo = aInfos.valueAt(i);
867 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
868 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
869 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
870 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
871 }
872 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700873 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800874 }
875 }
876
877 if (changed) {
878 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
879 }
880 }
881
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700882 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800883 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700884 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800885 if (authority == null) {
886 return 0;
887 }
888 return authority.delayUntil;
889 }
890 }
891
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700892 public void setDelayUntilTime(EndPoint info, long delayUntil) {
893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
894 Log.v(TAG, "setDelayUntil: " + info
895 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800896 }
897 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700898 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
899 if (authority.delayUntil == delayUntil) {
900 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700901 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700902 authority.delayUntil = delayUntil;
903 }
904 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
905 }
906
907 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
908 if (Log.isLoggable(TAG, Log.VERBOSE)) {
909 Log.v(TAG, "addPeriodicSync: " + info
910 + " -> period " + period + ", flex " + flextime + ", extras "
911 + extras.toString());
912 }
913 synchronized (mAuthorities) {
914 if (period <= 0) {
915 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
916 }
917 if (extras == null) {
918 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700919 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700920 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700921 PeriodicSync toUpdate;
922 if (info.target_provider) {
923 toUpdate = new PeriodicSync(info.account,
924 info.provider,
925 extras,
926 period,
927 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700928 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -0700929 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700930 }
931 AuthorityInfo authority =
932 getOrCreateAuthorityLocked(info, -1, false);
933 // add this periodic sync if an equivalent periodic doesn't already exist.
934 boolean alreadyPresent = false;
935 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
936 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
937 if (SyncManager.syncExtrasEquals(syncInfo.extras,
938 extras,
939 true /* includeSyncSettings*/)) {
940 if (period == syncInfo.period &&
941 flextime == syncInfo.flexTime) {
942 // Absolutely the same.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700943 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700944 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700945 authority.periodicSyncs.set(i, toUpdate);
946 alreadyPresent = true;
947 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700948 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700949 }
950 // If we added an entry to the periodicSyncs array also add an entry to
951 // the periodic syncs status to correspond to it.
952 if (!alreadyPresent) {
953 authority.periodicSyncs.add(toUpdate);
954 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
955 // A new periodic sync is initialised as already having been run.
956 status.setPeriodicSyncTime(
957 authority.periodicSyncs.size() - 1,
958 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800959 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700960 } finally {
961 writeAccountInfoLocked();
962 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800963 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800964 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800965 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
966 }
967
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700968 public void removePeriodicSync(EndPoint info, Bundle extras) {
969 synchronized(mAuthorities) {
970 try {
971 AuthorityInfo authority =
972 getOrCreateAuthorityLocked(info, -1, false);
Matthew Williams8ef22042013-07-26 12:56:39 -0700973 // Remove any periodic syncs that match the target and extras.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700974 SyncStatusInfo status = mSyncStatus.get(authority.ident);
975 boolean changed = false;
976 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
977 int i = 0;
978 while (iterator.hasNext()) {
979 PeriodicSync syncInfo = iterator.next();
980 if (SyncManager.syncExtrasEquals(syncInfo.extras,
981 extras,
982 true /* includeSyncSettings */)) {
983 iterator.remove();
984 changed = true;
985 // If we removed an entry from the periodicSyncs array also
986 // remove the corresponding entry from the status
987 if (status != null) {
988 status.removePeriodicSyncTime(i);
989 } else {
990 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
991 + " did not find it.");
992 }
993 } else {
994 i++;
995 }
996 }
997 if (!changed) {
998 return;
999 }
1000 } finally {
1001 writeAccountInfoLocked();
1002 writeStatusLocked();
1003 }
1004 }
1005 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001006 }
1007
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001008 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001009 * @return list of periodic syncs for a target. Never null. If no such syncs exist, returns an
1010 * empty list.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001011 */
1012 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001013 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001014 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1015 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1016 if (authorityInfo != null) {
1017 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001018 // Copy and send out. Necessary for thread-safety although it's parceled.
1019 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001020 }
1021 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001022 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001023 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001024 }
1025
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001027 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001028 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001029 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001030 return;
1031 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001032 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 writeAccountInfoLocked();
1034 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001035 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001036 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1037 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001038 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001039 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001040 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -08001041 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043
Amith Yamasani04e0d262012-02-14 11:50:53 -08001044 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001045 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001046 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001047 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 }
1049 }
Costin Manolache360e4542009-09-04 13:36:04 -07001050
Dianne Hackborn231cc602009-04-27 17:10:36 -07001051 public AuthorityInfo getAuthority(int authorityId) {
1052 synchronized (mAuthorities) {
1053 return mAuthorities.get(authorityId);
1054 }
1055 }
Costin Manolache360e4542009-09-04 13:36:04 -07001056
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001058 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001059 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001061 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001062 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001063 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001064 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001065 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 return true;
1067 }
1068 }
1069 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001070 return false;
1071 }
Costin Manolache360e4542009-09-04 13:36:04 -07001072
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001073 public PendingOperation insertIntoPending(SyncOperation op) {
1074 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001076 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1077 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001078 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001079 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001080 final EndPoint info = op.target;
1081 AuthorityInfo authority =
1082 getOrCreateAuthorityLocked(info,
1083 -1 /* desired identifier */,
1084 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001085 if (authority == null) {
1086 return null;
1087 }
Costin Manolache360e4542009-09-04 13:36:04 -07001088
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001089 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
Matthew Williams64280462014-01-09 10:49:23 -08001090 op.isExpedited());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001091 mPendingOperations.add(pop);
Matthew Williams06485a72013-07-26 12:56:39 -07001092 appendPendingOperationLocked(pop);
Costin Manolache360e4542009-09-04 13:36:04 -07001093
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1095 status.pending = true;
1096 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001097 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001098 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001099 }
1100
Matthew Williamsfa774182013-06-18 15:44:11 -07001101 /**
1102 * Remove from list of pending operations. If successful, search through list for matching
Matthew Williams8ef22042013-07-26 12:56:39 -07001103 * authorities. If there are no more pending syncs for the same target,
1104 * update the SyncStatusInfo for that target.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001105 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001106 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001107 public boolean deleteFromPending(PendingOperation op) {
1108 boolean res = false;
1109 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001110 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1111 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001112 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001113 if (mPendingOperations.remove(op)) {
1114 if (mPendingOperations.size() == 0
1115 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1116 writePendingOperationsLocked();
1117 mNumPendingFinished = 0;
1118 } else {
1119 mNumPendingFinished++;
1120 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001121 AuthorityInfo authority = getAuthorityLocked(op.target, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1124 Log.v(TAG, "removing - " + authority.toString());
1125 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001126 final int N = mPendingOperations.size();
1127 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001128 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001129 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001130 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 morePending = true;
1132 break;
1133 }
1134 }
Costin Manolache360e4542009-09-04 13:36:04 -07001135
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001137 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1139 status.pending = false;
1140 }
1141 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 res = true;
1143 }
1144 }
Costin Manolache360e4542009-09-04 13:36:04 -07001145
Fred Quintanaac9385e2009-06-22 18:00:59 -07001146 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 return res;
1148 }
1149
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 /**
1151 * Return a copy of the current array of pending operations. The
1152 * PendingOperation objects are the real objects stored inside, so that
1153 * they can be used with deleteFromPending().
1154 */
1155 public ArrayList<PendingOperation> getPendingOperations() {
1156 synchronized (mAuthorities) {
1157 return new ArrayList<PendingOperation>(mPendingOperations);
1158 }
1159 }
Costin Manolache360e4542009-09-04 13:36:04 -07001160
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 /**
1162 * Return the number of currently pending operations.
1163 */
1164 public int getPendingOperationCount() {
1165 synchronized (mAuthorities) {
1166 return mPendingOperations.size();
1167 }
1168 }
Costin Manolache360e4542009-09-04 13:36:04 -07001169
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 /**
1171 * Called when the set of account has changed, given the new array of
1172 * active accounts.
1173 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001174 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001176 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1177 Log.v(TAG, "Updating for new accounts...");
1178 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001179 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1180 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1181 while (accIt.hasNext()) {
1182 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001183 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1184 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001186 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001187 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001188 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001189 for (AuthorityInfo auth : acc.authorities.values()) {
1190 removing.put(auth.ident, auth);
1191 }
1192 accIt.remove();
1193 }
1194 }
Costin Manolache360e4542009-09-04 13:36:04 -07001195
Dianne Hackborn231cc602009-04-27 17:10:36 -07001196 // Clean out all data structures.
1197 int i = removing.size();
1198 if (i > 0) {
1199 while (i > 0) {
1200 i--;
1201 int ident = removing.keyAt(i);
1202 mAuthorities.remove(ident);
1203 int j = mSyncStatus.size();
1204 while (j > 0) {
1205 j--;
1206 if (mSyncStatus.keyAt(j) == ident) {
1207 mSyncStatus.remove(mSyncStatus.keyAt(j));
1208 }
1209 }
1210 j = mSyncHistory.size();
1211 while (j > 0) {
1212 j--;
1213 if (mSyncHistory.get(j).authorityId == ident) {
1214 mSyncHistory.remove(j);
1215 }
1216 }
1217 }
1218 writeAccountInfoLocked();
1219 writeStatusLocked();
1220 writePendingOperationsLocked();
1221 writeStatisticsLocked();
1222 }
1223 }
1224 }
1225
1226 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001227 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1228 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001229 */
Fred Quintana918339a2010-10-05 14:00:39 -07001230 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1231 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001232 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001233 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001234 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001235 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001236 + " src=" + activeSyncContext.mSyncOperation.syncSource
1237 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001238 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001239 final EndPoint info = activeSyncContext.mSyncOperation.target;
1240 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1241 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001242 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001243 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001244 syncInfo = new SyncInfo(
1245 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001246 authorityInfo.target.account,
1247 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001248 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001249 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001250 }
Fred Quintana918339a2010-10-05 14:00:39 -07001251 reportActiveChange();
1252 return syncInfo;
1253 }
1254
1255 /**
1256 * Called to indicate that a previously active sync is no longer active.
1257 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001258 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001259 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001260 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001261 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1262 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001263 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001264 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001265 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001266 }
1267
1268 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001269 }
1270
1271 /**
1272 * To allow others to send active change reports, to poke clients.
1273 */
1274 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001275 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001276 }
Costin Manolache360e4542009-09-04 13:36:04 -07001277
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001279 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001281 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001282 long id;
1283 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001284 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1285 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001286 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001287 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 if (authority == null) {
1289 return -1;
1290 }
1291 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001292 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001293 item.authorityId = authority.ident;
1294 item.historyId = mNextHistoryId++;
1295 if (mNextHistoryId < 0) mNextHistoryId = 0;
1296 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001297 item.source = op.syncSource;
1298 item.reason = op.reason;
1299 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 item.event = EVENT_START;
1301 mSyncHistory.add(0, item);
1302 while (mSyncHistory.size() > MAX_HISTORY) {
1303 mSyncHistory.remove(mSyncHistory.size()-1);
1304 }
1305 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001306 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 }
Costin Manolache360e4542009-09-04 13:36:04 -07001308
Fred Quintanaac9385e2009-06-22 18:00:59 -07001309 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001310 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312
Fred Quintana77c560f2010-03-29 22:20:26 -07001313 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001316 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001317 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1318 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001319 SyncHistoryItem item = null;
1320 int i = mSyncHistory.size();
1321 while (i > 0) {
1322 i--;
1323 item = mSyncHistory.get(i);
1324 if (item.historyId == historyId) {
1325 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Costin Manolache360e4542009-09-04 13:36:04 -07001329
Dianne Hackborn231cc602009-04-27 17:10:36 -07001330 if (item == null) {
1331 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1332 return;
1333 }
Costin Manolache360e4542009-09-04 13:36:04 -07001334
Dianne Hackborn231cc602009-04-27 17:10:36 -07001335 item.elapsedTime = elapsedTime;
1336 item.event = EVENT_STOP;
1337 item.mesg = resultMessage;
1338 item.downstreamActivity = downstreamActivity;
1339 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001340
Dianne Hackborn231cc602009-04-27 17:10:36 -07001341 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001342
Dianne Hackborn231cc602009-04-27 17:10:36 -07001343 status.numSyncs++;
1344 status.totalElapsedTime += elapsedTime;
1345 switch (item.source) {
1346 case SOURCE_LOCAL:
1347 status.numSourceLocal++;
1348 break;
1349 case SOURCE_POLL:
1350 status.numSourcePoll++;
1351 break;
1352 case SOURCE_USER:
1353 status.numSourceUser++;
1354 break;
1355 case SOURCE_SERVER:
1356 status.numSourceServer++;
1357 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001358 case SOURCE_PERIODIC:
1359 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001360 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 }
Costin Manolache360e4542009-09-04 13:36:04 -07001362
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001364 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 if (mDayStats[0] == null) {
1366 mDayStats[0] = new DayStats(day);
1367 } else if (day != mDayStats[0].day) {
1368 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1369 mDayStats[0] = new DayStats(day);
1370 writeStatisticsNow = true;
1371 } else if (mDayStats[0] == null) {
1372 }
1373 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001374
Dianne Hackborn231cc602009-04-27 17:10:36 -07001375 final long lastSyncTime = (item.eventTime + elapsedTime);
1376 boolean writeStatusNow = false;
1377 if (MESG_SUCCESS.equals(resultMessage)) {
1378 // - if successful, update the successful columns
1379 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1380 writeStatusNow = true;
1381 }
1382 status.lastSuccessTime = lastSyncTime;
1383 status.lastSuccessSource = item.source;
1384 status.lastFailureTime = 0;
1385 status.lastFailureSource = -1;
1386 status.lastFailureMesg = null;
1387 status.initialFailureTime = 0;
1388 ds.successCount++;
1389 ds.successTime += elapsedTime;
1390 } else if (!MESG_CANCELED.equals(resultMessage)) {
1391 if (status.lastFailureTime == 0) {
1392 writeStatusNow = true;
1393 }
1394 status.lastFailureTime = lastSyncTime;
1395 status.lastFailureSource = item.source;
1396 status.lastFailureMesg = resultMessage;
1397 if (status.initialFailureTime == 0) {
1398 status.initialFailureTime = lastSyncTime;
1399 }
1400 ds.failureCount++;
1401 ds.failureTime += elapsedTime;
1402 }
Costin Manolache360e4542009-09-04 13:36:04 -07001403
Dianne Hackborn231cc602009-04-27 17:10:36 -07001404 if (writeStatusNow) {
1405 writeStatusLocked();
1406 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1407 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1408 WRITE_STATUS_DELAY);
1409 }
1410 if (writeStatisticsNow) {
1411 writeStatisticsLocked();
1412 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1413 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1414 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001415 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001416 }
Costin Manolache360e4542009-09-04 13:36:04 -07001417
Fred Quintanaac9385e2009-06-22 18:00:59 -07001418 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001419 }
1420
1421 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001422 * Return a list of the currently active syncs. Note that the returned
1423 * items are the real, live active sync objects, so be careful what you do
1424 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001425 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001426 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001427 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001428 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001429 }
1430 }
Costin Manolache360e4542009-09-04 13:36:04 -07001431
Dianne Hackborn231cc602009-04-27 17:10:36 -07001432 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001433 * @return a copy of the current syncs data structure. Will not return
1434 * null.
1435 */
1436 public List<SyncInfo> getCurrentSyncsCopy(int userId) {
1437 synchronized (mAuthorities) {
1438 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1439 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1440 for (SyncInfo sync : syncs) {
1441 syncsCopy.add(new SyncInfo(sync));
1442 }
1443 return syncsCopy;
1444 }
1445 }
1446
1447 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1448 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1449 if (syncs == null) {
1450 syncs = new ArrayList<SyncInfo>();
1451 mCurrentSyncs.put(userId, syncs);
1452 }
1453 return syncs;
1454 }
1455
1456 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001457 * Return an array of the current sync status for all authorities. Note
1458 * that the objects inside the array are the real, live status objects,
1459 * so be careful what you do with them.
1460 */
1461 public ArrayList<SyncStatusInfo> getSyncStatus() {
1462 synchronized (mAuthorities) {
1463 final int N = mSyncStatus.size();
1464 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1465 for (int i=0; i<N; i++) {
1466 ops.add(mSyncStatus.valueAt(i));
1467 }
1468 return ops;
1469 }
1470 }
Costin Manolache360e4542009-09-04 13:36:04 -07001471
Dianne Hackborn231cc602009-04-27 17:10:36 -07001472 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001473 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001474 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001475 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001476 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001477 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001478 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001479 true /* write to storage if this results in a change */);
1480 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1481 }
1482 }
1483
1484 /**
1485 * Return a copy of all authorities with their corresponding sync status
1486 */
1487 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1488 synchronized (mAuthorities) {
1489 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1490 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1491 for (int i = 0; i < mAuthorities.size(); i++) {
1492 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001493 }
1494 return infos;
1495 }
1496 }
1497
1498 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001499 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001500 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001501 * @param info the endpoint target we are querying status info for.
1502 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001503 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001504 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1505 if (info.target_provider && (info.account == null || info.provider == null)) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001506 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001507 } else if (info.target_service && info.service == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001508 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001509 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001510 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001511 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001512 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001513 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001514 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001515 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001516 && ainfo.target.matchesSpec(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001517 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001518 }
1519 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001520 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001521 }
1522 }
Costin Manolache360e4542009-09-04 13:36:04 -07001523
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001524 /** Return true if the pending status is true of any matching authorities. */
1525 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 synchronized (mAuthorities) {
1527 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001528 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001529 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1531 if (ainfo == null) {
1532 continue;
1533 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001534 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001535 continue;
1536 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001537 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 return true;
1539 }
1540 }
1541 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
1543 }
1544
1545 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 * Return an array of the current sync status for all authorities. Note
1547 * that the objects inside the array are the real, live status objects,
1548 * so be careful what you do with them.
1549 */
1550 public ArrayList<SyncHistoryItem> getSyncHistory() {
1551 synchronized (mAuthorities) {
1552 final int N = mSyncHistory.size();
1553 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1554 for (int i=0; i<N; i++) {
1555 items.add(mSyncHistory.get(i));
1556 }
1557 return items;
1558 }
1559 }
Costin Manolache360e4542009-09-04 13:36:04 -07001560
Dianne Hackborn231cc602009-04-27 17:10:36 -07001561 /**
1562 * Return an array of the current per-day statistics. Note
1563 * that the objects inside the array are the real, live status objects,
1564 * so be careful what you do with them.
1565 */
1566 public DayStats[] getDayStatistics() {
1567 synchronized (mAuthorities) {
1568 DayStats[] ds = new DayStats[mDayStats.length];
1569 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1570 return ds;
1571 }
1572 }
Costin Manolache360e4542009-09-04 13:36:04 -07001573
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001574 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1575 AuthorityInfo authorityInfo) {
1576 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1577 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1578 }
1579
Dianne Hackborn55280a92009-05-07 15:53:46 -07001580 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001581 mCal.setTimeInMillis(System.currentTimeMillis());
1582 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1583 if (mYear != mCal.get(Calendar.YEAR)) {
1584 mYear = mCal.get(Calendar.YEAR);
1585 mCal.clear();
1586 mCal.set(Calendar.YEAR, mYear);
1587 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1588 }
1589 return dayOfYear + mYearInDays;
1590 }
Costin Manolache360e4542009-09-04 13:36:04 -07001591
Dianne Hackborn231cc602009-04-27 17:10:36 -07001592 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001593 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001594 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001595 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001596 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001597 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001598 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001599 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1600 if (info.target_service) {
1601 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1602 AuthorityInfo authority = null;
1603 if (aInfo != null) {
1604 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001605 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001606 if (authority == null) {
1607 if (tag != null) {
1608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001609 Log.v(TAG, tag + " No authority info found for " + info.service + " for"
1610 + " user " + info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001611 }
1612 }
1613 return null;
1614 }
1615 return authority;
1616 } else if (info.target_provider){
1617 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1618 AccountInfo accountInfo = mAccounts.get(au);
1619 if (accountInfo == null) {
1620 if (tag != null) {
1621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1622 Log.v(TAG, tag + ": unknown account " + au);
1623 }
1624 }
1625 return null;
1626 }
1627 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1628 if (authority == null) {
1629 if (tag != null) {
1630 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1631 Log.v(TAG, tag + ": unknown provider " + info.provider);
1632 }
1633 }
1634 return null;
1635 }
1636 return authority;
1637 } else {
1638 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001639 return null;
1640 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001641 }
Costin Manolache360e4542009-09-04 13:36:04 -07001642
Matthew Williamsfa774182013-06-18 15:44:11 -07001643 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001644 * @param info info identifying target.
1645 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001646 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001647 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001648 * exists.
1649 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001650 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1651 AuthorityInfo authority = null;
1652 if (info.target_service) {
1653 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1654 if (aInfo == null) {
1655 aInfo = new SparseArray<AuthorityInfo>();
1656 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001657 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001658 authority = aInfo.get(info.userId);
1659 if (authority == null) {
1660 authority = createAuthorityLocked(info, ident, doWrite);
1661 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001662 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001663 } else if (info.target_provider) {
1664 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1665 AccountInfo account = mAccounts.get(au);
1666 if (account == null) {
1667 account = new AccountInfo(au);
1668 mAccounts.put(au, account);
1669 }
1670 authority = account.authorities.get(info.provider);
1671 if (authority == null) {
1672 authority = createAuthorityLocked(info, ident, doWrite);
1673 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001674 }
1675 }
1676 return authority;
1677 }
1678
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001679 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1680 AuthorityInfo authority;
1681 if (ident < 0) {
1682 ident = mNextAuthorityId;
1683 mNextAuthorityId++;
1684 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001685 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001686 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1687 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001688 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001689 authority = new AuthorityInfo(info, ident);
1690 mAuthorities.put(ident, authority);
1691 if (doWrite) {
1692 writeAccountInfoLocked();
1693 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001694 return authority;
1695 }
Costin Manolache360e4542009-09-04 13:36:04 -07001696
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001697 public void removeAuthority(EndPoint info) {
1698 synchronized (mAuthorities) {
1699 if (info.target_provider) {
1700 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1701 } else {
1702 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1703 if (aInfos != null) {
1704 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1705 if (authorityInfo != null) {
1706 mAuthorities.remove(authorityInfo.ident);
1707 aInfos.delete(info.userId);
1708 writeAccountInfoLocked();
1709 }
1710 }
1711
1712 }
1713 }
1714 }
1715
1716 /**
1717 * Remove an authority associated with a provider. Needs to be a standalone function for
1718 * backward compatibility.
1719 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001720 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1721 boolean doWrite) {
1722 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001723 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001724 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1725 if (authorityInfo != null) {
1726 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001727 if (doWrite) {
1728 writeAccountInfoLocked();
1729 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001730 }
1731 }
1732 }
1733
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001734 /**
1735 * Updates (in a synchronized way) the periodic sync time of the specified
Matthew Williams8ef22042013-07-26 12:56:39 -07001736 * target id and target periodic sync
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001737 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001738 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001739 boolean found = false;
1740 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001741 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001742 authorityInfo = mAuthorities.get(authorityId);
1743 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001744 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1745 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001746 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001747 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001748 break;
1749 }
1750 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001751 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001752 if (!found) {
1753 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams8ef22042013-07-26 12:56:39 -07001754 "Authority: " + authorityInfo.target);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001755 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001756 }
1757
Dianne Hackborn231cc602009-04-27 17:10:36 -07001758 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1759 SyncStatusInfo status = mSyncStatus.get(authorityId);
1760 if (status == null) {
1761 status = new SyncStatusInfo(authorityId);
1762 mSyncStatus.put(authorityId, status);
1763 }
1764 return status;
1765 }
Costin Manolache360e4542009-09-04 13:36:04 -07001766
Dianne Hackborn55280a92009-05-07 15:53:46 -07001767 public void writeAllState() {
1768 synchronized (mAuthorities) {
1769 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001770
Dianne Hackborn55280a92009-05-07 15:53:46 -07001771 if (mNumPendingFinished > 0) {
1772 // Only write these if they are out of date.
1773 writePendingOperationsLocked();
1774 }
Costin Manolache360e4542009-09-04 13:36:04 -07001775
Dianne Hackborn55280a92009-05-07 15:53:46 -07001776 // Just always write these... they are likely out of date.
1777 writeStatusLocked();
1778 writeStatisticsLocked();
1779 }
1780 }
Costin Manolache360e4542009-09-04 13:36:04 -07001781
Dianne Hackborn231cc602009-04-27 17:10:36 -07001782 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001783 * public for testing
1784 */
1785 public void clearAndReadState() {
1786 synchronized (mAuthorities) {
1787 mAuthorities.clear();
1788 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001789 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001790 mPendingOperations.clear();
1791 mSyncStatus.clear();
1792 mSyncHistory.clear();
1793
1794 readAccountInfoLocked();
1795 readStatusLocked();
1796 readPendingOperationsLocked();
1797 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001798 readAndDeleteLegacyAccountInfoLocked();
1799 writeAccountInfoLocked();
1800 writeStatusLocked();
1801 writePendingOperationsLocked();
1802 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001803 }
1804 }
1805
1806 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001807 * Read all account information back in to the initial engine state.
1808 */
1809 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001810 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001813 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001814 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001815 Log.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001816 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001817 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001818 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001819 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001820 while (eventType != XmlPullParser.START_TAG &&
1821 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 eventType = parser.next();
1823 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001824 if (eventType == XmlPullParser.END_DOCUMENT) {
1825 Log.i(TAG, "No initial accounts");
1826 return;
1827 }
1828
Dianne Hackborn231cc602009-04-27 17:10:36 -07001829 String tagName = parser.getName();
1830 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001831 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001832 String versionString = parser.getAttributeValue(null, "version");
1833 int version;
1834 try {
1835 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1836 } catch (NumberFormatException e) {
1837 version = 0;
1838 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001839 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001840 try {
1841 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1842 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1843 } catch (NumberFormatException e) {
1844 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001845 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001846 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1847 try {
1848 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1849 } catch (NumberFormatException e) {
1850 mSyncRandomOffset = 0;
1851 }
1852 if (mSyncRandomOffset == 0) {
1853 Random random = new Random(System.currentTimeMillis());
1854 mSyncRandomOffset = random.nextInt(86400);
1855 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001856 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001857 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001858 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001859 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001860 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001861 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001862 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001863 if (parser.getDepth() == 2) {
1864 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001865 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001866 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001867 if (authority.ident > highestAuthorityId) {
1868 highestAuthorityId = authority.ident;
1869 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001870 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1871 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001872 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001873 } else if (parser.getDepth() == 3) {
1874 if ("periodicSync".equals(tagName) && authority != null) {
1875 periodicSync = parsePeriodicSync(parser, authority);
1876 }
1877 } else if (parser.getDepth() == 4 && periodicSync != null) {
1878 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001879 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001880 }
1881 }
1882 }
1883 eventType = parser.next();
1884 } while (eventType != XmlPullParser.END_DOCUMENT);
1885 }
1886 } catch (XmlPullParserException e) {
1887 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001888 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001889 } catch (java.io.IOException e) {
1890 if (fis == null) Log.i(TAG, "No initial accounts");
1891 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001892 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001893 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001894 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001895 if (fis != null) {
1896 try {
1897 fis.close();
1898 } catch (java.io.IOException e1) {
1899 }
1900 }
1901 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001902
Fred Quintana77c560f2010-03-29 22:20:26 -07001903 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001904 }
Costin Manolache360e4542009-09-04 13:36:04 -07001905
Fred Quintanafb084402010-03-23 17:57:03 -07001906 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001907 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1908 * pending.xml was used starting in KLP.
1909 * @param syncDir directory where the sync files are located.
1910 */
1911 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1912 File file = new File(syncDir, "pending.bin");
1913 if (!file.exists()) {
1914 return;
1915 } else {
1916 file.delete();
1917 }
1918 }
1919
1920 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001921 * some authority names have changed. copy over their settings and delete the old ones
1922 * @return true if a change was made
1923 */
1924 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1925 boolean writeNeeded = false;
1926
1927 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1928 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001929 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001930 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001931 // skip this authority if it doesn't target a provider
1932 if (authority.target.target_service) {
1933 continue;
1934 }
Fred Quintanafb084402010-03-23 17:57:03 -07001935 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001936 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001937 if (newAuthorityName == null) {
1938 continue;
1939 }
1940
1941 // remember this authority so we can remove it later. we can't remove it
1942 // now without messing up this loop iteration
1943 authoritiesToRemove.add(authority);
1944
1945 // this authority isn't enabled, no need to copy it to the new authority name since
1946 // the default is "disabled"
1947 if (!authority.enabled) {
1948 continue;
1949 }
1950
1951 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001952 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001953 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001954 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001955 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001956 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001957 continue;
1958 }
1959
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001960 AuthorityInfo newAuthority =
1961 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001962 newAuthority.enabled = true;
1963 writeNeeded = true;
1964 }
1965
1966 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001967 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001968 authorityInfo.target.account,
1969 authorityInfo.target.userId,
1970 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001971 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001972 writeNeeded = true;
1973 }
1974
1975 return writeNeeded;
1976 }
1977
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978 private void parseListenForTickles(XmlPullParser parser) {
1979 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1980 int userId = 0;
1981 try {
1982 userId = Integer.parseInt(user);
1983 } catch (NumberFormatException e) {
1984 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1985 } catch (NullPointerException e) {
1986 Log.e(TAG, "the user in listen-for-tickles is null", e);
1987 }
1988 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1989 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1990 mMasterSyncAutomatically.put(userId, listen);
1991 }
1992
Fred Quintanac2e46912010-03-15 16:10:44 -07001993 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001994 AuthorityInfo authority = null;
1995 int id = -1;
1996 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001997 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001998 } catch (NumberFormatException e) {
1999 Log.e(TAG, "error parsing the id of the authority", e);
2000 } catch (NullPointerException e) {
2001 Log.e(TAG, "the id of the authority is null", e);
2002 }
2003 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07002004 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002005 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07002006 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002007 String accountName = parser.getAttributeValue(null, "account");
2008 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002009 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07002010 String packageName = parser.getAttributeValue(null, "package");
2011 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002012 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07002013 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002014 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07002015 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002016 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002017 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002018 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002019 Log.v(TAG_FILE, "Adding authority:"
2020 + " account=" + accountName
2021 + " accountType=" + accountType
2022 + " auth=" + authorityName
2023 + " package=" + packageName
2024 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07002025 + " user=" + userId
2026 + " enabled=" + enabled
2027 + " syncable=" + syncable);
2028 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002029 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002030 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002031 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002032 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002033 EndPoint info;
2034 if (accountName != null && authorityName != null) {
2035 info = new EndPoint(
2036 new Account(accountName, accountType),
2037 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002038 } else {
Matthew Williams8ef22042013-07-26 12:56:39 -07002039 info = new EndPoint(
2040 new ComponentName(packageName, className),
2041 userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07002042 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002043 authority = getOrCreateAuthorityLocked(info, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07002044 // If the version is 0 then we are upgrading from a file format that did not
2045 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002046 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002047 // Otherwise clear out this default list since we will populate it later with
2048 // the periodic sync descriptions that are read from the configuration file.
2049 if (version > 0) {
2050 authority.periodicSyncs.clear();
2051 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002052 }
2053 if (authority != null) {
2054 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
2055 if ("unknown".equals(syncable)) {
2056 authority.syncable = -1;
2057 } else {
2058 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07002059 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002060 }
2061 } else {
2062 Log.w(TAG, "Failure adding authority: account="
2063 + accountName + " auth=" + authorityName
2064 + " enabled=" + enabled
2065 + " syncable=" + syncable);
2066 }
2067 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002068 return authority;
2069 }
2070
Matthew Williamsfa774182013-06-18 15:44:11 -07002071 /**
2072 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2073 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002074 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002075 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002076 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002077 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002078 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002079 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002080 try {
2081 period = Long.parseLong(periodValue);
2082 } catch (NumberFormatException e) {
2083 Log.e(TAG, "error parsing the period of a periodic sync", e);
2084 return null;
2085 } catch (NullPointerException e) {
2086 Log.e(TAG, "the period of a periodic sync is null", e);
2087 return null;
2088 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002089 try {
2090 flextime = Long.parseLong(flexValue);
2091 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002092 flextime = calculateDefaultFlexTime(period);
Matthew Williams8ef22042013-07-26 12:56:39 -07002093 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
2094 + ", using default: "
2095 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07002096 } catch (NullPointerException expected) {
2097 flextime = calculateDefaultFlexTime(period);
2098 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2099 + period + " flex: " + flextime);
2100 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002101 PeriodicSync periodicSync;
Matthew Williams8ef22042013-07-26 12:56:39 -07002102 if (authorityInfo.target.target_provider) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002103 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07002104 new PeriodicSync(authorityInfo.target.account,
2105 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002106 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002107 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002108 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002109 Log.e(TAG, "Unknown target.");
2110 return null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002111 }
2112 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002113 return periodicSync;
2114 }
2115
Matthew Williamsfa774182013-06-18 15:44:11 -07002116 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002117 String name = parser.getAttributeValue(null, "name");
2118 String type = parser.getAttributeValue(null, "type");
2119 String value1 = parser.getAttributeValue(null, "value1");
2120 String value2 = parser.getAttributeValue(null, "value2");
2121
2122 try {
2123 if ("long".equals(type)) {
2124 extras.putLong(name, Long.parseLong(value1));
2125 } else if ("integer".equals(type)) {
2126 extras.putInt(name, Integer.parseInt(value1));
2127 } else if ("double".equals(type)) {
2128 extras.putDouble(name, Double.parseDouble(value1));
2129 } else if ("float".equals(type)) {
2130 extras.putFloat(name, Float.parseFloat(value1));
2131 } else if ("boolean".equals(type)) {
2132 extras.putBoolean(name, Boolean.parseBoolean(value1));
2133 } else if ("string".equals(type)) {
2134 extras.putString(name, value1);
2135 } else if ("account".equals(type)) {
2136 extras.putParcelable(name, new Account(value1, value2));
2137 }
2138 } catch (NumberFormatException e) {
2139 Log.e(TAG, "error parsing bundle value", e);
2140 } catch (NullPointerException e) {
2141 Log.e(TAG, "error parsing bundle value", e);
2142 }
2143 }
2144
Dianne Hackborn231cc602009-04-27 17:10:36 -07002145 /**
2146 * Write all account information to the account file.
2147 */
2148 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002149 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002150 Log.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002151 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002152 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002153
Dianne Hackborn231cc602009-04-27 17:10:36 -07002154 try {
2155 fos = mAccountInfoFile.startWrite();
2156 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002157 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07002158 out.startDocument(null, true);
2159 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002160
Dianne Hackborn231cc602009-04-27 17:10:36 -07002161 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002162 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002163 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002164 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002165
2166 // Write the Sync Automatically flags for each user
2167 final int M = mMasterSyncAutomatically.size();
2168 for (int m = 0; m < M; m++) {
2169 int userId = mMasterSyncAutomatically.keyAt(m);
2170 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2171 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2172 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2173 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2174 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002175 }
Costin Manolache360e4542009-09-04 13:36:04 -07002176
Dianne Hackborn231cc602009-04-27 17:10:36 -07002177 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002178 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002179 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002180 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 out.startTag(null, "authority");
2182 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002183 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002184 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002185 if (info.service == null) {
2186 out.attribute(null, "account", info.account.name);
2187 out.attribute(null, "type", info.account.type);
2188 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002189 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002190 out.attribute(null, "package", info.service.getPackageName());
2191 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002192 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002193 if (authority.syncable < 0) {
2194 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002195 } else {
2196 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002197 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002198 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002199 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002200 out.attribute(null, "period", Long.toString(periodicSync.period));
2201 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2202 final Bundle extras = periodicSync.extras;
2203 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002204 out.endTag(null, "periodicSync");
2205 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002206 out.endTag(null, "authority");
2207 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002208 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002209 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002210 mAccountInfoFile.finishWrite(fos);
2211 } catch (java.io.IOException e1) {
2212 Log.w(TAG, "Error writing accounts", e1);
2213 if (fos != null) {
2214 mAccountInfoFile.failWrite(fos);
2215 }
2216 }
2217 }
Costin Manolache360e4542009-09-04 13:36:04 -07002218
Dianne Hackborn231cc602009-04-27 17:10:36 -07002219 static int getIntColumn(Cursor c, String name) {
2220 return c.getInt(c.getColumnIndex(name));
2221 }
Costin Manolache360e4542009-09-04 13:36:04 -07002222
Dianne Hackborn231cc602009-04-27 17:10:36 -07002223 static long getLongColumn(Cursor c, String name) {
2224 return c.getLong(c.getColumnIndex(name));
2225 }
Costin Manolache360e4542009-09-04 13:36:04 -07002226
Dianne Hackborn231cc602009-04-27 17:10:36 -07002227 /**
2228 * Load sync engine state from the old syncmanager database, and then
2229 * erase it. Note that we don't deal with pending operations, active
2230 * sync, or history.
2231 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002232 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002233 // Look for old database to initialize from.
2234 File file = mContext.getDatabasePath("syncmanager.db");
2235 if (!file.exists()) {
2236 return;
2237 }
2238 String path = file.getPath();
2239 SQLiteDatabase db = null;
2240 try {
2241 db = SQLiteDatabase.openDatabase(path, null,
2242 SQLiteDatabase.OPEN_READONLY);
2243 } catch (SQLiteException e) {
2244 }
Costin Manolache360e4542009-09-04 13:36:04 -07002245
Dianne Hackborn231cc602009-04-27 17:10:36 -07002246 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002247 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002248
Dianne Hackborn231cc602009-04-27 17:10:36 -07002249 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002250 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002251 Log.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002252 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2254 qb.setTables("stats, status");
2255 HashMap<String,String> map = new HashMap<String,String>();
2256 map.put("_id", "status._id as _id");
2257 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002258 if (hasType) {
2259 map.put("account_type", "stats.account_type as account_type");
2260 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002261 map.put("authority", "stats.authority as authority");
2262 map.put("totalElapsedTime", "totalElapsedTime");
2263 map.put("numSyncs", "numSyncs");
2264 map.put("numSourceLocal", "numSourceLocal");
2265 map.put("numSourcePoll", "numSourcePoll");
2266 map.put("numSourceServer", "numSourceServer");
2267 map.put("numSourceUser", "numSourceUser");
2268 map.put("lastSuccessSource", "lastSuccessSource");
2269 map.put("lastSuccessTime", "lastSuccessTime");
2270 map.put("lastFailureSource", "lastFailureSource");
2271 map.put("lastFailureTime", "lastFailureTime");
2272 map.put("lastFailureMesg", "lastFailureMesg");
2273 map.put("pending", "pending");
2274 qb.setProjectionMap(map);
2275 qb.appendWhere("stats._id = status.stats_id");
2276 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002278 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002279 String accountType = hasType
2280 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002281 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002282 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002284 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002285 AuthorityInfo authority =
2286 this.getOrCreateAuthorityLocked(
2287 new EndPoint(new Account(accountName, accountType),
2288 authorityName,
2289 0 /* legacy is single-user */)
2290 , -1,
2291 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002292 if (authority != null) {
2293 int i = mSyncStatus.size();
2294 boolean found = false;
2295 SyncStatusInfo st = null;
2296 while (i > 0) {
2297 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002298 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002299 if (st.authorityId == authority.ident) {
2300 found = true;
2301 break;
2302 }
2303 }
2304 if (!found) {
2305 st = new SyncStatusInfo(authority.ident);
2306 mSyncStatus.put(authority.ident, st);
2307 }
2308 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2309 st.numSyncs = getIntColumn(c, "numSyncs");
2310 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2311 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2312 st.numSourceServer = getIntColumn(c, "numSourceServer");
2313 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002314 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002315 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2316 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2317 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2318 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2319 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2320 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
Costin Manolache360e4542009-09-04 13:36:04 -07002323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002325
Dianne Hackborn231cc602009-04-27 17:10:36 -07002326 // Retrieve the settings.
2327 qb = new SQLiteQueryBuilder();
2328 qb.setTables("settings");
2329 c = qb.query(db, null, null, null, null, null, null);
2330 while (c.moveToNext()) {
2331 String name = c.getString(c.getColumnIndex("name"));
2332 String value = c.getString(c.getColumnIndex("value"));
2333 if (name == null) continue;
2334 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002335 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002336 } else if (name.startsWith("sync_provider_")) {
2337 String provider = name.substring("sync_provider_".length(),
2338 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002339 int i = mAuthorities.size();
2340 while (i > 0) {
2341 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002342 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002343 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002344 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002345 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002346 }
2347 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
Costin Manolache360e4542009-09-04 13:36:04 -07002350
Dianne Hackborn231cc602009-04-27 17:10:36 -07002351 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002352
Dianne Hackborn231cc602009-04-27 17:10:36 -07002353 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002354
Dianne Hackborn231cc602009-04-27 17:10:36 -07002355 (new File(path)).delete();
2356 }
2357 }
Costin Manolache360e4542009-09-04 13:36:04 -07002358
Dianne Hackborn231cc602009-04-27 17:10:36 -07002359 public static final int STATUS_FILE_END = 0;
2360 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002361
Dianne Hackborn231cc602009-04-27 17:10:36 -07002362 /**
2363 * Read all sync status back in to the initial engine state.
2364 */
2365 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002366 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002367 Log.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002368 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002369 try {
2370 byte[] data = mStatusFile.readFully();
2371 Parcel in = Parcel.obtain();
2372 in.unmarshall(data, 0, data.length);
2373 in.setDataPosition(0);
2374 int token;
2375 while ((token=in.readInt()) != STATUS_FILE_END) {
2376 if (token == STATUS_FILE_ITEM) {
2377 SyncStatusInfo status = new SyncStatusInfo(in);
2378 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2379 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002380 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002381 Log.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002382 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002383 mSyncStatus.put(status.authorityId, status);
2384 }
2385 } else {
2386 // Ooops.
2387 Log.w(TAG, "Unknown status token: " + token);
2388 break;
2389 }
2390 }
2391 } catch (java.io.IOException e) {
2392 Log.i(TAG, "No initial status");
2393 }
2394 }
Costin Manolache360e4542009-09-04 13:36:04 -07002395
Dianne Hackborn231cc602009-04-27 17:10:36 -07002396 /**
2397 * Write all sync status to the sync status file.
2398 */
2399 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002400 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002401 Log.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002402 }
Costin Manolache360e4542009-09-04 13:36:04 -07002403
Dianne Hackborn231cc602009-04-27 17:10:36 -07002404 // The file is being written, so we don't need to have a scheduled
2405 // write until the next change.
2406 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002407
Dianne Hackborn231cc602009-04-27 17:10:36 -07002408 FileOutputStream fos = null;
2409 try {
2410 fos = mStatusFile.startWrite();
2411 Parcel out = Parcel.obtain();
2412 final int N = mSyncStatus.size();
2413 for (int i=0; i<N; i++) {
2414 SyncStatusInfo status = mSyncStatus.valueAt(i);
2415 out.writeInt(STATUS_FILE_ITEM);
2416 status.writeToParcel(out, 0);
2417 }
2418 out.writeInt(STATUS_FILE_END);
2419 fos.write(out.marshall());
2420 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002421
Dianne Hackborn231cc602009-04-27 17:10:36 -07002422 mStatusFile.finishWrite(fos);
2423 } catch (java.io.IOException e1) {
2424 Log.w(TAG, "Error writing status", e1);
2425 if (fos != null) {
2426 mStatusFile.failWrite(fos);
2427 }
2428 }
2429 }
Costin Manolache360e4542009-09-04 13:36:04 -07002430
Matthew Williamsba352712013-08-13 15:53:31 -07002431 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002432
Matthew Williamsba352712013-08-13 15:53:31 -07002433 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002434 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002435 FileInputStream fis = null;
2436 if (!mPendingFile.getBaseFile().exists()) {
2437 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2438 Log.v(TAG_FILE, "No pending operation file.");
Matthew Williamsfa774182013-06-18 15:44:11 -07002439 }
Ji-Hwan Lee886113d2014-04-17 14:16:38 +09002440 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002441 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002442 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002443 fis = mPendingFile.openRead();
Matthew Williams06485a72013-07-26 12:56:39 -07002444 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2445 Log.v(TAG_FILE, "Reading " + mPendingFile.getBaseFile());
2446 }
Matthew Williamsba352712013-08-13 15:53:31 -07002447 XmlPullParser parser;
2448 parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002449 parser.setInput(fis, StandardCharsets.UTF_8.name());
Matthew Williamsba352712013-08-13 15:53:31 -07002450
Matthew Williamsfa774182013-06-18 15:44:11 -07002451 int eventType = parser.getEventType();
2452 while (eventType != XmlPullParser.START_TAG &&
2453 eventType != XmlPullParser.END_DOCUMENT) {
2454 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002455 }
Matthew Williamsba352712013-08-13 15:53:31 -07002456 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002457
Matthew Williamsba352712013-08-13 15:53:31 -07002458 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002459 PendingOperation pop = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07002460 if (eventType == XmlPullParser.START_TAG) {
2461 try {
Matthew Williams06485a72013-07-26 12:56:39 -07002462 String tagName = parser.getName();
Matthew Williams8ef22042013-07-26 12:56:39 -07002463 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2464 // Verify version.
2465 String versionString =
2466 parser.getAttributeValue(null, XML_ATTR_VERSION);
2467 if (versionString == null ||
2468 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2469 Log.w(TAG, "Unknown pending operation version " + versionString);
2470 throw new java.io.IOException("Unknown version.");
2471 }
2472 int authorityId = Integer.valueOf(parser.getAttributeValue(
2473 null, XML_ATTR_AUTHORITYID));
2474 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2475 null, XML_ATTR_EXPEDITED));
2476 int syncSource = Integer.valueOf(parser.getAttributeValue(
2477 null, XML_ATTR_SOURCE));
2478 int reason = Integer.valueOf(parser.getAttributeValue(
2479 null, XML_ATTR_REASON));
2480 AuthorityInfo authority = mAuthorities.get(authorityId);
2481 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2482 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2483 + reason);
2484 }
2485 if (authority != null) {
2486 pop = new PendingOperation(
2487 authority, reason, syncSource, new Bundle(), expedited);
2488 pop.flatExtras = null; // No longer used.
2489 mPendingOperations.add(pop);
Matthew Williamsba352712013-08-13 15:53:31 -07002490 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002491 Log.v(TAG_FILE, "Adding pending op: "
2492 + pop.target
Matthew Williamsfa774182013-06-18 15:44:11 -07002493 + " src=" + pop.syncSource
2494 + " reason=" + pop.reason
2495 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002496 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002497 } else {
2498 // Skip non-existent authority.
2499 pop = null;
2500 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2501 Log.v(TAG_FILE, "No authority found for " + authorityId
2502 + ", skipping");
Matthew Williamsfa774182013-06-18 15:44:11 -07002503 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002504 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002505 } else if (parser.getDepth() == 2 &&
2506 pop != null &&
2507 "extra".equals(tagName)) {
2508 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002509 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002510 } catch (NumberFormatException e) {
2511 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002512 }
Matthew Williams8ef22042013-07-26 12:56:39 -07002513 }
Matthew Williamsba352712013-08-13 15:53:31 -07002514 eventType = parser.next();
2515 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002516 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002517 Log.w(TAG_FILE, "Error reading pending data.", e);
2518 } catch (XmlPullParserException e) {
2519 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2520 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2521 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002522 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002523 if (fis != null) {
2524 try {
2525 fis.close();
2526 } catch (java.io.IOException e1) {}
2527 }
2528 }
2529 }
Matthew Williamsba352712013-08-13 15:53:31 -07002530
Dianne Hackborn231cc602009-04-27 17:10:36 -07002531 static private byte[] flattenBundle(Bundle bundle) {
2532 byte[] flatData = null;
2533 Parcel parcel = Parcel.obtain();
2534 try {
2535 bundle.writeToParcel(parcel, 0);
2536 flatData = parcel.marshall();
2537 } finally {
2538 parcel.recycle();
2539 }
2540 return flatData;
2541 }
Costin Manolache360e4542009-09-04 13:36:04 -07002542
Dianne Hackborn231cc602009-04-27 17:10:36 -07002543 static private Bundle unflattenBundle(byte[] flatData) {
2544 Bundle bundle;
2545 Parcel parcel = Parcel.obtain();
2546 try {
2547 parcel.unmarshall(flatData, 0, flatData.length);
2548 parcel.setDataPosition(0);
2549 bundle = parcel.readBundle();
2550 } catch (RuntimeException e) {
2551 // A RuntimeException is thrown if we were unable to parse the parcel.
2552 // Create an empty parcel in this case.
2553 bundle = new Bundle();
2554 } finally {
2555 parcel.recycle();
2556 }
2557 return bundle;
2558 }
Costin Manolache360e4542009-09-04 13:36:04 -07002559
Matthew Williams8ef22042013-07-26 12:56:39 -07002560 private static final String XML_ATTR_VERSION = "version";
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002561 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2562 private static final String XML_ATTR_SOURCE = "source";
2563 private static final String XML_ATTR_EXPEDITED = "expedited";
2564 private static final String XML_ATTR_REASON = "reason";
2565
2566 /**
2567 * Write all currently pending ops to the pending ops file.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002568 */
2569 private void writePendingOperationsLocked() {
2570 final int N = mPendingOperations.size();
2571 FileOutputStream fos = null;
2572 try {
2573 if (N == 0) {
2574 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2575 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2576 }
2577 mPendingFile.truncate();
2578 return;
2579 }
2580 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2581 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2582 }
2583 fos = mPendingFile.startWrite();
2584 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002585 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002586
2587 for (int i = 0; i < N; i++) {
2588 PendingOperation pop = mPendingOperations.get(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002589 writePendingOperationLocked(pop, out);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002590 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002591 out.endDocument();
2592 mPendingFile.finishWrite(fos);
2593 } catch (java.io.IOException e1) {
2594 Log.w(TAG, "Error writing pending operations", e1);
2595 if (fos != null) {
2596 mPendingFile.failWrite(fos);
2597 }
2598 }
2599 }
2600
Matthew Williams8ef22042013-07-26 12:56:39 -07002601 /** Write all currently pending ops to the pending ops file. */
2602 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2603 throws IOException {
2604 // Pending operation.
2605 out.startTag(null, "op");
2606
2607 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2608 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2609 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2610 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2611 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2612 extrasToXml(out, pop.extras);
2613
2614 out.endTag(null, "op");
2615 }
2616
2617 /**
2618 * Append the given operation to the pending ops file; if unable to,
2619 * write all pending ops.
2620 */
2621 private void appendPendingOperationLocked(PendingOperation op) {
2622 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2623 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2624 }
2625 FileOutputStream fos = null;
2626 try {
2627 fos = mPendingFile.openAppend();
2628 } catch (java.io.IOException e) {
2629 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2630 Log.v(TAG, "Failed append; writing full file");
2631 }
2632 writePendingOperationsLocked();
2633 return;
2634 }
2635
2636 try {
2637 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002638 out.setOutput(fos, StandardCharsets.UTF_8.name());
Matthew Williams8ef22042013-07-26 12:56:39 -07002639 writePendingOperationLocked(op, out);
2640 out.endDocument();
2641 mPendingFile.finishWrite(fos);
2642 } catch (java.io.IOException e1) {
2643 Log.w(TAG, "Error writing appending operation", e1);
2644 mPendingFile.failWrite(fos);
2645 } finally {
2646 try {
2647 fos.close();
2648 } catch (IOException e) {}
2649 }
2650 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002651
Matthew Williamsfa774182013-06-18 15:44:11 -07002652 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2653 for (String key : extras.keySet()) {
2654 out.startTag(null, "extra");
2655 out.attribute(null, "name", key);
2656 final Object value = extras.get(key);
2657 if (value instanceof Long) {
2658 out.attribute(null, "type", "long");
2659 out.attribute(null, "value1", value.toString());
2660 } else if (value instanceof Integer) {
2661 out.attribute(null, "type", "integer");
2662 out.attribute(null, "value1", value.toString());
2663 } else if (value instanceof Boolean) {
2664 out.attribute(null, "type", "boolean");
2665 out.attribute(null, "value1", value.toString());
2666 } else if (value instanceof Float) {
2667 out.attribute(null, "type", "float");
2668 out.attribute(null, "value1", value.toString());
2669 } else if (value instanceof Double) {
2670 out.attribute(null, "type", "double");
2671 out.attribute(null, "value1", value.toString());
2672 } else if (value instanceof String) {
2673 out.attribute(null, "type", "string");
2674 out.attribute(null, "value1", value.toString());
2675 } else if (value instanceof Account) {
2676 out.attribute(null, "type", "account");
2677 out.attribute(null, "value1", ((Account)value).name);
2678 out.attribute(null, "value2", ((Account)value).type);
2679 }
2680 out.endTag(null, "extra");
2681 }
2682 }
2683
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002684 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2685 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2686 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002687 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002688 } else {
2689 SyncRequest.Builder req =
2690 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002691 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002692 .setExtras(extras);
2693 if (authorityInfo.target.target_provider) {
2694 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002695 } else {
Matthew Williams5a9decd2014-06-04 09:25:11 -07002696 if (Log.isLoggable(TAG, Log.DEBUG)) {
2697 Log.d(TAG, "Unknown target, skipping sync request.");
2698 }
2699 return;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002700 }
2701 ContentResolver.requestSync(req.build());
2702 }
2703 }
2704
Alon Albert57286f92012-10-09 14:21:38 -07002705 private void requestSync(Account account, int userId, int reason, String authority,
2706 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002707 // If this is happening in the system process, then call the syncrequest listener
2708 // to make a request back to the SyncManager directly.
2709 // If this is probably a test instance, then call back through the ContentResolver
2710 // which will know which userId to apply based on the Binder id.
2711 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2712 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002713 mSyncRequestListener.onSyncRequest(
Matthew Williams8ef22042013-07-26 12:56:39 -07002714 new EndPoint(account, authority, userId),
2715 reason,
2716 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002717 } else {
2718 ContentResolver.requestSync(account, authority, extras);
2719 }
2720 }
2721
Dianne Hackborn231cc602009-04-27 17:10:36 -07002722 public static final int STATISTICS_FILE_END = 0;
2723 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2724 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002725
Dianne Hackborn231cc602009-04-27 17:10:36 -07002726 /**
2727 * Read all sync statistics back in to the initial engine state.
2728 */
2729 private void readStatisticsLocked() {
2730 try {
2731 byte[] data = mStatisticsFile.readFully();
2732 Parcel in = Parcel.obtain();
2733 in.unmarshall(data, 0, data.length);
2734 in.setDataPosition(0);
2735 int token;
2736 int index = 0;
2737 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2738 if (token == STATISTICS_FILE_ITEM
2739 || token == STATISTICS_FILE_ITEM_OLD) {
2740 int day = in.readInt();
2741 if (token == STATISTICS_FILE_ITEM_OLD) {
2742 day = day - 2009 + 14245; // Magic!
2743 }
2744 DayStats ds = new DayStats(day);
2745 ds.successCount = in.readInt();
2746 ds.successTime = in.readLong();
2747 ds.failureCount = in.readInt();
2748 ds.failureTime = in.readLong();
2749 if (index < mDayStats.length) {
2750 mDayStats[index] = ds;
2751 index++;
2752 }
2753 } else {
2754 // Ooops.
2755 Log.w(TAG, "Unknown stats token: " + token);
2756 break;
2757 }
2758 }
2759 } catch (java.io.IOException e) {
2760 Log.i(TAG, "No initial statistics");
2761 }
2762 }
Costin Manolache360e4542009-09-04 13:36:04 -07002763
Dianne Hackborn231cc602009-04-27 17:10:36 -07002764 /**
2765 * Write all sync statistics to the sync status file.
2766 */
2767 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002768 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2769 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2770 }
Costin Manolache360e4542009-09-04 13:36:04 -07002771
Dianne Hackborn231cc602009-04-27 17:10:36 -07002772 // The file is being written, so we don't need to have a scheduled
2773 // write until the next change.
2774 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002775
Dianne Hackborn231cc602009-04-27 17:10:36 -07002776 FileOutputStream fos = null;
2777 try {
2778 fos = mStatisticsFile.startWrite();
2779 Parcel out = Parcel.obtain();
2780 final int N = mDayStats.length;
2781 for (int i=0; i<N; i++) {
2782 DayStats ds = mDayStats[i];
2783 if (ds == null) {
2784 break;
2785 }
2786 out.writeInt(STATISTICS_FILE_ITEM);
2787 out.writeInt(ds.day);
2788 out.writeInt(ds.successCount);
2789 out.writeLong(ds.successTime);
2790 out.writeInt(ds.failureCount);
2791 out.writeLong(ds.failureTime);
2792 }
2793 out.writeInt(STATISTICS_FILE_END);
2794 fos.write(out.marshall());
2795 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002796
Dianne Hackborn231cc602009-04-27 17:10:36 -07002797 mStatisticsFile.finishWrite(fos);
2798 } catch (java.io.IOException e1) {
2799 Log.w(TAG, "Error writing stats", e1);
2800 if (fos != null) {
2801 mStatisticsFile.failWrite(fos);
2802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 }
2804 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002805
2806 /**
2807 * Dump state of PendingOperations.
2808 */
2809 public void dumpPendingOperations(StringBuilder sb) {
2810 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2811 for (PendingOperation pop : mPendingOperations) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002812 sb.append("(info: " + pop.target.toString())
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002813 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002814 .append(")\n");
2815 }
2816 }
Marvin Paula6533252014-11-24 12:57:48 -08002817
2818 /**
2819 * Let the BackupManager know that account sync settings have changed. This will trigger
2820 * {@link com.android.server.backup.SystemBackupAgent} to run.
2821 */
2822 public void queueBackup() {
2823 BackupManager.dataChanged("android");
2824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825}