blob: 6cc3d8ae87f15e4377002254027eadae5263d189 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Matthew Williamsfa774182013-06-18 15:44:11 -070021import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.ISyncStatusObserver;
25import android.content.PeriodicSync;
26import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070027import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070031import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070033import android.os.Bundle;
34import android.os.Environment;
35import android.os.Handler;
36import android.os.Message;
37import android.os.Parcel;
38import android.os.RemoteCallbackList;
39import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070040import android.os.UserHandle;
Dianne Hackborn39606a02012-07-31 17:54:35 -070041import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070044import android.util.SparseArray;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070045import android.util.ArrayMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070046import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080047
48import com.android.internal.annotations.VisibleForTesting;
49import com.android.internal.util.ArrayUtils;
50import com.android.internal.util.FastXmlSerializer;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Dianne Hackborn231cc602009-04-27 17:10:36 -070056import java.io.File;
57import java.io.FileInputStream;
58import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070059import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070061import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080064import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070065import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060066import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070069 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070071 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * @hide
73 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070074public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070077 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070078
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
80 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070081 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080082 private static final String XML_ATTR_ENABLED = "enabled";
83 private static final String XML_ATTR_USER = "user";
84 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
85
Matthew Williamsfa774182013-06-18 15:44:11 -070086 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080087 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
88
Matthew Williamsfa774182013-06-18 15:44:11 -070089 /** Percentage of period that is flex by default, if no flex is set. */
90 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
91
92 /** Lower bound on sync time from which we assign a default flex time. */
93 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
94
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080095 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070096 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a sync start event. */
99 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a sync stop event. */
102 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 // TODO: i18n -- grab these out of resources.
105 /** String names for the sync event types. */
106 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a server-initiated sync. */
109 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a local-initiated sync. */
112 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700113 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700114 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 /** Enum value for a user-initiated sync. */
117 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800119 /** Enum value for a periodic sync. */
120 public static final int SOURCE_PERIODIC = 4;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700121
122 /** Enum value for a sync started for a service. */
123 public static final int SOURCE_SERVICE = 5;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800124
Fred Quintana307da1a2010-01-21 14:24:20 -0800125 public static final long NOT_IN_BACKOFF_MODE = -1;
126
Dianne Hackborn231cc602009-04-27 17:10:36 -0700127 // TODO: i18n -- grab these out of resources.
128 /** String names for the sync source types. */
129 public static final String[] SOURCES = { "SERVER",
130 "LOCAL",
131 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800132 "USER",
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700133 "PERIODIC",
134 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborn231cc602009-04-27 17:10:36 -0700136 // The MESG column will contain one of these or one of the Error types.
137 public static final String MESG_SUCCESS = "success";
138 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700140 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700141
Dianne Hackborn231cc602009-04-27 17:10:36 -0700142 private static final int MSG_WRITE_STATUS = 1;
143 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 private static final int MSG_WRITE_STATISTICS = 2;
146 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700147
148 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700149
Fred Quintanac2e46912010-03-15 16:10:44 -0700150 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700151 private static final int ACCOUNTS_VERSION = 2;
152
153 private static HashMap<String, String> sAuthorityRenames;
154
155 static {
156 sAuthorityRenames = new HashMap<String, String>();
157 sAuthorityRenames.put("contacts", "com.android.contacts");
158 sAuthorityRenames.put("calendar", "com.android.calendar");
159 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700160
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 public static class PendingOperation {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700162 final EndPoint authority;
Alon Albert57286f92012-10-09 14:21:38 -0700163 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700164 final int syncSource;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800166 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700167
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168 final int authorityId;
169 // No longer used.
170 // Keep around for sake up updating from pending.bin to pending.xml
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700172
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 PendingOperation(AuthorityInfo authority, int reason, int source,
174 Bundle extras, boolean expedited) {
175 this.authority = authority.base;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700177 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800179 this.expedited = expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 this.authorityId = authority.ident;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700181 }
182
183 PendingOperation(PendingOperation other) {
Alon Albert57286f92012-10-09 14:21:38 -0700184 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 this.syncSource = other.syncSource;
186 this.authority = other.authority;
187 this.extras = other.extras;
188 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800189 this.expedited = other.expedited;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700190 }
191
192 /**
193 * Considered equal if they target the same sync adapter (A {@link android.content.SyncService}
194 * is considered an adapter), for the same userId.
195 * @param other PendingOperation to compare.
196 * @return true if the two pending ops are the same.
197 */
198 public boolean equals(PendingOperation other) {
199 return authority.matches(other.authority);
200 }
201
202 public String toString() {
203 return "service=" + authority.service
204 + " user=" + authority.userId
205 + " auth=" + authority
206 + " account=" + authority.account
207 + " src=" + syncSource
208 + " extras=" + extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 }
Costin Manolache360e4542009-09-04 13:36:04 -0700211
Dianne Hackborn231cc602009-04-27 17:10:36 -0700212 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800213 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700214 final HashMap<String, AuthorityInfo> authorities =
215 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700216
Amith Yamasani04e0d262012-02-14 11:50:53 -0800217 AccountInfo(AccountAndUser accountAndUser) {
218 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700219 }
220 }
Costin Manolache360e4542009-09-04 13:36:04 -0700221
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700222 /** Bare bones representation of a sync target. */
223 public static class EndPoint {
224 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
225 new EndPoint(null, null, UserHandle.USER_ALL);
Matthew Williamsfa774182013-06-18 15:44:11 -0700226 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700227 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800228 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700229 final String provider;
230 final boolean target_service;
231 final boolean target_provider;
232
233 public EndPoint(ComponentName service, int userId) {
234 this.service = service;
235 this.userId = userId;
236 this.account = null;
237 this.provider = null;
238 this.target_service = true;
239 this.target_provider = false;
240 }
241
242 public EndPoint(Account account, String provider, int userId) {
243 this.account = account;
244 this.provider = provider;
245 this.userId = userId;
246 this.service = null;
247 this.target_service = false;
248 this.target_provider = true;
249 }
250
251 /**
252 * An Authority for a sync matches if it targets the same sync adapter for the same user.
253 * If the authority is for a provider/account pair and the account or provider is null, it
254 * matches by default.
255 */
256 public boolean matches(EndPoint other) {
257 if (userId != other.userId
258 && userId != UserHandle.USER_ALL
259 && other.userId != UserHandle.USER_ALL) {
260 return false;
261 }
262 if (target_service && other.target_service) {
263 return service.equals(other.service);
264 } else if (target_provider && other.target_provider) {
265 boolean accountsMatch;
266 if (account == null || other.account == null) {
267 accountsMatch = true;
268 } else {
269 accountsMatch = account.equals(other.account);
270 }
271 boolean providersMatch;
272 if (provider == null || other.provider == null) {
273 providersMatch = true;
274 } else {
275 providersMatch = provider.equals(other.provider);
276 }
277 return accountsMatch && providersMatch;
278 }
279 return false;
280 }
281
282 public String toString() {
283 StringBuilder sb = new StringBuilder();
284 if (target_provider) {
285 sb.append(account == null ? "ALL ACCS" : account.name)
286 .append("/")
287 .append(provider == null ? "ALL PDRS" : provider);
288 } else if (target_service) {
289 sb.append(service.getPackageName());
290 } else {
291 sb.append("invalid target");
292 }
293 return sb.toString();
294 }
295 }
296
297 public static class AuthorityInfo {
298 final EndPoint base;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700299 final int ident;
300 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700301 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700302 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800303 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700304 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800305 long backoffDelay;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700306 /** Offset to add to any requests coming to this authority. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800307 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700308
Matthew Williamsfa774182013-06-18 15:44:11 -0700309 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700310
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700311 /**
312 * Copy constructor for making deep-ish copies. Only the bundles stored
313 * in periodic syncs can make unexpected changes.
314 *
315 * @param toCopy AuthorityInfo to be copied.
316 */
317 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700318 base = toCopy.base;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700319 ident = toCopy.ident;
320 enabled = toCopy.enabled;
321 syncable = toCopy.syncable;
322 backoffTime = toCopy.backoffTime;
323 backoffDelay = toCopy.backoffDelay;
324 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700325 periodicSyncs = new ArrayList<PeriodicSync>();
326 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700327 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700328 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700329 }
330 }
331
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700332 AuthorityInfo(EndPoint info, int id) {
333 base = info;
334 ident = id;
335 enabled = info.target_provider ?
336 SYNC_ENABLED_DEFAULT : true;
337 // Service is active by default,
338 if (info.target_service) {
339 this.syncable = 1;
340 }
341 periodicSyncs = new ArrayList<PeriodicSync>();
342 defaultInitialisation();
343 }
344
345 private void defaultInitialisation() {
Fred Quintana4a6679b2009-08-17 13:05:39 -0700346 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800347 backoffTime = -1; // if < 0 then we aren't in backoff mode
348 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700349 PeriodicSync defaultSync;
350 // Old version is one sync a day. Empty bundle gets replaced by any addPeriodicSync()
351 // call.
352 if (base.target_provider) {
353 defaultSync =
354 new PeriodicSync(base.account, base.provider,
355 new Bundle(),
356 DEFAULT_POLL_FREQUENCY_SECONDS,
357 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
358 periodicSyncs.add(defaultSync);
359 }
360
Matthew Williamsfa774182013-06-18 15:44:11 -0700361 }
362
363 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700364 * Two AuthorityInfos are considered equal if they have the same authority.
Matthew Williamsfa774182013-06-18 15:44:11 -0700365 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700366 public boolean equals(EndPoint other) {
367 return base.matches(other);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700368 }
369 }
Costin Manolache360e4542009-09-04 13:36:04 -0700370
Dianne Hackborn231cc602009-04-27 17:10:36 -0700371 public static class SyncHistoryItem {
372 int authorityId;
373 int historyId;
374 long eventTime;
375 long elapsedTime;
376 int source;
377 int event;
378 long upstreamActivity;
379 long downstreamActivity;
380 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700381 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700382 Bundle extras;
383 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700384 }
Costin Manolache360e4542009-09-04 13:36:04 -0700385
Dianne Hackborn231cc602009-04-27 17:10:36 -0700386 public static class DayStats {
387 public final int day;
388 public int successCount;
389 public long successTime;
390 public int failureCount;
391 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700392
Dianne Hackborn231cc602009-04-27 17:10:36 -0700393 public DayStats(int day) {
394 this.day = day;
395 }
396 }
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Amith Yamasani04e0d262012-02-14 11:50:53 -0800398 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700399
400 /** Called when a sync is needed on an account(s) due to some change in state. */
401 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800402 }
403
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 // Primary list of all syncable authorities. Also our global lock.
405 private final SparseArray<AuthorityInfo> mAuthorities =
406 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700407
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408 private final HashMap<AccountAndUser, AccountInfo> mAccounts
409 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410
Dianne Hackborn231cc602009-04-27 17:10:36 -0700411 private final ArrayList<PendingOperation> mPendingOperations =
412 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700413
Amith Yamasani04e0d262012-02-14 11:50:53 -0800414 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
415 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 private final SparseArray<SyncStatusInfo> mSyncStatus =
418 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 private final ArrayList<SyncHistoryItem> mSyncHistory =
421 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700422
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
424 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700425
Matthew Williamsfa774182013-06-18 15:44:11 -0700426 /** Reverse mapping for component name -> <userid -> authority id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700427 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
428 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700429
Fred Quintana77c560f2010-03-29 22:20:26 -0700430 private int mNextAuthorityId = 0;
431
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 // We keep 4 weeks of stats.
433 private final DayStats[] mDayStats = new DayStats[7*4];
434 private final Calendar mCal;
435 private int mYear;
436 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800439
Dianne Hackborn231cc602009-04-27 17:10:36 -0700440 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700441
Ashish Sharma69d95de2012-04-11 17:27:24 -0700442 private int mSyncRandomOffset;
443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 /**
445 * This file contains the core engine state: all accounts and the
446 * settings for them. It must never be lost, and should be changed
447 * infrequently, so it is stored as an XML file.
448 */
449 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700450
Dianne Hackborn231cc602009-04-27 17:10:36 -0700451 /**
452 * This file contains the current sync status. We would like to retain
453 * it across boots, but its loss is not the end of the world, so we store
454 * this information as binary data.
455 */
456 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700457
Dianne Hackborn231cc602009-04-27 17:10:36 -0700458 /**
459 * This file contains sync statistics. This is purely debugging information
460 * so is written infrequently and can be thrown away at any time.
461 */
462 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700463
Dianne Hackborn231cc602009-04-27 17:10:36 -0700464 /**
465 * This file contains the pending sync operations. It is a binary file,
466 * which must be updated every time an operation is added or removed,
467 * so we have special handling of it.
468 */
469 private final AtomicFile mPendingFile;
470 private static final int PENDING_FINISH_TO_WRITE = 4;
471 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700472
Dianne Hackborn231cc602009-04-27 17:10:36 -0700473 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800475 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800476
477 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700478
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800479 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700482
Dianne Hackborn231cc602009-04-27 17:10:36 -0700483 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700484
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800485 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
486 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
487
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 File systemDir = new File(dataDir, "system");
489 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800490 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700491
492 maybeDeleteLegacyPendingInfoLocked(syncDir);
493
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
495 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700496 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700497 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700498
Dianne Hackborn231cc602009-04-27 17:10:36 -0700499 readAccountInfoLocked();
500 readStatusLocked();
501 readPendingOperationsLocked();
502 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700503 readAndDeleteLegacyAccountInfoLocked();
504 writeAccountInfoLocked();
505 writeStatusLocked();
506 writePendingOperationsLocked();
507 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
510 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800511 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513
514 public static void init(Context context) {
515 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800516 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800518 // This call will return the correct directory whether Encrypted File Systems is
519 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600520 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800521 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
524 public static SyncStorageEngine getSingleton() {
525 if (sSyncStorageEngine == null) {
526 throw new IllegalStateException("not initialized");
527 }
528 return sSyncStorageEngine;
529 }
530
Amith Yamasani04e0d262012-02-14 11:50:53 -0800531 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
532 if (mSyncRequestListener == null) {
533 mSyncRequestListener = listener;
534 }
535 }
536
Dianne Hackborn231cc602009-04-27 17:10:36 -0700537 @Override public void handleMessage(Message msg) {
538 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700539 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700540 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700541 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700542 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700543 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546 }
547 }
Costin Manolache360e4542009-09-04 13:36:04 -0700548
Ashish Sharma69d95de2012-04-11 17:27:24 -0700549 public int getSyncRandomOffset() {
550 return mSyncRandomOffset;
551 }
552
Dianne Hackborn231cc602009-04-27 17:10:36 -0700553 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
554 synchronized (mAuthorities) {
555 mChangeListeners.register(callback, mask);
556 }
557 }
Costin Manolache360e4542009-09-04 13:36:04 -0700558
Dianne Hackborn231cc602009-04-27 17:10:36 -0700559 public void removeStatusChangeListener(ISyncStatusObserver callback) {
560 synchronized (mAuthorities) {
561 mChangeListeners.unregister(callback);
562 }
563 }
Costin Manolache360e4542009-09-04 13:36:04 -0700564
Matthew Williamsfa774182013-06-18 15:44:11 -0700565 /**
566 * Figure out a reasonable flex time for cases where none is provided (old api calls).
567 * @param syncTimeSeconds requested sync time from now.
568 * @return amount of seconds before syncTimeSeconds that the sync can occur.
569 * I.e.
570 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700571 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700572 */
573 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
574 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
575 // Small enough sync request time that we don't add flex time - developer probably
576 // wants to wait for an operation to occur before syncing so we honour the
577 // request time.
578 return 0L;
579 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
580 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
581 } else {
582 // Large enough sync request time that we cap the flex time.
583 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
584 }
585 }
586
Dianne Hackborn231cc602009-04-27 17:10:36 -0700587 private void reportChange(int which) {
588 ArrayList<ISyncStatusObserver> reports = null;
589 synchronized (mAuthorities) {
590 int i = mChangeListeners.beginBroadcast();
591 while (i > 0) {
592 i--;
593 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
594 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 continue;
596 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700597 if (reports == null) {
598 reports = new ArrayList<ISyncStatusObserver>(i);
599 }
600 reports.add(mChangeListeners.getBroadcastItem(i));
601 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700602 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700603 }
Costin Manolache360e4542009-09-04 13:36:04 -0700604
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700605 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700606 Log.v(TAG, "reportChange " + which + " to: " + reports);
607 }
Costin Manolache360e4542009-09-04 13:36:04 -0700608
Dianne Hackborn231cc602009-04-27 17:10:36 -0700609 if (reports != null) {
610 int i = reports.size();
611 while (i > 0) {
612 i--;
613 try {
614 reports.get(i).onStatusChanged(which);
615 } catch (RemoteException e) {
616 // The remote callback list will take care of this for us.
617 }
618 }
619 }
620 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700621
Amith Yamasani04e0d262012-02-14 11:50:53 -0800622 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700623 synchronized (mAuthorities) {
624 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700625 AuthorityInfo authority = getAuthorityLocked(
626 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700627 "getSyncAutomatically");
628 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700629 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700630
Dianne Hackborn231cc602009-04-27 17:10:36 -0700631 int i = mAuthorities.size();
632 while (i > 0) {
633 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700634 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
635 if (authorityInfo.base.matches(new EndPoint(account, providerName, userId))
636 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700637 return true;
638 }
639 }
640 return false;
641 }
642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643
Amith Yamasani04e0d262012-02-14 11:50:53 -0800644 public void setSyncAutomatically(Account account, int userId, String providerName,
645 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800647 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
648 + ", user " + userId + " -> " + sync);
649 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700650 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700651 AuthorityInfo authority =
652 getOrCreateAuthorityLocked(
653 new EndPoint(account, providerName, userId),
654 -1 /* ident */,
655 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700656 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700657 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800658 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
659 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700660 return;
661 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700662 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700663 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700665
Fred Quintana77c560f2010-03-29 22:20:26 -0700666 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700667 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
668 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700669 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700670 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672
Amith Yamasani04e0d262012-02-14 11:50:53 -0800673 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700674 synchronized (mAuthorities) {
675 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700676 AuthorityInfo authority = getAuthorityLocked(
677 new EndPoint(account, providerName, userId),
678 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700679 if (authority == null) {
680 return -1;
681 }
682 return authority.syncable;
683 }
684
685 int i = mAuthorities.size();
686 while (i > 0) {
687 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700688 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
689 if (authorityInfo.base != null
690 && authorityInfo.base.provider.equals(providerName)) {
691 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700692 }
693 }
694 return -1;
695 }
696 }
697
Amith Yamasani04e0d262012-02-14 11:50:53 -0800698 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700699 synchronized (mAuthorities) {
700 AuthorityInfo authority =
701 getOrCreateAuthorityLocked(
702 new EndPoint(account, providerName, userId),
703 -1 /* ident */,
704 false);
705 setSyncableLocked(authority, syncable);
706 }
707 }
708
709 public int getIsTargetServiceActive(ComponentName cname, int userId) {
710 synchronized (mAuthorities) {
711 if (cname != null) {
712 AuthorityInfo authority = getAuthorityLocked(
713 new EndPoint(cname, userId),
714 "get service enabled");
715 if (authority == null) {
716 return -1;
717 }
718 return authority.syncable;
719 }
720 return -1;
721 }
722 }
723
724 public void setIsEnabled(ComponentName cname, int userId, int syncable) {
725 synchronized (mAuthorities) {
726 AuthorityInfo authority =
727 getOrCreateAuthorityLocked(
728 new EndPoint(cname, userId), -1, false);
729 setSyncableLocked(authority, syncable);
730 }
731 }
732
733 /**
734 * An enabled sync service and a syncable provider's adapter both get resolved to the same
735 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
736 * @param aInfo
737 * @param syncable
738 */
739 private void setSyncableLocked(AuthorityInfo aInfo, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700740 if (syncable > 1) {
741 syncable = 1;
742 } else if (syncable < -1) {
743 syncable = -1;
744 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
746 Log.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700747 }
748
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 if (aInfo.syncable == syncable) {
750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
751 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
752 }
753 return;
754 }
755 aInfo.syncable = syncable;
756 writeAccountInfoLocked();
757
Fred Quintana77c560f2010-03-29 22:20:26 -0700758 if (syncable > 0) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700759 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700760 }
761 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
762 }
763
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700764 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800765 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700766 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
767 if (authority != null) {
768 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800769 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700770 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800771 }
772 }
773
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700774 /**
775 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
776 * the account or provider info be null, which signifies all accounts or providers.
777 */
778 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
780 Log.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800781 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
782 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700783 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800784 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700785 if (info.target_provider
786 && (info.account == null || info.provider == null)) {
787 // Do more work for a provider sync if the provided info has specified all
788 // accounts/providers.
789 changed = setBackoffLocked(
790 info.account /* may be null */,
791 info.userId,
792 info.provider /* may be null */,
793 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800794 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700795 AuthorityInfo authorityInfo =
796 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
797 if (authorityInfo.backoffTime == nextSyncTime
798 && authorityInfo.backoffDelay == nextDelay) {
799 changed = false;
800 } else {
801 authorityInfo.backoffTime = nextSyncTime;
802 authorityInfo.backoffDelay = nextDelay;
803 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800804 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800805 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800806 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800807 if (changed) {
808 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
809 }
810 }
811
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700812 /**
813 * Either set backoff for a specific authority, or set backoff for all the
814 * accounts on a specific adapter/all adapters.
815 *
816 * @param account account for which to set backoff. Null to specify all accounts.
817 * @param userId id of the user making this request.
818 * @param providerName provider for which to set backoff. Null to specify all providers.
819 */
820 private boolean setBackoffLocked(Account account, int userId, String providerName,
821 long nextSyncTime, long nextDelay) {
822 boolean changed = false;
823 for (AccountInfo accountInfo : mAccounts.values()) {
824 if (account != null && !account.equals(accountInfo.accountAndUser.account)
825 && userId != accountInfo.accountAndUser.userId) {
826 continue;
827 }
828 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
829 if (providerName != null
830 && !providerName.equals(authorityInfo.base.provider)) {
831 continue;
832 }
833 if (authorityInfo.backoffTime != nextSyncTime
834 || authorityInfo.backoffDelay != nextDelay) {
835 authorityInfo.backoffTime = nextSyncTime;
836 authorityInfo.backoffDelay = nextDelay;
837 changed = true;
838 }
839 }
840 }
841 return changed;
842 }
843
Alon Alberted1d2532011-02-15 14:02:14 -0800844 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800845 boolean changed = false;
846 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700847 synchronized (syncQueue) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700848 // Clear backoff for all sync adapters.
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700849 for (AccountInfo accountInfo : mAccounts.values()) {
850 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
851 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
852 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700853 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700854 Log.v(TAG, "clearAllBackoffs:"
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700855 + " authority:" + authorityInfo.base
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700856 + " account:" + accountInfo.accountAndUser.account.name
857 + " user:" + accountInfo.accountAndUser.userId
858 + " backoffTime was: " + authorityInfo.backoffTime
859 + " backoffDelay was: " + authorityInfo.backoffDelay);
860 }
861 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
862 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700863 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800864 }
Alon Albert744e310f2010-12-14 11:37:20 -0800865 }
866 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700867 // Clear backoff for all sync services.
868 for (ComponentName service : mServices.keySet()) {
869 SparseArray<AuthorityInfo> aInfos = mServices.get(service);
870 for (int i = 0; i < aInfos.size(); i++) {
871 AuthorityInfo authorityInfo = aInfos.valueAt(i);
872 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
873 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
874 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
875 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
876 }
877 }
878 }
879 syncQueue.clearBackoffs();
Alon Albert744e310f2010-12-14 11:37:20 -0800880 }
881 }
882
883 if (changed) {
884 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
885 }
886 }
887
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700888 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800889 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700890 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800891 if (authority == null) {
892 return 0;
893 }
894 return authority.delayUntil;
895 }
896 }
897
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700898 public void setDelayUntilTime(EndPoint info, long delayUntil) {
899 if (Log.isLoggable(TAG, Log.VERBOSE)) {
900 Log.v(TAG, "setDelayUntil: " + info
901 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800902 }
903 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700904 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
905 if (authority.delayUntil == delayUntil) {
906 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700907 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700908 authority.delayUntil = delayUntil;
909 }
910 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
911 }
912
913 public void updateOrAddPeriodicSync(EndPoint info, long period, long flextime, Bundle extras) {
914 if (Log.isLoggable(TAG, Log.VERBOSE)) {
915 Log.v(TAG, "addPeriodicSync: " + info
916 + " -> period " + period + ", flex " + flextime + ", extras "
917 + extras.toString());
918 }
919 synchronized (mAuthorities) {
920 if (period <= 0) {
921 Log.e(TAG, "period < 0, should never happen in updateOrAddPeriodicSync");
922 }
923 if (extras == null) {
924 Log.e(TAG, "null extras, should never happen in updateOrAddPeriodicSync:");
Matthew Williamsfa774182013-06-18 15:44:11 -0700925 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700926 try {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700927 PeriodicSync toUpdate;
928 if (info.target_provider) {
929 toUpdate = new PeriodicSync(info.account,
930 info.provider,
931 extras,
932 period,
933 flextime);
Fred Quintana77c560f2010-03-29 22:20:26 -0700934 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700935 toUpdate = new PeriodicSync(info.service,
936 extras,
937 period,
938 flextime);
939 }
940 AuthorityInfo authority =
941 getOrCreateAuthorityLocked(info, -1, false);
942 // add this periodic sync if an equivalent periodic doesn't already exist.
943 boolean alreadyPresent = false;
944 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
945 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
946 if (SyncManager.syncExtrasEquals(syncInfo.extras,
947 extras,
948 true /* includeSyncSettings*/)) {
949 if (period == syncInfo.period &&
950 flextime == syncInfo.flexTime) {
951 // Absolutely the same.
952 Log.e(TAG, "update psync: exactly the same.");
953 return;
Fred Quintana77c560f2010-03-29 22:20:26 -0700954 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700955 authority.periodicSyncs.set(i, toUpdate);
956 alreadyPresent = true;
957 break;
Fred Quintana77c560f2010-03-29 22:20:26 -0700958 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700959 }
960 // If we added an entry to the periodicSyncs array also add an entry to
961 // the periodic syncs status to correspond to it.
962 if (!alreadyPresent) {
963 authority.periodicSyncs.add(toUpdate);
964 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
965 // A new periodic sync is initialised as already having been run.
966 status.setPeriodicSyncTime(
967 authority.periodicSyncs.size() - 1,
968 System.currentTimeMillis());
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800969 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700970 } finally {
971 writeAccountInfoLocked();
972 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800973 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800974 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800975 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
976 }
977
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700978 public void removePeriodicSync(EndPoint info, Bundle extras) {
979 synchronized(mAuthorities) {
980 try {
981 AuthorityInfo authority =
982 getOrCreateAuthorityLocked(info, -1, false);
983 // Remove any periodic syncs that match the authority and extras.
984 SyncStatusInfo status = mSyncStatus.get(authority.ident);
985 boolean changed = false;
986 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
987 int i = 0;
988 while (iterator.hasNext()) {
989 PeriodicSync syncInfo = iterator.next();
990 if (SyncManager.syncExtrasEquals(syncInfo.extras,
991 extras,
992 true /* includeSyncSettings */)) {
993 iterator.remove();
994 changed = true;
995 // If we removed an entry from the periodicSyncs array also
996 // remove the corresponding entry from the status
997 if (status != null) {
998 status.removePeriodicSyncTime(i);
999 } else {
1000 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
1001 + " did not find it.");
1002 }
1003 } else {
1004 i++;
1005 }
1006 }
1007 if (!changed) {
1008 return;
1009 }
1010 } finally {
1011 writeAccountInfoLocked();
1012 writeStatusLocked();
1013 }
1014 }
1015 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001016 }
1017
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001018 /**
1019 * @return list of periodic syncs for an authority. Never returns null - if no such syncs
1020 * exist, returns an empty list.
1021 */
1022 public List<PeriodicSync> getPeriodicSyncs(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001023 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001024 AuthorityInfo authorityInfo = getAuthorityLocked(info, "getPeriodicSyncs");
1025 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
1026 if (authorityInfo != null) {
1027 for (PeriodicSync item : authorityInfo.periodicSyncs) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001028 // Copy and send out. Necessary for thread-safety although it's parceled.
1029 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001030 }
1031 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001032 return syncs;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001033 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001034 }
1035
Amith Yamasani04e0d262012-02-14 11:50:53 -08001036 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001037 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001038 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001039 if (auto != null && auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001040 return;
1041 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001043 writeAccountInfoLocked();
1044 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001045 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -07001046 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
1047 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -07001048 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001049 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -08001050 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052
Amith Yamasani04e0d262012-02-14 11:50:53 -08001053 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001055 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001056 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 }
1058 }
Costin Manolache360e4542009-09-04 13:36:04 -07001059
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 public AuthorityInfo getAuthority(int authorityId) {
1061 synchronized (mAuthorities) {
1062 return mAuthorities.get(authorityId);
1063 }
1064 }
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001067 * Returns true if there is currently a sync operation being actively processed for the given
1068 * authority.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001069 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001070 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001072 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001073 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001074 if (ainfo != null && ainfo.base.matches(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 return true;
1076 }
1077 }
1078 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001079 return false;
1080 }
Costin Manolache360e4542009-09-04 13:36:04 -07001081
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001082 public PendingOperation insertIntoPending(SyncOperation op) {
1083 PendingOperation pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001085 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1086 Log.v(TAG, "insertIntoPending: authority=" + op.target
Amith Yamasani04e0d262012-02-14 11:50:53 -08001087 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -07001088 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001089 final EndPoint info = op.target;
1090 AuthorityInfo authority =
1091 getOrCreateAuthorityLocked(info,
1092 -1 /* desired identifier */,
1093 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 if (authority == null) {
1095 return null;
1096 }
Costin Manolache360e4542009-09-04 13:36:04 -07001097
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001098 pop = new PendingOperation(authority, op.reason, op.syncSource, op.extras,
1099 op.expedited);
1100 mPendingOperations.add(pop);
1101 writePendingOperationsLocked();
Costin Manolache360e4542009-09-04 13:36:04 -07001102
Dianne Hackborn231cc602009-04-27 17:10:36 -07001103 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1104 status.pending = true;
1105 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001106 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001107 return pop;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 }
1109
Matthew Williamsfa774182013-06-18 15:44:11 -07001110 /**
1111 * Remove from list of pending operations. If successful, search through list for matching
1112 * authorities. If there are no more pending syncs for the same authority/account/userid,
1113 * update the SyncStatusInfo for that authority(authority here is the internal representation
1114 * of a 'sync operation'.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001115 * @param op Pending op to delete.
Matthew Williamsfa774182013-06-18 15:44:11 -07001116 */
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 public boolean deleteFromPending(PendingOperation op) {
1118 boolean res = false;
1119 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1121 Log.v(TAG, "deleteFromPending: account=" + op.toString());
Fred Quintana77c560f2010-03-29 22:20:26 -07001122 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 if (mPendingOperations.remove(op)) {
1124 if (mPendingOperations.size() == 0
1125 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
1126 writePendingOperationsLocked();
1127 mNumPendingFinished = 0;
1128 } else {
1129 mNumPendingFinished++;
1130 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001131 AuthorityInfo authority = getAuthorityLocked(op.authority, "deleteFromPending");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 if (authority != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001133 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1134 Log.v(TAG, "removing - " + authority.toString());
1135 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 final int N = mPendingOperations.size();
1137 boolean morePending = false;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001138 for (int i = 0; i < N; i++) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 PendingOperation cur = mPendingOperations.get(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001140 if (cur.equals(op)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 morePending = true;
1142 break;
1143 }
1144 }
Costin Manolache360e4542009-09-04 13:36:04 -07001145
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 if (!morePending) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001147 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1149 status.pending = false;
1150 }
1151 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 res = true;
1153 }
1154 }
Costin Manolache360e4542009-09-04 13:36:04 -07001155
Fred Quintanaac9385e2009-06-22 18:00:59 -07001156 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 return res;
1158 }
1159
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 /**
1161 * Return a copy of the current array of pending operations. The
1162 * PendingOperation objects are the real objects stored inside, so that
1163 * they can be used with deleteFromPending().
1164 */
1165 public ArrayList<PendingOperation> getPendingOperations() {
1166 synchronized (mAuthorities) {
1167 return new ArrayList<PendingOperation>(mPendingOperations);
1168 }
1169 }
Costin Manolache360e4542009-09-04 13:36:04 -07001170
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 /**
1172 * Return the number of currently pending operations.
1173 */
1174 public int getPendingOperationCount() {
1175 synchronized (mAuthorities) {
1176 return mPendingOperations.size();
1177 }
1178 }
Costin Manolache360e4542009-09-04 13:36:04 -07001179
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 /**
1181 * Called when the set of account has changed, given the new array of
1182 * active accounts.
1183 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001184 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001186 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001187 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1188 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1189 while (accIt.hasNext()) {
1190 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001191 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1192 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001193 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001195 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001196 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 for (AuthorityInfo auth : acc.authorities.values()) {
1198 removing.put(auth.ident, auth);
1199 }
1200 accIt.remove();
1201 }
1202 }
Costin Manolache360e4542009-09-04 13:36:04 -07001203
Dianne Hackborn231cc602009-04-27 17:10:36 -07001204 // Clean out all data structures.
1205 int i = removing.size();
1206 if (i > 0) {
1207 while (i > 0) {
1208 i--;
1209 int ident = removing.keyAt(i);
1210 mAuthorities.remove(ident);
1211 int j = mSyncStatus.size();
1212 while (j > 0) {
1213 j--;
1214 if (mSyncStatus.keyAt(j) == ident) {
1215 mSyncStatus.remove(mSyncStatus.keyAt(j));
1216 }
1217 }
1218 j = mSyncHistory.size();
1219 while (j > 0) {
1220 j--;
1221 if (mSyncHistory.get(j).authorityId == ident) {
1222 mSyncHistory.remove(j);
1223 }
1224 }
1225 }
1226 writeAccountInfoLocked();
1227 writeStatusLocked();
1228 writePendingOperationsLocked();
1229 writeStatisticsLocked();
1230 }
1231 }
1232 }
1233
1234 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001235 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1236 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 */
Fred Quintana918339a2010-10-05 14:00:39 -07001238 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1239 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001240 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001241 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001242 Log.v(TAG, "setActiveSync: account="
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001243 + " auth=" + activeSyncContext.mSyncOperation.target
Fred Quintana918339a2010-10-05 14:00:39 -07001244 + " src=" + activeSyncContext.mSyncOperation.syncSource
1245 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001246 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001247 final EndPoint info = activeSyncContext.mSyncOperation.target;
1248 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1249 info,
Fred Quintana918339a2010-10-05 14:00:39 -07001250 -1 /* assign a new identifier if creating a new authority */,
1251 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001252 syncInfo = new SyncInfo(
1253 authorityInfo.ident,
1254 authorityInfo.base.account,
1255 authorityInfo.base.provider,
1256 authorityInfo.base.service,
Fred Quintana918339a2010-10-05 14:00:39 -07001257 activeSyncContext.mStartTime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001258 getCurrentSyncs(authorityInfo.base.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001259 }
Fred Quintana918339a2010-10-05 14:00:39 -07001260 reportActiveChange();
1261 return syncInfo;
1262 }
1263
1264 /**
1265 * Called to indicate that a previously active sync is no longer active.
1266 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001268 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001269 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001270 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1271 + " user=" + userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001272 + " auth=" + syncInfo.authority
1273 + " service=" + syncInfo.service);
Fred Quintana918339a2010-10-05 14:00:39 -07001274 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001275 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001276 }
1277
1278 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001279 }
1280
1281 /**
1282 * To allow others to send active change reports, to poke clients.
1283 */
1284 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001285 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 }
Costin Manolache360e4542009-09-04 13:36:04 -07001287
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 /**
1289 * Note that sync has started for the given account and authority.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001290 *
1291 syncOperation.account, syncOperation.userId, syncOperation.reason,
1292 syncOperation.authority,
1293 now, source, syncOperation.isInitialization(), syncOperation.extras
Dianne Hackborn231cc602009-04-27 17:10:36 -07001294 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001295 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 long id;
1297 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001298 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1299 Log.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001300 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001301 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001302 if (authority == null) {
1303 return -1;
1304 }
1305 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001306 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 item.authorityId = authority.ident;
1308 item.historyId = mNextHistoryId++;
1309 if (mNextHistoryId < 0) mNextHistoryId = 0;
1310 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001311 item.source = op.syncSource;
1312 item.reason = op.reason;
1313 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001314 item.event = EVENT_START;
1315 mSyncHistory.add(0, item);
1316 while (mSyncHistory.size() > MAX_HISTORY) {
1317 mSyncHistory.remove(mSyncHistory.size()-1);
1318 }
1319 id = item.historyId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001320 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 }
Costin Manolache360e4542009-09-04 13:36:04 -07001322
Fred Quintanaac9385e2009-06-22 18:00:59 -07001323 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001324 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326
Fred Quintana77c560f2010-03-29 22:20:26 -07001327 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001330 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001331 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1332 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001333 SyncHistoryItem item = null;
1334 int i = mSyncHistory.size();
1335 while (i > 0) {
1336 i--;
1337 item = mSyncHistory.get(i);
1338 if (item.historyId == historyId) {
1339 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001341 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
Costin Manolache360e4542009-09-04 13:36:04 -07001343
Dianne Hackborn231cc602009-04-27 17:10:36 -07001344 if (item == null) {
1345 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1346 return;
1347 }
Costin Manolache360e4542009-09-04 13:36:04 -07001348
Dianne Hackborn231cc602009-04-27 17:10:36 -07001349 item.elapsedTime = elapsedTime;
1350 item.event = EVENT_STOP;
1351 item.mesg = resultMessage;
1352 item.downstreamActivity = downstreamActivity;
1353 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001354
Dianne Hackborn231cc602009-04-27 17:10:36 -07001355 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001356
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 status.numSyncs++;
1358 status.totalElapsedTime += elapsedTime;
1359 switch (item.source) {
1360 case SOURCE_LOCAL:
1361 status.numSourceLocal++;
1362 break;
1363 case SOURCE_POLL:
1364 status.numSourcePoll++;
1365 break;
1366 case SOURCE_USER:
1367 status.numSourceUser++;
1368 break;
1369 case SOURCE_SERVER:
1370 status.numSourceServer++;
1371 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001372 case SOURCE_PERIODIC:
1373 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001374 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001375 }
Costin Manolache360e4542009-09-04 13:36:04 -07001376
Dianne Hackborn231cc602009-04-27 17:10:36 -07001377 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001378 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 if (mDayStats[0] == null) {
1380 mDayStats[0] = new DayStats(day);
1381 } else if (day != mDayStats[0].day) {
1382 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1383 mDayStats[0] = new DayStats(day);
1384 writeStatisticsNow = true;
1385 } else if (mDayStats[0] == null) {
1386 }
1387 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001388
Dianne Hackborn231cc602009-04-27 17:10:36 -07001389 final long lastSyncTime = (item.eventTime + elapsedTime);
1390 boolean writeStatusNow = false;
1391 if (MESG_SUCCESS.equals(resultMessage)) {
1392 // - if successful, update the successful columns
1393 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1394 writeStatusNow = true;
1395 }
1396 status.lastSuccessTime = lastSyncTime;
1397 status.lastSuccessSource = item.source;
1398 status.lastFailureTime = 0;
1399 status.lastFailureSource = -1;
1400 status.lastFailureMesg = null;
1401 status.initialFailureTime = 0;
1402 ds.successCount++;
1403 ds.successTime += elapsedTime;
1404 } else if (!MESG_CANCELED.equals(resultMessage)) {
1405 if (status.lastFailureTime == 0) {
1406 writeStatusNow = true;
1407 }
1408 status.lastFailureTime = lastSyncTime;
1409 status.lastFailureSource = item.source;
1410 status.lastFailureMesg = resultMessage;
1411 if (status.initialFailureTime == 0) {
1412 status.initialFailureTime = lastSyncTime;
1413 }
1414 ds.failureCount++;
1415 ds.failureTime += elapsedTime;
1416 }
Costin Manolache360e4542009-09-04 13:36:04 -07001417
Dianne Hackborn231cc602009-04-27 17:10:36 -07001418 if (writeStatusNow) {
1419 writeStatusLocked();
1420 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1421 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1422 WRITE_STATUS_DELAY);
1423 }
1424 if (writeStatisticsNow) {
1425 writeStatisticsLocked();
1426 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1427 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1428 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001429 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001430 }
Costin Manolache360e4542009-09-04 13:36:04 -07001431
Fred Quintanaac9385e2009-06-22 18:00:59 -07001432 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001433 }
1434
1435 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001436 * Return a list of the currently active syncs. Note that the returned items are the
1437 * real, live active sync objects, so be careful what you do with it.
1438 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001439 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001440 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001441 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1442 if (syncs == null) {
1443 syncs = new ArrayList<SyncInfo>();
1444 mCurrentSyncs.put(userId, syncs);
1445 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001446 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 }
1448 }
Costin Manolache360e4542009-09-04 13:36:04 -07001449
Dianne Hackborn231cc602009-04-27 17:10:36 -07001450 /**
1451 * Return an array of the current sync status for all authorities. Note
1452 * that the objects inside the array are the real, live status objects,
1453 * so be careful what you do with them.
1454 */
1455 public ArrayList<SyncStatusInfo> getSyncStatus() {
1456 synchronized (mAuthorities) {
1457 final int N = mSyncStatus.size();
1458 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1459 for (int i=0; i<N; i++) {
1460 ops.add(mSyncStatus.valueAt(i));
1461 }
1462 return ops;
1463 }
1464 }
Costin Manolache360e4542009-09-04 13:36:04 -07001465
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 /**
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001467 * Return a copy of the specified authority with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001468 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001469 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001470 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001471 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001472 -1 /* assign a new identifier if creating a new authority */,
1473 true /* write to storage if this results in a change */);
1474 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1475 }
1476 }
1477
1478 /**
1479 * Return a copy of all authorities with their corresponding sync status
1480 */
1481 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1482 synchronized (mAuthorities) {
1483 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1484 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1485 for (int i = 0; i < mAuthorities.size(); i++) {
1486 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001487 }
1488 return infos;
1489 }
1490 }
1491
1492 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001493 * Returns the status that matches the authority and account.
1494 *
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001495 * @param info the target we want to check
1496 * @return the SyncStatusInfo for the target
Dianne Hackborn231cc602009-04-27 17:10:36 -07001497 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001498 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
1499 if (info.target_provider && (info.account == null || info.provider == null)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001500 throw new IllegalArgumentException();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001501 } else if (info.target_service && info.service == null) {
1502 throw new IllegalArgumentException();
Costin Manolacheb7520982009-09-02 18:03:05 -07001503 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001504 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001505 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001506 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001507 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001508 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001509 if (ainfo != null
1510 && ainfo.base.matches(info)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001511 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001512 }
1513 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001514 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001515 }
1516 }
Costin Manolache360e4542009-09-04 13:36:04 -07001517
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001518 /** Return true if the pending status is true of any matching authorities. */
1519 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 synchronized (mAuthorities) {
1521 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001522 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001523 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1525 if (ainfo == null) {
1526 continue;
1527 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001528 if (!ainfo.base.matches(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001529 continue;
1530 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001531 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001532 return true;
1533 }
1534 }
1535 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537 }
1538
1539 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001540 * Return an array of the current sync status for all authorities. Note
1541 * that the objects inside the array are the real, live status objects,
1542 * so be careful what you do with them.
1543 */
1544 public ArrayList<SyncHistoryItem> getSyncHistory() {
1545 synchronized (mAuthorities) {
1546 final int N = mSyncHistory.size();
1547 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1548 for (int i=0; i<N; i++) {
1549 items.add(mSyncHistory.get(i));
1550 }
1551 return items;
1552 }
1553 }
Costin Manolache360e4542009-09-04 13:36:04 -07001554
Dianne Hackborn231cc602009-04-27 17:10:36 -07001555 /**
1556 * Return an array of the current per-day statistics. Note
1557 * that the objects inside the array are the real, live status objects,
1558 * so be careful what you do with them.
1559 */
1560 public DayStats[] getDayStatistics() {
1561 synchronized (mAuthorities) {
1562 DayStats[] ds = new DayStats[mDayStats.length];
1563 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1564 return ds;
1565 }
1566 }
Costin Manolache360e4542009-09-04 13:36:04 -07001567
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001568 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1569 AuthorityInfo authorityInfo) {
1570 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1571 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1572 }
1573
Dianne Hackborn55280a92009-05-07 15:53:46 -07001574 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001575 mCal.setTimeInMillis(System.currentTimeMillis());
1576 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1577 if (mYear != mCal.get(Calendar.YEAR)) {
1578 mYear = mCal.get(Calendar.YEAR);
1579 mCal.clear();
1580 mCal.set(Calendar.YEAR, mYear);
1581 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1582 }
1583 return dayOfYear + mYearInDays;
1584 }
Costin Manolache360e4542009-09-04 13:36:04 -07001585
Dianne Hackborn231cc602009-04-27 17:10:36 -07001586 /**
1587 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001588 *
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001589 * @param info container for the info of the authority to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001590 * @param tag If non-null, this will be used in a log message if the
1591 * requested authority does not exist.
1592 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001593 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
1594 if (info.target_service) {
1595 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1596 AuthorityInfo authority = null;
1597 if (aInfo != null) {
1598 authority = aInfo.get(info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001599 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001600 if (authority == null) {
1601 if (tag != null) {
1602 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1603 Log.v(TAG, tag + " No authority info found for " + info.service + " for user "
1604 + info.userId);
1605 }
1606 }
1607 return null;
1608 }
1609 return authority;
1610 } else if (info.target_provider){
1611 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1612 AccountInfo accountInfo = mAccounts.get(au);
1613 if (accountInfo == null) {
1614 if (tag != null) {
1615 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1616 Log.v(TAG, tag + ": unknown account " + au);
1617 }
1618 }
1619 return null;
1620 }
1621 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1622 if (authority == null) {
1623 if (tag != null) {
1624 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1625 Log.v(TAG, tag + ": unknown provider " + info.provider);
1626 }
1627 }
1628 return null;
1629 }
1630 return authority;
1631 } else {
1632 Log.e(TAG, tag + " Authority : " + info + ", invalid target");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001633 return null;
1634 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001635 }
Costin Manolache360e4542009-09-04 13:36:04 -07001636
Matthew Williamsfa774182013-06-18 15:44:11 -07001637 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001638 * @param info info identifying authority.
Matthew Williamsfa774182013-06-18 15:44:11 -07001639 * @param ident unique identifier for authority. -1 for none.
1640 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001641 * @return the authority that corresponds to the provided sync authority, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001642 * exists.
1643 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001644 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1645 AuthorityInfo authority = null;
1646 if (info.target_service) {
1647 SparseArray<AuthorityInfo> aInfo = mServices.get(info.service);
1648 if (aInfo == null) {
1649 aInfo = new SparseArray<AuthorityInfo>();
1650 mServices.put(info.service, aInfo);
Matthew Williamsfa774182013-06-18 15:44:11 -07001651 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001652 authority = aInfo.get(info.userId);
1653 if (authority == null) {
1654 authority = createAuthorityLocked(info, ident, doWrite);
1655 aInfo.put(info.userId, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001656 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001657 } else if (info.target_provider) {
1658 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1659 AccountInfo account = mAccounts.get(au);
1660 if (account == null) {
1661 account = new AccountInfo(au);
1662 mAccounts.put(au, account);
1663 }
1664 authority = account.authorities.get(info.provider);
1665 if (authority == null) {
1666 authority = createAuthorityLocked(info, ident, doWrite);
1667 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001668 }
1669 }
1670 return authority;
1671 }
1672
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001673 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1674 AuthorityInfo authority;
1675 if (ident < 0) {
1676 ident = mNextAuthorityId;
1677 mNextAuthorityId++;
1678 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001679 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1681 Log.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001682 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001683 authority = new AuthorityInfo(info, ident);
1684 mAuthorities.put(ident, authority);
1685 if (doWrite) {
1686 writeAccountInfoLocked();
1687 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001688 return authority;
1689 }
Costin Manolache360e4542009-09-04 13:36:04 -07001690
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001691 public void removeAuthority(EndPoint info) {
1692 synchronized (mAuthorities) {
1693 if (info.target_provider) {
1694 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
1695 } else {
1696 SparseArray<AuthorityInfo> aInfos = mServices.get(info.service);
1697 if (aInfos != null) {
1698 AuthorityInfo authorityInfo = aInfos.get(info.userId);
1699 if (authorityInfo != null) {
1700 mAuthorities.remove(authorityInfo.ident);
1701 aInfos.delete(info.userId);
1702 writeAccountInfoLocked();
1703 }
1704 }
1705
1706 }
1707 }
1708 }
1709
1710 /**
1711 * Remove an authority associated with a provider. Needs to be a standalone function for
1712 * backward compatibility.
1713 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001714 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1715 boolean doWrite) {
1716 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001717 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001718 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1719 if (authorityInfo != null) {
1720 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001721 if (doWrite) {
1722 writeAccountInfoLocked();
1723 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001724 }
1725 }
1726 }
1727
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001728 /**
1729 * Updates (in a synchronized way) the periodic sync time of the specified
1730 * authority id and target periodic sync
1731 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001732 public void setPeriodicSyncTime(int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001733 boolean found = false;
1734 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001735 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001736 authorityInfo = mAuthorities.get(authorityId);
1737 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001738 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1739 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001740 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001741 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001742 break;
1743 }
1744 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001745 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001746 if (!found) {
1747 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001748 "Authority: " + authorityInfo.base);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001749 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001750 }
1751
Dianne Hackborn231cc602009-04-27 17:10:36 -07001752 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1753 SyncStatusInfo status = mSyncStatus.get(authorityId);
1754 if (status == null) {
1755 status = new SyncStatusInfo(authorityId);
1756 mSyncStatus.put(authorityId, status);
1757 }
1758 return status;
1759 }
Costin Manolache360e4542009-09-04 13:36:04 -07001760
Dianne Hackborn55280a92009-05-07 15:53:46 -07001761 public void writeAllState() {
1762 synchronized (mAuthorities) {
1763 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001764
Dianne Hackborn55280a92009-05-07 15:53:46 -07001765 if (mNumPendingFinished > 0) {
1766 // Only write these if they are out of date.
1767 writePendingOperationsLocked();
1768 }
Costin Manolache360e4542009-09-04 13:36:04 -07001769
Dianne Hackborn55280a92009-05-07 15:53:46 -07001770 // Just always write these... they are likely out of date.
1771 writeStatusLocked();
1772 writeStatisticsLocked();
1773 }
1774 }
Costin Manolache360e4542009-09-04 13:36:04 -07001775
Dianne Hackborn231cc602009-04-27 17:10:36 -07001776 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001777 * public for testing
1778 */
1779 public void clearAndReadState() {
1780 synchronized (mAuthorities) {
1781 mAuthorities.clear();
1782 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001783 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001784 mPendingOperations.clear();
1785 mSyncStatus.clear();
1786 mSyncHistory.clear();
1787
1788 readAccountInfoLocked();
1789 readStatusLocked();
1790 readPendingOperationsLocked();
1791 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001792 readAndDeleteLegacyAccountInfoLocked();
1793 writeAccountInfoLocked();
1794 writeStatusLocked();
1795 writePendingOperationsLocked();
1796 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001797 }
1798 }
1799
1800 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001801 * Read all account information back in to the initial engine state.
1802 */
1803 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001804 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001805 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001807 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001808 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1809 Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1810 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 XmlPullParser parser = Xml.newPullParser();
1812 parser.setInput(fis, null);
1813 int eventType = parser.getEventType();
1814 while (eventType != XmlPullParser.START_TAG) {
1815 eventType = parser.next();
1816 }
1817 String tagName = parser.getName();
1818 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001819 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001820 String versionString = parser.getAttributeValue(null, "version");
1821 int version;
1822 try {
1823 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1824 } catch (NumberFormatException e) {
1825 version = 0;
1826 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001827 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001828 try {
1829 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1830 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1831 } catch (NumberFormatException e) {
1832 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001833 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001834 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1835 try {
1836 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1837 } catch (NumberFormatException e) {
1838 mSyncRandomOffset = 0;
1839 }
1840 if (mSyncRandomOffset == 0) {
1841 Random random = new Random(System.currentTimeMillis());
1842 mSyncRandomOffset = random.nextInt(86400);
1843 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001844 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001845 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001846 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001847 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001848 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001849 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001850 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001851 if (parser.getDepth() == 2) {
1852 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001853 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001854 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001855 if (authority.ident > highestAuthorityId) {
1856 highestAuthorityId = authority.ident;
1857 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001858 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1859 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001860 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001861 } else if (parser.getDepth() == 3) {
1862 if ("periodicSync".equals(tagName) && authority != null) {
1863 periodicSync = parsePeriodicSync(parser, authority);
1864 }
1865 } else if (parser.getDepth() == 4 && periodicSync != null) {
1866 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001867 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001868 }
1869 }
1870 }
1871 eventType = parser.next();
1872 } while (eventType != XmlPullParser.END_DOCUMENT);
1873 }
1874 } catch (XmlPullParserException e) {
1875 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001876 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001877 } catch (java.io.IOException e) {
1878 if (fis == null) Log.i(TAG, "No initial accounts");
1879 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001880 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001881 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001882 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001883 if (fis != null) {
1884 try {
1885 fis.close();
1886 } catch (java.io.IOException e1) {
1887 }
1888 }
1889 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001890
Fred Quintana77c560f2010-03-29 22:20:26 -07001891 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001892 }
Costin Manolache360e4542009-09-04 13:36:04 -07001893
Fred Quintanafb084402010-03-23 17:57:03 -07001894 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001895 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1896 * pending.xml was used starting in KLP.
1897 * @param syncDir directory where the sync files are located.
1898 */
1899 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1900 File file = new File(syncDir, "pending.bin");
1901 if (!file.exists()) {
1902 return;
1903 } else {
1904 file.delete();
1905 }
1906 }
1907
1908 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001909 * some authority names have changed. copy over their settings and delete the old ones
1910 * @return true if a change was made
1911 */
1912 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1913 boolean writeNeeded = false;
1914
1915 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1916 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001917 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001918 AuthorityInfo authority = mAuthorities.valueAt(i);
1919 // skip this authority if it isn't one of the renamed ones
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001920 final String newAuthorityName = sAuthorityRenames.get(authority.base);
Fred Quintanafb084402010-03-23 17:57:03 -07001921 if (newAuthorityName == null) {
1922 continue;
1923 }
1924
1925 // remember this authority so we can remove it later. we can't remove it
1926 // now without messing up this loop iteration
1927 authoritiesToRemove.add(authority);
1928
1929 // this authority isn't enabled, no need to copy it to the new authority name since
1930 // the default is "disabled"
1931 if (!authority.enabled) {
1932 continue;
1933 }
1934
1935 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001936 EndPoint newInfo =
1937 new EndPoint(authority.base.account,
1938 newAuthorityName,
1939 authority.base.userId);
1940 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001941 continue;
1942 }
1943
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001944 AuthorityInfo newAuthority =
1945 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001946 newAuthority.enabled = true;
1947 writeNeeded = true;
1948 }
1949
1950 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001951 removeAuthorityLocked(
1952 authorityInfo.base.account,
1953 authorityInfo.base.userId,
1954 authorityInfo.base.provider,
1955 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001956 writeNeeded = true;
1957 }
1958
1959 return writeNeeded;
1960 }
1961
Amith Yamasani04e0d262012-02-14 11:50:53 -08001962 private void parseListenForTickles(XmlPullParser parser) {
1963 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1964 int userId = 0;
1965 try {
1966 userId = Integer.parseInt(user);
1967 } catch (NumberFormatException e) {
1968 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1969 } catch (NullPointerException e) {
1970 Log.e(TAG, "the user in listen-for-tickles is null", e);
1971 }
1972 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1973 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1974 mMasterSyncAutomatically.put(userId, listen);
1975 }
1976
Fred Quintanac2e46912010-03-15 16:10:44 -07001977 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001978 AuthorityInfo authority = null;
1979 int id = -1;
1980 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001981 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001982 } catch (NumberFormatException e) {
1983 Log.e(TAG, "error parsing the id of the authority", e);
1984 } catch (NullPointerException e) {
1985 Log.e(TAG, "the id of the authority is null", e);
1986 }
1987 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001988 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001989 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001990 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001991 String accountName = parser.getAttributeValue(null, "account");
1992 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001993 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001994 String packageName = parser.getAttributeValue(null, "package");
1995 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001996 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001997 if (accountType == null) {
1998 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001999 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002000 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002001 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07002002 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2003 Log.v(TAG, "Adding authority: account="
2004 + accountName + " auth=" + authorityName
2005 + " user=" + userId
2006 + " enabled=" + enabled
2007 + " syncable=" + syncable);
2008 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002009 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07002010 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002011 Log.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07002012 }
2013 if (accountName != null && accountType != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002014 EndPoint info =
2015 new EndPoint(
2016 new Account(accountName, accountType),
2017 authorityName, userId);
2018 authority = getOrCreateAuthorityLocked(info, id, false);
Matthew Williamsfa774182013-06-18 15:44:11 -07002019 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002020 EndPoint info =
2021 new EndPoint(new ComponentName(packageName, className), userId);
2022 authority = getOrCreateAuthorityLocked(info, id, false);
Matthew Williamsfa774182013-06-18 15:44:11 -07002023 }
Fred Quintanac2e46912010-03-15 16:10:44 -07002024 // If the version is 0 then we are upgrading from a file format that did not
2025 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07002026 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07002027 // Otherwise clear out this default list since we will populate it later with
2028 // the periodic sync descriptions that are read from the configuration file.
2029 if (version > 0) {
2030 authority.periodicSyncs.clear();
2031 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002032 }
2033 if (authority != null) {
2034 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
2035 if ("unknown".equals(syncable)) {
2036 authority.syncable = -1;
2037 } else {
2038 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07002039 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002040 }
2041 } else {
2042 Log.w(TAG, "Failure adding authority: account="
2043 + accountName + " auth=" + authorityName
2044 + " enabled=" + enabled
2045 + " syncable=" + syncable);
2046 }
2047 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002048 return authority;
2049 }
2050
Matthew Williamsfa774182013-06-18 15:44:11 -07002051 /**
2052 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
2053 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002054 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07002055 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002056 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07002057 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002058 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07002059 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002060 try {
2061 period = Long.parseLong(periodValue);
2062 } catch (NumberFormatException e) {
2063 Log.e(TAG, "error parsing the period of a periodic sync", e);
2064 return null;
2065 } catch (NullPointerException e) {
2066 Log.e(TAG, "the period of a periodic sync is null", e);
2067 return null;
2068 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002069 try {
2070 flextime = Long.parseLong(flexValue);
2071 } catch (NumberFormatException e) {
2072 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue);
2073 flextime = calculateDefaultFlexTime(period);
2074 } catch (NullPointerException expected) {
2075 flextime = calculateDefaultFlexTime(period);
2076 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
2077 + period + " flex: " + flextime);
2078 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002079 PeriodicSync periodicSync;
2080 if (authorityInfo.base.target_provider) {
2081 periodicSync =
2082 new PeriodicSync(authorityInfo.base.account,
2083 authorityInfo.base.provider,
2084 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07002085 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002086 } else {
2087 periodicSync =
2088 new PeriodicSync(
2089 authorityInfo.base.service,
2090 extras,
2091 period,
2092 flextime);
2093 }
2094 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002095 return periodicSync;
2096 }
2097
Matthew Williamsfa774182013-06-18 15:44:11 -07002098 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002099 String name = parser.getAttributeValue(null, "name");
2100 String type = parser.getAttributeValue(null, "type");
2101 String value1 = parser.getAttributeValue(null, "value1");
2102 String value2 = parser.getAttributeValue(null, "value2");
2103
2104 try {
2105 if ("long".equals(type)) {
2106 extras.putLong(name, Long.parseLong(value1));
2107 } else if ("integer".equals(type)) {
2108 extras.putInt(name, Integer.parseInt(value1));
2109 } else if ("double".equals(type)) {
2110 extras.putDouble(name, Double.parseDouble(value1));
2111 } else if ("float".equals(type)) {
2112 extras.putFloat(name, Float.parseFloat(value1));
2113 } else if ("boolean".equals(type)) {
2114 extras.putBoolean(name, Boolean.parseBoolean(value1));
2115 } else if ("string".equals(type)) {
2116 extras.putString(name, value1);
2117 } else if ("account".equals(type)) {
2118 extras.putParcelable(name, new Account(value1, value2));
2119 }
2120 } catch (NumberFormatException e) {
2121 Log.e(TAG, "error parsing bundle value", e);
2122 } catch (NullPointerException e) {
2123 Log.e(TAG, "error parsing bundle value", e);
2124 }
2125 }
2126
Dianne Hackborn231cc602009-04-27 17:10:36 -07002127 /**
2128 * Write all account information to the account file.
2129 */
2130 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002131 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2132 Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
2133 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002135
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 try {
2137 fos = mAccountInfoFile.startWrite();
2138 XmlSerializer out = new FastXmlSerializer();
2139 out.setOutput(fos, "utf-8");
2140 out.startDocument(null, true);
2141 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002142
Dianne Hackborn231cc602009-04-27 17:10:36 -07002143 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002144 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002145 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002146 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002147
2148 // Write the Sync Automatically flags for each user
2149 final int M = mMasterSyncAutomatically.size();
2150 for (int m = 0; m < M; m++) {
2151 int userId = mMasterSyncAutomatically.keyAt(m);
2152 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2153 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2154 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2155 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2156 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002157 }
Costin Manolache360e4542009-09-04 13:36:04 -07002158
Dianne Hackborn231cc602009-04-27 17:10:36 -07002159 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002160 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002161 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002162 EndPoint info = authority.base;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 out.startTag(null, "authority");
2164 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002165 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002166 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002167 if (info.service == null) {
2168 out.attribute(null, "account", info.account.name);
2169 out.attribute(null, "type", info.account.type);
2170 out.attribute(null, "authority", info.provider);
Matthew Williamsfa774182013-06-18 15:44:11 -07002171 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002172 out.attribute(null, "package", info.service.getPackageName());
2173 out.attribute(null, "class", info.service.getClassName());
Matthew Williamsfa774182013-06-18 15:44:11 -07002174 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002175 if (authority.syncable < 0) {
2176 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002177 } else {
2178 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002179 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002180 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002181 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002182 out.attribute(null, "period", Long.toString(periodicSync.period));
2183 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2184 final Bundle extras = periodicSync.extras;
2185 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002186 out.endTag(null, "periodicSync");
2187 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002188 out.endTag(null, "authority");
2189 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002190 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002191 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002192 mAccountInfoFile.finishWrite(fos);
2193 } catch (java.io.IOException e1) {
2194 Log.w(TAG, "Error writing accounts", e1);
2195 if (fos != null) {
2196 mAccountInfoFile.failWrite(fos);
2197 }
2198 }
2199 }
Costin Manolache360e4542009-09-04 13:36:04 -07002200
Dianne Hackborn231cc602009-04-27 17:10:36 -07002201 static int getIntColumn(Cursor c, String name) {
2202 return c.getInt(c.getColumnIndex(name));
2203 }
Costin Manolache360e4542009-09-04 13:36:04 -07002204
Dianne Hackborn231cc602009-04-27 17:10:36 -07002205 static long getLongColumn(Cursor c, String name) {
2206 return c.getLong(c.getColumnIndex(name));
2207 }
Costin Manolache360e4542009-09-04 13:36:04 -07002208
Dianne Hackborn231cc602009-04-27 17:10:36 -07002209 /**
2210 * Load sync engine state from the old syncmanager database, and then
2211 * erase it. Note that we don't deal with pending operations, active
2212 * sync, or history.
2213 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002214 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002215 // Look for old database to initialize from.
2216 File file = mContext.getDatabasePath("syncmanager.db");
2217 if (!file.exists()) {
2218 return;
2219 }
2220 String path = file.getPath();
2221 SQLiteDatabase db = null;
2222 try {
2223 db = SQLiteDatabase.openDatabase(path, null,
2224 SQLiteDatabase.OPEN_READONLY);
2225 } catch (SQLiteException e) {
2226 }
Costin Manolache360e4542009-09-04 13:36:04 -07002227
Dianne Hackborn231cc602009-04-27 17:10:36 -07002228 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002229 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002230
Dianne Hackborn231cc602009-04-27 17:10:36 -07002231 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002232 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2233 Log.v(TAG, "Reading legacy sync accounts db");
2234 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002235 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2236 qb.setTables("stats, status");
2237 HashMap<String,String> map = new HashMap<String,String>();
2238 map.put("_id", "status._id as _id");
2239 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002240 if (hasType) {
2241 map.put("account_type", "stats.account_type as account_type");
2242 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002243 map.put("authority", "stats.authority as authority");
2244 map.put("totalElapsedTime", "totalElapsedTime");
2245 map.put("numSyncs", "numSyncs");
2246 map.put("numSourceLocal", "numSourceLocal");
2247 map.put("numSourcePoll", "numSourcePoll");
2248 map.put("numSourceServer", "numSourceServer");
2249 map.put("numSourceUser", "numSourceUser");
2250 map.put("lastSuccessSource", "lastSuccessSource");
2251 map.put("lastSuccessTime", "lastSuccessTime");
2252 map.put("lastFailureSource", "lastFailureSource");
2253 map.put("lastFailureTime", "lastFailureTime");
2254 map.put("lastFailureMesg", "lastFailureMesg");
2255 map.put("pending", "pending");
2256 qb.setProjectionMap(map);
2257 qb.appendWhere("stats._id = status.stats_id");
2258 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002260 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002261 String accountType = hasType
2262 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002263 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002264 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002266 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002267 AuthorityInfo authority =
2268 this.getOrCreateAuthorityLocked(
2269 new EndPoint(new Account(accountName, accountType),
2270 authorityName,
2271 0 /* legacy is single-user */)
2272 , -1,
2273 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002274 if (authority != null) {
2275 int i = mSyncStatus.size();
2276 boolean found = false;
2277 SyncStatusInfo st = null;
2278 while (i > 0) {
2279 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002280 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002281 if (st.authorityId == authority.ident) {
2282 found = true;
2283 break;
2284 }
2285 }
2286 if (!found) {
2287 st = new SyncStatusInfo(authority.ident);
2288 mSyncStatus.put(authority.ident, st);
2289 }
2290 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2291 st.numSyncs = getIntColumn(c, "numSyncs");
2292 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2293 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2294 st.numSourceServer = getIntColumn(c, "numSourceServer");
2295 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002296 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002297 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2298 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2299 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2300 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2301 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2302 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
Costin Manolache360e4542009-09-04 13:36:04 -07002305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002307
Dianne Hackborn231cc602009-04-27 17:10:36 -07002308 // Retrieve the settings.
2309 qb = new SQLiteQueryBuilder();
2310 qb.setTables("settings");
2311 c = qb.query(db, null, null, null, null, null, null);
2312 while (c.moveToNext()) {
2313 String name = c.getString(c.getColumnIndex("name"));
2314 String value = c.getString(c.getColumnIndex("value"));
2315 if (name == null) continue;
2316 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002317 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002318 } else if (name.startsWith("sync_provider_")) {
2319 String provider = name.substring("sync_provider_".length(),
2320 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002321 int i = mAuthorities.size();
2322 while (i > 0) {
2323 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002324 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002325 if (authority.base.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002326 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002327 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002328 }
2329 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 }
Costin Manolache360e4542009-09-04 13:36:04 -07002332
Dianne Hackborn231cc602009-04-27 17:10:36 -07002333 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002334
Dianne Hackborn231cc602009-04-27 17:10:36 -07002335 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002336
Dianne Hackborn231cc602009-04-27 17:10:36 -07002337 (new File(path)).delete();
2338 }
2339 }
Costin Manolache360e4542009-09-04 13:36:04 -07002340
Dianne Hackborn231cc602009-04-27 17:10:36 -07002341 public static final int STATUS_FILE_END = 0;
2342 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002343
Dianne Hackborn231cc602009-04-27 17:10:36 -07002344 /**
2345 * Read all sync status back in to the initial engine state.
2346 */
2347 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002348 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2349 Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
2350 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002351 try {
2352 byte[] data = mStatusFile.readFully();
2353 Parcel in = Parcel.obtain();
2354 in.unmarshall(data, 0, data.length);
2355 in.setDataPosition(0);
2356 int token;
2357 while ((token=in.readInt()) != STATUS_FILE_END) {
2358 if (token == STATUS_FILE_ITEM) {
2359 SyncStatusInfo status = new SyncStatusInfo(in);
2360 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2361 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002362 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2363 Log.v(TAG, "Adding status for id "
2364 + status.authorityId);
2365 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002366 mSyncStatus.put(status.authorityId, status);
2367 }
2368 } else {
2369 // Ooops.
2370 Log.w(TAG, "Unknown status token: " + token);
2371 break;
2372 }
2373 }
2374 } catch (java.io.IOException e) {
2375 Log.i(TAG, "No initial status");
2376 }
2377 }
Costin Manolache360e4542009-09-04 13:36:04 -07002378
Dianne Hackborn231cc602009-04-27 17:10:36 -07002379 /**
2380 * Write all sync status to the sync status file.
2381 */
2382 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002383 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2384 Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
2385 }
Costin Manolache360e4542009-09-04 13:36:04 -07002386
Dianne Hackborn231cc602009-04-27 17:10:36 -07002387 // The file is being written, so we don't need to have a scheduled
2388 // write until the next change.
2389 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002390
Dianne Hackborn231cc602009-04-27 17:10:36 -07002391 FileOutputStream fos = null;
2392 try {
2393 fos = mStatusFile.startWrite();
2394 Parcel out = Parcel.obtain();
2395 final int N = mSyncStatus.size();
2396 for (int i=0; i<N; i++) {
2397 SyncStatusInfo status = mSyncStatus.valueAt(i);
2398 out.writeInt(STATUS_FILE_ITEM);
2399 status.writeToParcel(out, 0);
2400 }
2401 out.writeInt(STATUS_FILE_END);
2402 fos.write(out.marshall());
2403 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002404
Dianne Hackborn231cc602009-04-27 17:10:36 -07002405 mStatusFile.finishWrite(fos);
2406 } catch (java.io.IOException e1) {
2407 Log.w(TAG, "Error writing status", e1);
2408 if (fos != null) {
2409 mStatusFile.failWrite(fos);
2410 }
2411 }
2412 }
Costin Manolache360e4542009-09-04 13:36:04 -07002413
Matthew Williamsba352712013-08-13 15:53:31 -07002414 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002415
Matthew Williamsba352712013-08-13 15:53:31 -07002416 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002417 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002418 FileInputStream fis = null;
2419 if (!mPendingFile.getBaseFile().exists()) {
2420 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2421 Log.v(TAG_FILE, "No pending operation file.");
2422 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002423 }
2424 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002425 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002426 fis = mPendingFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07002427 XmlPullParser parser;
2428 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002429 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002430
Matthew Williamsfa774182013-06-18 15:44:11 -07002431 int eventType = parser.getEventType();
2432 while (eventType != XmlPullParser.START_TAG &&
2433 eventType != XmlPullParser.END_DOCUMENT) {
2434 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002435 }
Matthew Williamsba352712013-08-13 15:53:31 -07002436 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002437
2438 String tagName = parser.getName();
Matthew Williamsba352712013-08-13 15:53:31 -07002439 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002440 PendingOperation pop = null;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002441 if (eventType == XmlPullParser.START_TAG) {
2442 try {
2443 tagName = parser.getName();
2444 if (parser.getDepth() == 2 && "op".equals(tagName)) {
2445 int authorityId = Integer.valueOf(parser.getAttributeValue(
2446 null, XML_ATTR_AUTHORITYID));
2447 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2448 null, XML_ATTR_EXPEDITED));
2449 int syncSource = Integer.valueOf(parser.getAttributeValue(
2450 null, XML_ATTR_SOURCE));
2451 int reason = Integer.valueOf(parser.getAttributeValue(
2452 null, XML_ATTR_REASON));
2453 AuthorityInfo authority = mAuthorities.get(authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002454 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002455 Log.v(TAG_FILE, authorityId + " " + expedited + " " +
2456 syncSource + " " + reason);
2457 }
2458 if (authority != null) {
2459 pop = new PendingOperation(
2460 authority, reason, syncSource, new Bundle(), expedited);
2461 pop.flatExtras = null; // No longer used.
2462 mPendingOperations.add(pop);
2463 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2464 Log.v(TAG_FILE, "Adding pending op: "
Matthew Williamsba352712013-08-13 15:53:31 -07002465 + pop.authority
Matthew Williamsfa774182013-06-18 15:44:11 -07002466 + " src=" + pop.syncSource
2467 + " reason=" + pop.reason
2468 + " expedited=" + pop.expedited);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002469 }
2470 } else {
2471 // Skip non-existent authority.
2472 pop = null;
2473 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2474 Log.v(TAG_FILE, "No authority found for " + authorityId
2475 + ", skipping");
2476 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002477 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002478 } else if (parser.getDepth() == 2 &&
2479 pop != null &&
2480 "extra".equals(tagName)) {
2481 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002482 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002483 } catch (NumberFormatException e) {
2484 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002485 }
2486 }
Matthew Williamsba352712013-08-13 15:53:31 -07002487 eventType = parser.next();
2488 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002489 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002490 Log.w(TAG_FILE, "Error reading pending data.", e);
2491 } catch (XmlPullParserException e) {
2492 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2493 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2494 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002495 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002496 if (fis != null) {
2497 try {
2498 fis.close();
2499 } catch (java.io.IOException e1) {}
2500 }
2501 }
2502 }
Matthew Williamsba352712013-08-13 15:53:31 -07002503
Dianne Hackborn231cc602009-04-27 17:10:36 -07002504 static private byte[] flattenBundle(Bundle bundle) {
2505 byte[] flatData = null;
2506 Parcel parcel = Parcel.obtain();
2507 try {
2508 bundle.writeToParcel(parcel, 0);
2509 flatData = parcel.marshall();
2510 } finally {
2511 parcel.recycle();
2512 }
2513 return flatData;
2514 }
Costin Manolache360e4542009-09-04 13:36:04 -07002515
Dianne Hackborn231cc602009-04-27 17:10:36 -07002516 static private Bundle unflattenBundle(byte[] flatData) {
2517 Bundle bundle;
2518 Parcel parcel = Parcel.obtain();
2519 try {
2520 parcel.unmarshall(flatData, 0, flatData.length);
2521 parcel.setDataPosition(0);
2522 bundle = parcel.readBundle();
2523 } catch (RuntimeException e) {
2524 // A RuntimeException is thrown if we were unable to parse the parcel.
2525 // Create an empty parcel in this case.
2526 bundle = new Bundle();
2527 } finally {
2528 parcel.recycle();
2529 }
2530 return bundle;
2531 }
Costin Manolache360e4542009-09-04 13:36:04 -07002532
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002533 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2534 private static final String XML_ATTR_SOURCE = "source";
2535 private static final String XML_ATTR_EXPEDITED = "expedited";
2536 private static final String XML_ATTR_REASON = "reason";
2537
2538 /**
2539 * Write all currently pending ops to the pending ops file.
2540 * TODO: Change this from xml so that we can append to this file as before.
2541 */
2542 private void writePendingOperationsLocked() {
2543 final int N = mPendingOperations.size();
2544 FileOutputStream fos = null;
2545 try {
2546 if (N == 0) {
2547 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)){
2548 Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2549 }
2550 mPendingFile.truncate();
2551 return;
2552 }
2553 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2554 Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2555 }
2556 fos = mPendingFile.startWrite();
2557 XmlSerializer out = new FastXmlSerializer();
2558 out.setOutput(fos, "utf-8");
2559 out.startDocument(null, true);
2560 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2561
2562 out.startTag(null, "pending");
2563 out.attribute(null, "version", Integer.toString(PENDING_OPERATION_VERSION));
2564
2565 for (int i = 0; i < N; i++) {
2566 PendingOperation pop = mPendingOperations.get(i);
2567 out.startTag(null, "op");
2568 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2569 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2570 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2571 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2572 extrasToXml(out, pop.extras);
2573 out.endTag(null, "op");
2574 }
2575 out.endTag(null, "pending");
2576 out.endDocument();
2577 mPendingFile.finishWrite(fos);
2578 } catch (java.io.IOException e1) {
2579 Log.w(TAG, "Error writing pending operations", e1);
2580 if (fos != null) {
2581 mPendingFile.failWrite(fos);
2582 }
2583 }
2584 }
2585
2586
Matthew Williamsfa774182013-06-18 15:44:11 -07002587 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2588 for (String key : extras.keySet()) {
2589 out.startTag(null, "extra");
2590 out.attribute(null, "name", key);
2591 final Object value = extras.get(key);
2592 if (value instanceof Long) {
2593 out.attribute(null, "type", "long");
2594 out.attribute(null, "value1", value.toString());
2595 } else if (value instanceof Integer) {
2596 out.attribute(null, "type", "integer");
2597 out.attribute(null, "value1", value.toString());
2598 } else if (value instanceof Boolean) {
2599 out.attribute(null, "type", "boolean");
2600 out.attribute(null, "value1", value.toString());
2601 } else if (value instanceof Float) {
2602 out.attribute(null, "type", "float");
2603 out.attribute(null, "value1", value.toString());
2604 } else if (value instanceof Double) {
2605 out.attribute(null, "type", "double");
2606 out.attribute(null, "value1", value.toString());
2607 } else if (value instanceof String) {
2608 out.attribute(null, "type", "string");
2609 out.attribute(null, "value1", value.toString());
2610 } else if (value instanceof Account) {
2611 out.attribute(null, "type", "account");
2612 out.attribute(null, "value1", ((Account)value).name);
2613 out.attribute(null, "value2", ((Account)value).type);
2614 }
2615 out.endTag(null, "extra");
2616 }
2617 }
2618
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002619 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2620 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2621 && mSyncRequestListener != null) {
2622 mSyncRequestListener.onSyncRequest(authorityInfo.base, reason, extras);
2623 } else {
2624 SyncRequest.Builder req =
2625 new SyncRequest.Builder()
2626 .syncOnce(0, 0)
2627 .setExtras(extras);
2628 if (authorityInfo.base.target_provider) {
2629 req.setSyncAdapter(
2630 authorityInfo.base.account,
2631 authorityInfo.base.provider);
2632 } else {
2633 req.setSyncAdapter(authorityInfo.base.service);
2634 }
2635 ContentResolver.requestSync(req.build());
2636 }
2637 }
2638
Alon Albert57286f92012-10-09 14:21:38 -07002639 private void requestSync(Account account, int userId, int reason, String authority,
2640 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002641 // If this is happening in the system process, then call the syncrequest listener
2642 // to make a request back to the SyncManager directly.
2643 // If this is probably a test instance, then call back through the ContentResolver
2644 // which will know which userId to apply based on the Binder id.
2645 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2646 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002647 mSyncRequestListener.onSyncRequest(
2648 new EndPoint(account, authority, userId),
2649 reason,
2650 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002651 } else {
2652 ContentResolver.requestSync(account, authority, extras);
2653 }
2654 }
2655
Dianne Hackborn231cc602009-04-27 17:10:36 -07002656 public static final int STATISTICS_FILE_END = 0;
2657 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2658 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002659
Dianne Hackborn231cc602009-04-27 17:10:36 -07002660 /**
2661 * Read all sync statistics back in to the initial engine state.
2662 */
2663 private void readStatisticsLocked() {
2664 try {
2665 byte[] data = mStatisticsFile.readFully();
2666 Parcel in = Parcel.obtain();
2667 in.unmarshall(data, 0, data.length);
2668 in.setDataPosition(0);
2669 int token;
2670 int index = 0;
2671 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2672 if (token == STATISTICS_FILE_ITEM
2673 || token == STATISTICS_FILE_ITEM_OLD) {
2674 int day = in.readInt();
2675 if (token == STATISTICS_FILE_ITEM_OLD) {
2676 day = day - 2009 + 14245; // Magic!
2677 }
2678 DayStats ds = new DayStats(day);
2679 ds.successCount = in.readInt();
2680 ds.successTime = in.readLong();
2681 ds.failureCount = in.readInt();
2682 ds.failureTime = in.readLong();
2683 if (index < mDayStats.length) {
2684 mDayStats[index] = ds;
2685 index++;
2686 }
2687 } else {
2688 // Ooops.
2689 Log.w(TAG, "Unknown stats token: " + token);
2690 break;
2691 }
2692 }
2693 } catch (java.io.IOException e) {
2694 Log.i(TAG, "No initial statistics");
2695 }
2696 }
Costin Manolache360e4542009-09-04 13:36:04 -07002697
Dianne Hackborn231cc602009-04-27 17:10:36 -07002698 /**
2699 * Write all sync statistics to the sync status file.
2700 */
2701 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002702 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2703 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2704 }
Costin Manolache360e4542009-09-04 13:36:04 -07002705
Dianne Hackborn231cc602009-04-27 17:10:36 -07002706 // The file is being written, so we don't need to have a scheduled
2707 // write until the next change.
2708 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002709
Dianne Hackborn231cc602009-04-27 17:10:36 -07002710 FileOutputStream fos = null;
2711 try {
2712 fos = mStatisticsFile.startWrite();
2713 Parcel out = Parcel.obtain();
2714 final int N = mDayStats.length;
2715 for (int i=0; i<N; i++) {
2716 DayStats ds = mDayStats[i];
2717 if (ds == null) {
2718 break;
2719 }
2720 out.writeInt(STATISTICS_FILE_ITEM);
2721 out.writeInt(ds.day);
2722 out.writeInt(ds.successCount);
2723 out.writeLong(ds.successTime);
2724 out.writeInt(ds.failureCount);
2725 out.writeLong(ds.failureTime);
2726 }
2727 out.writeInt(STATISTICS_FILE_END);
2728 fos.write(out.marshall());
2729 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002730
Dianne Hackborn231cc602009-04-27 17:10:36 -07002731 mStatisticsFile.finishWrite(fos);
2732 } catch (java.io.IOException e1) {
2733 Log.w(TAG, "Error writing stats", e1);
2734 if (fos != null) {
2735 mStatisticsFile.failWrite(fos);
2736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002739
2740 /**
2741 * Dump state of PendingOperations.
2742 */
2743 public void dumpPendingOperations(StringBuilder sb) {
2744 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2745 for (PendingOperation pop : mPendingOperations) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002746 sb.append("(info: " + pop.authority.toString())
2747 .append(", extras: " + pop.extras)
Matthew Williamsfa774182013-06-18 15:44:11 -07002748 .append(")\n");
2749 }
2750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751}