blob: be1e796594a3cf19569e23dfcfc367986eb6210d [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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017package android.content;
18
Dianne Hackborn231cc602009-04-27 17:10:36 -070019import com.android.internal.util.ArrayUtils;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080020import com.android.internal.util.FastXmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021
Jason parksa3cdaa52011-01-13 14:15:43 -060022import org.xmlpull.v1.XmlPullParser;
23import org.xmlpull.v1.XmlPullParserException;
24import org.xmlpull.v1.XmlSerializer;
25
Fred Quintanad9d2f112009-04-23 13:36:27 -070026import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070027import android.accounts.AccountAndUser;
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;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.util.SparseArray;
42import android.util.Xml;
Jason parksa3cdaa52011-01-13 14:15:43 -060043import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Dianne Hackborn231cc602009-04-27 17:10:36 -070045import java.io.File;
46import java.io.FileInputStream;
47import java.io.FileOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070049import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070051import java.util.Iterator;
Ashish Sharma69d95de2012-04-11 17:27:24 -070052import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060053import java.util.TimeZone;
Jason parksa3cdaa52011-01-13 14:15:43 -060054import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
56/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070057 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070059 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 * @hide
61 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070062public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 private static final String TAG = "SyncManager";
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 private static final boolean DEBUG_FILE = false;
Costin Manolache360e4542009-09-04 13:36:04 -070066
Amith Yamasani04e0d262012-02-14 11:50:53 -080067 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
68 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070069 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080070 private static final String XML_ATTR_ENABLED = "enabled";
71 private static final String XML_ATTR_USER = "user";
72 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
73
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080074 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
75
Dianne Hackborn231cc602009-04-27 17:10:36 -070076 // @VisibleForTesting
77 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Dianne Hackborn231cc602009-04-27 17:10:36 -070079 /** Enum value for a sync start event. */
80 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Dianne Hackborn231cc602009-04-27 17:10:36 -070082 /** Enum value for a sync stop event. */
83 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Dianne Hackborn231cc602009-04-27 17:10:36 -070085 // TODO: i18n -- grab these out of resources.
86 /** String names for the sync event types. */
87 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
Dianne Hackborn231cc602009-04-27 17:10:36 -070089 /** Enum value for a server-initiated sync. */
90 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 /** Enum value for a local-initiated sync. */
93 public static final int SOURCE_LOCAL = 1;
94 /**
95 * Enum value for a poll-based sync (e.g., upon connection to
96 * network)
97 */
98 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a user-initiated sync. */
101 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800103 /** Enum value for a periodic sync. */
104 public static final int SOURCE_PERIODIC = 4;
105
Fred Quintana307da1a2010-01-21 14:24:20 -0800106 public static final long NOT_IN_BACKOFF_MODE = -1;
107
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700108 public static final Intent SYNC_CONNECTION_SETTING_CHANGED_INTENT =
Fred Quintanaac9385e2009-06-22 18:00:59 -0700109 new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 // TODO: i18n -- grab these out of resources.
112 /** String names for the sync source types. */
113 public static final String[] SOURCES = { "SERVER",
114 "LOCAL",
115 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800116 "USER",
117 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 // The MESG column will contain one of these or one of the Error types.
120 public static final String MESG_SUCCESS = "success";
121 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700123 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 private static final int MSG_WRITE_STATUS = 1;
126 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700127
Dianne Hackborn231cc602009-04-27 17:10:36 -0700128 private static final int MSG_WRITE_STATISTICS = 2;
129 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700130
131 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700132
Fred Quintanac2e46912010-03-15 16:10:44 -0700133 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700134 private static final int ACCOUNTS_VERSION = 2;
135
136 private static HashMap<String, String> sAuthorityRenames;
137
138 static {
139 sAuthorityRenames = new HashMap<String, String>();
140 sAuthorityRenames.put("contacts", "com.android.contacts");
141 sAuthorityRenames.put("calendar", "com.android.calendar");
142 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700143
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700145 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800146 final int userId;
Alon Albert57286f92012-10-09 14:21:38 -0700147 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700148 final int syncSource;
149 final String authority;
150 final Bundle extras; // note: read-only.
Fred Quintana307da1a2010-01-21 14:24:20 -0800151 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700152
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 int authorityId;
154 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Alon Albert57286f92012-10-09 14:21:38 -0700156 PendingOperation(Account account, int userId, int reason,int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800157 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800159 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700160 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700161 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700162 this.authority = authority;
163 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800164 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700165 this.authorityId = -1;
166 }
167
168 PendingOperation(PendingOperation other) {
169 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800170 this.userId = other.userId;
Alon Albert57286f92012-10-09 14:21:38 -0700171 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700172 this.syncSource = other.syncSource;
173 this.authority = other.authority;
174 this.extras = other.extras;
175 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800176 this.expedited = other.expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 }
Costin Manolache360e4542009-09-04 13:36:04 -0700179
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800181 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700182 final HashMap<String, AuthorityInfo> authorities =
183 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700184
Amith Yamasani04e0d262012-02-14 11:50:53 -0800185 AccountInfo(AccountAndUser accountAndUser) {
186 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700187 }
188 }
Costin Manolache360e4542009-09-04 13:36:04 -0700189
Dianne Hackborn231cc602009-04-27 17:10:36 -0700190 public static class AuthorityInfo {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700191 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800192 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700193 final String authority;
194 final int ident;
195 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700196 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800197 long backoffTime;
198 long backoffDelay;
199 long delayUntil;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800200 final ArrayList<Pair<Bundle, Long>> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700201
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700202 /**
203 * Copy constructor for making deep-ish copies. Only the bundles stored
204 * in periodic syncs can make unexpected changes.
205 *
206 * @param toCopy AuthorityInfo to be copied.
207 */
208 AuthorityInfo(AuthorityInfo toCopy) {
209 account = toCopy.account;
210 userId = toCopy.userId;
211 authority = toCopy.authority;
212 ident = toCopy.ident;
213 enabled = toCopy.enabled;
214 syncable = toCopy.syncable;
215 backoffTime = toCopy.backoffTime;
216 backoffDelay = toCopy.backoffDelay;
217 delayUntil = toCopy.delayUntil;
218 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
219 for (Pair<Bundle, Long> sync : toCopy.periodicSyncs) {
220 // Still not a perfect copy, because we are just copying the mappings.
221 periodicSyncs.add(Pair.create(new Bundle(sync.first), sync.second));
222 }
223 }
224
Amith Yamasani04e0d262012-02-14 11:50:53 -0800225 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700226 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800227 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700228 this.authority = authority;
229 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700230 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700231 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800232 backoffTime = -1; // if < 0 then we aren't in backoff mode
233 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800234 periodicSyncs = new ArrayList<Pair<Bundle, Long>>();
235 periodicSyncs.add(Pair.create(new Bundle(), DEFAULT_POLL_FREQUENCY_SECONDS));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700236 }
237 }
Costin Manolache360e4542009-09-04 13:36:04 -0700238
Dianne Hackborn231cc602009-04-27 17:10:36 -0700239 public static class SyncHistoryItem {
240 int authorityId;
241 int historyId;
242 long eventTime;
243 long elapsedTime;
244 int source;
245 int event;
246 long upstreamActivity;
247 long downstreamActivity;
248 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700249 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700250 Bundle extras;
251 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700252 }
Costin Manolache360e4542009-09-04 13:36:04 -0700253
Dianne Hackborn231cc602009-04-27 17:10:36 -0700254 public static class DayStats {
255 public final int day;
256 public int successCount;
257 public long successTime;
258 public int failureCount;
259 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700260
Dianne Hackborn231cc602009-04-27 17:10:36 -0700261 public DayStats(int day) {
262 this.day = day;
263 }
264 }
Costin Manolache360e4542009-09-04 13:36:04 -0700265
Amith Yamasani04e0d262012-02-14 11:50:53 -0800266 interface OnSyncRequestListener {
267 /**
268 * Called when a sync is needed on an account(s) due to some change in state.
269 * @param account
270 * @param userId
Alon Albert57286f92012-10-09 14:21:38 -0700271 * @param reason
Amith Yamasani04e0d262012-02-14 11:50:53 -0800272 * @param authority
273 * @param extras
274 */
Alon Albert57286f92012-10-09 14:21:38 -0700275 public void onSyncRequest(Account account, int userId, int reason, String authority,
276 Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800277 }
278
Dianne Hackborn231cc602009-04-27 17:10:36 -0700279 // Primary list of all syncable authorities. Also our global lock.
280 private final SparseArray<AuthorityInfo> mAuthorities =
281 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700282
Amith Yamasani04e0d262012-02-14 11:50:53 -0800283 private final HashMap<AccountAndUser, AccountInfo> mAccounts
284 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285
Dianne Hackborn231cc602009-04-27 17:10:36 -0700286 private final ArrayList<PendingOperation> mPendingOperations =
287 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700288
Amith Yamasani04e0d262012-02-14 11:50:53 -0800289 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
290 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700291
Dianne Hackborn231cc602009-04-27 17:10:36 -0700292 private final SparseArray<SyncStatusInfo> mSyncStatus =
293 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700294
Dianne Hackborn231cc602009-04-27 17:10:36 -0700295 private final ArrayList<SyncHistoryItem> mSyncHistory =
296 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
299 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700300
Fred Quintana77c560f2010-03-29 22:20:26 -0700301 private int mNextAuthorityId = 0;
302
Dianne Hackborn231cc602009-04-27 17:10:36 -0700303 // We keep 4 weeks of stats.
304 private final DayStats[] mDayStats = new DayStats[7*4];
305 private final Calendar mCal;
306 private int mYear;
307 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700308
Dianne Hackborn231cc602009-04-27 17:10:36 -0700309 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800310
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700312
Ashish Sharma69d95de2012-04-11 17:27:24 -0700313 private int mSyncRandomOffset;
314
Dianne Hackborn231cc602009-04-27 17:10:36 -0700315 /**
316 * This file contains the core engine state: all accounts and the
317 * settings for them. It must never be lost, and should be changed
318 * infrequently, so it is stored as an XML file.
319 */
320 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700321
Dianne Hackborn231cc602009-04-27 17:10:36 -0700322 /**
323 * This file contains the current sync status. We would like to retain
324 * it across boots, but its loss is not the end of the world, so we store
325 * this information as binary data.
326 */
327 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700328
Dianne Hackborn231cc602009-04-27 17:10:36 -0700329 /**
330 * This file contains sync statistics. This is purely debugging information
331 * so is written infrequently and can be thrown away at any time.
332 */
333 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700334
Dianne Hackborn231cc602009-04-27 17:10:36 -0700335 /**
336 * This file contains the pending sync operations. It is a binary file,
337 * which must be updated every time an operation is added or removed,
338 * so we have special handling of it.
339 */
340 private final AtomicFile mPendingFile;
341 private static final int PENDING_FINISH_TO_WRITE = 4;
342 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700343
Dianne Hackborn231cc602009-04-27 17:10:36 -0700344 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800345 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800346 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800347
348 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700349
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800350 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700355
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800356 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
357 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
358
Dianne Hackborn231cc602009-04-27 17:10:36 -0700359 File systemDir = new File(dataDir, "system");
360 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800361 syncDir.mkdirs();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700362 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
363 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
364 mPendingFile = new AtomicFile(new File(syncDir, "pending.bin"));
365 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700366
Dianne Hackborn231cc602009-04-27 17:10:36 -0700367 readAccountInfoLocked();
368 readStatusLocked();
369 readPendingOperationsLocked();
370 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700371 readAndDeleteLegacyAccountInfoLocked();
372 writeAccountInfoLocked();
373 writeStatusLocked();
374 writePendingOperationsLocked();
375 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
377
378 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800379 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
382 public static void init(Context context) {
383 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800384 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800386 // This call will return the correct directory whether Encrypted File Systems is
387 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600388 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800389 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
391
392 public static SyncStorageEngine getSingleton() {
393 if (sSyncStorageEngine == null) {
394 throw new IllegalStateException("not initialized");
395 }
396 return sSyncStorageEngine;
397 }
398
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
400 if (mSyncRequestListener == null) {
401 mSyncRequestListener = listener;
402 }
403 }
404
Dianne Hackborn231cc602009-04-27 17:10:36 -0700405 @Override public void handleMessage(Message msg) {
406 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700407 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700408 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700409 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700410 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700411 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700412 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 }
414 }
415 }
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Ashish Sharma69d95de2012-04-11 17:27:24 -0700417 public int getSyncRandomOffset() {
418 return mSyncRandomOffset;
419 }
420
Dianne Hackborn231cc602009-04-27 17:10:36 -0700421 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
422 synchronized (mAuthorities) {
423 mChangeListeners.register(callback, mask);
424 }
425 }
Costin Manolache360e4542009-09-04 13:36:04 -0700426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 public void removeStatusChangeListener(ISyncStatusObserver callback) {
428 synchronized (mAuthorities) {
429 mChangeListeners.unregister(callback);
430 }
431 }
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 private void reportChange(int which) {
434 ArrayList<ISyncStatusObserver> reports = null;
435 synchronized (mAuthorities) {
436 int i = mChangeListeners.beginBroadcast();
437 while (i > 0) {
438 i--;
439 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
440 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 continue;
442 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700443 if (reports == null) {
444 reports = new ArrayList<ISyncStatusObserver>(i);
445 }
446 reports.add(mChangeListeners.getBroadcastItem(i));
447 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700448 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700449 }
Costin Manolache360e4542009-09-04 13:36:04 -0700450
Fred Quintana77c560f2010-03-29 22:20:26 -0700451 if (Log.isLoggable(TAG, Log.VERBOSE)) {
452 Log.v(TAG, "reportChange " + which + " to: " + reports);
453 }
Costin Manolache360e4542009-09-04 13:36:04 -0700454
Dianne Hackborn231cc602009-04-27 17:10:36 -0700455 if (reports != null) {
456 int i = reports.size();
457 while (i > 0) {
458 i--;
459 try {
460 reports.get(i).onStatusChanged(which);
461 } catch (RemoteException e) {
462 // The remote callback list will take care of this for us.
463 }
464 }
465 }
466 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700467
Amith Yamasani04e0d262012-02-14 11:50:53 -0800468 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 synchronized (mAuthorities) {
470 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800471 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700472 "getSyncAutomatically");
473 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700475
Dianne Hackborn231cc602009-04-27 17:10:36 -0700476 int i = mAuthorities.size();
477 while (i > 0) {
478 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700479 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700480 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800481 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700482 && authority.enabled) {
483 return true;
484 }
485 }
486 return false;
487 }
488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489
Amith Yamasani04e0d262012-02-14 11:50:53 -0800490 public void setSyncAutomatically(Account account, int userId, String providerName,
491 boolean sync) {
492 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
493 + ", user " + userId + " -> " + sync);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800495 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
496 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700497 if (authority.enabled == sync) {
498 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
499 return;
500 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700501 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700502 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700504
Fred Quintana77c560f2010-03-29 22:20:26 -0700505 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700506 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
507 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700508 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700509 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 }
511
Amith Yamasani04e0d262012-02-14 11:50:53 -0800512 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700513 synchronized (mAuthorities) {
514 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800515 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700516 "getIsSyncable");
517 if (authority == null) {
518 return -1;
519 }
520 return authority.syncable;
521 }
522
523 int i = mAuthorities.size();
524 while (i > 0) {
525 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700526 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700527 if (authority.authority.equals(providerName)) {
528 return authority.syncable;
529 }
530 }
531 return -1;
532 }
533 }
534
Amith Yamasani04e0d262012-02-14 11:50:53 -0800535 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700536 if (syncable > 1) {
537 syncable = 1;
538 } else if (syncable < -1) {
539 syncable = -1;
540 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800541 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
542 + ", user " + userId + " -> " + syncable);
Fred Quintana5e787c42009-08-16 23:13:53 -0700543 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800544 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
545 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700546 if (authority.syncable == syncable) {
547 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
548 return;
549 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700550 authority.syncable = syncable;
551 writeAccountInfoLocked();
552 }
553
Fred Quintana77c560f2010-03-29 22:20:26 -0700554 if (syncable > 0) {
Alon Albert57286f92012-10-09 14:21:38 -0700555 requestSync(account, userId, SyncOperation.REASON_IS_SYNCABLE, providerName,
556 new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700557 }
558 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
559 }
560
Amith Yamasani04e0d262012-02-14 11:50:53 -0800561 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800562 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
564 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800565 if (authority == null || authority.backoffTime < 0) {
566 return null;
567 }
568 return Pair.create(authority.backoffTime, authority.backoffDelay);
569 }
570 }
571
Amith Yamasani04e0d262012-02-14 11:50:53 -0800572 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800573 long nextSyncTime, long nextDelay) {
574 if (Log.isLoggable(TAG, Log.VERBOSE)) {
575 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800576 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800577 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
578 }
579 boolean changed = false;
580 synchronized (mAuthorities) {
581 if (account == null || providerName == null) {
582 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800583 if (account != null && !account.equals(accountInfo.accountAndUser.account)
584 && userId != accountInfo.accountAndUser.userId) {
585 continue;
586 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800587 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
588 if (providerName != null && !providerName.equals(authorityInfo.authority)) {
589 continue;
590 }
591 if (authorityInfo.backoffTime != nextSyncTime
592 || authorityInfo.backoffDelay != nextDelay) {
593 authorityInfo.backoffTime = nextSyncTime;
594 authorityInfo.backoffDelay = nextDelay;
595 changed = true;
596 }
597 }
598 }
599 } else {
600 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800601 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
602 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800603 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
604 return;
605 }
606 authority.backoffTime = nextSyncTime;
607 authority.backoffDelay = nextDelay;
608 changed = true;
609 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800610 }
611
612 if (changed) {
613 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
614 }
615 }
616
Alon Alberted1d2532011-02-15 14:02:14 -0800617 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800618 boolean changed = false;
619 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700620 synchronized (syncQueue) {
621 for (AccountInfo accountInfo : mAccounts.values()) {
622 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
623 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
624 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
626 Log.v(TAG, "clearAllBackoffs:"
627 + " authority:" + authorityInfo.authority
628 + " account:" + accountInfo.accountAndUser.account.name
629 + " user:" + accountInfo.accountAndUser.userId
630 + " backoffTime was: " + authorityInfo.backoffTime
631 + " backoffDelay was: " + authorityInfo.backoffDelay);
632 }
633 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
634 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
635 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
636 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
637 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800638 }
Alon Albert744e310f2010-12-14 11:37:20 -0800639 }
640 }
641 }
642 }
643
644 if (changed) {
645 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
646 }
647 }
648
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 public void setDelayUntilTime(Account account, int userId, String providerName,
650 long delayUntil) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800651 if (Log.isLoggable(TAG, Log.VERBOSE)) {
652 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800653 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800654 }
655 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800656 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800657 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800658 if (authority.delayUntil == delayUntil) {
659 return;
660 }
661 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800662 }
663
664 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
665 }
666
Amith Yamasani04e0d262012-02-14 11:50:53 -0800667 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800668 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800669 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
670 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800671 if (authority == null) {
672 return 0;
673 }
674 return authority.delayUntil;
675 }
676 }
677
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 private void updateOrRemovePeriodicSync(Account account, int userId, String providerName,
679 Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800680 long period, boolean add) {
681 if (period <= 0) {
682 period = 0;
683 }
684 if (extras == null) {
685 extras = new Bundle();
686 }
687 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800688 Log.v(TAG, "addOrRemovePeriodicSync: " + account + ", user " + userId
689 + ", provider " + providerName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800690 + " -> period " + period + ", extras " + extras);
691 }
692 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700693 try {
694 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800695 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700696 if (add) {
697 // add this periodic sync if one with the same extras doesn't already
698 // exist in the periodicSyncs array
699 boolean alreadyPresent = false;
700 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
701 Pair<Bundle, Long> syncInfo = authority.periodicSyncs.get(i);
702 final Bundle existingExtras = syncInfo.first;
703 if (equals(existingExtras, extras)) {
704 if (syncInfo.second == period) {
705 return;
706 }
707 authority.periodicSyncs.set(i, Pair.create(extras, period));
708 alreadyPresent = true;
709 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800710 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700711 }
712 // if we added an entry to the periodicSyncs array also add an entry to
713 // the periodic syncs status to correspond to it
714 if (!alreadyPresent) {
715 authority.periodicSyncs.add(Pair.create(extras, period));
716 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
717 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0);
718 }
719 } else {
720 // remove any periodic syncs that match the authority and extras
721 SyncStatusInfo status = mSyncStatus.get(authority.ident);
722 boolean changed = false;
723 Iterator<Pair<Bundle, Long>> iterator = authority.periodicSyncs.iterator();
724 int i = 0;
725 while (iterator.hasNext()) {
726 Pair<Bundle, Long> syncInfo = iterator.next();
727 if (equals(syncInfo.first, extras)) {
728 iterator.remove();
729 changed = true;
730 // if we removed an entry from the periodicSyncs array also
731 // remove the corresponding entry from the status
732 if (status != null) {
733 status.removePeriodicSyncTime(i);
734 }
735 } else {
736 i++;
737 }
738 }
739 if (!changed) {
740 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800741 }
742 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700743 } finally {
744 writeAccountInfoLocked();
745 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800746 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800747 }
748
749 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
750 }
751
Amith Yamasani04e0d262012-02-14 11:50:53 -0800752 public void addPeriodicSync(Account account, int userId, String providerName, Bundle extras,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800753 long pollFrequency) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800754 updateOrRemovePeriodicSync(account, userId, providerName, extras, pollFrequency,
755 true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800756 }
757
Amith Yamasani04e0d262012-02-14 11:50:53 -0800758 public void removePeriodicSync(Account account, int userId, String providerName,
759 Bundle extras) {
760 updateOrRemovePeriodicSync(account, userId, providerName, extras, 0 /* period, ignored */,
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800761 false /* remove */);
762 }
763
Amith Yamasani04e0d262012-02-14 11:50:53 -0800764 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800765 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
766 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800767 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
768 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800769 if (authority != null) {
770 for (Pair<Bundle, Long> item : authority.periodicSyncs) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 syncs.add(new PeriodicSync(account, providerName, item.first,
772 item.second));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800773 }
774 }
775 }
776 return syncs;
777 }
778
Amith Yamasani04e0d262012-02-14 11:50:53 -0800779 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700780 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800781 Boolean auto = mMasterSyncAutomatically.get(userId);
782 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700783 return;
784 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800785 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700786 writeAccountInfoLocked();
787 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700788 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700789 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
790 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700791 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700792 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
793 mContext.sendBroadcast(SYNC_CONNECTION_SETTING_CHANGED_INTENT);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
Amith Yamasani04e0d262012-02-14 11:50:53 -0800796 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700797 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800798 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800799 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700800 }
801 }
Costin Manolache360e4542009-09-04 13:36:04 -0700802
Amith Yamasani04e0d262012-02-14 11:50:53 -0800803 public AuthorityInfo getOrCreateAuthority(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700804 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800805 return getOrCreateAuthorityLocked(account, userId, authority,
Fred Quintana1bbcd102010-02-10 10:04:33 -0800806 -1 /* assign a new identifier if creating a new authority */,
807 true /* write to storage if this results in a change */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700808 }
809 }
Costin Manolache360e4542009-09-04 13:36:04 -0700810
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700812 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800813 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700814 }
815 }
816
Dianne Hackborn231cc602009-04-27 17:10:36 -0700817 public AuthorityInfo getAuthority(int authorityId) {
818 synchronized (mAuthorities) {
819 return mAuthorities.get(authorityId);
820 }
821 }
Costin Manolache360e4542009-09-04 13:36:04 -0700822
Dianne Hackborn231cc602009-04-27 17:10:36 -0700823 /**
824 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700825 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700826 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800827 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700828 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800829 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700830 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700831 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800832 && ainfo.authority.equals(authority)
833 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700834 return true;
835 }
836 }
837 }
Costin Manolache360e4542009-09-04 13:36:04 -0700838
Dianne Hackborn231cc602009-04-27 17:10:36 -0700839 return false;
840 }
Costin Manolache360e4542009-09-04 13:36:04 -0700841
Dianne Hackborn231cc602009-04-27 17:10:36 -0700842 public PendingOperation insertIntoPending(PendingOperation op) {
843 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
845 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800846 + " user=" + op.userId
847 + " auth=" + op.authority
848 + " src=" + op.syncSource
849 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700850 }
Costin Manolache360e4542009-09-04 13:36:04 -0700851
Amith Yamasani04e0d262012-02-14 11:50:53 -0800852 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700853 op.authority,
854 -1 /* desired identifier */,
855 true /* write accounts to storage */);
856 if (authority == null) {
857 return null;
858 }
Costin Manolache360e4542009-09-04 13:36:04 -0700859
Dianne Hackborn231cc602009-04-27 17:10:36 -0700860 op = new PendingOperation(op);
861 op.authorityId = authority.ident;
862 mPendingOperations.add(op);
863 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700864
Dianne Hackborn231cc602009-04-27 17:10:36 -0700865 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
866 status.pending = true;
867 }
Costin Manolache360e4542009-09-04 13:36:04 -0700868
Fred Quintanaac9385e2009-06-22 18:00:59 -0700869 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700870 return op;
871 }
872
873 public boolean deleteFromPending(PendingOperation op) {
874 boolean res = false;
875 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700876 if (Log.isLoggable(TAG, Log.VERBOSE)) {
877 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800878 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700879 + " auth=" + op.authority
880 + " src=" + op.syncSource
881 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700882 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 if (mPendingOperations.remove(op)) {
884 if (mPendingOperations.size() == 0
885 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
886 writePendingOperationsLocked();
887 mNumPendingFinished = 0;
888 } else {
889 mNumPendingFinished++;
890 }
Costin Manolache360e4542009-09-04 13:36:04 -0700891
Amith Yamasani04e0d262012-02-14 11:50:53 -0800892 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700893 "deleteFromPending");
894 if (authority != null) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700895 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "removing - " + authority);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700896 final int N = mPendingOperations.size();
897 boolean morePending = false;
898 for (int i=0; i<N; i++) {
899 PendingOperation cur = mPendingOperations.get(i);
900 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800901 && cur.authority.equals(op.authority)
902 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700903 morePending = true;
904 break;
905 }
906 }
Costin Manolache360e4542009-09-04 13:36:04 -0700907
Dianne Hackborn231cc602009-04-27 17:10:36 -0700908 if (!morePending) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700909 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700910 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
911 status.pending = false;
912 }
913 }
Costin Manolache360e4542009-09-04 13:36:04 -0700914
Dianne Hackborn231cc602009-04-27 17:10:36 -0700915 res = true;
916 }
917 }
Costin Manolache360e4542009-09-04 13:36:04 -0700918
Fred Quintanaac9385e2009-06-22 18:00:59 -0700919 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700920 return res;
921 }
922
Dianne Hackborn231cc602009-04-27 17:10:36 -0700923 /**
924 * Return a copy of the current array of pending operations. The
925 * PendingOperation objects are the real objects stored inside, so that
926 * they can be used with deleteFromPending().
927 */
928 public ArrayList<PendingOperation> getPendingOperations() {
929 synchronized (mAuthorities) {
930 return new ArrayList<PendingOperation>(mPendingOperations);
931 }
932 }
Costin Manolache360e4542009-09-04 13:36:04 -0700933
Dianne Hackborn231cc602009-04-27 17:10:36 -0700934 /**
935 * Return the number of currently pending operations.
936 */
937 public int getPendingOperationCount() {
938 synchronized (mAuthorities) {
939 return mPendingOperations.size();
940 }
941 }
Costin Manolache360e4542009-09-04 13:36:04 -0700942
Dianne Hackborn231cc602009-04-27 17:10:36 -0700943 /**
944 * Called when the set of account has changed, given the new array of
945 * active accounts.
946 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800947 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700948 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700949 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.w(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
951 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
952 while (accIt.hasNext()) {
953 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800954 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
955 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 // This account no longer exists...
Fred Quintana77c560f2010-03-29 22:20:26 -0700957 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 Log.w(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700959 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 for (AuthorityInfo auth : acc.authorities.values()) {
961 removing.put(auth.ident, auth);
962 }
963 accIt.remove();
964 }
965 }
Costin Manolache360e4542009-09-04 13:36:04 -0700966
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 // Clean out all data structures.
968 int i = removing.size();
969 if (i > 0) {
970 while (i > 0) {
971 i--;
972 int ident = removing.keyAt(i);
973 mAuthorities.remove(ident);
974 int j = mSyncStatus.size();
975 while (j > 0) {
976 j--;
977 if (mSyncStatus.keyAt(j) == ident) {
978 mSyncStatus.remove(mSyncStatus.keyAt(j));
979 }
980 }
981 j = mSyncHistory.size();
982 while (j > 0) {
983 j--;
984 if (mSyncHistory.get(j).authorityId == ident) {
985 mSyncHistory.remove(j);
986 }
987 }
988 }
989 writeAccountInfoLocked();
990 writeStatusLocked();
991 writePendingOperationsLocked();
992 writeStatisticsLocked();
993 }
994 }
995 }
996
997 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700998 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
999 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 */
Fred Quintana918339a2010-10-05 14:00:39 -07001001 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1002 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 synchronized (mAuthorities) {
Fred Quintana918339a2010-10-05 14:00:39 -07001004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1005 Log.v(TAG, "setActiveSync: account="
1006 + activeSyncContext.mSyncOperation.account
1007 + " auth=" + activeSyncContext.mSyncOperation.authority
1008 + " src=" + activeSyncContext.mSyncOperation.syncSource
1009 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001010 }
Fred Quintana918339a2010-10-05 14:00:39 -07001011 AuthorityInfo authority = getOrCreateAuthorityLocked(
1012 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001013 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001014 activeSyncContext.mSyncOperation.authority,
1015 -1 /* assign a new identifier if creating a new authority */,
1016 true /* write to storage if this results in a change */);
1017 syncInfo = new SyncInfo(authority.ident,
1018 authority.account, authority.authority,
1019 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001020 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 }
Costin Manolache360e4542009-09-04 13:36:04 -07001022
Fred Quintana918339a2010-10-05 14:00:39 -07001023 reportActiveChange();
1024 return syncInfo;
1025 }
1026
1027 /**
1028 * Called to indicate that a previously active sync is no longer active.
1029 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001030 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001031 synchronized (mAuthorities) {
1032 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001033 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1034 + " user=" + userId
1035 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001036 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001038 }
1039
1040 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 }
1042
1043 /**
1044 * To allow others to send active change reports, to poke clients.
1045 */
1046 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001047 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 }
Costin Manolache360e4542009-09-04 13:36:04 -07001049
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 /**
1051 * Note that sync has started for the given account and authority.
1052 */
Alon Albert57286f92012-10-09 14:21:38 -07001053 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1054 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 long id;
1056 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001057 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001058 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001059 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001060 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001061 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001062 "insertStartSyncEvent");
1063 if (authority == null) {
1064 return -1;
1065 }
1066 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001067 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 item.authorityId = authority.ident;
1069 item.historyId = mNextHistoryId++;
1070 if (mNextHistoryId < 0) mNextHistoryId = 0;
1071 item.eventTime = now;
1072 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001073 item.reason = reason;
1074 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 item.event = EVENT_START;
1076 mSyncHistory.add(0, item);
1077 while (mSyncHistory.size() > MAX_HISTORY) {
1078 mSyncHistory.remove(mSyncHistory.size()-1);
1079 }
1080 id = item.historyId;
Fred Quintana77c560f2010-03-29 22:20:26 -07001081 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001082 }
Costin Manolache360e4542009-09-04 13:36:04 -07001083
Fred Quintanaac9385e2009-06-22 18:00:59 -07001084 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001085 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001088 public static boolean equals(Bundle b1, Bundle b2) {
1089 if (b1.size() != b2.size()) {
1090 return false;
1091 }
1092 if (b1.isEmpty()) {
1093 return true;
1094 }
1095 for (String key : b1.keySet()) {
1096 if (!b2.containsKey(key)) {
1097 return false;
1098 }
1099 if (!b1.get(key).equals(b2.get(key))) {
1100 return false;
1101 }
1102 }
1103 return true;
1104 }
1105
Fred Quintana77c560f2010-03-29 22:20:26 -07001106 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 synchronized (mAuthorities) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1110 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1111 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 SyncHistoryItem item = null;
1113 int i = mSyncHistory.size();
1114 while (i > 0) {
1115 i--;
1116 item = mSyncHistory.get(i);
1117 if (item.historyId == historyId) {
1118 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001120 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
Costin Manolache360e4542009-09-04 13:36:04 -07001122
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 if (item == null) {
1124 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1125 return;
1126 }
Costin Manolache360e4542009-09-04 13:36:04 -07001127
Dianne Hackborn231cc602009-04-27 17:10:36 -07001128 item.elapsedTime = elapsedTime;
1129 item.event = EVENT_STOP;
1130 item.mesg = resultMessage;
1131 item.downstreamActivity = downstreamActivity;
1132 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001133
Dianne Hackborn231cc602009-04-27 17:10:36 -07001134 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001135
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 status.numSyncs++;
1137 status.totalElapsedTime += elapsedTime;
1138 switch (item.source) {
1139 case SOURCE_LOCAL:
1140 status.numSourceLocal++;
1141 break;
1142 case SOURCE_POLL:
1143 status.numSourcePoll++;
1144 break;
1145 case SOURCE_USER:
1146 status.numSourceUser++;
1147 break;
1148 case SOURCE_SERVER:
1149 status.numSourceServer++;
1150 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001151 case SOURCE_PERIODIC:
1152 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001153 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001154 }
Costin Manolache360e4542009-09-04 13:36:04 -07001155
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001157 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001158 if (mDayStats[0] == null) {
1159 mDayStats[0] = new DayStats(day);
1160 } else if (day != mDayStats[0].day) {
1161 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1162 mDayStats[0] = new DayStats(day);
1163 writeStatisticsNow = true;
1164 } else if (mDayStats[0] == null) {
1165 }
1166 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001167
Dianne Hackborn231cc602009-04-27 17:10:36 -07001168 final long lastSyncTime = (item.eventTime + elapsedTime);
1169 boolean writeStatusNow = false;
1170 if (MESG_SUCCESS.equals(resultMessage)) {
1171 // - if successful, update the successful columns
1172 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1173 writeStatusNow = true;
1174 }
1175 status.lastSuccessTime = lastSyncTime;
1176 status.lastSuccessSource = item.source;
1177 status.lastFailureTime = 0;
1178 status.lastFailureSource = -1;
1179 status.lastFailureMesg = null;
1180 status.initialFailureTime = 0;
1181 ds.successCount++;
1182 ds.successTime += elapsedTime;
1183 } else if (!MESG_CANCELED.equals(resultMessage)) {
1184 if (status.lastFailureTime == 0) {
1185 writeStatusNow = true;
1186 }
1187 status.lastFailureTime = lastSyncTime;
1188 status.lastFailureSource = item.source;
1189 status.lastFailureMesg = resultMessage;
1190 if (status.initialFailureTime == 0) {
1191 status.initialFailureTime = lastSyncTime;
1192 }
1193 ds.failureCount++;
1194 ds.failureTime += elapsedTime;
1195 }
Costin Manolache360e4542009-09-04 13:36:04 -07001196
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 if (writeStatusNow) {
1198 writeStatusLocked();
1199 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1200 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1201 WRITE_STATUS_DELAY);
1202 }
1203 if (writeStatisticsNow) {
1204 writeStatisticsLocked();
1205 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1206 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1207 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001208 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 }
Costin Manolache360e4542009-09-04 13:36:04 -07001210
Fred Quintanaac9385e2009-06-22 18:00:59 -07001211 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001212 }
1213
1214 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001215 * Return a list of the currently active syncs. Note that the returned items are the
1216 * real, live active sync objects, so be careful what you do with it.
1217 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001218 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001219 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001220 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1221 if (syncs == null) {
1222 syncs = new ArrayList<SyncInfo>();
1223 mCurrentSyncs.put(userId, syncs);
1224 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001225 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 }
1227 }
Costin Manolache360e4542009-09-04 13:36:04 -07001228
Dianne Hackborn231cc602009-04-27 17:10:36 -07001229 /**
1230 * Return an array of the current sync status for all authorities. Note
1231 * that the objects inside the array are the real, live status objects,
1232 * so be careful what you do with them.
1233 */
1234 public ArrayList<SyncStatusInfo> getSyncStatus() {
1235 synchronized (mAuthorities) {
1236 final int N = mSyncStatus.size();
1237 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1238 for (int i=0; i<N; i++) {
1239 ops.add(mSyncStatus.valueAt(i));
1240 }
1241 return ops;
1242 }
1243 }
Costin Manolache360e4542009-09-04 13:36:04 -07001244
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001246 * Return an array of the current authorities. Note
1247 * that the objects inside the array are the real, live objects,
1248 * so be careful what you do with them.
1249 */
1250 public ArrayList<AuthorityInfo> getAuthorities() {
1251 synchronized (mAuthorities) {
1252 final int N = mAuthorities.size();
1253 ArrayList<AuthorityInfo> infos = new ArrayList<AuthorityInfo>(N);
1254 for (int i=0; i<N; i++) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -07001255 // Make deep copy because AuthorityInfo syncs are liable to change.
1256 infos.add(new AuthorityInfo(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001257 }
1258 return infos;
1259 }
1260 }
1261
1262 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001263 * Returns the status that matches the authority and account.
1264 *
1265 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001267 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001269 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1270 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001271 if (account == null || authority == null) {
1272 throw new IllegalArgumentException();
1273 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001274 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001275 final int N = mSyncStatus.size();
1276 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001277 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001279
Amith Yamasani04e0d262012-02-14 11:50:53 -08001280 if (ainfo != null && ainfo.authority.equals(authority)
1281 && ainfo.userId == userId
1282 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001283 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 }
1285 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001286 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001287 }
1288 }
Costin Manolache360e4542009-09-04 13:36:04 -07001289
Dianne Hackborn231cc602009-04-27 17:10:36 -07001290 /**
1291 * Return true if the pending status is true of any matching authorities.
1292 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001293 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001294 synchronized (mAuthorities) {
1295 final int N = mSyncStatus.size();
1296 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001297 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001298 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1299 if (ainfo == null) {
1300 continue;
1301 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001302 if (userId != ainfo.userId) {
1303 continue;
1304 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 if (account != null && !ainfo.account.equals(account)) {
1306 continue;
1307 }
1308 if (ainfo.authority.equals(authority) && cur.pending) {
1309 return true;
1310 }
1311 }
1312 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 }
1314 }
1315
1316 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001317 * Return an array of the current sync status for all authorities. Note
1318 * that the objects inside the array are the real, live status objects,
1319 * so be careful what you do with them.
1320 */
1321 public ArrayList<SyncHistoryItem> getSyncHistory() {
1322 synchronized (mAuthorities) {
1323 final int N = mSyncHistory.size();
1324 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1325 for (int i=0; i<N; i++) {
1326 items.add(mSyncHistory.get(i));
1327 }
1328 return items;
1329 }
1330 }
Costin Manolache360e4542009-09-04 13:36:04 -07001331
Dianne Hackborn231cc602009-04-27 17:10:36 -07001332 /**
1333 * Return an array of the current per-day statistics. Note
1334 * that the objects inside the array are the real, live status objects,
1335 * so be careful what you do with them.
1336 */
1337 public DayStats[] getDayStatistics() {
1338 synchronized (mAuthorities) {
1339 DayStats[] ds = new DayStats[mDayStats.length];
1340 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1341 return ds;
1342 }
1343 }
Costin Manolache360e4542009-09-04 13:36:04 -07001344
Dianne Hackborn55280a92009-05-07 15:53:46 -07001345 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001346 mCal.setTimeInMillis(System.currentTimeMillis());
1347 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1348 if (mYear != mCal.get(Calendar.YEAR)) {
1349 mYear = mCal.get(Calendar.YEAR);
1350 mCal.clear();
1351 mCal.set(Calendar.YEAR, mYear);
1352 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1353 }
1354 return dayOfYear + mYearInDays;
1355 }
Costin Manolache360e4542009-09-04 13:36:04 -07001356
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 /**
1358 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001359 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 * @param accountName The name of the account for the authority.
1361 * @param authorityName The name of the authority itself.
1362 * @param tag If non-null, this will be used in a log message if the
1363 * requested authority does not exist.
1364 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001365 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001367 AccountAndUser au = new AccountAndUser(accountName, userId);
1368 AccountInfo accountInfo = mAccounts.get(au);
1369 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001370 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001371 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001372 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001373 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 }
1375 return null;
1376 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001377 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 if (authority == null) {
1379 if (tag != null) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001380 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1381 Log.v(TAG, tag + ": unknown authority " + authorityName);
1382 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001383 }
1384 return null;
1385 }
Costin Manolache360e4542009-09-04 13:36:04 -07001386
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 return authority;
1388 }
Costin Manolache360e4542009-09-04 13:36:04 -07001389
Amith Yamasani04e0d262012-02-14 11:50:53 -08001390 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001391 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001392 AccountAndUser au = new AccountAndUser(accountName, userId);
1393 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001395 account = new AccountInfo(au);
1396 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001397 }
1398 AuthorityInfo authority = account.authorities.get(authorityName);
1399 if (authority == null) {
1400 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001401 ident = mNextAuthorityId;
1402 mNextAuthorityId++;
1403 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001404 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001405 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1406 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001407 + ", user " + userId
1408 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001409 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001410 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001411 account.authorities.put(authorityName, authority);
1412 mAuthorities.put(ident, authority);
1413 if (doWrite) {
1414 writeAccountInfoLocked();
1415 }
1416 }
Costin Manolache360e4542009-09-04 13:36:04 -07001417
Dianne Hackborn231cc602009-04-27 17:10:36 -07001418 return authority;
1419 }
Costin Manolache360e4542009-09-04 13:36:04 -07001420
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1422 boolean doWrite) {
1423 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001424 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001425 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1426 if (authorityInfo != null) {
1427 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001428 if (doWrite) {
1429 writeAccountInfoLocked();
1430 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001431 }
1432 }
1433 }
1434
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001435 public SyncStatusInfo getOrCreateSyncStatus(AuthorityInfo authority) {
1436 synchronized (mAuthorities) {
1437 return getOrCreateSyncStatusLocked(authority.ident);
1438 }
1439 }
1440
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1442 SyncStatusInfo status = mSyncStatus.get(authorityId);
1443 if (status == null) {
1444 status = new SyncStatusInfo(authorityId);
1445 mSyncStatus.put(authorityId, status);
1446 }
1447 return status;
1448 }
Costin Manolache360e4542009-09-04 13:36:04 -07001449
Dianne Hackborn55280a92009-05-07 15:53:46 -07001450 public void writeAllState() {
1451 synchronized (mAuthorities) {
1452 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001453
Dianne Hackborn55280a92009-05-07 15:53:46 -07001454 if (mNumPendingFinished > 0) {
1455 // Only write these if they are out of date.
1456 writePendingOperationsLocked();
1457 }
Costin Manolache360e4542009-09-04 13:36:04 -07001458
Dianne Hackborn55280a92009-05-07 15:53:46 -07001459 // Just always write these... they are likely out of date.
1460 writeStatusLocked();
1461 writeStatisticsLocked();
1462 }
1463 }
Costin Manolache360e4542009-09-04 13:36:04 -07001464
Dianne Hackborn231cc602009-04-27 17:10:36 -07001465 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001466 * public for testing
1467 */
1468 public void clearAndReadState() {
1469 synchronized (mAuthorities) {
1470 mAuthorities.clear();
1471 mAccounts.clear();
1472 mPendingOperations.clear();
1473 mSyncStatus.clear();
1474 mSyncHistory.clear();
1475
1476 readAccountInfoLocked();
1477 readStatusLocked();
1478 readPendingOperationsLocked();
1479 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001480 readAndDeleteLegacyAccountInfoLocked();
1481 writeAccountInfoLocked();
1482 writeStatusLocked();
1483 writePendingOperationsLocked();
1484 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001485 }
1486 }
1487
1488 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001489 * Read all account information back in to the initial engine state.
1490 */
1491 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001492 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001493 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001495 fis = mAccountInfoFile.openRead();
1496 if (DEBUG_FILE) Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1497 XmlPullParser parser = Xml.newPullParser();
1498 parser.setInput(fis, null);
1499 int eventType = parser.getEventType();
1500 while (eventType != XmlPullParser.START_TAG) {
1501 eventType = parser.next();
1502 }
1503 String tagName = parser.getName();
1504 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001505 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001506 String versionString = parser.getAttributeValue(null, "version");
1507 int version;
1508 try {
1509 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1510 } catch (NumberFormatException e) {
1511 version = 0;
1512 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001513 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001514 try {
1515 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1516 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1517 } catch (NumberFormatException e) {
1518 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001519 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001520 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1521 try {
1522 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1523 } catch (NumberFormatException e) {
1524 mSyncRandomOffset = 0;
1525 }
1526 if (mSyncRandomOffset == 0) {
1527 Random random = new Random(System.currentTimeMillis());
1528 mSyncRandomOffset = random.nextInt(86400);
1529 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001530 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001531 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001532 AuthorityInfo authority = null;
1533 Pair<Bundle, Long> periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001534 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001535 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001536 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001537 if (parser.getDepth() == 2) {
1538 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001539 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001540 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001541 if (authority.ident > highestAuthorityId) {
1542 highestAuthorityId = authority.ident;
1543 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001544 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1545 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001547 } else if (parser.getDepth() == 3) {
1548 if ("periodicSync".equals(tagName) && authority != null) {
1549 periodicSync = parsePeriodicSync(parser, authority);
1550 }
1551 } else if (parser.getDepth() == 4 && periodicSync != null) {
1552 if ("extra".equals(tagName)) {
1553 parseExtra(parser, periodicSync);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001554 }
1555 }
1556 }
1557 eventType = parser.next();
1558 } while (eventType != XmlPullParser.END_DOCUMENT);
1559 }
1560 } catch (XmlPullParserException e) {
1561 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001562 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001563 } catch (java.io.IOException e) {
1564 if (fis == null) Log.i(TAG, "No initial accounts");
1565 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001566 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001567 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001568 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001569 if (fis != null) {
1570 try {
1571 fis.close();
1572 } catch (java.io.IOException e1) {
1573 }
1574 }
1575 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001576
Fred Quintana77c560f2010-03-29 22:20:26 -07001577 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001578 }
Costin Manolache360e4542009-09-04 13:36:04 -07001579
Fred Quintanafb084402010-03-23 17:57:03 -07001580 /**
1581 * some authority names have changed. copy over their settings and delete the old ones
1582 * @return true if a change was made
1583 */
1584 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1585 boolean writeNeeded = false;
1586
1587 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1588 final int N = mAuthorities.size();
1589 for (int i=0; i<N; i++) {
1590 AuthorityInfo authority = mAuthorities.valueAt(i);
1591 // skip this authority if it isn't one of the renamed ones
1592 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1593 if (newAuthorityName == null) {
1594 continue;
1595 }
1596
1597 // remember this authority so we can remove it later. we can't remove it
1598 // now without messing up this loop iteration
1599 authoritiesToRemove.add(authority);
1600
1601 // this authority isn't enabled, no need to copy it to the new authority name since
1602 // the default is "disabled"
1603 if (!authority.enabled) {
1604 continue;
1605 }
1606
1607 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001608 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1609 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001610 continue;
1611 }
1612
1613 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001614 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001615 newAuthority.enabled = true;
1616 writeNeeded = true;
1617 }
1618
1619 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001620 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1621 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001622 writeNeeded = true;
1623 }
1624
1625 return writeNeeded;
1626 }
1627
Amith Yamasani04e0d262012-02-14 11:50:53 -08001628 private void parseListenForTickles(XmlPullParser parser) {
1629 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1630 int userId = 0;
1631 try {
1632 userId = Integer.parseInt(user);
1633 } catch (NumberFormatException e) {
1634 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1635 } catch (NullPointerException e) {
1636 Log.e(TAG, "the user in listen-for-tickles is null", e);
1637 }
1638 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1639 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1640 mMasterSyncAutomatically.put(userId, listen);
1641 }
1642
Fred Quintanac2e46912010-03-15 16:10:44 -07001643 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001644 AuthorityInfo authority = null;
1645 int id = -1;
1646 try {
1647 id = Integer.parseInt(parser.getAttributeValue(
1648 null, "id"));
1649 } catch (NumberFormatException e) {
1650 Log.e(TAG, "error parsing the id of the authority", e);
1651 } catch (NullPointerException e) {
1652 Log.e(TAG, "the id of the authority is null", e);
1653 }
1654 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001655 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001656 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001657 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001658 String accountName = parser.getAttributeValue(null, "account");
1659 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001660 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1661 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001662 if (accountType == null) {
1663 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001664 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001665 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001666 authority = mAuthorities.get(id);
1667 if (DEBUG_FILE) Log.v(TAG, "Adding authority: account="
1668 + accountName + " auth=" + authorityName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001669 + " user=" + userId
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001670 + " enabled=" + enabled
1671 + " syncable=" + syncable);
1672 if (authority == null) {
1673 if (DEBUG_FILE) Log.v(TAG, "Creating entry");
1674 authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001675 new Account(accountName, accountType), userId, authorityName, id, false);
Fred Quintanac2e46912010-03-15 16:10:44 -07001676 // If the version is 0 then we are upgrading from a file format that did not
1677 // know about periodic syncs. In that case don't clear the list since we
1678 // want the default, which is a daily periodioc sync.
1679 // Otherwise clear out this default list since we will populate it later with
1680 // the periodic sync descriptions that are read from the configuration file.
1681 if (version > 0) {
1682 authority.periodicSyncs.clear();
1683 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001684 }
1685 if (authority != null) {
1686 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1687 if ("unknown".equals(syncable)) {
1688 authority.syncable = -1;
1689 } else {
1690 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001691 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001692 }
1693 } else {
1694 Log.w(TAG, "Failure adding authority: account="
1695 + accountName + " auth=" + authorityName
1696 + " enabled=" + enabled
1697 + " syncable=" + syncable);
1698 }
1699 }
1700
1701 return authority;
1702 }
1703
1704 private Pair<Bundle, Long> parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1705 Bundle extras = new Bundle();
1706 String periodValue = parser.getAttributeValue(null, "period");
1707 final long period;
1708 try {
1709 period = Long.parseLong(periodValue);
1710 } catch (NumberFormatException e) {
1711 Log.e(TAG, "error parsing the period of a periodic sync", e);
1712 return null;
1713 } catch (NullPointerException e) {
1714 Log.e(TAG, "the period of a periodic sync is null", e);
1715 return null;
1716 }
1717 final Pair<Bundle, Long> periodicSync = Pair.create(extras, period);
1718 authority.periodicSyncs.add(periodicSync);
Fred Quintanac2e46912010-03-15 16:10:44 -07001719
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001720 return periodicSync;
1721 }
1722
1723 private void parseExtra(XmlPullParser parser, Pair<Bundle, Long> periodicSync) {
1724 final Bundle extras = periodicSync.first;
1725 String name = parser.getAttributeValue(null, "name");
1726 String type = parser.getAttributeValue(null, "type");
1727 String value1 = parser.getAttributeValue(null, "value1");
1728 String value2 = parser.getAttributeValue(null, "value2");
1729
1730 try {
1731 if ("long".equals(type)) {
1732 extras.putLong(name, Long.parseLong(value1));
1733 } else if ("integer".equals(type)) {
1734 extras.putInt(name, Integer.parseInt(value1));
1735 } else if ("double".equals(type)) {
1736 extras.putDouble(name, Double.parseDouble(value1));
1737 } else if ("float".equals(type)) {
1738 extras.putFloat(name, Float.parseFloat(value1));
1739 } else if ("boolean".equals(type)) {
1740 extras.putBoolean(name, Boolean.parseBoolean(value1));
1741 } else if ("string".equals(type)) {
1742 extras.putString(name, value1);
1743 } else if ("account".equals(type)) {
1744 extras.putParcelable(name, new Account(value1, value2));
1745 }
1746 } catch (NumberFormatException e) {
1747 Log.e(TAG, "error parsing bundle value", e);
1748 } catch (NullPointerException e) {
1749 Log.e(TAG, "error parsing bundle value", e);
1750 }
1751 }
1752
Dianne Hackborn231cc602009-04-27 17:10:36 -07001753 /**
1754 * Write all account information to the account file.
1755 */
1756 private void writeAccountInfoLocked() {
1757 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1758 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001759
Dianne Hackborn231cc602009-04-27 17:10:36 -07001760 try {
1761 fos = mAccountInfoFile.startWrite();
1762 XmlSerializer out = new FastXmlSerializer();
1763 out.setOutput(fos, "utf-8");
1764 out.startDocument(null, true);
1765 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001766
Dianne Hackborn231cc602009-04-27 17:10:36 -07001767 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001768 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001769 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001770 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001771
1772 // Write the Sync Automatically flags for each user
1773 final int M = mMasterSyncAutomatically.size();
1774 for (int m = 0; m < M; m++) {
1775 int userId = mMasterSyncAutomatically.keyAt(m);
1776 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1777 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1778 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1779 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1780 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001781 }
Costin Manolache360e4542009-09-04 13:36:04 -07001782
Dianne Hackborn231cc602009-04-27 17:10:36 -07001783 final int N = mAuthorities.size();
1784 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001785 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 out.startTag(null, "authority");
1787 out.attribute(null, "id", Integer.toString(authority.ident));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001788 out.attribute(null, "account", authority.account.name);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001789 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001790 out.attribute(null, "type", authority.account.type);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001791 out.attribute(null, "authority", authority.authority);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001792 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Fred Quintana5e787c42009-08-16 23:13:53 -07001793 if (authority.syncable < 0) {
1794 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07001795 } else {
1796 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07001797 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001798 for (Pair<Bundle, Long> periodicSync : authority.periodicSyncs) {
1799 out.startTag(null, "periodicSync");
1800 out.attribute(null, "period", Long.toString(periodicSync.second));
1801 final Bundle extras = periodicSync.first;
1802 for (String key : extras.keySet()) {
1803 out.startTag(null, "extra");
1804 out.attribute(null, "name", key);
1805 final Object value = extras.get(key);
1806 if (value instanceof Long) {
1807 out.attribute(null, "type", "long");
1808 out.attribute(null, "value1", value.toString());
1809 } else if (value instanceof Integer) {
1810 out.attribute(null, "type", "integer");
1811 out.attribute(null, "value1", value.toString());
1812 } else if (value instanceof Boolean) {
1813 out.attribute(null, "type", "boolean");
1814 out.attribute(null, "value1", value.toString());
1815 } else if (value instanceof Float) {
1816 out.attribute(null, "type", "float");
1817 out.attribute(null, "value1", value.toString());
1818 } else if (value instanceof Double) {
1819 out.attribute(null, "type", "double");
1820 out.attribute(null, "value1", value.toString());
1821 } else if (value instanceof String) {
1822 out.attribute(null, "type", "string");
1823 out.attribute(null, "value1", value.toString());
1824 } else if (value instanceof Account) {
1825 out.attribute(null, "type", "account");
1826 out.attribute(null, "value1", ((Account)value).name);
1827 out.attribute(null, "value2", ((Account)value).type);
1828 }
1829 out.endTag(null, "extra");
1830 }
1831 out.endTag(null, "periodicSync");
1832 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 out.endTag(null, "authority");
1834 }
Costin Manolache360e4542009-09-04 13:36:04 -07001835
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 out.endTag(null, "accounts");
Costin Manolache360e4542009-09-04 13:36:04 -07001837
Dianne Hackborn231cc602009-04-27 17:10:36 -07001838 out.endDocument();
Costin Manolache360e4542009-09-04 13:36:04 -07001839
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 mAccountInfoFile.finishWrite(fos);
1841 } catch (java.io.IOException e1) {
1842 Log.w(TAG, "Error writing accounts", e1);
1843 if (fos != null) {
1844 mAccountInfoFile.failWrite(fos);
1845 }
1846 }
1847 }
Costin Manolache360e4542009-09-04 13:36:04 -07001848
Dianne Hackborn231cc602009-04-27 17:10:36 -07001849 static int getIntColumn(Cursor c, String name) {
1850 return c.getInt(c.getColumnIndex(name));
1851 }
Costin Manolache360e4542009-09-04 13:36:04 -07001852
Dianne Hackborn231cc602009-04-27 17:10:36 -07001853 static long getLongColumn(Cursor c, String name) {
1854 return c.getLong(c.getColumnIndex(name));
1855 }
Costin Manolache360e4542009-09-04 13:36:04 -07001856
Dianne Hackborn231cc602009-04-27 17:10:36 -07001857 /**
1858 * Load sync engine state from the old syncmanager database, and then
1859 * erase it. Note that we don't deal with pending operations, active
1860 * sync, or history.
1861 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001862 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001863 // Look for old database to initialize from.
1864 File file = mContext.getDatabasePath("syncmanager.db");
1865 if (!file.exists()) {
1866 return;
1867 }
1868 String path = file.getPath();
1869 SQLiteDatabase db = null;
1870 try {
1871 db = SQLiteDatabase.openDatabase(path, null,
1872 SQLiteDatabase.OPEN_READONLY);
1873 } catch (SQLiteException e) {
1874 }
Costin Manolache360e4542009-09-04 13:36:04 -07001875
Dianne Hackborn231cc602009-04-27 17:10:36 -07001876 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001877 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001878
Dianne Hackborn231cc602009-04-27 17:10:36 -07001879 // Copy in all of the status information, as well as accounts.
1880 if (DEBUG_FILE) Log.v(TAG, "Reading legacy sync accounts db");
1881 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1882 qb.setTables("stats, status");
1883 HashMap<String,String> map = new HashMap<String,String>();
1884 map.put("_id", "status._id as _id");
1885 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001886 if (hasType) {
1887 map.put("account_type", "stats.account_type as account_type");
1888 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001889 map.put("authority", "stats.authority as authority");
1890 map.put("totalElapsedTime", "totalElapsedTime");
1891 map.put("numSyncs", "numSyncs");
1892 map.put("numSourceLocal", "numSourceLocal");
1893 map.put("numSourcePoll", "numSourcePoll");
1894 map.put("numSourceServer", "numSourceServer");
1895 map.put("numSourceUser", "numSourceUser");
1896 map.put("lastSuccessSource", "lastSuccessSource");
1897 map.put("lastSuccessTime", "lastSuccessTime");
1898 map.put("lastFailureSource", "lastFailureSource");
1899 map.put("lastFailureTime", "lastFailureTime");
1900 map.put("lastFailureMesg", "lastFailureMesg");
1901 map.put("pending", "pending");
1902 qb.setProjectionMap(map);
1903 qb.appendWhere("stats._id = status.stats_id");
1904 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001906 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001907 String accountType = hasType
1908 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001909 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001910 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001912 String authorityName = c.getString(c.getColumnIndex("authority"));
1913 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08001914 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07001915 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001916 if (authority != null) {
1917 int i = mSyncStatus.size();
1918 boolean found = false;
1919 SyncStatusInfo st = null;
1920 while (i > 0) {
1921 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001922 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 if (st.authorityId == authority.ident) {
1924 found = true;
1925 break;
1926 }
1927 }
1928 if (!found) {
1929 st = new SyncStatusInfo(authority.ident);
1930 mSyncStatus.put(authority.ident, st);
1931 }
1932 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1933 st.numSyncs = getIntColumn(c, "numSyncs");
1934 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1935 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1936 st.numSourceServer = getIntColumn(c, "numSourceServer");
1937 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001938 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1940 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1941 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1942 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1943 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1944 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
Costin Manolache360e4542009-09-04 13:36:04 -07001947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001949
Dianne Hackborn231cc602009-04-27 17:10:36 -07001950 // Retrieve the settings.
1951 qb = new SQLiteQueryBuilder();
1952 qb.setTables("settings");
1953 c = qb.query(db, null, null, null, null, null, null);
1954 while (c.moveToNext()) {
1955 String name = c.getString(c.getColumnIndex("name"));
1956 String value = c.getString(c.getColumnIndex("value"));
1957 if (name == null) continue;
1958 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001959 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 } else if (name.startsWith("sync_provider_")) {
1961 String provider = name.substring("sync_provider_".length(),
1962 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001963 int i = mAuthorities.size();
1964 while (i > 0) {
1965 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001966 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07001967 if (authority.authority.equals(provider)) {
1968 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001969 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001970 }
1971 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
Costin Manolache360e4542009-09-04 13:36:04 -07001974
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001976
Dianne Hackborn231cc602009-04-27 17:10:36 -07001977 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001978
Dianne Hackborn231cc602009-04-27 17:10:36 -07001979 (new File(path)).delete();
1980 }
1981 }
Costin Manolache360e4542009-09-04 13:36:04 -07001982
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 public static final int STATUS_FILE_END = 0;
1984 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001985
Dianne Hackborn231cc602009-04-27 17:10:36 -07001986 /**
1987 * Read all sync status back in to the initial engine state.
1988 */
1989 private void readStatusLocked() {
1990 if (DEBUG_FILE) Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
1991 try {
1992 byte[] data = mStatusFile.readFully();
1993 Parcel in = Parcel.obtain();
1994 in.unmarshall(data, 0, data.length);
1995 in.setDataPosition(0);
1996 int token;
1997 while ((token=in.readInt()) != STATUS_FILE_END) {
1998 if (token == STATUS_FILE_ITEM) {
1999 SyncStatusInfo status = new SyncStatusInfo(in);
2000 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2001 status.pending = false;
2002 if (DEBUG_FILE) Log.v(TAG, "Adding status for id "
2003 + status.authorityId);
2004 mSyncStatus.put(status.authorityId, status);
2005 }
2006 } else {
2007 // Ooops.
2008 Log.w(TAG, "Unknown status token: " + token);
2009 break;
2010 }
2011 }
2012 } catch (java.io.IOException e) {
2013 Log.i(TAG, "No initial status");
2014 }
2015 }
Costin Manolache360e4542009-09-04 13:36:04 -07002016
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 /**
2018 * Write all sync status to the sync status file.
2019 */
2020 private void writeStatusLocked() {
2021 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002022
Dianne Hackborn231cc602009-04-27 17:10:36 -07002023 // The file is being written, so we don't need to have a scheduled
2024 // write until the next change.
2025 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002026
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 FileOutputStream fos = null;
2028 try {
2029 fos = mStatusFile.startWrite();
2030 Parcel out = Parcel.obtain();
2031 final int N = mSyncStatus.size();
2032 for (int i=0; i<N; i++) {
2033 SyncStatusInfo status = mSyncStatus.valueAt(i);
2034 out.writeInt(STATUS_FILE_ITEM);
2035 status.writeToParcel(out, 0);
2036 }
2037 out.writeInt(STATUS_FILE_END);
2038 fos.write(out.marshall());
2039 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002040
Dianne Hackborn231cc602009-04-27 17:10:36 -07002041 mStatusFile.finishWrite(fos);
2042 } catch (java.io.IOException e1) {
2043 Log.w(TAG, "Error writing status", e1);
2044 if (fos != null) {
2045 mStatusFile.failWrite(fos);
2046 }
2047 }
2048 }
Costin Manolache360e4542009-09-04 13:36:04 -07002049
Alon Albert57286f92012-10-09 14:21:38 -07002050 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002051
Dianne Hackborn231cc602009-04-27 17:10:36 -07002052 /**
2053 * Read all pending operations back in to the initial engine state.
2054 */
2055 private void readPendingOperationsLocked() {
2056 if (DEBUG_FILE) Log.v(TAG, "Reading " + mPendingFile.getBaseFile());
2057 try {
2058 byte[] data = mPendingFile.readFully();
2059 Parcel in = Parcel.obtain();
2060 in.unmarshall(data, 0, data.length);
2061 in.setDataPosition(0);
2062 final int SIZE = in.dataSize();
2063 while (in.dataPosition() < SIZE) {
2064 int version = in.readInt();
Fred Quintana307da1a2010-01-21 14:24:20 -08002065 if (version != PENDING_OPERATION_VERSION && version != 1) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002066 Log.w(TAG, "Unknown pending operation version "
2067 + version + "; dropping all ops");
2068 break;
2069 }
2070 int authorityId = in.readInt();
2071 int syncSource = in.readInt();
2072 byte[] flatExtras = in.createByteArray();
Fred Quintana307da1a2010-01-21 14:24:20 -08002073 boolean expedited;
2074 if (version == PENDING_OPERATION_VERSION) {
2075 expedited = in.readInt() != 0;
2076 } else {
2077 expedited = false;
2078 }
Alon Albert57286f92012-10-09 14:21:38 -07002079 int reason = in.readInt();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 AuthorityInfo authority = mAuthorities.get(authorityId);
2081 if (authority != null) {
Fred Quintana5695c7b2010-12-06 15:07:52 -08002082 Bundle extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002083 if (flatExtras != null) {
2084 extras = unflattenBundle(flatExtras);
Fred Quintana5695c7b2010-12-06 15:07:52 -08002085 } else {
2086 // if we are unable to parse the extras for whatever reason convert this
2087 // to a regular sync by creating an empty extras
2088 extras = new Bundle();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002089 }
2090 PendingOperation op = new PendingOperation(
Alon Albert57286f92012-10-09 14:21:38 -07002091 authority.account, authority.userId, reason, syncSource,
Fred Quintana307da1a2010-01-21 14:24:20 -08002092 authority.authority, extras, expedited);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002093 op.authorityId = authorityId;
2094 op.flatExtras = flatExtras;
2095 if (DEBUG_FILE) Log.v(TAG, "Adding pending op: account=" + op.account
2096 + " auth=" + op.authority
2097 + " src=" + op.syncSource
Alon Albert57286f92012-10-09 14:21:38 -07002098 + " reason=" + op.reason
Fred Quintana307da1a2010-01-21 14:24:20 -08002099 + " expedited=" + op.expedited
Dianne Hackborn231cc602009-04-27 17:10:36 -07002100 + " extras=" + op.extras);
2101 mPendingOperations.add(op);
2102 }
2103 }
2104 } catch (java.io.IOException e) {
2105 Log.i(TAG, "No initial pending operations");
2106 }
2107 }
Costin Manolache360e4542009-09-04 13:36:04 -07002108
Dianne Hackborn231cc602009-04-27 17:10:36 -07002109 private void writePendingOperationLocked(PendingOperation op, Parcel out) {
2110 out.writeInt(PENDING_OPERATION_VERSION);
2111 out.writeInt(op.authorityId);
2112 out.writeInt(op.syncSource);
2113 if (op.flatExtras == null && op.extras != null) {
2114 op.flatExtras = flattenBundle(op.extras);
2115 }
2116 out.writeByteArray(op.flatExtras);
Fred Quintana307da1a2010-01-21 14:24:20 -08002117 out.writeInt(op.expedited ? 1 : 0);
Alon Albert57286f92012-10-09 14:21:38 -07002118 out.writeInt(op.reason);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002119 }
Costin Manolache360e4542009-09-04 13:36:04 -07002120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 /**
2122 * Write all currently pending ops to the pending ops file.
2123 */
2124 private void writePendingOperationsLocked() {
2125 final int N = mPendingOperations.size();
2126 FileOutputStream fos = null;
2127 try {
2128 if (N == 0) {
2129 if (DEBUG_FILE) Log.v(TAG, "Truncating " + mPendingFile.getBaseFile());
2130 mPendingFile.truncate();
2131 return;
2132 }
Costin Manolache360e4542009-09-04 13:36:04 -07002133
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mPendingFile.getBaseFile());
2135 fos = mPendingFile.startWrite();
Costin Manolache360e4542009-09-04 13:36:04 -07002136
Dianne Hackborn231cc602009-04-27 17:10:36 -07002137 Parcel out = Parcel.obtain();
2138 for (int i=0; i<N; i++) {
2139 PendingOperation op = mPendingOperations.get(i);
2140 writePendingOperationLocked(op, out);
2141 }
2142 fos.write(out.marshall());
2143 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002144
Dianne Hackborn231cc602009-04-27 17:10:36 -07002145 mPendingFile.finishWrite(fos);
2146 } catch (java.io.IOException e1) {
2147 Log.w(TAG, "Error writing pending operations", e1);
2148 if (fos != null) {
2149 mPendingFile.failWrite(fos);
2150 }
2151 }
2152 }
Costin Manolache360e4542009-09-04 13:36:04 -07002153
Dianne Hackborn231cc602009-04-27 17:10:36 -07002154 /**
2155 * Append the given operation to the pending ops file; if unable to,
2156 * write all pending ops.
2157 */
2158 private void appendPendingOperationLocked(PendingOperation op) {
2159 if (DEBUG_FILE) Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2160 FileOutputStream fos = null;
2161 try {
2162 fos = mPendingFile.openAppend();
2163 } catch (java.io.IOException e) {
2164 if (DEBUG_FILE) Log.v(TAG, "Failed append; writing full file");
2165 writePendingOperationsLocked();
2166 return;
2167 }
Costin Manolache360e4542009-09-04 13:36:04 -07002168
Dianne Hackborn231cc602009-04-27 17:10:36 -07002169 try {
2170 Parcel out = Parcel.obtain();
2171 writePendingOperationLocked(op, out);
2172 fos.write(out.marshall());
2173 out.recycle();
2174 } catch (java.io.IOException e1) {
2175 Log.w(TAG, "Error writing pending operations", e1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 } finally {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002177 try {
2178 fos.close();
2179 } catch (java.io.IOException e2) {
2180 }
2181 }
2182 }
Costin Manolache360e4542009-09-04 13:36:04 -07002183
Dianne Hackborn231cc602009-04-27 17:10:36 -07002184 static private byte[] flattenBundle(Bundle bundle) {
2185 byte[] flatData = null;
2186 Parcel parcel = Parcel.obtain();
2187 try {
2188 bundle.writeToParcel(parcel, 0);
2189 flatData = parcel.marshall();
2190 } finally {
2191 parcel.recycle();
2192 }
2193 return flatData;
2194 }
Costin Manolache360e4542009-09-04 13:36:04 -07002195
Dianne Hackborn231cc602009-04-27 17:10:36 -07002196 static private Bundle unflattenBundle(byte[] flatData) {
2197 Bundle bundle;
2198 Parcel parcel = Parcel.obtain();
2199 try {
2200 parcel.unmarshall(flatData, 0, flatData.length);
2201 parcel.setDataPosition(0);
2202 bundle = parcel.readBundle();
2203 } catch (RuntimeException e) {
2204 // A RuntimeException is thrown if we were unable to parse the parcel.
2205 // Create an empty parcel in this case.
2206 bundle = new Bundle();
2207 } finally {
2208 parcel.recycle();
2209 }
2210 return bundle;
2211 }
Costin Manolache360e4542009-09-04 13:36:04 -07002212
Alon Albert57286f92012-10-09 14:21:38 -07002213 private void requestSync(Account account, int userId, int reason, String authority,
2214 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002215 // If this is happening in the system process, then call the syncrequest listener
2216 // to make a request back to the SyncManager directly.
2217 // If this is probably a test instance, then call back through the ContentResolver
2218 // which will know which userId to apply based on the Binder id.
2219 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2220 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002221 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002222 } else {
2223 ContentResolver.requestSync(account, authority, extras);
2224 }
2225 }
2226
Dianne Hackborn231cc602009-04-27 17:10:36 -07002227 public static final int STATISTICS_FILE_END = 0;
2228 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2229 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002230
Dianne Hackborn231cc602009-04-27 17:10:36 -07002231 /**
2232 * Read all sync statistics back in to the initial engine state.
2233 */
2234 private void readStatisticsLocked() {
2235 try {
2236 byte[] data = mStatisticsFile.readFully();
2237 Parcel in = Parcel.obtain();
2238 in.unmarshall(data, 0, data.length);
2239 in.setDataPosition(0);
2240 int token;
2241 int index = 0;
2242 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2243 if (token == STATISTICS_FILE_ITEM
2244 || token == STATISTICS_FILE_ITEM_OLD) {
2245 int day = in.readInt();
2246 if (token == STATISTICS_FILE_ITEM_OLD) {
2247 day = day - 2009 + 14245; // Magic!
2248 }
2249 DayStats ds = new DayStats(day);
2250 ds.successCount = in.readInt();
2251 ds.successTime = in.readLong();
2252 ds.failureCount = in.readInt();
2253 ds.failureTime = in.readLong();
2254 if (index < mDayStats.length) {
2255 mDayStats[index] = ds;
2256 index++;
2257 }
2258 } else {
2259 // Ooops.
2260 Log.w(TAG, "Unknown stats token: " + token);
2261 break;
2262 }
2263 }
2264 } catch (java.io.IOException e) {
2265 Log.i(TAG, "No initial statistics");
2266 }
2267 }
Costin Manolache360e4542009-09-04 13:36:04 -07002268
Dianne Hackborn231cc602009-04-27 17:10:36 -07002269 /**
2270 * Write all sync statistics to the sync status file.
2271 */
2272 private void writeStatisticsLocked() {
2273 if (DEBUG_FILE) Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Costin Manolache360e4542009-09-04 13:36:04 -07002274
Dianne Hackborn231cc602009-04-27 17:10:36 -07002275 // The file is being written, so we don't need to have a scheduled
2276 // write until the next change.
2277 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002278
Dianne Hackborn231cc602009-04-27 17:10:36 -07002279 FileOutputStream fos = null;
2280 try {
2281 fos = mStatisticsFile.startWrite();
2282 Parcel out = Parcel.obtain();
2283 final int N = mDayStats.length;
2284 for (int i=0; i<N; i++) {
2285 DayStats ds = mDayStats[i];
2286 if (ds == null) {
2287 break;
2288 }
2289 out.writeInt(STATISTICS_FILE_ITEM);
2290 out.writeInt(ds.day);
2291 out.writeInt(ds.successCount);
2292 out.writeLong(ds.successTime);
2293 out.writeInt(ds.failureCount);
2294 out.writeLong(ds.failureTime);
2295 }
2296 out.writeInt(STATISTICS_FILE_END);
2297 fos.write(out.marshall());
2298 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002299
Dianne Hackborn231cc602009-04-27 17:10:36 -07002300 mStatisticsFile.finishWrite(fos);
2301 } catch (java.io.IOException e1) {
2302 Log.w(TAG, "Error writing stats", e1);
2303 if (fos != null) {
2304 mStatisticsFile.failWrite(fos);
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307 }
2308}