blob: 0b99fcacdbd6ecec68b43dcb790837a3b0d39cfe [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;
27import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070030import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.os.Bundle;
33import android.os.Environment;
34import android.os.Handler;
35import android.os.Message;
36import android.os.Parcel;
37import android.os.RemoteCallbackList;
38import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070039import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080041import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070042import android.util.SparseArray;
43import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080044
45import com.android.internal.annotations.VisibleForTesting;
46import com.android.internal.util.ArrayUtils;
47import com.android.internal.util.FastXmlSerializer;
48
49import org.xmlpull.v1.XmlPullParser;
50import org.xmlpull.v1.XmlPullParserException;
51import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Dianne Hackborn231cc602009-04-27 17:10:36 -070053import java.io.File;
54import java.io.FileInputStream;
55import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080060import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070061import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060062import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * @hide
69 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070070public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "SyncManager";
Matthew Williamsfa774182013-06-18 15:44:11 -070073 private static final boolean DEBUG = true;
74 private static final boolean DEBUG_FILE = true;
Costin Manolache360e4542009-09-04 13:36:04 -070075
Amith Yamasani04e0d262012-02-14 11:50:53 -080076 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
77 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070078 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_ENABLED = "enabled";
80 private static final String XML_ATTR_USER = "user";
81 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
82
Matthew Williamsfa774182013-06-18 15:44:11 -070083 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080084 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
85
Matthew Williamsfa774182013-06-18 15:44:11 -070086 /** Percentage of period that is flex by default, if no flex is set. */
87 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
88
89 /** Lower bound on sync time from which we assign a default flex time. */
90 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
91
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080092 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070093 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Dianne Hackborn231cc602009-04-27 17:10:36 -070095 /** Enum value for a sync start event. */
96 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a sync stop event. */
99 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 // TODO: i18n -- grab these out of resources.
102 /** String names for the sync event types. */
103 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Dianne Hackborn231cc602009-04-27 17:10:36 -0700105 /** Enum value for a server-initiated sync. */
106 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a local-initiated sync. */
109 public static final int SOURCE_LOCAL = 1;
110 /**
111 * Enum value for a poll-based sync (e.g., upon connection to
112 * network)
113 */
114 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;
121
Fred Quintana307da1a2010-01-21 14:24:20 -0800122 public static final long NOT_IN_BACKOFF_MODE = -1;
123
Dianne Hackborn231cc602009-04-27 17:10:36 -0700124 // TODO: i18n -- grab these out of resources.
125 /** String names for the sync source types. */
126 public static final String[] SOURCES = { "SERVER",
127 "LOCAL",
128 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800129 "USER",
130 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Dianne Hackborn231cc602009-04-27 17:10:36 -0700132 // The MESG column will contain one of these or one of the Error types.
133 public static final String MESG_SUCCESS = "success";
134 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700136 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700137
Dianne Hackborn231cc602009-04-27 17:10:36 -0700138 private static final int MSG_WRITE_STATUS = 1;
139 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700140
Dianne Hackborn231cc602009-04-27 17:10:36 -0700141 private static final int MSG_WRITE_STATISTICS = 2;
142 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700143
144 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700145
Fred Quintanac2e46912010-03-15 16:10:44 -0700146 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700147 private static final int ACCOUNTS_VERSION = 2;
148
149 private static HashMap<String, String> sAuthorityRenames;
150
151 static {
152 sAuthorityRenames = new HashMap<String, String>();
153 sAuthorityRenames.put("contacts", "com.android.contacts");
154 sAuthorityRenames.put("calendar", "com.android.calendar");
155 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700156
Dianne Hackborn231cc602009-04-27 17:10:36 -0700157 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700158 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800159 final int userId;
Alon Albert57286f92012-10-09 14:21:38 -0700160 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 final int syncSource;
162 final String authority;
163 final Bundle extras; // note: read-only.
Matthew Williamsfa774182013-06-18 15:44:11 -0700164 final ComponentName serviceName;
Fred Quintana307da1a2010-01-21 14:24:20 -0800165 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700166
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 int authorityId;
168 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700169
Matthew Williamsfa774182013-06-18 15:44:11 -0700170 PendingOperation(Account account, int userId, int reason, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800171 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700172 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800173 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700174 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700175 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 this.authority = authority;
177 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800178 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 this.authorityId = -1;
Matthew Williamsfa774182013-06-18 15:44:11 -0700180 this.serviceName = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700181 }
182
183 PendingOperation(PendingOperation other) {
184 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800185 this.userId = other.userId;
Alon Albert57286f92012-10-09 14:21:38 -0700186 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 this.syncSource = other.syncSource;
188 this.authority = other.authority;
189 this.extras = other.extras;
190 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800191 this.expedited = other.expedited;
Matthew Williamsfa774182013-06-18 15:44:11 -0700192 this.serviceName = other.serviceName;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 }
Costin Manolache360e4542009-09-04 13:36:04 -0700195
Dianne Hackborn231cc602009-04-27 17:10:36 -0700196 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800197 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700198 final HashMap<String, AuthorityInfo> authorities =
199 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700200
Amith Yamasani04e0d262012-02-14 11:50:53 -0800201 AccountInfo(AccountAndUser accountAndUser) {
202 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700203 }
204 }
Costin Manolache360e4542009-09-04 13:36:04 -0700205
Dianne Hackborn231cc602009-04-27 17:10:36 -0700206 public static class AuthorityInfo {
Matthew Williamsfa774182013-06-18 15:44:11 -0700207 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700208 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800209 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700210 final String authority;
211 final int ident;
212 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700213 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800214 long backoffTime;
215 long backoffDelay;
216 long delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700217 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700218
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700219 /**
220 * Copy constructor for making deep-ish copies. Only the bundles stored
221 * in periodic syncs can make unexpected changes.
222 *
223 * @param toCopy AuthorityInfo to be copied.
224 */
225 AuthorityInfo(AuthorityInfo toCopy) {
226 account = toCopy.account;
227 userId = toCopy.userId;
228 authority = toCopy.authority;
Matthew Williamsfa774182013-06-18 15:44:11 -0700229 service = toCopy.service;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700230 ident = toCopy.ident;
231 enabled = toCopy.enabled;
232 syncable = toCopy.syncable;
233 backoffTime = toCopy.backoffTime;
234 backoffDelay = toCopy.backoffDelay;
235 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700236 periodicSyncs = new ArrayList<PeriodicSync>();
237 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700238 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700239 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700240 }
241 }
242
Matthew Williamsfa774182013-06-18 15:44:11 -0700243 /**
244 * Create an authority with one periodic sync scheduled with an empty bundle and syncing
245 * every day. An empty bundle is considered equal to any other bundle see
246 * {@link PeriodicSync.syncExtrasEquals}.
247 * @param account Account that this authority syncs.
248 * @param userId which user this sync is registered for.
249 * @param userId user for which this authority is registered.
250 * @param ident id of this authority.
251 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800252 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700253 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800254 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700255 this.authority = authority;
Matthew Williamsfa774182013-06-18 15:44:11 -0700256 this.service = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700257 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700258 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700259 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800260 backoffTime = -1; // if < 0 then we aren't in backoff mode
261 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williamsfa774182013-06-18 15:44:11 -0700262 periodicSyncs = new ArrayList<PeriodicSync>();
263 // Old version adds one periodic sync a day.
264 periodicSyncs.add(new PeriodicSync(account, authority,
265 new Bundle(),
266 DEFAULT_POLL_FREQUENCY_SECONDS,
267 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS)));
268 }
269
270 /**
271 * Create an authority with one periodic sync scheduled with an empty bundle and syncing
272 * every day using a sync service.
273 * @param cname sync service identifier.
274 * @param userId user for which this authority is registered.
275 * @param ident id of this authority.
276 */
277 AuthorityInfo(ComponentName cname, int userId, int ident) {
278 this.account = null;
279 this.userId = userId;
280 this.authority = null;
281 this.service = cname;
282 this.ident = ident;
283 // Sync service is always enabled.
284 enabled = true;
285 syncable = -1; // default to "unknown"
286 backoffTime = -1; // if < 0 then we aren't in backoff mode
287 backoffDelay = -1; // if < 0 then we aren't in backoff mode
288 periodicSyncs = new ArrayList<PeriodicSync>();
289 periodicSyncs.add(new PeriodicSync(account, authority,
290 new Bundle(),
291 DEFAULT_POLL_FREQUENCY_SECONDS,
292 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS)));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700293 }
294 }
Costin Manolache360e4542009-09-04 13:36:04 -0700295
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 public static class SyncHistoryItem {
297 int authorityId;
298 int historyId;
299 long eventTime;
300 long elapsedTime;
301 int source;
302 int event;
303 long upstreamActivity;
304 long downstreamActivity;
305 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700306 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700307 Bundle extras;
308 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700309 }
Costin Manolache360e4542009-09-04 13:36:04 -0700310
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 public static class DayStats {
312 public final int day;
313 public int successCount;
314 public long successTime;
315 public int failureCount;
316 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700317
Dianne Hackborn231cc602009-04-27 17:10:36 -0700318 public DayStats(int day) {
319 this.day = day;
320 }
321 }
Costin Manolache360e4542009-09-04 13:36:04 -0700322
Amith Yamasani04e0d262012-02-14 11:50:53 -0800323 interface OnSyncRequestListener {
324 /**
325 * Called when a sync is needed on an account(s) due to some change in state.
326 * @param account
327 * @param userId
Alon Albert57286f92012-10-09 14:21:38 -0700328 * @param reason
Amith Yamasani04e0d262012-02-14 11:50:53 -0800329 * @param authority
330 * @param extras
331 */
Alon Albert57286f92012-10-09 14:21:38 -0700332 public void onSyncRequest(Account account, int userId, int reason, String authority,
333 Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800334 }
335
Dianne Hackborn231cc602009-04-27 17:10:36 -0700336 // Primary list of all syncable authorities. Also our global lock.
337 private final SparseArray<AuthorityInfo> mAuthorities =
338 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700339
Amith Yamasani04e0d262012-02-14 11:50:53 -0800340 private final HashMap<AccountAndUser, AccountInfo> mAccounts
341 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342
Dianne Hackborn231cc602009-04-27 17:10:36 -0700343 private final ArrayList<PendingOperation> mPendingOperations =
344 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700345
Amith Yamasani04e0d262012-02-14 11:50:53 -0800346 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
347 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700348
Dianne Hackborn231cc602009-04-27 17:10:36 -0700349 private final SparseArray<SyncStatusInfo> mSyncStatus =
350 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700351
Dianne Hackborn231cc602009-04-27 17:10:36 -0700352 private final ArrayList<SyncHistoryItem> mSyncHistory =
353 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700354
Dianne Hackborn231cc602009-04-27 17:10:36 -0700355 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
356 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700357
Matthew Williamsfa774182013-06-18 15:44:11 -0700358 /** Reverse mapping for component name -> <userid -> authority id>. */
359 private final HashMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
360 new HashMap<ComponentName, SparseArray<AuthorityInfo>>();
361
Fred Quintana77c560f2010-03-29 22:20:26 -0700362 private int mNextAuthorityId = 0;
363
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 // We keep 4 weeks of stats.
365 private final DayStats[] mDayStats = new DayStats[7*4];
366 private final Calendar mCal;
367 private int mYear;
368 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700369
Dianne Hackborn231cc602009-04-27 17:10:36 -0700370 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700373
Ashish Sharma69d95de2012-04-11 17:27:24 -0700374 private int mSyncRandomOffset;
375
Dianne Hackborn231cc602009-04-27 17:10:36 -0700376 /**
377 * This file contains the core engine state: all accounts and the
378 * settings for them. It must never be lost, and should be changed
379 * infrequently, so it is stored as an XML file.
380 */
381 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700382
Dianne Hackborn231cc602009-04-27 17:10:36 -0700383 /**
384 * This file contains the current sync status. We would like to retain
385 * it across boots, but its loss is not the end of the world, so we store
386 * this information as binary data.
387 */
388 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700389
Dianne Hackborn231cc602009-04-27 17:10:36 -0700390 /**
391 * This file contains sync statistics. This is purely debugging information
392 * so is written infrequently and can be thrown away at any time.
393 */
394 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700395
Dianne Hackborn231cc602009-04-27 17:10:36 -0700396 /**
397 * This file contains the pending sync operations. It is a binary file,
398 * which must be updated every time an operation is added or removed,
399 * so we have special handling of it.
400 */
401 private final AtomicFile mPendingFile;
402 private static final int PENDING_FINISH_TO_WRITE = 4;
403 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700404
Dianne Hackborn231cc602009-04-27 17:10:36 -0700405 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800407 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408
409 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800411 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700414
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800417 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
418 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 File systemDir = new File(dataDir, "system");
421 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800422 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
424 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
425 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
426 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 readAccountInfoLocked();
429 readStatusLocked();
430 readPendingOperationsLocked();
431 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700432 readAndDeleteLegacyAccountInfoLocked();
433 writeAccountInfoLocked();
434 writeStatusLocked();
435 writePendingOperationsLocked();
436 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 }
438
439 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800440 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
443 public static void init(Context context) {
444 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800445 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800447 // This call will return the correct directory whether Encrypted File Systems is
448 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600449 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800450 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
453 public static SyncStorageEngine getSingleton() {
454 if (sSyncStorageEngine == null) {
455 throw new IllegalStateException("not initialized");
456 }
457 return sSyncStorageEngine;
458 }
459
Amith Yamasani04e0d262012-02-14 11:50:53 -0800460 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
461 if (mSyncRequestListener == null) {
462 mSyncRequestListener = listener;
463 }
464 }
465
Dianne Hackborn231cc602009-04-27 17:10:36 -0700466 @Override public void handleMessage(Message msg) {
467 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700468 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700470 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700472 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700473 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 }
475 }
476 }
Costin Manolache360e4542009-09-04 13:36:04 -0700477
Ashish Sharma69d95de2012-04-11 17:27:24 -0700478 public int getSyncRandomOffset() {
479 return mSyncRandomOffset;
480 }
481
Dianne Hackborn231cc602009-04-27 17:10:36 -0700482 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
483 synchronized (mAuthorities) {
484 mChangeListeners.register(callback, mask);
485 }
486 }
Costin Manolache360e4542009-09-04 13:36:04 -0700487
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 public void removeStatusChangeListener(ISyncStatusObserver callback) {
489 synchronized (mAuthorities) {
490 mChangeListeners.unregister(callback);
491 }
492 }
Costin Manolache360e4542009-09-04 13:36:04 -0700493
Matthew Williamsfa774182013-06-18 15:44:11 -0700494 /**
495 * Figure out a reasonable flex time for cases where none is provided (old api calls).
496 * @param syncTimeSeconds requested sync time from now.
497 * @return amount of seconds before syncTimeSeconds that the sync can occur.
498 * I.e.
499 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
500 * The flex time is capped at a percentage of the {@link DEFAULT_POLL_FREQUENCY_SECONDS}.
501 */
502 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
503 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
504 // Small enough sync request time that we don't add flex time - developer probably
505 // wants to wait for an operation to occur before syncing so we honour the
506 // request time.
507 return 0L;
508 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
509 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
510 } else {
511 // Large enough sync request time that we cap the flex time.
512 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
513 }
514 }
515
Dianne Hackborn231cc602009-04-27 17:10:36 -0700516 private void reportChange(int which) {
517 ArrayList<ISyncStatusObserver> reports = null;
518 synchronized (mAuthorities) {
519 int i = mChangeListeners.beginBroadcast();
520 while (i > 0) {
521 i--;
522 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
523 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 continue;
525 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700526 if (reports == null) {
527 reports = new ArrayList<ISyncStatusObserver>(i);
528 }
529 reports.add(mChangeListeners.getBroadcastItem(i));
530 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700531 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700532 }
Costin Manolache360e4542009-09-04 13:36:04 -0700533
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800534 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700535 Log.v(TAG, "reportChange " + which + " to: " + reports);
536 }
Costin Manolache360e4542009-09-04 13:36:04 -0700537
Dianne Hackborn231cc602009-04-27 17:10:36 -0700538 if (reports != null) {
539 int i = reports.size();
540 while (i > 0) {
541 i--;
542 try {
543 reports.get(i).onStatusChanged(which);
544 } catch (RemoteException e) {
545 // The remote callback list will take care of this for us.
546 }
547 }
548 }
549 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700550
Amith Yamasani04e0d262012-02-14 11:50:53 -0800551 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700552 synchronized (mAuthorities) {
553 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800554 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700555 "getSyncAutomatically");
556 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700557 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700558
Dianne Hackborn231cc602009-04-27 17:10:36 -0700559 int i = mAuthorities.size();
560 while (i > 0) {
561 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700562 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700563 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800564 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700565 && authority.enabled) {
566 return true;
567 }
568 }
569 return false;
570 }
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572
Amith Yamasani04e0d262012-02-14 11:50:53 -0800573 public void setSyncAutomatically(Account account, int userId, String providerName,
574 boolean sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800575 if (DEBUG) {
576 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
577 + ", user " + userId + " -> " + sync);
578 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700579 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800580 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
581 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700582 if (authority.enabled == sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800583 if (DEBUG) {
584 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
585 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700586 return;
587 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700588 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700589 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700591
Fred Quintana77c560f2010-03-29 22:20:26 -0700592 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700593 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
594 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700595 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700596 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 }
598
Amith Yamasani04e0d262012-02-14 11:50:53 -0800599 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700600 synchronized (mAuthorities) {
601 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800602 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700603 "getIsSyncable");
604 if (authority == null) {
605 return -1;
606 }
607 return authority.syncable;
608 }
609
610 int i = mAuthorities.size();
611 while (i > 0) {
612 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700613 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700614 if (authority.authority.equals(providerName)) {
615 return authority.syncable;
616 }
617 }
618 return -1;
619 }
620 }
621
Amith Yamasani04e0d262012-02-14 11:50:53 -0800622 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700623 if (syncable > 1) {
624 syncable = 1;
625 } else if (syncable < -1) {
626 syncable = -1;
627 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800628 if (DEBUG) {
629 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
630 + ", user " + userId + " -> " + syncable);
631 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700632 synchronized (mAuthorities) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700633 AuthorityInfo authority =
634 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700635 if (authority.syncable == syncable) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800636 if (DEBUG) {
637 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
638 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700639 return;
640 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700641 authority.syncable = syncable;
642 writeAccountInfoLocked();
643 }
644
Fred Quintana77c560f2010-03-29 22:20:26 -0700645 if (syncable > 0) {
Alon Albert57286f92012-10-09 14:21:38 -0700646 requestSync(account, userId, SyncOperation.REASON_IS_SYNCABLE, providerName,
647 new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700648 }
649 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
650 }
651
Amith Yamasani04e0d262012-02-14 11:50:53 -0800652 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800653 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800654 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
655 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800656 if (authority == null || authority.backoffTime < 0) {
657 return null;
658 }
659 return Pair.create(authority.backoffTime, authority.backoffDelay);
660 }
661 }
662
Amith Yamasani04e0d262012-02-14 11:50:53 -0800663 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800664 long nextSyncTime, long nextDelay) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800665 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800666 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800667 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800668 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
669 }
670 boolean changed = false;
671 synchronized (mAuthorities) {
672 if (account == null || providerName == null) {
673 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800674 if (account != null && !account.equals(accountInfo.accountAndUser.account)
675 && userId != accountInfo.accountAndUser.userId) {
676 continue;
677 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800678 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
679 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
680 continue;
681 }
682 if (authorityInfo.backoffTime != nextSyncTime
683 || authorityInfo.backoffDelay != nextDelay) {
684 authorityInfo.backoffTime = nextSyncTime;
685 authorityInfo.backoffDelay = nextDelay;
686 changed = true;
687 }
688 }
689 }
690 } else {
691 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800692 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
693 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800694 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
695 return;
696 }
697 authority.backoffTime = nextSyncTime;
698 authority.backoffDelay = nextDelay;
699 changed = true;
700 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800701 }
702
703 if (changed) {
704 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
705 }
706 }
707
Alon Alberted1d2532011-02-15 14:02:14 -0800708 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800709 boolean changed = false;
710 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700711 synchronized (syncQueue) {
712 for (AccountInfo accountInfo : mAccounts.values()) {
713 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
714 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
715 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800716 if (DEBUG) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700717 Log.v(TAG, "clearAllBackoffs:"
718 + " authority:" + authorityInfo.authority
719 + " account:" + accountInfo.accountAndUser.account.name
720 + " user:" + accountInfo.accountAndUser.userId
721 + " backoffTime was: " + authorityInfo.backoffTime
722 + " backoffDelay was: " + authorityInfo.backoffDelay);
723 }
724 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
725 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
726 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
727 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
728 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800729 }
Alon Albert744e310f2010-12-14 11:37:20 -0800730 }
731 }
732 }
733 }
734
735 if (changed) {
736 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
737 }
738 }
739
Amith Yamasani04e0d262012-02-14 11:50:53 -0800740 public void setDelayUntilTime(Account account, int userId, String providerName,
741 long delayUntil) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800742 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800743 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800744 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800745 }
746 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800747 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800748 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800749 if (authority.delayUntil == delayUntil) {
750 return;
751 }
752 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800753 }
754
755 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
756 }
757
Amith Yamasani04e0d262012-02-14 11:50:53 -0800758 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800759 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800760 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
761 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800762 if (authority == null) {
763 return 0;
764 }
765 return authority.delayUntil;
766 }
767 }
768
Matthew Williamsfa774182013-06-18 15:44:11 -0700769 private void updateOrRemovePeriodicSync(PeriodicSync toUpdate, int userId, boolean add) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800770 if (DEBUG) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700771 Log.v(TAG, "addOrRemovePeriodicSync: " + toUpdate.account + ", user " + userId
772 + ", provider " + toUpdate.authority
773 + " -> period " + toUpdate.period + ", extras " + toUpdate.extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800774 }
775 synchronized (mAuthorities) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700776 if (toUpdate.period <= 0 && add) {
777 Log.e(TAG, "period < 0, should never happen in updateOrRemovePeriodicSync: add-" + add);
778 }
779 if (toUpdate.extras == null) {
780 Log.e(TAG, "period < 0, should never happen in updateOrRemovePeriodicSync: add-" + add);
781 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700782 try {
783 AuthorityInfo authority =
Matthew Williamsfa774182013-06-18 15:44:11 -0700784 getOrCreateAuthorityLocked(toUpdate.account, userId, toUpdate.authority,
785 -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700786 if (add) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700787 // add this periodic sync if an equivalent periodic doesn't already exist.
Fred Quintana77c560f2010-03-29 22:20:26 -0700788 boolean alreadyPresent = false;
789 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700790 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
791 if (PeriodicSync.syncExtrasEquals(
792 toUpdate.extras,
793 syncInfo.extras)) {
794 if (toUpdate.period == syncInfo.period &&
795 toUpdate.flexTime == syncInfo.flexTime) {
796 // Absolutely the same.
Fred Quintana77c560f2010-03-29 22:20:26 -0700797 return;
798 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700799 authority.periodicSyncs.set(i, new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700800 alreadyPresent = true;
801 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800802 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700803 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700804 // If we added an entry to the periodicSyncs array also add an entry to
805 // the periodic syncs status to correspond to it.
Fred Quintana77c560f2010-03-29 22:20:26 -0700806 if (!alreadyPresent) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700807 authority.periodicSyncs.add(new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700808 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
809 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
810 }
811 } else {
Matthew Williamsfa774182013-06-18 15:44:11 -0700812 // Remove any periodic syncs that match the authority and extras.
Fred Quintana77c560f2010-03-29 22:20:26 -0700813 SyncStatusInfo status = mSyncStatus.get(authority.ident);
814 boolean changed = false;
Matthew Williamsfa774182013-06-18 15:44:11 -0700815 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
Fred Quintana77c560f2010-03-29 22:20:26 -0700816 int i = 0;
817 while (iterator.hasNext()) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700818 PeriodicSync syncInfo = iterator.next();
819 if (PeriodicSync.syncExtrasEquals(syncInfo.extras, toUpdate.extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700820 iterator.remove();
821 changed = true;
Matthew Williamsfa774182013-06-18 15:44:11 -0700822 // If we removed an entry from the periodicSyncs array also
Fred Quintana77c560f2010-03-29 22:20:26 -0700823 // remove the corresponding entry from the status
824 if (status != null) {
825 status.removePeriodicSyncTime(i);
Matthew Williamsfa774182013-06-18 15:44:11 -0700826 } else {
827 Log.e(TAG, "Tried removing sync status on remove periodic sync but did not find it.");
Fred Quintana77c560f2010-03-29 22:20:26 -0700828 }
829 } else {
830 i++;
831 }
832 }
833 if (!changed) {
834 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800835 }
836 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700837 } finally {
838 writeAccountInfoLocked();
839 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800840 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800841 }
842
843 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
844 }
845
Matthew Williamsfa774182013-06-18 15:44:11 -0700846 public void addPeriodicSync(PeriodicSync toAdd, int userId) {
847 updateOrRemovePeriodicSync(toAdd, userId, true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800848 }
849
Matthew Williamsfa774182013-06-18 15:44:11 -0700850 public void removePeriodicSync(PeriodicSync toRemove, int userId) {
851 updateOrRemovePeriodicSync(toRemove, userId, false /* remove */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800852 }
853
Amith Yamasani04e0d262012-02-14 11:50:53 -0800854 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800855 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
856 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800857 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
858 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800859 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700860 for (PeriodicSync item : authority.periodicSyncs) {
861 // Copy and send out. Necessary for thread-safety although it's parceled.
862 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800863 }
864 }
865 }
866 return syncs;
867 }
868
Amith Yamasani04e0d262012-02-14 11:50:53 -0800869 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700870 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 Boolean auto = mMasterSyncAutomatically.get(userId);
872 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700873 return;
874 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800875 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700876 writeAccountInfoLocked();
877 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700878 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700879 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
880 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700881 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700882 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800883 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885
Amith Yamasani04e0d262012-02-14 11:50:53 -0800886 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800888 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800889 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700890 }
891 }
Costin Manolache360e4542009-09-04 13:36:04 -0700892
Amith Yamasani04e0d262012-02-14 11:50:53 -0800893 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700894 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800895 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700896 }
897 }
898
Dianne Hackborn231cc602009-04-27 17:10:36 -0700899 public AuthorityInfo getAuthority(int authorityId) {
900 synchronized (mAuthorities) {
901 return mAuthorities.get(authorityId);
902 }
903 }
Costin Manolache360e4542009-09-04 13:36:04 -0700904
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 /**
906 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700907 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700908 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800909 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700910 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700912 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700913 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 && ainfo.authority.equals(authority)
915 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 return true;
917 }
918 }
919 }
Costin Manolache360e4542009-09-04 13:36:04 -0700920
Dianne Hackborn231cc602009-04-27 17:10:36 -0700921 return false;
922 }
Costin Manolache360e4542009-09-04 13:36:04 -0700923
Dianne Hackborn231cc602009-04-27 17:10:36 -0700924 public PendingOperation insertIntoPending(PendingOperation op) {
925 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800926 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700927 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800928 + " user=" + op.userId
929 + " auth=" + op.authority
930 + " src=" + op.syncSource
931 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700932 }
Costin Manolache360e4542009-09-04 13:36:04 -0700933
Amith Yamasani04e0d262012-02-14 11:50:53 -0800934 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700935 op.authority,
936 -1 /* desired identifier */,
937 true /* write accounts to storage */);
938 if (authority == null) {
939 return null;
940 }
Costin Manolache360e4542009-09-04 13:36:04 -0700941
Dianne Hackborn231cc602009-04-27 17:10:36 -0700942 op = new PendingOperation(op);
943 op.authorityId = authority.ident;
944 mPendingOperations.add(op);
Matthew Williamsfa774182013-06-18 15:44:11 -0700945 writePendingOperationsLocked();
Costin Manolache360e4542009-09-04 13:36:04 -0700946
Dianne Hackborn231cc602009-04-27 17:10:36 -0700947 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
948 status.pending = true;
949 }
Costin Manolache360e4542009-09-04 13:36:04 -0700950
Fred Quintanaac9385e2009-06-22 18:00:59 -0700951 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 return op;
953 }
954
Matthew Williamsfa774182013-06-18 15:44:11 -0700955 /**
956 * Remove from list of pending operations. If successful, search through list for matching
957 * authorities. If there are no more pending syncs for the same authority/account/userid,
958 * update the SyncStatusInfo for that authority(authority here is the internal representation
959 * of a 'sync operation'.
960 * @param op
961 * @return
962 */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 public boolean deleteFromPending(PendingOperation op) {
964 boolean res = false;
965 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800966 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700967 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800968 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 + " auth=" + op.authority
970 + " src=" + op.syncSource
971 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700972 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 if (mPendingOperations.remove(op)) {
974 if (mPendingOperations.size() == 0
975 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
976 writePendingOperationsLocked();
977 mNumPendingFinished = 0;
978 } else {
979 mNumPendingFinished++;
980 }
Costin Manolache360e4542009-09-04 13:36:04 -0700981
Amith Yamasani04e0d262012-02-14 11:50:53 -0800982 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700983 "deleteFromPending");
984 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700985 if (DEBUG) Log.v(TAG, "removing - " + authority.toString());
Dianne Hackborn231cc602009-04-27 17:10:36 -0700986 final int N = mPendingOperations.size();
987 boolean morePending = false;
988 for (int i=0; i<N; i++) {
989 PendingOperation cur = mPendingOperations.get(i);
990 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800991 && cur.authority.equals(op.authority)
992 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700993 morePending = true;
994 break;
995 }
996 }
Costin Manolache360e4542009-09-04 13:36:04 -0700997
Dianne Hackborn231cc602009-04-27 17:10:36 -0700998 if (!morePending) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800999 if (DEBUG) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1001 status.pending = false;
1002 }
1003 }
Costin Manolache360e4542009-09-04 13:36:04 -07001004
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 res = true;
1006 }
1007 }
Costin Manolache360e4542009-09-04 13:36:04 -07001008
Fred Quintanaac9385e2009-06-22 18:00:59 -07001009 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001010 return res;
1011 }
1012
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 /**
1014 * Return a copy of the current array of pending operations. The
1015 * PendingOperation objects are the real objects stored inside, so that
1016 * they can be used with deleteFromPending().
1017 */
1018 public ArrayList<PendingOperation> getPendingOperations() {
1019 synchronized (mAuthorities) {
1020 return new ArrayList<PendingOperation>(mPendingOperations);
1021 }
1022 }
Costin Manolache360e4542009-09-04 13:36:04 -07001023
Dianne Hackborn231cc602009-04-27 17:10:36 -07001024 /**
1025 * Return the number of currently pending operations.
1026 */
1027 public int getPendingOperationCount() {
1028 synchronized (mAuthorities) {
1029 return mPendingOperations.size();
1030 }
1031 }
Costin Manolache360e4542009-09-04 13:36:04 -07001032
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 /**
1034 * Called when the set of account has changed, given the new array of
1035 * active accounts.
1036 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001039 if (DEBUG) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1041 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1042 while (accIt.hasNext()) {
1043 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001044 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1045 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 // This account no longer exists...
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001047 if (DEBUG) {
1048 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001049 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 for (AuthorityInfo auth : acc.authorities.values()) {
1051 removing.put(auth.ident, auth);
1052 }
1053 accIt.remove();
1054 }
1055 }
Costin Manolache360e4542009-09-04 13:36:04 -07001056
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 // Clean out all data structures.
1058 int i = removing.size();
1059 if (i > 0) {
1060 while (i > 0) {
1061 i--;
1062 int ident = removing.keyAt(i);
1063 mAuthorities.remove(ident);
1064 int j = mSyncStatus.size();
1065 while (j > 0) {
1066 j--;
1067 if (mSyncStatus.keyAt(j) == ident) {
1068 mSyncStatus.remove(mSyncStatus.keyAt(j));
1069 }
1070 }
1071 j = mSyncHistory.size();
1072 while (j > 0) {
1073 j--;
1074 if (mSyncHistory.get(j).authorityId == ident) {
1075 mSyncHistory.remove(j);
1076 }
1077 }
1078 }
1079 writeAccountInfoLocked();
1080 writeStatusLocked();
1081 writePendingOperationsLocked();
1082 writeStatisticsLocked();
1083 }
1084 }
1085 }
1086
1087 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001088 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1089 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 */
Fred Quintana918339a2010-10-05 14:00:39 -07001091 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1092 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001093 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001094 if (DEBUG) {
Fred Quintana918339a2010-10-05 14:00:39 -07001095 Log.v(TAG, "setActiveSync: account="
1096 + activeSyncContext.mSyncOperation.account
1097 + " auth=" + activeSyncContext.mSyncOperation.authority
1098 + " src=" + activeSyncContext.mSyncOperation.syncSource
1099 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 }
Fred Quintana918339a2010-10-05 14:00:39 -07001101 AuthorityInfo authority = getOrCreateAuthorityLocked(
1102 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001104 activeSyncContext.mSyncOperation.authority,
1105 -1 /* assign a new identifier if creating a new authority */,
1106 true /* write to storage if this results in a change */);
1107 syncInfo = new SyncInfo(authority.ident,
1108 authority.account, authority.authority,
1109 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001110 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 }
Costin Manolache360e4542009-09-04 13:36:04 -07001112
Fred Quintana918339a2010-10-05 14:00:39 -07001113 reportActiveChange();
1114 return syncInfo;
1115 }
1116
1117 /**
1118 * Called to indicate that a previously active sync is no longer active.
1119 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001120 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001121 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001122 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001123 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1124 + " user=" + userId
1125 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001126 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001128 }
1129
1130 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 }
1132
1133 /**
1134 * To allow others to send active change reports, to poke clients.
1135 */
1136 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001137 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 }
Costin Manolache360e4542009-09-04 13:36:04 -07001139
Dianne Hackborn231cc602009-04-27 17:10:36 -07001140 /**
1141 * Note that sync has started for the given account and authority.
1142 */
Alon Albert57286f92012-10-09 14:21:38 -07001143 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1144 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 long id;
1146 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001147 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001148 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001150 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001151 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 "insertStartSyncEvent");
1153 if (authority == null) {
1154 return -1;
1155 }
1156 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001157 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001158 item.authorityId = authority.ident;
1159 item.historyId = mNextHistoryId++;
1160 if (mNextHistoryId < 0) mNextHistoryId = 0;
1161 item.eventTime = now;
1162 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001163 item.reason = reason;
1164 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 item.event = EVENT_START;
1166 mSyncHistory.add(0, item);
1167 while (mSyncHistory.size() > MAX_HISTORY) {
1168 mSyncHistory.remove(mSyncHistory.size()-1);
1169 }
1170 id = item.historyId;
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001171 if (DEBUG) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001172 }
Costin Manolache360e4542009-09-04 13:36:04 -07001173
Fred Quintanaac9385e2009-06-22 18:00:59 -07001174 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177
Fred Quintana77c560f2010-03-29 22:20:26 -07001178 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001181 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001182 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1183 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001184 SyncHistoryItem item = null;
1185 int i = mSyncHistory.size();
1186 while (i > 0) {
1187 i--;
1188 item = mSyncHistory.get(i);
1189 if (item.historyId == historyId) {
1190 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
Costin Manolache360e4542009-09-04 13:36:04 -07001194
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 if (item == null) {
1196 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1197 return;
1198 }
Costin Manolache360e4542009-09-04 13:36:04 -07001199
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 item.elapsedTime = elapsedTime;
1201 item.event = EVENT_STOP;
1202 item.mesg = resultMessage;
1203 item.downstreamActivity = downstreamActivity;
1204 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001205
Dianne Hackborn231cc602009-04-27 17:10:36 -07001206 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001207
Dianne Hackborn231cc602009-04-27 17:10:36 -07001208 status.numSyncs++;
1209 status.totalElapsedTime += elapsedTime;
1210 switch (item.source) {
1211 case SOURCE_LOCAL:
1212 status.numSourceLocal++;
1213 break;
1214 case SOURCE_POLL:
1215 status.numSourcePoll++;
1216 break;
1217 case SOURCE_USER:
1218 status.numSourceUser++;
1219 break;
1220 case SOURCE_SERVER:
1221 status.numSourceServer++;
1222 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001223 case SOURCE_PERIODIC:
1224 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001225 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 }
Costin Manolache360e4542009-09-04 13:36:04 -07001227
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001229 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001230 if (mDayStats[0] == null) {
1231 mDayStats[0] = new DayStats(day);
1232 } else if (day != mDayStats[0].day) {
1233 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1234 mDayStats[0] = new DayStats(day);
1235 writeStatisticsNow = true;
1236 } else if (mDayStats[0] == null) {
1237 }
1238 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001239
Dianne Hackborn231cc602009-04-27 17:10:36 -07001240 final long lastSyncTime = (item.eventTime + elapsedTime);
1241 boolean writeStatusNow = false;
1242 if (MESG_SUCCESS.equals(resultMessage)) {
1243 // - if successful, update the successful columns
1244 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1245 writeStatusNow = true;
1246 }
1247 status.lastSuccessTime = lastSyncTime;
1248 status.lastSuccessSource = item.source;
1249 status.lastFailureTime = 0;
1250 status.lastFailureSource = -1;
1251 status.lastFailureMesg = null;
1252 status.initialFailureTime = 0;
1253 ds.successCount++;
1254 ds.successTime += elapsedTime;
1255 } else if (!MESG_CANCELED.equals(resultMessage)) {
1256 if (status.lastFailureTime == 0) {
1257 writeStatusNow = true;
1258 }
1259 status.lastFailureTime = lastSyncTime;
1260 status.lastFailureSource = item.source;
1261 status.lastFailureMesg = resultMessage;
1262 if (status.initialFailureTime == 0) {
1263 status.initialFailureTime = lastSyncTime;
1264 }
1265 ds.failureCount++;
1266 ds.failureTime += elapsedTime;
1267 }
Costin Manolache360e4542009-09-04 13:36:04 -07001268
Dianne Hackborn231cc602009-04-27 17:10:36 -07001269 if (writeStatusNow) {
1270 writeStatusLocked();
1271 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1272 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1273 WRITE_STATUS_DELAY);
1274 }
1275 if (writeStatisticsNow) {
1276 writeStatisticsLocked();
1277 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1278 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1279 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001280 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001281 }
Costin Manolache360e4542009-09-04 13:36:04 -07001282
Fred Quintanaac9385e2009-06-22 18:00:59 -07001283 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 }
1285
1286 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001287 * Return a list of the currently active syncs. Note that the returned items are the
1288 * real, live active sync objects, so be careful what you do with it.
1289 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001291 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1293 if (syncs == null) {
1294 syncs = new ArrayList<SyncInfo>();
1295 mCurrentSyncs.put(userId, syncs);
1296 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001297 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001298 }
1299 }
Costin Manolache360e4542009-09-04 13:36:04 -07001300
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 /**
1302 * Return an array of the current sync status for all authorities. Note
1303 * that the objects inside the array are the real, live status objects,
1304 * so be careful what you do with them.
1305 */
1306 public ArrayList<SyncStatusInfo> getSyncStatus() {
1307 synchronized (mAuthorities) {
1308 final int N = mSyncStatus.size();
1309 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1310 for (int i=0; i<N; i++) {
1311 ops.add(mSyncStatus.valueAt(i));
1312 }
1313 return ops;
1314 }
1315 }
Costin Manolache360e4542009-09-04 13:36:04 -07001316
Dianne Hackborn231cc602009-04-27 17:10:36 -07001317 /**
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001318 * Return a copy of the specified authority with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001319 */
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001320 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(
1321 Account account, int userId, String authority) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001322 synchronized (mAuthorities) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001323 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(account, userId, authority,
1324 -1 /* assign a new identifier if creating a new authority */,
1325 true /* write to storage if this results in a change */);
1326 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1327 }
1328 }
1329
1330 /**
1331 * Return a copy of all authorities with their corresponding sync status
1332 */
1333 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1334 synchronized (mAuthorities) {
1335 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1336 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1337 for (int i = 0; i < mAuthorities.size(); i++) {
1338 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001339 }
1340 return infos;
1341 }
1342 }
1343
1344 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001345 * Returns the status that matches the authority and account.
1346 *
1347 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001348 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001349 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001350 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001351 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1352 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001353 if (account == null || authority == null) {
1354 throw new IllegalArgumentException();
1355 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 final int N = mSyncStatus.size();
1358 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001359 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001361
Amith Yamasani04e0d262012-02-14 11:50:53 -08001362 if (ainfo != null && ainfo.authority.equals(authority)
1363 && ainfo.userId == userId
1364 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001365 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 }
1367 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001368 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 }
1370 }
Costin Manolache360e4542009-09-04 13:36:04 -07001371
Dianne Hackborn231cc602009-04-27 17:10:36 -07001372 /**
1373 * Return true if the pending status is true of any matching authorities.
1374 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001375 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001376 synchronized (mAuthorities) {
1377 final int N = mSyncStatus.size();
1378 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001379 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1381 if (ainfo == null) {
1382 continue;
1383 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001384 if (userId != ainfo.userId) {
1385 continue;
1386 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 if (account != null && !ainfo.account.equals(account)) {
1388 continue;
1389 }
1390 if (ainfo.authority.equals(authority) && cur.pending) {
1391 return true;
1392 }
1393 }
1394 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396 }
1397
1398 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001399 * Return an array of the current sync status for all authorities. Note
1400 * that the objects inside the array are the real, live status objects,
1401 * so be careful what you do with them.
1402 */
1403 public ArrayList<SyncHistoryItem> getSyncHistory() {
1404 synchronized (mAuthorities) {
1405 final int N = mSyncHistory.size();
1406 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1407 for (int i=0; i<N; i++) {
1408 items.add(mSyncHistory.get(i));
1409 }
1410 return items;
1411 }
1412 }
Costin Manolache360e4542009-09-04 13:36:04 -07001413
Dianne Hackborn231cc602009-04-27 17:10:36 -07001414 /**
1415 * Return an array of the current per-day statistics. Note
1416 * that the objects inside the array are the real, live status objects,
1417 * so be careful what you do with them.
1418 */
1419 public DayStats[] getDayStatistics() {
1420 synchronized (mAuthorities) {
1421 DayStats[] ds = new DayStats[mDayStats.length];
1422 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1423 return ds;
1424 }
1425 }
Costin Manolache360e4542009-09-04 13:36:04 -07001426
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001427 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1428 AuthorityInfo authorityInfo) {
1429 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1430 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1431 }
1432
Dianne Hackborn55280a92009-05-07 15:53:46 -07001433 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001434 mCal.setTimeInMillis(System.currentTimeMillis());
1435 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1436 if (mYear != mCal.get(Calendar.YEAR)) {
1437 mYear = mCal.get(Calendar.YEAR);
1438 mCal.clear();
1439 mCal.set(Calendar.YEAR, mYear);
1440 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1441 }
1442 return dayOfYear + mYearInDays;
1443 }
Costin Manolache360e4542009-09-04 13:36:04 -07001444
Dianne Hackborn231cc602009-04-27 17:10:36 -07001445 /**
1446 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001447 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001448 * @param accountName The name of the account for the authority.
1449 * @param authorityName The name of the authority itself.
1450 * @param tag If non-null, this will be used in a log message if the
1451 * requested authority does not exist.
1452 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001453 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001455 AccountAndUser au = new AccountAndUser(accountName, userId);
1456 AccountInfo accountInfo = mAccounts.get(au);
1457 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001458 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001459 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001460 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001461 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001462 }
1463 return null;
1464 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001465 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 if (authority == null) {
1467 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001468 if (DEBUG) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001469 Log.v(TAG, tag + ": unknown authority " + authorityName);
1470 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 }
1472 return null;
1473 }
Costin Manolache360e4542009-09-04 13:36:04 -07001474
Dianne Hackborn231cc602009-04-27 17:10:36 -07001475 return authority;
1476 }
Costin Manolache360e4542009-09-04 13:36:04 -07001477
Matthew Williamsfa774182013-06-18 15:44:11 -07001478 /**
1479 * Retrieve an authority, returning null if one does not exist.
1480 *
1481 * @param service The service name used for this sync.
1482 * @param userId The user for whom this sync is scheduled.
1483 * @param tag If non-null, this will be used in a log message if the
1484 * requested authority does not exist.
1485 */
1486 private AuthorityInfo getAuthorityLocked(ComponentName service, int userId, String tag) {
1487 AuthorityInfo authority = mServices.get(service).get(userId);
1488 if (authority == null) {
1489 if (tag != null) {
1490 if (DEBUG) {
1491 Log.v(TAG, tag + " No authority info found for " + service + " for user "
1492 + userId);
1493 }
1494 }
1495 return null;
1496 }
1497 return authority;
1498 }
1499
1500 /**
1501 * @param cname identifier for the service.
1502 * @param userId for the syncs corresponding to this authority.
1503 * @param ident unique identifier for authority. -1 for none.
1504 * @param doWrite if true, update the accounts.xml file on the disk.
1505 * @return the authority that corresponds to the provided sync service, creating it if none
1506 * exists.
1507 */
1508 private AuthorityInfo getOrCreateAuthorityLocked(ComponentName cname, int userId, int ident,
1509 boolean doWrite) {
1510 SparseArray<AuthorityInfo> aInfo = mServices.get(cname);
1511 if (aInfo == null) {
1512 aInfo = new SparseArray<AuthorityInfo>();
1513 mServices.put(cname, aInfo);
1514 }
1515 AuthorityInfo authority = aInfo.get(userId);
1516 if (authority == null) {
1517 if (ident < 0) {
1518 ident = mNextAuthorityId;
1519 mNextAuthorityId++;
1520 doWrite = true;
1521 }
1522 if (DEBUG) {
1523 Log.v(TAG, "created a new AuthorityInfo for " + cname.getPackageName()
1524 + ", " + cname.getClassName()
1525 + ", user: " + userId);
1526 }
1527 authority = new AuthorityInfo(cname, userId, ident);
1528 aInfo.put(userId, authority);
1529 mAuthorities.put(ident, authority);
1530 if (doWrite) {
1531 writeAccountInfoLocked();
1532 }
1533 }
1534 return authority;
1535 }
1536
Amith Yamasani04e0d262012-02-14 11:50:53 -08001537 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001539 AccountAndUser au = new AccountAndUser(accountName, userId);
1540 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001541 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001542 account = new AccountInfo(au);
1543 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001544 }
1545 AuthorityInfo authority = account.authorities.get(authorityName);
1546 if (authority == null) {
1547 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001548 ident = mNextAuthorityId;
1549 mNextAuthorityId++;
1550 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001551 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001552 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001553 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001554 + ", user " + userId
1555 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001556 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001557 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 account.authorities.put(authorityName, authority);
1559 mAuthorities.put(ident, authority);
1560 if (doWrite) {
1561 writeAccountInfoLocked();
1562 }
1563 }
Costin Manolache360e4542009-09-04 13:36:04 -07001564
Dianne Hackborn231cc602009-04-27 17:10:36 -07001565 return authority;
1566 }
Costin Manolache360e4542009-09-04 13:36:04 -07001567
Amith Yamasani04e0d262012-02-14 11:50:53 -08001568 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1569 boolean doWrite) {
1570 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001571 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001572 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1573 if (authorityInfo != null) {
1574 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001575 if (doWrite) {
1576 writeAccountInfoLocked();
1577 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001578 }
1579 }
1580 }
1581
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001582 /**
1583 * Updates (in a synchronized way) the periodic sync time of the specified
1584 * authority id and target periodic sync
1585 */
1586 public void setPeriodicSyncTime(
Matthew Williamsfa774182013-06-18 15:44:11 -07001587 int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001588 boolean found = false;
1589 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001590 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001591 authorityInfo = mAuthorities.get(authorityId);
1592 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001593 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1594 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001595 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001596 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001597 break;
1598 }
1599 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001600 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001601 if (!found) {
1602 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
1603 "Authority: " + authorityInfo.authority);
1604 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001605 }
1606
Dianne Hackborn231cc602009-04-27 17:10:36 -07001607 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1608 SyncStatusInfo status = mSyncStatus.get(authorityId);
1609 if (status == null) {
1610 status = new SyncStatusInfo(authorityId);
1611 mSyncStatus.put(authorityId, status);
1612 }
1613 return status;
1614 }
Costin Manolache360e4542009-09-04 13:36:04 -07001615
Dianne Hackborn55280a92009-05-07 15:53:46 -07001616 public void writeAllState() {
1617 synchronized (mAuthorities) {
1618 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001619
Dianne Hackborn55280a92009-05-07 15:53:46 -07001620 if (mNumPendingFinished > 0) {
1621 // Only write these if they are out of date.
1622 writePendingOperationsLocked();
1623 }
Costin Manolache360e4542009-09-04 13:36:04 -07001624
Dianne Hackborn55280a92009-05-07 15:53:46 -07001625 // Just always write these... they are likely out of date.
1626 writeStatusLocked();
1627 writeStatisticsLocked();
1628 }
1629 }
Costin Manolache360e4542009-09-04 13:36:04 -07001630
Dianne Hackborn231cc602009-04-27 17:10:36 -07001631 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001632 * public for testing
1633 */
1634 public void clearAndReadState() {
1635 synchronized (mAuthorities) {
1636 mAuthorities.clear();
1637 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001638 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001639 mPendingOperations.clear();
1640 mSyncStatus.clear();
1641 mSyncHistory.clear();
1642
1643 readAccountInfoLocked();
1644 readStatusLocked();
1645 readPendingOperationsLocked();
1646 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001647 readAndDeleteLegacyAccountInfoLocked();
1648 writeAccountInfoLocked();
1649 writeStatusLocked();
1650 writePendingOperationsLocked();
1651 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001652 }
1653 }
1654
1655 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001656 * Read all account information back in to the initial engine state.
1657 */
1658 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001659 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001660 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001662 fis = mAccountInfoFile.openRead();
1663 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1664 XmlPullParser parser = Xml.newPullParser();
1665 parser.setInput(fis, null);
1666 int eventType = parser.getEventType();
1667 while (eventType != XmlPullParser.START_TAG) {
1668 eventType = parser.next();
1669 }
1670 String tagName = parser.getName();
1671 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001672 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001673 String versionString = parser.getAttributeValue(null, "version");
1674 int version;
1675 try {
1676 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1677 } catch (NumberFormatException e) {
1678 version = 0;
1679 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001680 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001681 try {
1682 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1683 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1684 } catch (NumberFormatException e) {
1685 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001686 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001687 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1688 try {
1689 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1690 } catch (NumberFormatException e) {
1691 mSyncRandomOffset = 0;
1692 }
1693 if (mSyncRandomOffset == 0) {
1694 Random random = new Random(System.currentTimeMillis());
1695 mSyncRandomOffset = random.nextInt(86400);
1696 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001697 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001698 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001699 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001700 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001701 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001702 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001703 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001704 if (parser.getDepth() == 2) {
1705 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001706 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001707 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001708 if (authority.ident > highestAuthorityId) {
1709 highestAuthorityId = authority.ident;
1710 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1712 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001713 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001714 } else if (parser.getDepth() == 3) {
1715 if ("periodicSync".equals(tagName) && authority != null) {
1716 periodicSync = parsePeriodicSync(parser, authority);
1717 }
1718 } else if (parser.getDepth() == 4 && periodicSync != null) {
1719 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001720 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001721 }
1722 }
1723 }
1724 eventType = parser.next();
1725 } while (eventType != XmlPullParser.END_DOCUMENT);
1726 }
1727 } catch (XmlPullParserException e) {
1728 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001729 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001730 } catch (java.io.IOException e) {
1731 if (fis == null) Log.i(TAG, "No initial accounts");
1732 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001733 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001734 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001735 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001736 if (fis != null) {
1737 try {
1738 fis.close();
1739 } catch (java.io.IOException e1) {
1740 }
1741 }
1742 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001743
Fred Quintana77c560f2010-03-29 22:20:26 -07001744 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001745 }
Costin Manolache360e4542009-09-04 13:36:04 -07001746
Fred Quintanafb084402010-03-23 17:57:03 -07001747 /**
1748 * some authority names have changed. copy over their settings and delete the old ones
1749 * @return true if a change was made
1750 */
1751 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1752 boolean writeNeeded = false;
1753
1754 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1755 final int N = mAuthorities.size();
1756 for (int i=0; i<N; i++) {
1757 AuthorityInfo authority = mAuthorities.valueAt(i);
1758 // skip this authority if it isn't one of the renamed ones
1759 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1760 if (newAuthorityName == null) {
1761 continue;
1762 }
1763
1764 // remember this authority so we can remove it later. we can't remove it
1765 // now without messing up this loop iteration
1766 authoritiesToRemove.add(authority);
1767
1768 // this authority isn't enabled, no need to copy it to the new authority name since
1769 // the default is "disabled"
1770 if (!authority.enabled) {
1771 continue;
1772 }
1773
1774 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001775 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1776 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001777 continue;
1778 }
1779
1780 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001781 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001782 newAuthority.enabled = true;
1783 writeNeeded = true;
1784 }
1785
1786 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001787 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1788 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001789 writeNeeded = true;
1790 }
1791
1792 return writeNeeded;
1793 }
1794
Amith Yamasani04e0d262012-02-14 11:50:53 -08001795 private void parseListenForTickles(XmlPullParser parser) {
1796 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1797 int userId = 0;
1798 try {
1799 userId = Integer.parseInt(user);
1800 } catch (NumberFormatException e) {
1801 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1802 } catch (NullPointerException e) {
1803 Log.e(TAG, "the user in listen-for-tickles is null", e);
1804 }
1805 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1806 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1807 mMasterSyncAutomatically.put(userId, listen);
1808 }
1809
Fred Quintanac2e46912010-03-15 16:10:44 -07001810 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001811 AuthorityInfo authority = null;
1812 int id = -1;
1813 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001814 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001815 } catch (NumberFormatException e) {
1816 Log.e(TAG, "error parsing the id of the authority", e);
1817 } catch (NullPointerException e) {
1818 Log.e(TAG, "the id of the authority is null", e);
1819 }
1820 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001821 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001822 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001823 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001824 String accountName = parser.getAttributeValue(null, "account");
1825 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001826 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001827 String packageName = parser.getAttributeValue(null, "package");
1828 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001829 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001830 if (accountType == null) {
1831 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001832 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001833 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001834 authority = mAuthorities.get(id);
1835 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1836 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001837 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001838 + " enabled=" + enabled
1839 + " syncable=" + syncable);
1840 if (authority == null) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001841 if (DEBUG_FILE) {
1842 Log.v(TAG, "Creating entry");
1843 }
1844 if (accountName != null && accountType != null) {
1845 authority = getOrCreateAuthorityLocked(
1846 new Account(accountName, accountType), userId, authorityName, id, false);
1847 } else {
1848 authority = getOrCreateAuthorityLocked(
1849 new ComponentName(packageName, className), userId, id, false);
1850 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001851 // If the version is 0 then we are upgrading from a file format that did not
1852 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07001853 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07001854 // Otherwise clear out this default list since we will populate it later with
1855 // the periodic sync descriptions that are read from the configuration file.
1856 if (version > 0) {
1857 authority.periodicSyncs.clear();
1858 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001859 }
1860 if (authority != null) {
1861 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1862 if ("unknown".equals(syncable)) {
1863 authority.syncable = -1;
1864 } else {
1865 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001866 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001867 }
1868 } else {
1869 Log.w(TAG, "Failure adding authority: account="
1870 + accountName + " auth=" + authorityName
1871 + " enabled=" + enabled
1872 + " syncable=" + syncable);
1873 }
1874 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001875 return authority;
1876 }
1877
Matthew Williamsfa774182013-06-18 15:44:11 -07001878 /**
1879 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1880 */
1881 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1882 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001883 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001884 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001885 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001886 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001887 try {
1888 period = Long.parseLong(periodValue);
1889 } catch (NumberFormatException e) {
1890 Log.e(TAG, "error parsing the period of a periodic sync", e);
1891 return null;
1892 } catch (NullPointerException e) {
1893 Log.e(TAG, "the period of a periodic sync is null", e);
1894 return null;
1895 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001896 try {
1897 flextime = Long.parseLong(flexValue);
1898 } catch (NumberFormatException e) {
1899 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue);
1900 flextime = calculateDefaultFlexTime(period);
1901 } catch (NullPointerException expected) {
1902 flextime = calculateDefaultFlexTime(period);
1903 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
1904 + period + " flex: " + flextime);
1905 }
1906 final PeriodicSync periodicSync =
1907 new PeriodicSync(authority.account, authority.authority, extras,
1908 period, flextime);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001909 authority.periodicSyncs.add(periodicSync);
1910 return periodicSync;
1911 }
1912
Matthew Williamsfa774182013-06-18 15:44:11 -07001913 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001914 String name = parser.getAttributeValue(null, "name");
1915 String type = parser.getAttributeValue(null, "type");
1916 String value1 = parser.getAttributeValue(null, "value1");
1917 String value2 = parser.getAttributeValue(null, "value2");
1918
1919 try {
1920 if ("long".equals(type)) {
1921 extras.putLong(name, Long.parseLong(value1));
1922 } else if ("integer".equals(type)) {
1923 extras.putInt(name, Integer.parseInt(value1));
1924 } else if ("double".equals(type)) {
1925 extras.putDouble(name, Double.parseDouble(value1));
1926 } else if ("float".equals(type)) {
1927 extras.putFloat(name, Float.parseFloat(value1));
1928 } else if ("boolean".equals(type)) {
1929 extras.putBoolean(name, Boolean.parseBoolean(value1));
1930 } else if ("string".equals(type)) {
1931 extras.putString(name, value1);
1932 } else if ("account".equals(type)) {
1933 extras.putParcelable(name, new Account(value1, value2));
1934 }
1935 } catch (NumberFormatException e) {
1936 Log.e(TAG, "error parsing bundle value", e);
1937 } catch (NullPointerException e) {
1938 Log.e(TAG, "error parsing bundle value", e);
1939 }
1940 }
1941
Dianne Hackborn231cc602009-04-27 17:10:36 -07001942 /**
1943 * Write all account information to the account file.
1944 */
1945 private void writeAccountInfoLocked() {
1946 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1947 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001948
Dianne Hackborn231cc602009-04-27 17:10:36 -07001949 try {
1950 fos = mAccountInfoFile.startWrite();
1951 XmlSerializer out = new FastXmlSerializer();
1952 out.setOutput(fos, "utf-8");
1953 out.startDocument(null, true);
1954 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001955
Dianne Hackborn231cc602009-04-27 17:10:36 -07001956 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001957 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001958 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001959 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001960
1961 // Write the Sync Automatically flags for each user
1962 final int M = mMasterSyncAutomatically.size();
1963 for (int m = 0; m < M; m++) {
1964 int userId = mMasterSyncAutomatically.keyAt(m);
1965 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1966 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1967 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1968 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1969 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001970 }
Costin Manolache360e4542009-09-04 13:36:04 -07001971
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001973 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001974 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 out.startTag(null, "authority");
1976 out.attribute(null, "id", Integer.toString(authority.ident));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001977 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williamsfa774182013-06-18 15:44:11 -07001979 if (authority.service == null) {
1980 out.attribute(null, "account", authority.account.name);
1981 out.attribute(null, "type", authority.account.type);
1982 out.attribute(null, "authority", authority.authority);
1983 } else {
1984 out.attribute(null, "package", authority.service.getPackageName());
1985 out.attribute(null, "class", authority.service.getClassName());
1986 }
Fred Quintana5e787c42009-08-16 23:13:53 -07001987 if (authority.syncable < 0) {
1988 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001989 } else {
1990 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001991 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001992 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001993 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07001994 out.attribute(null, "period", Long.toString(periodicSync.period));
1995 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
1996 final Bundle extras = periodicSync.extras;
1997 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001998 out.endTag(null, "periodicSync");
1999 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 out.endTag(null, "authority");
2001 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002003 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 mAccountInfoFile.finishWrite(fos);
2005 } catch (java.io.IOException e1) {
2006 Log.w(TAG, "Error writing accounts", e1);
2007 if (fos != null) {
2008 mAccountInfoFile.failWrite(fos);
2009 }
2010 }
2011 }
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 static int getIntColumn(Cursor c, String name) {
2014 return c.getInt(c.getColumnIndex(name));
2015 }
Costin Manolache360e4542009-09-04 13:36:04 -07002016
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 static long getLongColumn(Cursor c, String name) {
2018 return c.getLong(c.getColumnIndex(name));
2019 }
Costin Manolache360e4542009-09-04 13:36:04 -07002020
Dianne Hackborn231cc602009-04-27 17:10:36 -07002021 /**
2022 * Load sync engine state from the old syncmanager database, and then
2023 * erase it. Note that we don't deal with pending operations, active
2024 * sync, or history.
2025 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002026 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 // Look for old database to initialize from.
2028 File file = mContext.getDatabasePath("syncmanager.db");
2029 if (!file.exists()) {
2030 return;
2031 }
2032 String path = file.getPath();
2033 SQLiteDatabase db = null;
2034 try {
2035 db = SQLiteDatabase.openDatabase(path, null,
2036 SQLiteDatabase.OPEN_READONLY);
2037 } catch (SQLiteException e) {
2038 }
Costin Manolache360e4542009-09-04 13:36:04 -07002039
Dianne Hackborn231cc602009-04-27 17:10:36 -07002040 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002041 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002042
Dianne Hackborn231cc602009-04-27 17:10:36 -07002043 // Copy in all of the status information, as well as accounts.
2044 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
2045 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2046 qb.setTables("stats, status");
2047 HashMap<String,String> map = new HashMap<String,String>();
2048 map.put("_id", "status._id as _id");
2049 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002050 if (hasType) {
2051 map.put("account_type", "stats.account_type as account_type");
2052 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002053 map.put("authority", "stats.authority as authority");
2054 map.put("totalElapsedTime", "totalElapsedTime");
2055 map.put("numSyncs", "numSyncs");
2056 map.put("numSourceLocal", "numSourceLocal");
2057 map.put("numSourcePoll", "numSourcePoll");
2058 map.put("numSourceServer", "numSourceServer");
2059 map.put("numSourceUser", "numSourceUser");
2060 map.put("lastSuccessSource", "lastSuccessSource");
2061 map.put("lastSuccessTime", "lastSuccessTime");
2062 map.put("lastFailureSource", "lastFailureSource");
2063 map.put("lastFailureTime", "lastFailureTime");
2064 map.put("lastFailureMesg", "lastFailureMesg");
2065 map.put("pending", "pending");
2066 qb.setProjectionMap(map);
2067 qb.appendWhere("stats._id = status.stats_id");
2068 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002070 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002071 String accountType = hasType
2072 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002073 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002074 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 String authorityName = c.getString(c.getColumnIndex("authority"));
2077 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002078 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07002079 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 if (authority != null) {
2081 int i = mSyncStatus.size();
2082 boolean found = false;
2083 SyncStatusInfo st = null;
2084 while (i > 0) {
2085 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002086 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002087 if (st.authorityId == authority.ident) {
2088 found = true;
2089 break;
2090 }
2091 }
2092 if (!found) {
2093 st = new SyncStatusInfo(authority.ident);
2094 mSyncStatus.put(authority.ident, st);
2095 }
2096 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2097 st.numSyncs = getIntColumn(c, "numSyncs");
2098 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2099 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2100 st.numSourceServer = getIntColumn(c, "numSourceServer");
2101 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002102 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002103 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2104 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2105 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2106 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2107 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2108 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 }
Costin Manolache360e4542009-09-04 13:36:04 -07002111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002113
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 // Retrieve the settings.
2115 qb = new SQLiteQueryBuilder();
2116 qb.setTables("settings");
2117 c = qb.query(db, null, null, null, null, null, null);
2118 while (c.moveToNext()) {
2119 String name = c.getString(c.getColumnIndex("name"));
2120 String value = c.getString(c.getColumnIndex("value"));
2121 if (name == null) continue;
2122 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002123 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002124 } else if (name.startsWith("sync_provider_")) {
2125 String provider = name.substring("sync_provider_".length(),
2126 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002127 int i = mAuthorities.size();
2128 while (i > 0) {
2129 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002130 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07002131 if (authority.authority.equals(provider)) {
2132 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002133 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002134 }
2135 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
Costin Manolache360e4542009-09-04 13:36:04 -07002138
Dianne Hackborn231cc602009-04-27 17:10:36 -07002139 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002140
Dianne Hackborn231cc602009-04-27 17:10:36 -07002141 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002142
Dianne Hackborn231cc602009-04-27 17:10:36 -07002143 (new File(path)).delete();
2144 }
2145 }
Costin Manolache360e4542009-09-04 13:36:04 -07002146
Dianne Hackborn231cc602009-04-27 17:10:36 -07002147 public static final int STATUS_FILE_END = 0;
2148 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002149
Dianne Hackborn231cc602009-04-27 17:10:36 -07002150 /**
2151 * Read all sync status back in to the initial engine state.
2152 */
2153 private void readStatusLocked() {
2154 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
2155 try {
2156 byte[] data = mStatusFile.readFully();
2157 Parcel in = Parcel.obtain();
2158 in.unmarshall(data, 0, data.length);
2159 in.setDataPosition(0);
2160 int token;
2161 while ((token=in.readInt()) != STATUS_FILE_END) {
2162 if (token == STATUS_FILE_ITEM) {
2163 SyncStatusInfo status = new SyncStatusInfo(in);
2164 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2165 status.pending = false;
2166 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
2167 + status.authorityId);
2168 mSyncStatus.put(status.authorityId, status);
2169 }
2170 } else {
2171 // Ooops.
2172 Log.w(TAG, "Unknown status token: " + token);
2173 break;
2174 }
2175 }
2176 } catch (java.io.IOException e) {
2177 Log.i(TAG, "No initial status");
2178 }
2179 }
Costin Manolache360e4542009-09-04 13:36:04 -07002180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 /**
2182 * Write all sync status to the sync status file.
2183 */
2184 private void writeStatusLocked() {
2185 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002186
Dianne Hackborn231cc602009-04-27 17:10:36 -07002187 // The file is being written, so we don't need to have a scheduled
2188 // write until the next change.
2189 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002190
Dianne Hackborn231cc602009-04-27 17:10:36 -07002191 FileOutputStream fos = null;
2192 try {
2193 fos = mStatusFile.startWrite();
2194 Parcel out = Parcel.obtain();
2195 final int N = mSyncStatus.size();
2196 for (int i=0; i<N; i++) {
2197 SyncStatusInfo status = mSyncStatus.valueAt(i);
2198 out.writeInt(STATUS_FILE_ITEM);
2199 status.writeToParcel(out, 0);
2200 }
2201 out.writeInt(STATUS_FILE_END);
2202 fos.write(out.marshall());
2203 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002204
Dianne Hackborn231cc602009-04-27 17:10:36 -07002205 mStatusFile.finishWrite(fos);
2206 } catch (java.io.IOException e1) {
2207 Log.w(TAG, "Error writing status", e1);
2208 if (fos != null) {
2209 mStatusFile.failWrite(fos);
2210 }
2211 }
2212 }
Costin Manolache360e4542009-09-04 13:36:04 -07002213
Matthew Williamsfa774182013-06-18 15:44:11 -07002214 public static final int PENDING_OPERATION_VERSION = 4;
Costin Manolache360e4542009-09-04 13:36:04 -07002215
Dianne Hackborn231cc602009-04-27 17:10:36 -07002216 /**
2217 * Read all pending operations back in to the initial engine state.
2218 */
2219 private void readPendingOperationsLocked() {
2220 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2221 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002222 readPendingAsXml();
2223 } catch (XmlPullParserException e) {
2224 Log.d(TAG, "Error parsing pending as xml, trying as parcel.");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002225 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002226 readPendingAsParcelled();
2227 } catch (java.io.IOException e1) {
2228 Log.i(TAG, "No initial pending operations");
2229 }
2230 }
2231 }
2232
2233 private void readPendingAsXml() throws XmlPullParserException {
2234 FileInputStream fis = null;
2235 try {
2236 Log.v(TAG, "is this thing on");
2237 fis = mPendingFile.openRead();
2238 XmlPullParser parser = Xml.newPullParser();
2239 parser.setInput(fis, null);
2240 int eventType = parser.getEventType();
2241 while (eventType != XmlPullParser.START_TAG &&
2242 eventType != XmlPullParser.END_DOCUMENT) {
2243 eventType = parser.next();
2244 Log.v(TAG, "go: " + eventType);
2245 }
2246 if (eventType == XmlPullParser.END_DOCUMENT) return;
2247
2248 String tagName = parser.getName();
2249 if (DEBUG_FILE) {
2250 Log.v(TAG, "got " + tagName);
2251 }
2252 if ("pending".equals(tagName)) {
2253 int version = -1;
2254 String versionString = parser.getAttributeValue(null, "version");
2255 if (versionString == null ||
2256 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2257 Log.w(TAG, "Unknown pending operation version "
2258 + version + "; trying to read as binary.");
2259 throw new XmlPullParserException("Unknown version.");
2260 }
2261 eventType = parser.next();
2262 PendingOperation pop = null;
2263 do {
2264 if (DEBUG_FILE) {
2265 Log.v(TAG, "parsing xml file");
2266 }
2267 if (eventType == XmlPullParser.START_TAG) {
2268 try {
2269 tagName = parser.getName();
2270 if (parser.getDepth() == 2 && "op".equals(tagName)) {
2271 int authorityId = Integer.valueOf(parser.getAttributeValue(
2272 null, XML_ATTR_AUTHORITYID));
2273 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2274 null, XML_ATTR_EXPEDITED));
2275 int syncSource = Integer.valueOf(parser.getAttributeValue(
2276 null, XML_ATTR_SOURCE));
2277 int reason = Integer.valueOf(parser.getAttributeValue(
2278 null, XML_ATTR_REASON));
2279 AuthorityInfo authority = mAuthorities.get(authorityId);
2280 if (DEBUG_FILE) {
2281 Log.v(TAG, authorityId + " " + expedited + " " + syncSource + " " + reason);
2282 }
2283 if (authority != null) {
2284 pop = new PendingOperation(
2285 authority.account, authority.userId, reason, syncSource,
2286 authority.authority, new Bundle(), expedited);
2287 pop.authorityId = authorityId;
2288 pop.flatExtras = null; // No longer used.
2289 mPendingOperations.add(pop);
2290 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + pop.account
2291 + " auth=" + pop.authority
2292 + " src=" + pop.syncSource
2293 + " reason=" + pop.reason
2294 + " expedited=" + pop.expedited);
2295 } else {
2296 // Skip non-existent authority;
2297 pop = null;
2298 if (DEBUG_FILE) {
2299 Log.v(TAG, "No authority found for " + authorityId
2300 + ", skipping");
2301 }
2302 }
2303 } else if (parser.getDepth() == 3 &&
2304 pop != null &&
2305 "extra".equals(tagName)) {
2306 parseExtra(parser, pop.extras);
2307 }
2308 } catch (NumberFormatException e) {
2309 Log.d(TAG, "Invalid data in xml file.", e);
2310 }
2311 }
2312 eventType = parser.next();
2313 } while(eventType != XmlPullParser.END_DOCUMENT);
2314 }
2315 } catch (java.io.IOException e) {
2316 if (fis == null) Log.i(TAG, "No initial pending operations.");
2317 else Log.w(TAG, "Error reading pending data.", e);
2318 return;
2319 } finally {
2320 if (DEBUG_FILE) Log.v(TAG, "Done reading pending ops");
2321 if (fis != null) {
2322 try {
2323 fis.close();
2324 } catch (java.io.IOException e1) {}
2325 }
2326 }
2327 }
2328 /**
2329 * Old format of reading pending.bin as a parcelled file. Replaced in lieu of JSON because
2330 * persisting parcels is unsafe.
2331 * @throws java.io.IOException
2332 */
2333 private void readPendingAsParcelled() throws java.io.IOException {
2334 byte[] data = mPendingFile.readFully();
2335 Parcel in = Parcel.obtain();
2336 in.unmarshall(data, 0, data.length);
2337 in.setDataPosition(0);
2338 final int SIZE = in.dataSize();
2339 while (in.dataPosition() < SIZE) {
2340 int version = in.readInt();
2341 if (version != 3 && version != 1) {
2342 Log.w(TAG, "Unknown pending operation version "
2343 + version + "; dropping all ops");
2344 break;
2345 }
2346 int authorityId = in.readInt();
2347 int syncSource = in.readInt();
2348 byte[] flatExtras = in.createByteArray();
2349 boolean expedited;
2350 if (version == PENDING_OPERATION_VERSION) {
2351 expedited = in.readInt() != 0;
2352 } else {
2353 expedited = false;
2354 }
2355 int reason = in.readInt();
2356 AuthorityInfo authority = mAuthorities.get(authorityId);
2357 if (authority != null) {
2358 Bundle extras;
2359 if (flatExtras != null) {
2360 extras = unflattenBundle(flatExtras);
2361 } else {
2362 // if we are unable to parse the extras for whatever reason convert this
2363 // to a regular sync by creating an empty extras
2364 extras = new Bundle();
2365 }
2366 PendingOperation op = new PendingOperation(
2367 authority.account, authority.userId, reason, syncSource,
2368 authority.authority, extras, expedited);
2369 op.authorityId = authorityId;
2370 op.flatExtras = flatExtras;
2371 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2372 + " auth=" + op.authority
2373 + " src=" + op.syncSource
2374 + " reason=" + op.reason
2375 + " expedited=" + op.expedited
2376 + " extras=" + op.extras);
2377 mPendingOperations.add(op);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002378 }
2379 }
2380 }
Costin Manolache360e4542009-09-04 13:36:04 -07002381
Dianne Hackborn231cc602009-04-27 17:10:36 -07002382 static private byte[] flattenBundle(Bundle bundle) {
2383 byte[] flatData = null;
2384 Parcel parcel = Parcel.obtain();
2385 try {
2386 bundle.writeToParcel(parcel, 0);
2387 flatData = parcel.marshall();
2388 } finally {
2389 parcel.recycle();
2390 }
2391 return flatData;
2392 }
Costin Manolache360e4542009-09-04 13:36:04 -07002393
Dianne Hackborn231cc602009-04-27 17:10:36 -07002394 static private Bundle unflattenBundle(byte[] flatData) {
2395 Bundle bundle;
2396 Parcel parcel = Parcel.obtain();
2397 try {
2398 parcel.unmarshall(flatData, 0, flatData.length);
2399 parcel.setDataPosition(0);
2400 bundle = parcel.readBundle();
2401 } catch (RuntimeException e) {
2402 // A RuntimeException is thrown if we were unable to parse the parcel.
2403 // Create an empty parcel in this case.
2404 bundle = new Bundle();
2405 } finally {
2406 parcel.recycle();
2407 }
2408 return bundle;
2409 }
Costin Manolache360e4542009-09-04 13:36:04 -07002410
Matthew Williamsfa774182013-06-18 15:44:11 -07002411 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2412 private static final String XML_ATTR_SOURCE = "source";
2413 private static final String XML_ATTR_EXPEDITED = "expedited";
2414 private static final String XML_ATTR_REASON = "reason";
2415 /**
2416 * Write all currently pending ops to the pending ops file. TODO: Change this from xml
2417 * so that we can append to this file as before.
2418 */
2419 private void writePendingOperationsLocked() {
2420 final int N = mPendingOperations.size();
2421 FileOutputStream fos = null;
2422 try {
2423 if (N == 0) {
2424 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2425 mPendingFile.truncate();
2426 return;
2427 }
2428 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2429 fos = mPendingFile.startWrite();
2430 XmlSerializer out = new FastXmlSerializer();
2431 out.setOutput(fos, "utf-8");
2432 out.startDocument(null, true);
2433 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
2434
2435 out.startTag(null, "pending");
2436 out.attribute(null, "version", Integer.toString(PENDING_OPERATION_VERSION));
2437
2438 for (int i = 0; i < N; i++) {
2439 PendingOperation pop = mPendingOperations.get(i);
2440 out.startTag(null, "op");
2441 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2442 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2443 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2444 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2445 extrasToXml(out, pop.extras);
2446 out.endTag(null, "op");
2447 }
2448 out.endTag(null, "pending");
2449 out.endDocument();
2450 mPendingFile.finishWrite(fos);
2451 } catch (java.io.IOException e1) {
2452 Log.w(TAG, "Error writing pending operations", e1);
2453 if (fos != null) {
2454 mPendingFile.failWrite(fos);
2455 }
2456 }
2457 }
2458
2459 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2460 for (String key : extras.keySet()) {
2461 out.startTag(null, "extra");
2462 out.attribute(null, "name", key);
2463 final Object value = extras.get(key);
2464 if (value instanceof Long) {
2465 out.attribute(null, "type", "long");
2466 out.attribute(null, "value1", value.toString());
2467 } else if (value instanceof Integer) {
2468 out.attribute(null, "type", "integer");
2469 out.attribute(null, "value1", value.toString());
2470 } else if (value instanceof Boolean) {
2471 out.attribute(null, "type", "boolean");
2472 out.attribute(null, "value1", value.toString());
2473 } else if (value instanceof Float) {
2474 out.attribute(null, "type", "float");
2475 out.attribute(null, "value1", value.toString());
2476 } else if (value instanceof Double) {
2477 out.attribute(null, "type", "double");
2478 out.attribute(null, "value1", value.toString());
2479 } else if (value instanceof String) {
2480 out.attribute(null, "type", "string");
2481 out.attribute(null, "value1", value.toString());
2482 } else if (value instanceof Account) {
2483 out.attribute(null, "type", "account");
2484 out.attribute(null, "value1", ((Account)value).name);
2485 out.attribute(null, "value2", ((Account)value).type);
2486 }
2487 out.endTag(null, "extra");
2488 }
2489 }
2490
2491// /**
2492// * Update the pending ops file, if e
2493// */
2494// private void appendPendingOperationLocked(PendingOperation op) {
2495// if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2496// FileOutputStream fos = null;
2497// try {
2498// fos = mPendingFile.openAppend();
2499// } catch (java.io.IOException e) {
2500// if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2501// writePendingOperationsLocked();
2502// return;
2503// }
2504//
2505// try {
2506// Parcel out = Parcel.obtain();
2507// writePendingOperationLocked(op, out);
2508// fos.write(out.marshall());
2509// out.recycle();
2510// } catch (java.io.IOException e1) {
2511// Log.w(TAG, "Error writing pending operations", e1);
2512// } finally {
2513// try {
2514// fos.close();
2515// } catch (java.io.IOException e2) {
2516// }
2517// }
2518// }
2519
Alon Albert57286f92012-10-09 14:21:38 -07002520 private void requestSync(Account account, int userId, int reason, String authority,
2521 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 // If this is happening in the system process, then call the syncrequest listener
2523 // to make a request back to the SyncManager directly.
2524 // If this is probably a test instance, then call back through the ContentResolver
2525 // which will know which userId to apply based on the Binder id.
2526 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2527 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002528 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002529 } else {
2530 ContentResolver.requestSync(account, authority, extras);
2531 }
2532 }
2533
Dianne Hackborn231cc602009-04-27 17:10:36 -07002534 public static final int STATISTICS_FILE_END = 0;
2535 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2536 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002537
Dianne Hackborn231cc602009-04-27 17:10:36 -07002538 /**
2539 * Read all sync statistics back in to the initial engine state.
2540 */
2541 private void readStatisticsLocked() {
2542 try {
2543 byte[] data = mStatisticsFile.readFully();
2544 Parcel in = Parcel.obtain();
2545 in.unmarshall(data, 0, data.length);
2546 in.setDataPosition(0);
2547 int token;
2548 int index = 0;
2549 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2550 if (token == STATISTICS_FILE_ITEM
2551 || token == STATISTICS_FILE_ITEM_OLD) {
2552 int day = in.readInt();
2553 if (token == STATISTICS_FILE_ITEM_OLD) {
2554 day = day - 2009 + 14245; // Magic!
2555 }
2556 DayStats ds = new DayStats(day);
2557 ds.successCount = in.readInt();
2558 ds.successTime = in.readLong();
2559 ds.failureCount = in.readInt();
2560 ds.failureTime = in.readLong();
2561 if (index < mDayStats.length) {
2562 mDayStats[index] = ds;
2563 index++;
2564 }
2565 } else {
2566 // Ooops.
2567 Log.w(TAG, "Unknown stats token: " + token);
2568 break;
2569 }
2570 }
2571 } catch (java.io.IOException e) {
2572 Log.i(TAG, "No initial statistics");
2573 }
2574 }
Costin Manolache360e4542009-09-04 13:36:04 -07002575
Dianne Hackborn231cc602009-04-27 17:10:36 -07002576 /**
2577 * Write all sync statistics to the sync status file.
2578 */
2579 private void writeStatisticsLocked() {
2580 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002581
Dianne Hackborn231cc602009-04-27 17:10:36 -07002582 // The file is being written, so we don't need to have a scheduled
2583 // write until the next change.
2584 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002585
Dianne Hackborn231cc602009-04-27 17:10:36 -07002586 FileOutputStream fos = null;
2587 try {
2588 fos = mStatisticsFile.startWrite();
2589 Parcel out = Parcel.obtain();
2590 final int N = mDayStats.length;
2591 for (int i=0; i<N; i++) {
2592 DayStats ds = mDayStats[i];
2593 if (ds == null) {
2594 break;
2595 }
2596 out.writeInt(STATISTICS_FILE_ITEM);
2597 out.writeInt(ds.day);
2598 out.writeInt(ds.successCount);
2599 out.writeLong(ds.successTime);
2600 out.writeInt(ds.failureCount);
2601 out.writeLong(ds.failureTime);
2602 }
2603 out.writeInt(STATISTICS_FILE_END);
2604 fos.write(out.marshall());
2605 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002606
Dianne Hackborn231cc602009-04-27 17:10:36 -07002607 mStatisticsFile.finishWrite(fos);
2608 } catch (java.io.IOException e1) {
2609 Log.w(TAG, "Error writing stats", e1);
2610 if (fos != null) {
2611 mStatisticsFile.failWrite(fos);
2612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 }
2614 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002615
2616 /**
2617 * Dump state of PendingOperations.
2618 */
2619 public void dumpPendingOperations(StringBuilder sb) {
2620 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2621 for (PendingOperation pop : mPendingOperations) {
2622 sb.append("(" + pop.account)
2623 .append(", " + pop.userId)
2624 .append(", " + pop.authority)
2625 .append(", " + pop.extras)
2626 .append(")\n");
2627 }
2628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629}